blob: 548a6113725979d9db65cb0d5d87ccec0eb86917 [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 Antao90927002016-04-26 14:54:23 +0000329 // Do the check specified in \a Check to all component lists and return true
330 // if any issue is found.
331 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 Antao90927002016-04-26 14:54:23 +0000358 // Create a new mappable expression component list associated with a given
359 // declaration and initialize it with the provided list of components.
360 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
922 // behaviour.
923 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);
Alexey Bataev38e89532015-04-16 04:54:05 +00001092 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
1093 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:
1597 case OMPD_teams: {
Alexey Bataev9959db52014-05-06 10:08:46 +00001598 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001599 QualType KmpInt32PtrTy =
1600 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001601 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001602 std::make_pair(".global_tid.", KmpInt32PtrTy),
1603 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1604 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001605 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001606 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1607 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001608 break;
1609 }
Kelvin Li70a12c52016-07-13 21:51:49 +00001610 case OMPD_simd:
1611 case OMPD_for:
1612 case OMPD_for_simd:
1613 case OMPD_sections:
1614 case OMPD_section:
1615 case OMPD_single:
1616 case OMPD_master:
1617 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00001618 case OMPD_taskgroup:
1619 case OMPD_distribute:
Kelvin Li70a12c52016-07-13 21:51:49 +00001620 case OMPD_ordered:
1621 case OMPD_atomic:
1622 case OMPD_target_data:
1623 case OMPD_target:
1624 case OMPD_target_parallel:
1625 case OMPD_target_parallel_for:
Kelvin Li986330c2016-07-20 22:57:10 +00001626 case OMPD_target_parallel_for_simd:
1627 case OMPD_target_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001628 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001629 std::make_pair(StringRef(), QualType()) // __context with shared vars
1630 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001631 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1632 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001633 break;
1634 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001635 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001636 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001637 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1638 FunctionProtoType::ExtProtoInfo EPI;
1639 EPI.Variadic = true;
1640 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001641 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001642 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataev48591dd2016-04-20 04:01:36 +00001643 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1644 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
1645 std::make_pair(".copy_fn.",
1646 Context.getPointerType(CopyFnType).withConst()),
1647 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001648 std::make_pair(StringRef(), QualType()) // __context with shared vars
1649 };
1650 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1651 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001652 // Mark this captured region as inlined, because we don't use outlined
1653 // function directly.
1654 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1655 AlwaysInlineAttr::CreateImplicit(
1656 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001657 break;
1658 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00001659 case OMPD_taskloop:
1660 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00001661 QualType KmpInt32Ty =
1662 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1663 QualType KmpUInt64Ty =
1664 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
1665 QualType KmpInt64Ty =
1666 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
1667 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1668 FunctionProtoType::ExtProtoInfo EPI;
1669 EPI.Variadic = true;
1670 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00001671 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00001672 std::make_pair(".global_tid.", KmpInt32Ty),
1673 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1674 std::make_pair(".privates.",
1675 Context.VoidPtrTy.withConst().withRestrict()),
1676 std::make_pair(
1677 ".copy_fn.",
1678 Context.getPointerType(CopyFnType).withConst().withRestrict()),
1679 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1680 std::make_pair(".lb.", KmpUInt64Ty),
1681 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
1682 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataev49f6e782015-12-01 04:18:41 +00001683 std::make_pair(StringRef(), QualType()) // __context with shared vars
1684 };
1685 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1686 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00001687 // Mark this captured region as inlined, because we don't use outlined
1688 // function directly.
1689 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1690 AlwaysInlineAttr::CreateImplicit(
1691 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev49f6e782015-12-01 04:18:41 +00001692 break;
1693 }
Kelvin Li4a39add2016-07-05 05:00:15 +00001694 case OMPD_distribute_parallel_for_simd:
Kelvin Li787f3fc2016-07-06 04:45:38 +00001695 case OMPD_distribute_simd:
Kelvin Li02532872016-08-05 14:37:37 +00001696 case OMPD_distribute_parallel_for:
Kelvin Li4e325f72016-10-25 12:50:55 +00001697 case OMPD_teams_distribute:
Kelvin Li579e41c2016-11-30 23:51:03 +00001698 case OMPD_teams_distribute_simd:
1699 case OMPD_teams_distribute_parallel_for_simd: {
Carlo Bertolli9925f152016-06-27 14:55:37 +00001700 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1701 QualType KmpInt32PtrTy =
1702 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1703 Sema::CapturedParamNameType Params[] = {
1704 std::make_pair(".global_tid.", KmpInt32PtrTy),
1705 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1706 std::make_pair(".previous.lb.", Context.getSizeType()),
1707 std::make_pair(".previous.ub.", Context.getSizeType()),
1708 std::make_pair(StringRef(), QualType()) // __context with shared vars
1709 };
1710 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1711 Params);
1712 break;
1713 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001714 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001715 case OMPD_taskyield:
1716 case OMPD_barrier:
1717 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001718 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00001719 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00001720 case OMPD_flush:
Samuel Antaodf67fc42016-01-19 19:15:56 +00001721 case OMPD_target_enter_data:
Samuel Antao72590762016-01-19 20:04:50 +00001722 case OMPD_target_exit_data:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00001723 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00001724 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001725 case OMPD_declare_target:
1726 case OMPD_end_declare_target:
Samuel Antao686c70c2016-05-26 17:30:50 +00001727 case OMPD_target_update:
Alexey Bataev9959db52014-05-06 10:08:46 +00001728 llvm_unreachable("OpenMP Directive is not allowed");
1729 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001730 llvm_unreachable("Unknown OpenMP directive");
1731 }
1732}
1733
Alexey Bataev3392d762016-02-16 11:18:12 +00001734static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00001735 Expr *CaptureExpr, bool WithInit,
1736 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001737 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00001738 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00001739 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00001740 QualType Ty = Init->getType();
1741 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
1742 if (S.getLangOpts().CPlusPlus)
1743 Ty = C.getLValueReferenceType(Ty);
1744 else {
1745 Ty = C.getPointerType(Ty);
1746 ExprResult Res =
1747 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
1748 if (!Res.isUsable())
1749 return nullptr;
1750 Init = Res.get();
1751 }
Alexey Bataev61205072016-03-02 04:57:40 +00001752 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00001753 }
1754 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001755 if (!WithInit)
1756 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
Alexey Bataev4244be22016-02-11 05:35:55 +00001757 S.CurContext->addHiddenDecl(CED);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001758 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false,
1759 /*TypeMayContainAuto=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00001760 return CED;
1761}
1762
Alexey Bataev61205072016-03-02 04:57:40 +00001763static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
1764 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00001765 OMPCapturedExprDecl *CD;
1766 if (auto *VD = S.IsOpenMPCapturedDecl(D))
1767 CD = cast<OMPCapturedExprDecl>(VD);
1768 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00001769 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
1770 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001771 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00001772 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00001773}
1774
Alexey Bataev5a3af132016-03-29 08:58:54 +00001775static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
1776 if (!Ref) {
1777 auto *CD =
1778 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
1779 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
1780 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
1781 CaptureExpr->getExprLoc());
1782 }
1783 ExprResult Res = Ref;
1784 if (!S.getLangOpts().CPlusPlus &&
1785 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
1786 Ref->getType()->isPointerType())
1787 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
1788 if (!Res.isUsable())
1789 return ExprError();
1790 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00001791}
1792
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001793StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1794 ArrayRef<OMPClause *> Clauses) {
1795 if (!S.isUsable()) {
1796 ActOnCapturedRegionError();
1797 return StmtError();
1798 }
Alexey Bataev993d2802015-12-28 06:23:08 +00001799
1800 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00001801 OMPScheduleClause *SC = nullptr;
Alexey Bataev993d2802015-12-28 06:23:08 +00001802 SmallVector<OMPLinearClause *, 4> LCs;
Alexey Bataev040d5402015-05-12 08:35:28 +00001803 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001804 for (auto *Clause : Clauses) {
Alexey Bataev16dc7b62015-05-20 03:46:04 +00001805 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001806 Clause->getClauseKind() == OMPC_copyprivate ||
1807 (getLangOpts().OpenMPUseTLS &&
1808 getASTContext().getTargetInfo().isTLSSupported() &&
1809 Clause->getClauseKind() == OMPC_copyin)) {
1810 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00001811 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001812 for (auto *VarRef : Clause->children()) {
1813 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00001814 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001815 }
1816 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001817 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001818 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
Alexey Bataev040d5402015-05-12 08:35:28 +00001819 // Mark all variables in private list clauses as used in inner region.
1820 // Required for proper codegen of combined directives.
1821 // TODO: add processing for other clauses.
Alexey Bataev3392d762016-02-16 11:18:12 +00001822 if (auto *C = OMPClauseWithPreInit::get(Clause)) {
Alexey Bataev005248a2016-02-25 05:25:57 +00001823 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
1824 for (auto *D : DS->decls())
Alexey Bataev3392d762016-02-16 11:18:12 +00001825 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
1826 }
Alexey Bataev4244be22016-02-11 05:35:55 +00001827 }
Alexey Bataev005248a2016-02-25 05:25:57 +00001828 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
1829 if (auto *E = C->getPostUpdateExpr())
1830 MarkDeclarationsReferencedInExpr(E);
1831 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001832 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001833 if (Clause->getClauseKind() == OMPC_schedule)
1834 SC = cast<OMPScheduleClause>(Clause);
1835 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00001836 OC = cast<OMPOrderedClause>(Clause);
1837 else if (Clause->getClauseKind() == OMPC_linear)
1838 LCs.push_back(cast<OMPLinearClause>(Clause));
1839 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001840 bool ErrorFound = false;
1841 // OpenMP, 2.7.1 Loop Construct, Restrictions
1842 // The nonmonotonic modifier cannot be specified if an ordered clause is
1843 // specified.
1844 if (SC &&
1845 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
1846 SC->getSecondScheduleModifier() ==
1847 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
1848 OC) {
1849 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
1850 ? SC->getFirstScheduleModifierLoc()
1851 : SC->getSecondScheduleModifierLoc(),
1852 diag::err_omp_schedule_nonmonotonic_ordered)
1853 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1854 ErrorFound = true;
1855 }
Alexey Bataev993d2802015-12-28 06:23:08 +00001856 if (!LCs.empty() && OC && OC->getNumForLoops()) {
1857 for (auto *C : LCs) {
1858 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
1859 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1860 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001861 ErrorFound = true;
1862 }
Alexey Bataev113438c2015-12-30 12:06:23 +00001863 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
1864 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
1865 OC->getNumForLoops()) {
1866 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
1867 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
1868 ErrorFound = true;
1869 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001870 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00001871 ActOnCapturedRegionError();
1872 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001873 }
1874 return ActOnCapturedRegionEnd(S.get());
1875}
1876
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001877static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1878 OpenMPDirectiveKind CurrentRegion,
1879 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001880 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001881 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001882 if (Stack->getCurScope()) {
1883 auto ParentRegion = Stack->getParentDirective();
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001884 auto OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00001885 bool NestingProhibited = false;
1886 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00001887 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001888 enum {
1889 NoRecommend,
1890 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00001891 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00001892 ShouldBeInTargetRegion,
1893 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001894 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00001895 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001896 // OpenMP [2.16, Nesting of Regions]
1897 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00001898 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00001899 // An ordered construct with the simd clause is the only OpenMP
1900 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00001901 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00001902 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
1903 // message.
1904 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
1905 ? diag::err_omp_prohibited_region_simd
1906 : diag::warn_omp_nesting_simd);
1907 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00001908 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001909 if (ParentRegion == OMPD_atomic) {
1910 // OpenMP [2.16, Nesting of Regions]
1911 // OpenMP constructs may not be nested inside an atomic region.
1912 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1913 return true;
1914 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001915 if (CurrentRegion == OMPD_section) {
1916 // OpenMP [2.7.2, sections Construct, Restrictions]
1917 // Orphaned section directives are prohibited. That is, the section
1918 // directives must appear within the sections construct and must not be
1919 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001920 if (ParentRegion != OMPD_sections &&
1921 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001922 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
1923 << (ParentRegion != OMPD_unknown)
1924 << getOpenMPDirectiveName(ParentRegion);
1925 return true;
1926 }
1927 return false;
1928 }
Kelvin Li2b51f722016-07-26 04:32:50 +00001929 // Allow some constructs (except teams) to be orphaned (they could be
David Majnemer9d168222016-08-05 17:44:54 +00001930 // used in functions, called from OpenMP regions with the required
Kelvin Li2b51f722016-07-26 04:32:50 +00001931 // preconditions).
1932 if (ParentRegion == OMPD_unknown && !isOpenMPTeamsDirective(CurrentRegion))
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001933 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00001934 if (CurrentRegion == OMPD_cancellation_point ||
1935 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001936 // OpenMP [2.16, Nesting of Regions]
1937 // A cancellation point construct for which construct-type-clause is
1938 // taskgroup must be nested inside a task construct. A cancellation
1939 // point construct for which construct-type-clause is not taskgroup must
1940 // be closely nested inside an OpenMP construct that matches the type
1941 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00001942 // A cancel construct for which construct-type-clause is taskgroup must be
1943 // nested inside a task construct. A cancel construct for which
1944 // construct-type-clause is not taskgroup must be closely nested inside an
1945 // OpenMP construct that matches the type specified in
1946 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001947 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00001948 !((CancelRegion == OMPD_parallel &&
1949 (ParentRegion == OMPD_parallel ||
1950 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00001951 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00001952 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
1953 ParentRegion == OMPD_target_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001954 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
1955 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00001956 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
1957 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001958 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00001959 // OpenMP [2.16, Nesting of Regions]
1960 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001961 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00001962 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00001963 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001964 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
1965 // OpenMP [2.16, Nesting of Regions]
1966 // A critical region may not be nested (closely or otherwise) inside a
1967 // critical region with the same name. Note that this restriction is not
1968 // sufficient to prevent deadlock.
1969 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00001970 bool DeadLock = Stack->hasDirective(
1971 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
1972 const DeclarationNameInfo &DNI,
1973 SourceLocation Loc) -> bool {
1974 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
1975 PreviousCriticalLoc = Loc;
1976 return true;
1977 } else
1978 return false;
1979 },
1980 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001981 if (DeadLock) {
1982 SemaRef.Diag(StartLoc,
1983 diag::err_omp_prohibited_region_critical_same_name)
1984 << CurrentName.getName();
1985 if (PreviousCriticalLoc.isValid())
1986 SemaRef.Diag(PreviousCriticalLoc,
1987 diag::note_omp_previous_critical_region);
1988 return true;
1989 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001990 } else if (CurrentRegion == OMPD_barrier) {
1991 // OpenMP [2.16, Nesting of Regions]
1992 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001993 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00001994 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
1995 isOpenMPTaskingDirective(ParentRegion) ||
1996 ParentRegion == OMPD_master ||
1997 ParentRegion == OMPD_critical ||
1998 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00001999 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00002000 !isOpenMPParallelDirective(CurrentRegion) &&
2001 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002002 // OpenMP [2.16, Nesting of Regions]
2003 // A worksharing region may not be closely nested inside a worksharing,
2004 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002005 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2006 isOpenMPTaskingDirective(ParentRegion) ||
2007 ParentRegion == OMPD_master ||
2008 ParentRegion == OMPD_critical ||
2009 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002010 Recommend = ShouldBeInParallelRegion;
2011 } else if (CurrentRegion == OMPD_ordered) {
2012 // OpenMP [2.16, Nesting of Regions]
2013 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002014 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002015 // An ordered region must be closely nested inside a loop region (or
2016 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002017 // OpenMP [2.8.1,simd Construct, Restrictions]
2018 // An ordered construct with the simd clause is the only OpenMP construct
2019 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002020 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002021 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002022 !(isOpenMPSimdDirective(ParentRegion) ||
2023 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002024 Recommend = ShouldBeInOrderedRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002025 } else if (isOpenMPTeamsDirective(CurrentRegion)) {
2026 // OpenMP [2.16, Nesting of Regions]
2027 // If specified, a teams construct must be contained within a target
2028 // construct.
2029 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00002030 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002031 Recommend = ShouldBeInTargetRegion;
2032 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2033 }
Kelvin Li02532872016-08-05 14:37:37 +00002034 if (!NestingProhibited && ParentRegion == OMPD_teams) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002035 // OpenMP [2.16, Nesting of Regions]
2036 // distribute, parallel, parallel sections, parallel workshare, and the
2037 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2038 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002039 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2040 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002041 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002042 }
David Majnemer9d168222016-08-05 17:44:54 +00002043 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00002044 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002045 // OpenMP 4.5 [2.17 Nesting of Regions]
2046 // The region associated with the distribute construct must be strictly
2047 // nested inside a teams region
Kelvin Li02532872016-08-05 14:37:37 +00002048 NestingProhibited = ParentRegion != OMPD_teams;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002049 Recommend = ShouldBeInTeamsRegion;
2050 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002051 if (!NestingProhibited &&
2052 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2053 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2054 // OpenMP 4.5 [2.17 Nesting of Regions]
2055 // If a target, target update, target data, target enter data, or
2056 // target exit data construct is encountered during execution of a
2057 // target region, the behavior is unspecified.
2058 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002059 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2060 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002061 if (isOpenMPTargetExecutionDirective(K)) {
2062 OffendingRegion = K;
2063 return true;
2064 } else
2065 return false;
2066 },
2067 false /* don't skip top directive */);
2068 CloseNesting = false;
2069 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002070 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00002071 if (OrphanSeen) {
2072 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2073 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2074 } else {
2075 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2076 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2077 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2078 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002079 return true;
2080 }
2081 }
2082 return false;
2083}
2084
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002085static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2086 ArrayRef<OMPClause *> Clauses,
2087 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2088 bool ErrorFound = false;
2089 unsigned NamedModifiersNumber = 0;
2090 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2091 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002092 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002093 for (const auto *C : Clauses) {
2094 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2095 // At most one if clause without a directive-name-modifier can appear on
2096 // the directive.
2097 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2098 if (FoundNameModifiers[CurNM]) {
2099 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2100 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2101 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2102 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002103 } else if (CurNM != OMPD_unknown) {
2104 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002105 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002106 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002107 FoundNameModifiers[CurNM] = IC;
2108 if (CurNM == OMPD_unknown)
2109 continue;
2110 // Check if the specified name modifier is allowed for the current
2111 // directive.
2112 // At most one if clause with the particular directive-name-modifier can
2113 // appear on the directive.
2114 bool MatchFound = false;
2115 for (auto NM : AllowedNameModifiers) {
2116 if (CurNM == NM) {
2117 MatchFound = true;
2118 break;
2119 }
2120 }
2121 if (!MatchFound) {
2122 S.Diag(IC->getNameModifierLoc(),
2123 diag::err_omp_wrong_if_directive_name_modifier)
2124 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2125 ErrorFound = true;
2126 }
2127 }
2128 }
2129 // If any if clause on the directive includes a directive-name-modifier then
2130 // all if clauses on the directive must include a directive-name-modifier.
2131 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2132 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2133 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2134 diag::err_omp_no_more_if_clause);
2135 } else {
2136 std::string Values;
2137 std::string Sep(", ");
2138 unsigned AllowedCnt = 0;
2139 unsigned TotalAllowedNum =
2140 AllowedNameModifiers.size() - NamedModifiersNumber;
2141 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2142 ++Cnt) {
2143 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2144 if (!FoundNameModifiers[NM]) {
2145 Values += "'";
2146 Values += getOpenMPDirectiveName(NM);
2147 Values += "'";
2148 if (AllowedCnt + 2 == TotalAllowedNum)
2149 Values += " or ";
2150 else if (AllowedCnt + 1 != TotalAllowedNum)
2151 Values += Sep;
2152 ++AllowedCnt;
2153 }
2154 }
2155 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2156 diag::err_omp_unnamed_if_clause)
2157 << (TotalAllowedNum > 1) << Values;
2158 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002159 for (auto Loc : NameModifierLoc) {
2160 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2161 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002162 ErrorFound = true;
2163 }
2164 return ErrorFound;
2165}
2166
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002167StmtResult Sema::ActOnOpenMPExecutableDirective(
2168 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2169 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2170 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002171 StmtResult Res = StmtError();
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002172 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
2173 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002174 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002175
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002176 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002177 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002178 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002179 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00002180 if (AStmt) {
2181 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2182
2183 // Check default data sharing attributes for referenced variables.
2184 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
2185 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
2186 if (DSAChecker.isErrorFound())
2187 return StmtError();
2188 // Generate list of implicitly defined firstprivate variables.
2189 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00002190
2191 if (!DSAChecker.getImplicitFirstprivate().empty()) {
2192 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2193 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
2194 SourceLocation(), SourceLocation())) {
2195 ClausesWithImplicit.push_back(Implicit);
2196 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2197 DSAChecker.getImplicitFirstprivate().size();
2198 } else
2199 ErrorFound = true;
2200 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002201 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002202
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002203 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002204 switch (Kind) {
2205 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00002206 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2207 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002208 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002209 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002210 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002211 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2212 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002213 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002214 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002215 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2216 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002217 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00002218 case OMPD_for_simd:
2219 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2220 EndLoc, VarsWithInheritedDSA);
2221 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002222 case OMPD_sections:
2223 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2224 EndLoc);
2225 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002226 case OMPD_section:
2227 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00002228 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002229 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2230 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002231 case OMPD_single:
2232 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2233 EndLoc);
2234 break;
Alexander Musman80c22892014-07-17 08:54:58 +00002235 case OMPD_master:
2236 assert(ClausesWithImplicit.empty() &&
2237 "No clauses are allowed for 'omp master' directive");
2238 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2239 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002240 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00002241 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2242 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002243 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002244 case OMPD_parallel_for:
2245 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2246 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002247 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002248 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00002249 case OMPD_parallel_for_simd:
2250 Res = ActOnOpenMPParallelForSimdDirective(
2251 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002252 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002253 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002254 case OMPD_parallel_sections:
2255 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2256 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002257 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002258 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002259 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002260 Res =
2261 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002262 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002263 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00002264 case OMPD_taskyield:
2265 assert(ClausesWithImplicit.empty() &&
2266 "No clauses are allowed for 'omp taskyield' directive");
2267 assert(AStmt == nullptr &&
2268 "No associated statement allowed for 'omp taskyield' directive");
2269 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2270 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002271 case OMPD_barrier:
2272 assert(ClausesWithImplicit.empty() &&
2273 "No clauses are allowed for 'omp barrier' directive");
2274 assert(AStmt == nullptr &&
2275 "No associated statement allowed for 'omp barrier' directive");
2276 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2277 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00002278 case OMPD_taskwait:
2279 assert(ClausesWithImplicit.empty() &&
2280 "No clauses are allowed for 'omp taskwait' directive");
2281 assert(AStmt == nullptr &&
2282 "No associated statement allowed for 'omp taskwait' directive");
2283 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2284 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002285 case OMPD_taskgroup:
2286 assert(ClausesWithImplicit.empty() &&
2287 "No clauses are allowed for 'omp taskgroup' directive");
2288 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
2289 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00002290 case OMPD_flush:
2291 assert(AStmt == nullptr &&
2292 "No associated statement allowed for 'omp flush' directive");
2293 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2294 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002295 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00002296 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2297 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002298 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00002299 case OMPD_atomic:
2300 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2301 EndLoc);
2302 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002303 case OMPD_teams:
2304 Res =
2305 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2306 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002307 case OMPD_target:
2308 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2309 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002310 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002311 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002312 case OMPD_target_parallel:
2313 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2314 StartLoc, EndLoc);
2315 AllowedNameModifiers.push_back(OMPD_target);
2316 AllowedNameModifiers.push_back(OMPD_parallel);
2317 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002318 case OMPD_target_parallel_for:
2319 Res = ActOnOpenMPTargetParallelForDirective(
2320 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2321 AllowedNameModifiers.push_back(OMPD_target);
2322 AllowedNameModifiers.push_back(OMPD_parallel);
2323 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002324 case OMPD_cancellation_point:
2325 assert(ClausesWithImplicit.empty() &&
2326 "No clauses are allowed for 'omp cancellation point' directive");
2327 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2328 "cancellation point' directive");
2329 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2330 break;
Alexey Bataev80909872015-07-02 11:25:17 +00002331 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00002332 assert(AStmt == nullptr &&
2333 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00002334 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2335 CancelRegion);
2336 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00002337 break;
Michael Wong65f367f2015-07-21 13:44:28 +00002338 case OMPD_target_data:
2339 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2340 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002341 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00002342 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00002343 case OMPD_target_enter_data:
2344 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
2345 EndLoc);
2346 AllowedNameModifiers.push_back(OMPD_target_enter_data);
2347 break;
Samuel Antao72590762016-01-19 20:04:50 +00002348 case OMPD_target_exit_data:
2349 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
2350 EndLoc);
2351 AllowedNameModifiers.push_back(OMPD_target_exit_data);
2352 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00002353 case OMPD_taskloop:
2354 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
2355 EndLoc, VarsWithInheritedDSA);
2356 AllowedNameModifiers.push_back(OMPD_taskloop);
2357 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002358 case OMPD_taskloop_simd:
2359 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2360 EndLoc, VarsWithInheritedDSA);
2361 AllowedNameModifiers.push_back(OMPD_taskloop);
2362 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002363 case OMPD_distribute:
2364 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
2365 EndLoc, VarsWithInheritedDSA);
2366 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00002367 case OMPD_target_update:
2368 assert(!AStmt && "Statement is not allowed for target update");
2369 Res =
2370 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc);
2371 AllowedNameModifiers.push_back(OMPD_target_update);
2372 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00002373 case OMPD_distribute_parallel_for:
2374 Res = ActOnOpenMPDistributeParallelForDirective(
2375 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2376 AllowedNameModifiers.push_back(OMPD_parallel);
2377 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00002378 case OMPD_distribute_parallel_for_simd:
2379 Res = ActOnOpenMPDistributeParallelForSimdDirective(
2380 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2381 AllowedNameModifiers.push_back(OMPD_parallel);
2382 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00002383 case OMPD_distribute_simd:
2384 Res = ActOnOpenMPDistributeSimdDirective(
2385 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2386 break;
Kelvin Lia579b912016-07-14 02:54:56 +00002387 case OMPD_target_parallel_for_simd:
2388 Res = ActOnOpenMPTargetParallelForSimdDirective(
2389 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2390 AllowedNameModifiers.push_back(OMPD_target);
2391 AllowedNameModifiers.push_back(OMPD_parallel);
2392 break;
Kelvin Li986330c2016-07-20 22:57:10 +00002393 case OMPD_target_simd:
2394 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2395 EndLoc, VarsWithInheritedDSA);
2396 AllowedNameModifiers.push_back(OMPD_target);
2397 break;
Kelvin Li02532872016-08-05 14:37:37 +00002398 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00002399 Res = ActOnOpenMPTeamsDistributeDirective(
2400 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00002401 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00002402 case OMPD_teams_distribute_simd:
2403 Res = ActOnOpenMPTeamsDistributeSimdDirective(
2404 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2405 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00002406 case OMPD_teams_distribute_parallel_for_simd:
2407 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
2408 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2409 AllowedNameModifiers.push_back(OMPD_parallel);
2410 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002411 case OMPD_declare_target:
2412 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002413 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002414 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002415 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002416 llvm_unreachable("OpenMP Directive is not allowed");
2417 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002418 llvm_unreachable("Unknown OpenMP directive");
2419 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002420
Alexey Bataev4acb8592014-07-07 13:01:15 +00002421 for (auto P : VarsWithInheritedDSA) {
2422 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2423 << P.first << P.second->getSourceRange();
2424 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002425 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
2426
2427 if (!AllowedNameModifiers.empty())
2428 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
2429 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002430
Alexey Bataeved09d242014-05-28 05:53:51 +00002431 if (ErrorFound)
2432 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002433 return Res;
2434}
2435
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002436Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
2437 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00002438 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00002439 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
2440 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00002441 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00002442 assert(Linears.size() == LinModifiers.size());
2443 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00002444 if (!DG || DG.get().isNull())
2445 return DeclGroupPtrTy();
2446
2447 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00002448 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002449 return DG;
2450 }
2451 auto *ADecl = DG.get().getSingleDecl();
2452 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
2453 ADecl = FTD->getTemplatedDecl();
2454
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002455 auto *FD = dyn_cast<FunctionDecl>(ADecl);
2456 if (!FD) {
2457 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002458 return DeclGroupPtrTy();
2459 }
2460
Alexey Bataev2af33e32016-04-07 12:45:37 +00002461 // OpenMP [2.8.2, declare simd construct, Description]
2462 // The parameter of the simdlen clause must be a constant positive integer
2463 // expression.
2464 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002465 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00002466 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002467 // OpenMP [2.8.2, declare simd construct, Description]
2468 // The special this pointer can be used as if was one of the arguments to the
2469 // function in any of the linear, aligned, or uniform clauses.
2470 // The uniform clause declares one or more arguments to have an invariant
2471 // value for all concurrent invocations of the function in the execution of a
2472 // single SIMD loop.
Alexey Bataevecba70f2016-04-12 11:02:11 +00002473 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
2474 Expr *UniformedLinearThis = nullptr;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002475 for (auto *E : Uniforms) {
2476 E = E->IgnoreParenImpCasts();
2477 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2478 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
2479 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2480 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00002481 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
2482 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002483 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002484 }
2485 if (isa<CXXThisExpr>(E)) {
2486 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002487 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002488 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002489 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2490 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00002491 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00002492 // OpenMP [2.8.2, declare simd construct, Description]
2493 // The aligned clause declares that the object to which each list item points
2494 // is aligned to the number of bytes expressed in the optional parameter of
2495 // the aligned clause.
2496 // The special this pointer can be used as if was one of the arguments to the
2497 // function in any of the linear, aligned, or uniform clauses.
2498 // The type of list items appearing in the aligned clause must be array,
2499 // pointer, reference to array, or reference to pointer.
2500 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
2501 Expr *AlignedThis = nullptr;
2502 for (auto *E : Aligneds) {
2503 E = E->IgnoreParenImpCasts();
2504 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2505 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2506 auto *CanonPVD = PVD->getCanonicalDecl();
2507 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2508 FD->getParamDecl(PVD->getFunctionScopeIndex())
2509 ->getCanonicalDecl() == CanonPVD) {
2510 // OpenMP [2.8.1, simd construct, Restrictions]
2511 // A list-item cannot appear in more than one aligned clause.
2512 if (AlignedArgs.count(CanonPVD) > 0) {
2513 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2514 << 1 << E->getSourceRange();
2515 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
2516 diag::note_omp_explicit_dsa)
2517 << getOpenMPClauseName(OMPC_aligned);
2518 continue;
2519 }
2520 AlignedArgs[CanonPVD] = E;
2521 QualType QTy = PVD->getType()
2522 .getNonReferenceType()
2523 .getUnqualifiedType()
2524 .getCanonicalType();
2525 const Type *Ty = QTy.getTypePtrOrNull();
2526 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
2527 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
2528 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
2529 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
2530 }
2531 continue;
2532 }
2533 }
2534 if (isa<CXXThisExpr>(E)) {
2535 if (AlignedThis) {
2536 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2537 << 2 << E->getSourceRange();
2538 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
2539 << getOpenMPClauseName(OMPC_aligned);
2540 }
2541 AlignedThis = E;
2542 continue;
2543 }
2544 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2545 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2546 }
2547 // The optional parameter of the aligned clause, alignment, must be a constant
2548 // positive integer expression. If no optional parameter is specified,
2549 // implementation-defined default alignments for SIMD instructions on the
2550 // target platforms are assumed.
2551 SmallVector<Expr *, 4> NewAligns;
2552 for (auto *E : Alignments) {
2553 ExprResult Align;
2554 if (E)
2555 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
2556 NewAligns.push_back(Align.get());
2557 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00002558 // OpenMP [2.8.2, declare simd construct, Description]
2559 // The linear clause declares one or more list items to be private to a SIMD
2560 // lane and to have a linear relationship with respect to the iteration space
2561 // of a loop.
2562 // The special this pointer can be used as if was one of the arguments to the
2563 // function in any of the linear, aligned, or uniform clauses.
2564 // When a linear-step expression is specified in a linear clause it must be
2565 // either a constant integer expression or an integer-typed parameter that is
2566 // specified in a uniform clause on the directive.
2567 llvm::DenseMap<Decl *, Expr *> LinearArgs;
2568 const bool IsUniformedThis = UniformedLinearThis != nullptr;
2569 auto MI = LinModifiers.begin();
2570 for (auto *E : Linears) {
2571 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
2572 ++MI;
2573 E = E->IgnoreParenImpCasts();
2574 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2575 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2576 auto *CanonPVD = PVD->getCanonicalDecl();
2577 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2578 FD->getParamDecl(PVD->getFunctionScopeIndex())
2579 ->getCanonicalDecl() == CanonPVD) {
2580 // OpenMP [2.15.3.7, linear Clause, Restrictions]
2581 // A list-item cannot appear in more than one linear clause.
2582 if (LinearArgs.count(CanonPVD) > 0) {
2583 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2584 << getOpenMPClauseName(OMPC_linear)
2585 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
2586 Diag(LinearArgs[CanonPVD]->getExprLoc(),
2587 diag::note_omp_explicit_dsa)
2588 << getOpenMPClauseName(OMPC_linear);
2589 continue;
2590 }
2591 // Each argument can appear in at most one uniform or linear clause.
2592 if (UniformedArgs.count(CanonPVD) > 0) {
2593 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2594 << getOpenMPClauseName(OMPC_linear)
2595 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
2596 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
2597 diag::note_omp_explicit_dsa)
2598 << getOpenMPClauseName(OMPC_uniform);
2599 continue;
2600 }
2601 LinearArgs[CanonPVD] = E;
2602 if (E->isValueDependent() || E->isTypeDependent() ||
2603 E->isInstantiationDependent() ||
2604 E->containsUnexpandedParameterPack())
2605 continue;
2606 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
2607 PVD->getOriginalType());
2608 continue;
2609 }
2610 }
2611 if (isa<CXXThisExpr>(E)) {
2612 if (UniformedLinearThis) {
2613 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2614 << getOpenMPClauseName(OMPC_linear)
2615 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
2616 << E->getSourceRange();
2617 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
2618 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
2619 : OMPC_linear);
2620 continue;
2621 }
2622 UniformedLinearThis = E;
2623 if (E->isValueDependent() || E->isTypeDependent() ||
2624 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
2625 continue;
2626 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
2627 E->getType());
2628 continue;
2629 }
2630 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2631 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2632 }
2633 Expr *Step = nullptr;
2634 Expr *NewStep = nullptr;
2635 SmallVector<Expr *, 4> NewSteps;
2636 for (auto *E : Steps) {
2637 // Skip the same step expression, it was checked already.
2638 if (Step == E || !E) {
2639 NewSteps.push_back(E ? NewStep : nullptr);
2640 continue;
2641 }
2642 Step = E;
2643 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
2644 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2645 auto *CanonPVD = PVD->getCanonicalDecl();
2646 if (UniformedArgs.count(CanonPVD) == 0) {
2647 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
2648 << Step->getSourceRange();
2649 } else if (E->isValueDependent() || E->isTypeDependent() ||
2650 E->isInstantiationDependent() ||
2651 E->containsUnexpandedParameterPack() ||
2652 CanonPVD->getType()->hasIntegerRepresentation())
2653 NewSteps.push_back(Step);
2654 else {
2655 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
2656 << Step->getSourceRange();
2657 }
2658 continue;
2659 }
2660 NewStep = Step;
2661 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
2662 !Step->isInstantiationDependent() &&
2663 !Step->containsUnexpandedParameterPack()) {
2664 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
2665 .get();
2666 if (NewStep)
2667 NewStep = VerifyIntegerConstantExpression(NewStep).get();
2668 }
2669 NewSteps.push_back(NewStep);
2670 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002671 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
2672 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00002673 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00002674 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
2675 const_cast<Expr **>(Linears.data()), Linears.size(),
2676 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
2677 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002678 ADecl->addAttr(NewAttr);
2679 return ConvertDeclToDeclGroup(ADecl);
2680}
2681
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002682StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2683 Stmt *AStmt,
2684 SourceLocation StartLoc,
2685 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002686 if (!AStmt)
2687 return StmtError();
2688
Alexey Bataev9959db52014-05-06 10:08:46 +00002689 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2690 // 1.2.2 OpenMP Language Terminology
2691 // Structured block - An executable statement with a single entry at the
2692 // top and a single exit at the bottom.
2693 // The point of exit cannot be a branch out of the structured block.
2694 // longjmp() and throw() must not violate the entry/exit criteria.
2695 CS->getCapturedDecl()->setNothrow();
2696
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002697 getCurFunction()->setHasBranchProtectedScope();
2698
Alexey Bataev25e5b442015-09-15 12:52:43 +00002699 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
2700 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002701}
2702
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002703namespace {
2704/// \brief Helper class for checking canonical form of the OpenMP loops and
2705/// extracting iteration space of each loop in the loop nest, that will be used
2706/// for IR generation.
2707class OpenMPIterationSpaceChecker {
2708 /// \brief Reference to Sema.
2709 Sema &SemaRef;
2710 /// \brief A location for diagnostics (when there is no some better location).
2711 SourceLocation DefaultLoc;
2712 /// \brief A location for diagnostics (when increment is not compatible).
2713 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002714 /// \brief A source location for referring to loop init later.
2715 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002716 /// \brief A source location for referring to condition later.
2717 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002718 /// \brief A source location for referring to increment later.
2719 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002720 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002721 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002722 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002723 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002724 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002725 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002726 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002727 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002728 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002729 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002730 /// \brief This flag is true when condition is one of:
2731 /// Var < UB
2732 /// Var <= UB
2733 /// UB > Var
2734 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002735 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002736 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002737 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002738 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002739 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002740
2741public:
2742 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002743 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002744 /// \brief Check init-expr for canonical loop form and save loop counter
2745 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00002746 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002747 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2748 /// for less/greater and for strict/non-strict comparison.
2749 bool CheckCond(Expr *S);
2750 /// \brief Check incr-expr for canonical loop form and return true if it
2751 /// does not conform, otherwise save loop step (#Step).
2752 bool CheckInc(Expr *S);
2753 /// \brief Return the loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002754 ValueDecl *GetLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002755 /// \brief Return the reference expression to loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002756 Expr *GetLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002757 /// \brief Source range of the loop init.
2758 SourceRange GetInitSrcRange() const { return InitSrcRange; }
2759 /// \brief Source range of the loop condition.
2760 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2761 /// \brief Source range of the loop increment.
2762 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2763 /// \brief True if the step should be subtracted.
2764 bool ShouldSubtractStep() const { return SubtractStep; }
2765 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00002766 Expr *
2767 BuildNumIterations(Scope *S, const bool LimitedType,
2768 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00002769 /// \brief Build the precondition expression for the loops.
Alexey Bataev5a3af132016-03-29 08:58:54 +00002770 Expr *BuildPreCond(Scope *S, Expr *Cond,
2771 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002772 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002773 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
2774 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00002775 /// \brief Build reference expression to the private counter be used for
2776 /// codegen.
2777 Expr *BuildPrivateCounterVar() const;
David Majnemer9d168222016-08-05 17:44:54 +00002778 /// \brief Build initialization of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002779 Expr *BuildCounterInit() const;
2780 /// \brief Build step of the counter be used for codegen.
2781 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002782 /// \brief Return true if any expression is dependent.
2783 bool Dependent() const;
2784
2785private:
2786 /// \brief Check the right-hand side of an assignment in the increment
2787 /// expression.
2788 bool CheckIncRHS(Expr *RHS);
2789 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002790 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002791 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00002792 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00002793 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002794 /// \brief Helper to set loop increment.
2795 bool SetStep(Expr *NewStep, bool Subtract);
2796};
2797
2798bool OpenMPIterationSpaceChecker::Dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002799 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002800 assert(!LB && !UB && !Step);
2801 return false;
2802 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002803 return LCDecl->getType()->isDependentType() ||
2804 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
2805 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002806}
2807
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002808static Expr *getExprAsWritten(Expr *E) {
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002809 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
2810 E = ExprTemp->getSubExpr();
2811
2812 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2813 E = MTE->GetTemporaryExpr();
2814
2815 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
2816 E = Binder->getSubExpr();
2817
2818 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2819 E = ICE->getSubExprAsWritten();
2820 return E->IgnoreParens();
2821}
2822
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002823bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
2824 Expr *NewLCRefExpr,
2825 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002826 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002827 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002828 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002829 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002830 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002831 LCDecl = getCanonicalDecl(NewLCDecl);
2832 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002833 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
2834 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00002835 if ((Ctor->isCopyOrMoveConstructor() ||
2836 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2837 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002838 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002839 LB = NewLB;
2840 return false;
2841}
2842
2843bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00002844 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002845 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002846 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
2847 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002848 if (!NewUB)
2849 return true;
2850 UB = NewUB;
2851 TestIsLessOp = LessOp;
2852 TestIsStrictOp = StrictOp;
2853 ConditionSrcRange = SR;
2854 ConditionLoc = SL;
2855 return false;
2856}
2857
2858bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2859 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002860 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002861 if (!NewStep)
2862 return true;
2863 if (!NewStep->isValueDependent()) {
2864 // Check that the step is integer expression.
2865 SourceLocation StepLoc = NewStep->getLocStart();
2866 ExprResult Val =
2867 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2868 if (Val.isInvalid())
2869 return true;
2870 NewStep = Val.get();
2871
2872 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2873 // If test-expr is of form var relational-op b and relational-op is < or
2874 // <= then incr-expr must cause var to increase on each iteration of the
2875 // loop. If test-expr is of form var relational-op b and relational-op is
2876 // > or >= then incr-expr must cause var to decrease on each iteration of
2877 // the loop.
2878 // If test-expr is of form b relational-op var and relational-op is < or
2879 // <= then incr-expr must cause var to decrease on each iteration of the
2880 // loop. If test-expr is of form b relational-op var and relational-op is
2881 // > or >= then incr-expr must cause var to increase on each iteration of
2882 // the loop.
2883 llvm::APSInt Result;
2884 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
2885 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
2886 bool IsConstNeg =
2887 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002888 bool IsConstPos =
2889 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002890 bool IsConstZero = IsConstant && !Result.getBoolValue();
2891 if (UB && (IsConstZero ||
2892 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00002893 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002894 SemaRef.Diag(NewStep->getExprLoc(),
2895 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002896 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002897 SemaRef.Diag(ConditionLoc,
2898 diag::note_omp_loop_cond_requres_compatible_incr)
2899 << TestIsLessOp << ConditionSrcRange;
2900 return true;
2901 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002902 if (TestIsLessOp == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00002903 NewStep =
2904 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
2905 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00002906 Subtract = !Subtract;
2907 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002908 }
2909
2910 Step = NewStep;
2911 SubtractStep = Subtract;
2912 return false;
2913}
2914
Alexey Bataev9c821032015-04-30 04:23:23 +00002915bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002916 // Check init-expr for canonical loop form and save loop counter
2917 // variable - #Var and its initialization value - #LB.
2918 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
2919 // var = lb
2920 // integer-type var = lb
2921 // random-access-iterator-type var = lb
2922 // pointer-type var = lb
2923 //
2924 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00002925 if (EmitDiags) {
2926 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
2927 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002928 return true;
2929 }
Tim Shen4a05bb82016-06-21 20:29:17 +00002930 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
2931 if (!ExprTemp->cleanupsHaveSideEffects())
2932 S = ExprTemp->getSubExpr();
2933
Alexander Musmana5f070a2014-10-01 06:03:56 +00002934 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002935 if (Expr *E = dyn_cast<Expr>(S))
2936 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00002937 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002938 if (BO->getOpcode() == BO_Assign) {
2939 auto *LHS = BO->getLHS()->IgnoreParens();
2940 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
2941 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
2942 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
2943 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
2944 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
2945 }
2946 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
2947 if (ME->isArrow() &&
2948 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
2949 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
2950 }
2951 }
David Majnemer9d168222016-08-05 17:44:54 +00002952 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002953 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00002954 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00002955 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002956 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00002957 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002958 SemaRef.Diag(S->getLocStart(),
2959 diag::ext_omp_loop_not_canonical_init)
2960 << S->getSourceRange();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002961 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002962 }
2963 }
2964 }
David Majnemer9d168222016-08-05 17:44:54 +00002965 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002966 if (CE->getOperator() == OO_Equal) {
2967 auto *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00002968 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002969 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
2970 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
2971 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
2972 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
2973 }
2974 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
2975 if (ME->isArrow() &&
2976 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
2977 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
2978 }
2979 }
2980 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002981
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002982 if (Dependent() || SemaRef.CurContext->isDependentContext())
2983 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00002984 if (EmitDiags) {
2985 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
2986 << S->getSourceRange();
2987 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002988 return true;
2989}
2990
Alexey Bataev23b69422014-06-18 07:08:49 +00002991/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002992/// variable (which may be the loop variable) if possible.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002993static const ValueDecl *GetInitLCDecl(Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002994 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00002995 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002996 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002997 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
2998 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00002999 if ((Ctor->isCopyOrMoveConstructor() ||
3000 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3001 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003002 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003003 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
3004 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
3005 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
3006 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3007 return getCanonicalDecl(ME->getMemberDecl());
3008 return getCanonicalDecl(VD);
3009 }
3010 }
3011 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3012 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3013 return getCanonicalDecl(ME->getMemberDecl());
3014 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003015}
3016
3017bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3018 // Check test-expr for canonical form, save upper-bound UB, flags for
3019 // less/greater and for strict/non-strict comparison.
3020 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3021 // var relational-op b
3022 // b relational-op var
3023 //
3024 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003025 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003026 return true;
3027 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003028 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003029 SourceLocation CondLoc = S->getLocStart();
David Majnemer9d168222016-08-05 17:44:54 +00003030 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003031 if (BO->isRelationalOp()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003032 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003033 return SetUB(BO->getRHS(),
3034 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3035 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3036 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003037 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003038 return SetUB(BO->getLHS(),
3039 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3040 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3041 BO->getSourceRange(), BO->getOperatorLoc());
3042 }
David Majnemer9d168222016-08-05 17:44:54 +00003043 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003044 if (CE->getNumArgs() == 2) {
3045 auto Op = CE->getOperator();
3046 switch (Op) {
3047 case OO_Greater:
3048 case OO_GreaterEqual:
3049 case OO_Less:
3050 case OO_LessEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003051 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003052 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3053 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3054 CE->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003055 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003056 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3057 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3058 CE->getOperatorLoc());
3059 break;
3060 default:
3061 break;
3062 }
3063 }
3064 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003065 if (Dependent() || SemaRef.CurContext->isDependentContext())
3066 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003067 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003068 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003069 return true;
3070}
3071
3072bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3073 // RHS of canonical loop form increment can be:
3074 // var + incr
3075 // incr + var
3076 // var - incr
3077 //
3078 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00003079 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003080 if (BO->isAdditiveOp()) {
3081 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003082 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003083 return SetStep(BO->getRHS(), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003084 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003085 return SetStep(BO->getLHS(), false);
3086 }
David Majnemer9d168222016-08-05 17:44:54 +00003087 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003088 bool IsAdd = CE->getOperator() == OO_Plus;
3089 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003090 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003091 return SetStep(CE->getArg(1), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003092 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003093 return SetStep(CE->getArg(0), false);
3094 }
3095 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003096 if (Dependent() || SemaRef.CurContext->isDependentContext())
3097 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003098 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003099 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003100 return true;
3101}
3102
3103bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3104 // Check incr-expr for canonical loop form and return true if it
3105 // does not conform.
3106 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3107 // ++var
3108 // var++
3109 // --var
3110 // var--
3111 // var += incr
3112 // var -= incr
3113 // var = var + incr
3114 // var = incr + var
3115 // var = var - incr
3116 //
3117 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003118 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003119 return true;
3120 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003121 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3122 if (!ExprTemp->cleanupsHaveSideEffects())
3123 S = ExprTemp->getSubExpr();
3124
Alexander Musmana5f070a2014-10-01 06:03:56 +00003125 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003126 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003127 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003128 if (UO->isIncrementDecrementOp() &&
3129 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003130 return SetStep(SemaRef
3131 .ActOnIntegerConstant(UO->getLocStart(),
3132 (UO->isDecrementOp() ? -1 : 1))
3133 .get(),
3134 false);
3135 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003136 switch (BO->getOpcode()) {
3137 case BO_AddAssign:
3138 case BO_SubAssign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003139 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003140 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3141 break;
3142 case BO_Assign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003143 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003144 return CheckIncRHS(BO->getRHS());
3145 break;
3146 default:
3147 break;
3148 }
David Majnemer9d168222016-08-05 17:44:54 +00003149 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003150 switch (CE->getOperator()) {
3151 case OO_PlusPlus:
3152 case OO_MinusMinus:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003153 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003154 return SetStep(SemaRef
3155 .ActOnIntegerConstant(
3156 CE->getLocStart(),
3157 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3158 .get(),
3159 false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003160 break;
3161 case OO_PlusEqual:
3162 case OO_MinusEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003163 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003164 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3165 break;
3166 case OO_Equal:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003167 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003168 return CheckIncRHS(CE->getArg(1));
3169 break;
3170 default:
3171 break;
3172 }
3173 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003174 if (Dependent() || SemaRef.CurContext->isDependentContext())
3175 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003176 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003177 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003178 return true;
3179}
Alexander Musmana5f070a2014-10-01 06:03:56 +00003180
Alexey Bataev5a3af132016-03-29 08:58:54 +00003181static ExprResult
3182tryBuildCapture(Sema &SemaRef, Expr *Capture,
3183 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00003184 if (SemaRef.CurContext->isDependentContext())
3185 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003186 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3187 return SemaRef.PerformImplicitConversion(
3188 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3189 /*AllowExplicit=*/true);
3190 auto I = Captures.find(Capture);
3191 if (I != Captures.end())
3192 return buildCapture(SemaRef, Capture, I->second);
3193 DeclRefExpr *Ref = nullptr;
3194 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3195 Captures[Capture] = Ref;
3196 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003197}
3198
Alexander Musmana5f070a2014-10-01 06:03:56 +00003199/// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003200Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3201 Scope *S, const bool LimitedType,
3202 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003203 ExprResult Diff;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003204 auto VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003205 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003206 SemaRef.getLangOpts().CPlusPlus) {
3207 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003208 auto *UBExpr = TestIsLessOp ? UB : LB;
3209 auto *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00003210 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3211 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003212 if (!Upper || !Lower)
3213 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003214
3215 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3216
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003217 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003218 // BuildBinOp already emitted error, this one is to point user to upper
3219 // and lower bound, and to tell what is passed to 'operator-'.
3220 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3221 << Upper->getSourceRange() << Lower->getSourceRange();
3222 return nullptr;
3223 }
3224 }
3225
3226 if (!Diff.isUsable())
3227 return nullptr;
3228
3229 // Upper - Lower [- 1]
3230 if (TestIsStrictOp)
3231 Diff = SemaRef.BuildBinOp(
3232 S, DefaultLoc, BO_Sub, Diff.get(),
3233 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3234 if (!Diff.isUsable())
3235 return nullptr;
3236
3237 // Upper - Lower [- 1] + Step
Alexey Bataev5a3af132016-03-29 08:58:54 +00003238 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3239 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003240 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003241 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003242 if (!Diff.isUsable())
3243 return nullptr;
3244
3245 // Parentheses (for dumping/debugging purposes only).
3246 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3247 if (!Diff.isUsable())
3248 return nullptr;
3249
3250 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003251 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003252 if (!Diff.isUsable())
3253 return nullptr;
3254
Alexander Musman174b3ca2014-10-06 11:16:29 +00003255 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003256 QualType Type = Diff.get()->getType();
3257 auto &C = SemaRef.Context;
3258 bool UseVarType = VarType->hasIntegerRepresentation() &&
3259 C.getTypeSize(Type) > C.getTypeSize(VarType);
3260 if (!Type->isIntegerType() || UseVarType) {
3261 unsigned NewSize =
3262 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3263 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3264 : Type->hasSignedIntegerRepresentation();
3265 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00003266 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3267 Diff = SemaRef.PerformImplicitConversion(
3268 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3269 if (!Diff.isUsable())
3270 return nullptr;
3271 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003272 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003273 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00003274 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3275 if (NewSize != C.getTypeSize(Type)) {
3276 if (NewSize < C.getTypeSize(Type)) {
3277 assert(NewSize == 64 && "incorrect loop var size");
3278 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3279 << InitSrcRange << ConditionSrcRange;
3280 }
3281 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003282 NewSize, Type->hasSignedIntegerRepresentation() ||
3283 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00003284 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3285 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3286 Sema::AA_Converting, true);
3287 if (!Diff.isUsable())
3288 return nullptr;
3289 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003290 }
3291 }
3292
Alexander Musmana5f070a2014-10-01 06:03:56 +00003293 return Diff.get();
3294}
3295
Alexey Bataev5a3af132016-03-29 08:58:54 +00003296Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3297 Scope *S, Expr *Cond,
3298 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003299 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3300 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3301 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003302
Alexey Bataev5a3af132016-03-29 08:58:54 +00003303 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3304 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3305 if (!NewLB.isUsable() || !NewUB.isUsable())
3306 return nullptr;
3307
Alexey Bataev62dbb972015-04-22 11:59:37 +00003308 auto CondExpr = SemaRef.BuildBinOp(
3309 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3310 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003311 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003312 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003313 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
3314 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00003315 CondExpr = SemaRef.PerformImplicitConversion(
3316 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3317 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003318 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00003319 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3320 // Otherwise use original loop conditon and evaluate it in runtime.
3321 return CondExpr.isUsable() ? CondExpr.get() : Cond;
3322}
3323
Alexander Musmana5f070a2014-10-01 06:03:56 +00003324/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003325DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003326 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003327 auto *VD = dyn_cast<VarDecl>(LCDecl);
3328 if (!VD) {
3329 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
3330 auto *Ref = buildDeclRefExpr(
3331 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003332 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
3333 // If the loop control decl is explicitly marked as private, do not mark it
3334 // as captured again.
3335 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
3336 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003337 return Ref;
3338 }
3339 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00003340 DefaultLoc);
3341}
3342
3343Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003344 if (LCDecl && !LCDecl->isInvalidDecl()) {
3345 auto Type = LCDecl->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00003346 auto *PrivateVar =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003347 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
3348 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00003349 if (PrivateVar->isInvalidDecl())
3350 return nullptr;
3351 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3352 }
3353 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003354}
3355
David Majnemer9d168222016-08-05 17:44:54 +00003356/// \brief Build instillation of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003357Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3358
3359/// \brief Build step of the counter be used for codegen.
3360Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3361
3362/// \brief Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003363struct LoopIterationSpace final {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003364 /// \brief Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003365 Expr *PreCond = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003366 /// \brief This expression calculates the number of iterations in the loop.
3367 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003368 Expr *NumIterations = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003369 /// \brief The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003370 Expr *CounterVar = nullptr;
Alexey Bataeva8899172015-08-06 12:30:57 +00003371 /// \brief Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003372 Expr *PrivateCounterVar = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003373 /// \brief This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00003374 Expr *CounterInit = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003375 /// \brief This is step for the #CounterVar used to generate its update:
3376 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00003377 Expr *CounterStep = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003378 /// \brief Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00003379 bool Subtract = false;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003380 /// \brief Source range of the loop init.
3381 SourceRange InitSrcRange;
3382 /// \brief Source range of the loop condition.
3383 SourceRange CondSrcRange;
3384 /// \brief Source range of the loop increment.
3385 SourceRange IncSrcRange;
3386};
3387
Alexey Bataev23b69422014-06-18 07:08:49 +00003388} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003389
Alexey Bataev9c821032015-04-30 04:23:23 +00003390void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
3391 assert(getLangOpts().OpenMP && "OpenMP is not active.");
3392 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003393 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
3394 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00003395 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
3396 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003397 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
3398 if (auto *D = ISC.GetLoopDecl()) {
3399 auto *VD = dyn_cast<VarDecl>(D);
3400 if (!VD) {
3401 if (auto *Private = IsOpenMPCapturedDecl(D))
3402 VD = Private;
3403 else {
3404 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
3405 /*WithInit=*/false);
3406 VD = cast<VarDecl>(Ref->getDecl());
3407 }
3408 }
3409 DSAStack->addLoopControlVariable(D, VD);
3410 }
3411 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003412 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00003413 }
3414}
3415
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003416/// \brief Called on a for stmt to check and extract its iteration space
3417/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00003418static bool CheckOpenMPIterationSpace(
3419 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3420 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003421 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003422 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003423 LoopIterationSpace &ResultIterSpace,
3424 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003425 // OpenMP [2.6, Canonical Loop Form]
3426 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00003427 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003428 if (!For) {
3429 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003430 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
3431 << getOpenMPDirectiveName(DKind) << NestedLoopCount
3432 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
3433 if (NestedLoopCount > 1) {
3434 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
3435 SemaRef.Diag(DSA.getConstructLoc(),
3436 diag::note_omp_collapse_ordered_expr)
3437 << 2 << CollapseLoopCountExpr->getSourceRange()
3438 << OrderedLoopCountExpr->getSourceRange();
3439 else if (CollapseLoopCountExpr)
3440 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3441 diag::note_omp_collapse_ordered_expr)
3442 << 0 << CollapseLoopCountExpr->getSourceRange();
3443 else
3444 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3445 diag::note_omp_collapse_ordered_expr)
3446 << 1 << OrderedLoopCountExpr->getSourceRange();
3447 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003448 return true;
3449 }
3450 assert(For->getBody());
3451
3452 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3453
3454 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003455 auto Init = For->getInit();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003456 if (ISC.CheckInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003457 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003458
3459 bool HasErrors = false;
3460
3461 // Check loop variable's type.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003462 if (auto *LCDecl = ISC.GetLoopDecl()) {
3463 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003464
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003465 // OpenMP [2.6, Canonical Loop Form]
3466 // Var is one of the following:
3467 // A variable of signed or unsigned integer type.
3468 // For C++, a variable of a random access iterator type.
3469 // For C, a variable of a pointer type.
3470 auto VarType = LCDecl->getType().getNonReferenceType();
3471 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
3472 !VarType->isPointerType() &&
3473 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
3474 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
3475 << SemaRef.getLangOpts().CPlusPlus;
3476 HasErrors = true;
3477 }
3478
3479 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
3480 // a Construct
3481 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3482 // parallel for construct is (are) private.
3483 // The loop iteration variable in the associated for-loop of a simd
3484 // construct with just one associated for-loop is linear with a
3485 // constant-linear-step that is the increment of the associated for-loop.
3486 // Exclude loop var from the list of variables with implicitly defined data
3487 // sharing attributes.
3488 VarsWithImplicitDSA.erase(LCDecl);
3489
3490 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
3491 // in a Construct, C/C++].
3492 // The loop iteration variable in the associated for-loop of a simd
3493 // construct with just one associated for-loop may be listed in a linear
3494 // clause with a constant-linear-step that is the increment of the
3495 // associated for-loop.
3496 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3497 // parallel for construct may be listed in a private or lastprivate clause.
3498 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
3499 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
3500 // declared in the loop and it is predetermined as a private.
3501 auto PredeterminedCKind =
3502 isOpenMPSimdDirective(DKind)
3503 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
3504 : OMPC_private;
3505 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3506 DVar.CKind != PredeterminedCKind) ||
3507 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
3508 isOpenMPDistributeDirective(DKind)) &&
3509 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3510 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
3511 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
3512 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
3513 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
3514 << getOpenMPClauseName(PredeterminedCKind);
3515 if (DVar.RefExpr == nullptr)
3516 DVar.CKind = PredeterminedCKind;
3517 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
3518 HasErrors = true;
3519 } else if (LoopDeclRefExpr != nullptr) {
3520 // Make the loop iteration variable private (for worksharing constructs),
3521 // linear (for simd directives with the only one associated loop) or
3522 // lastprivate (for simd directives with several collapsed or ordered
3523 // loops).
3524 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003525 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
3526 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003527 /*FromParent=*/false);
3528 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
3529 }
3530
3531 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
3532
3533 // Check test-expr.
3534 HasErrors |= ISC.CheckCond(For->getCond());
3535
3536 // Check incr-expr.
3537 HasErrors |= ISC.CheckInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003538 }
3539
Alexander Musmana5f070a2014-10-01 06:03:56 +00003540 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003541 return HasErrors;
3542
Alexander Musmana5f070a2014-10-01 06:03:56 +00003543 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003544 ResultIterSpace.PreCond =
3545 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexander Musman174b3ca2014-10-06 11:16:29 +00003546 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00003547 DSA.getCurScope(),
3548 (isOpenMPWorksharingDirective(DKind) ||
3549 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
3550 Captures);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003551 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
Alexey Bataeva8899172015-08-06 12:30:57 +00003552 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003553 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
3554 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
3555 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
3556 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
3557 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
3558 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
3559
Alexey Bataev62dbb972015-04-22 11:59:37 +00003560 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
3561 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003562 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00003563 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003564 ResultIterSpace.CounterInit == nullptr ||
3565 ResultIterSpace.CounterStep == nullptr);
3566
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003567 return HasErrors;
3568}
3569
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003570/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003571static ExprResult
3572BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
3573 ExprResult Start,
3574 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003575 // Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003576 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
3577 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003578 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00003579 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00003580 VarRef.get()->getType())) {
3581 NewStart = SemaRef.PerformImplicitConversion(
3582 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
3583 /*AllowExplicit=*/true);
3584 if (!NewStart.isUsable())
3585 return ExprError();
3586 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003587
3588 auto Init =
3589 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3590 return Init;
3591}
3592
Alexander Musmana5f070a2014-10-01 06:03:56 +00003593/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003594static ExprResult
3595BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
3596 ExprResult VarRef, ExprResult Start, ExprResult Iter,
3597 ExprResult Step, bool Subtract,
3598 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003599 // Add parentheses (for debugging purposes only).
3600 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
3601 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
3602 !Step.isUsable())
3603 return ExprError();
3604
Alexey Bataev5a3af132016-03-29 08:58:54 +00003605 ExprResult NewStep = Step;
3606 if (Captures)
3607 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003608 if (NewStep.isInvalid())
3609 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003610 ExprResult Update =
3611 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003612 if (!Update.isUsable())
3613 return ExprError();
3614
Alexey Bataevc0214e02016-02-16 12:13:49 +00003615 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
3616 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003617 ExprResult NewStart = Start;
3618 if (Captures)
3619 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003620 if (NewStart.isInvalid())
3621 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003622
Alexey Bataevc0214e02016-02-16 12:13:49 +00003623 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
3624 ExprResult SavedUpdate = Update;
3625 ExprResult UpdateVal;
3626 if (VarRef.get()->getType()->isOverloadableType() ||
3627 NewStart.get()->getType()->isOverloadableType() ||
3628 Update.get()->getType()->isOverloadableType()) {
3629 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3630 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3631 Update =
3632 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3633 if (Update.isUsable()) {
3634 UpdateVal =
3635 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
3636 VarRef.get(), SavedUpdate.get());
3637 if (UpdateVal.isUsable()) {
3638 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
3639 UpdateVal.get());
3640 }
3641 }
3642 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3643 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003644
Alexey Bataevc0214e02016-02-16 12:13:49 +00003645 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
3646 if (!Update.isUsable() || !UpdateVal.isUsable()) {
3647 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
3648 NewStart.get(), SavedUpdate.get());
3649 if (!Update.isUsable())
3650 return ExprError();
3651
Alexey Bataev11481f52016-02-17 10:29:05 +00003652 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
3653 VarRef.get()->getType())) {
3654 Update = SemaRef.PerformImplicitConversion(
3655 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
3656 if (!Update.isUsable())
3657 return ExprError();
3658 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00003659
3660 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
3661 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003662 return Update;
3663}
3664
3665/// \brief Convert integer expression \a E to make it have at least \a Bits
3666/// bits.
David Majnemer9d168222016-08-05 17:44:54 +00003667static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003668 if (E == nullptr)
3669 return ExprError();
3670 auto &C = SemaRef.Context;
3671 QualType OldType = E->getType();
3672 unsigned HasBits = C.getTypeSize(OldType);
3673 if (HasBits >= Bits)
3674 return ExprResult(E);
3675 // OK to convert to signed, because new type has more bits than old.
3676 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
3677 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
3678 true);
3679}
3680
3681/// \brief Check if the given expression \a E is a constant integer that fits
3682/// into \a Bits bits.
3683static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
3684 if (E == nullptr)
3685 return false;
3686 llvm::APSInt Result;
3687 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
3688 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
3689 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003690}
3691
Alexey Bataev5a3af132016-03-29 08:58:54 +00003692/// Build preinits statement for the given declarations.
3693static Stmt *buildPreInits(ASTContext &Context,
3694 SmallVectorImpl<Decl *> &PreInits) {
3695 if (!PreInits.empty()) {
3696 return new (Context) DeclStmt(
3697 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
3698 SourceLocation(), SourceLocation());
3699 }
3700 return nullptr;
3701}
3702
3703/// Build preinits statement for the given declarations.
3704static Stmt *buildPreInits(ASTContext &Context,
3705 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3706 if (!Captures.empty()) {
3707 SmallVector<Decl *, 16> PreInits;
3708 for (auto &Pair : Captures)
3709 PreInits.push_back(Pair.second->getDecl());
3710 return buildPreInits(Context, PreInits);
3711 }
3712 return nullptr;
3713}
3714
3715/// Build postupdate expression for the given list of postupdates expressions.
3716static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
3717 Expr *PostUpdate = nullptr;
3718 if (!PostUpdates.empty()) {
3719 for (auto *E : PostUpdates) {
3720 Expr *ConvE = S.BuildCStyleCastExpr(
3721 E->getExprLoc(),
3722 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
3723 E->getExprLoc(), E)
3724 .get();
3725 PostUpdate = PostUpdate
3726 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
3727 PostUpdate, ConvE)
3728 .get()
3729 : ConvE;
3730 }
3731 }
3732 return PostUpdate;
3733}
3734
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003735/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00003736/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
3737/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003738static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00003739CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
3740 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
3741 DSAStackTy &DSA,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003742 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00003743 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003744 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003745 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003746 // Found 'collapse' clause - calculate collapse number.
3747 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003748 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003749 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00003750 }
3751 if (OrderedLoopCountExpr) {
3752 // Found 'ordered' clause - calculate collapse number.
3753 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003754 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
3755 if (Result.getLimitedValue() < NestedLoopCount) {
3756 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3757 diag::err_omp_wrong_ordered_loop_count)
3758 << OrderedLoopCountExpr->getSourceRange();
3759 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3760 diag::note_collapse_loop_count)
3761 << CollapseLoopCountExpr->getSourceRange();
3762 }
3763 NestedLoopCount = Result.getLimitedValue();
3764 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003765 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003766 // This is helper routine for loop directives (e.g., 'for', 'simd',
3767 // 'for simd', etc.).
Alexey Bataev5a3af132016-03-29 08:58:54 +00003768 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003769 SmallVector<LoopIterationSpace, 4> IterSpaces;
3770 IterSpaces.resize(NestedLoopCount);
3771 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003772 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003773 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003774 NestedLoopCount, CollapseLoopCountExpr,
3775 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003776 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00003777 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003778 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003779 // OpenMP [2.8.1, simd construct, Restrictions]
3780 // All loops associated with the construct must be perfectly nested; that
3781 // is, there must be no intervening code nor any OpenMP directive between
3782 // any two loops.
3783 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003784 }
3785
Alexander Musmana5f070a2014-10-01 06:03:56 +00003786 Built.clear(/* size */ NestedLoopCount);
3787
3788 if (SemaRef.CurContext->isDependentContext())
3789 return NestedLoopCount;
3790
3791 // An example of what is generated for the following code:
3792 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00003793 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00003794 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003795 // for (k = 0; k < NK; ++k)
3796 // for (j = J0; j < NJ; j+=2) {
3797 // <loop body>
3798 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003799 //
3800 // We generate the code below.
3801 // Note: the loop body may be outlined in CodeGen.
3802 // Note: some counters may be C++ classes, operator- is used to find number of
3803 // iterations and operator+= to calculate counter value.
3804 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
3805 // or i64 is currently supported).
3806 //
3807 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
3808 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
3809 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
3810 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
3811 // // similar updates for vars in clauses (e.g. 'linear')
3812 // <loop body (using local i and j)>
3813 // }
3814 // i = NI; // assign final values of counters
3815 // j = NJ;
3816 //
3817
3818 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
3819 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00003820 // Precondition tests if there is at least one iteration (all conditions are
3821 // true).
3822 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003823 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003824 ExprResult LastIteration32 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00003825 32 /* Bits */, SemaRef
3826 .PerformImplicitConversion(
3827 N0->IgnoreImpCasts(), N0->getType(),
3828 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003829 .get(),
3830 SemaRef);
3831 ExprResult LastIteration64 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00003832 64 /* Bits */, SemaRef
3833 .PerformImplicitConversion(
3834 N0->IgnoreImpCasts(), N0->getType(),
3835 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003836 .get(),
3837 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003838
3839 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
3840 return NestedLoopCount;
3841
3842 auto &C = SemaRef.Context;
3843 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
3844
3845 Scope *CurScope = DSA.getCurScope();
3846 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003847 if (PreCond.isUsable()) {
3848 PreCond = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_LAnd,
3849 PreCond.get(), IterSpaces[Cnt].PreCond);
3850 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003851 auto N = IterSpaces[Cnt].NumIterations;
3852 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
3853 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003854 LastIteration32 = SemaRef.BuildBinOp(
3855 CurScope, SourceLocation(), BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00003856 SemaRef
3857 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3858 Sema::AA_Converting,
3859 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003860 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003861 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003862 LastIteration64 = SemaRef.BuildBinOp(
3863 CurScope, SourceLocation(), BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00003864 SemaRef
3865 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3866 Sema::AA_Converting,
3867 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003868 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003869 }
3870
3871 // Choose either the 32-bit or 64-bit version.
3872 ExprResult LastIteration = LastIteration64;
3873 if (LastIteration32.isUsable() &&
3874 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
3875 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
3876 FitsInto(
3877 32 /* Bits */,
3878 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
3879 LastIteration64.get(), SemaRef)))
3880 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00003881 QualType VType = LastIteration.get()->getType();
3882 QualType RealVType = VType;
3883 QualType StrideVType = VType;
3884 if (isOpenMPTaskLoopDirective(DKind)) {
3885 VType =
3886 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3887 StrideVType =
3888 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3889 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003890
3891 if (!LastIteration.isUsable())
3892 return 0;
3893
3894 // Save the number of iterations.
3895 ExprResult NumIterations = LastIteration;
3896 {
3897 LastIteration = SemaRef.BuildBinOp(
3898 CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
3899 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3900 if (!LastIteration.isUsable())
3901 return 0;
3902 }
3903
3904 // Calculate the last iteration number beforehand instead of doing this on
3905 // each iteration. Do not do this if the number of iterations may be kfold-ed.
3906 llvm::APSInt Result;
3907 bool IsConstant =
3908 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
3909 ExprResult CalcLastIteration;
3910 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003911 ExprResult SaveRef =
3912 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003913 LastIteration = SaveRef;
3914
3915 // Prepare SaveRef + 1.
3916 NumIterations = SemaRef.BuildBinOp(
Alexey Bataev5a3af132016-03-29 08:58:54 +00003917 CurScope, SourceLocation(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00003918 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3919 if (!NumIterations.isUsable())
3920 return 0;
3921 }
3922
3923 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
3924
David Majnemer9d168222016-08-05 17:44:54 +00003925 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolli9925f152016-06-27 14:55:37 +00003926 ExprResult LB, UB, IL, ST, EUB, PrevLB, PrevUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003927 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
3928 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003929 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00003930 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
3931 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003932 SemaRef.AddInitializerToDecl(
3933 LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3934 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3935
3936 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00003937 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
3938 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003939 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
3940 /*DirectInit*/ false,
3941 /*TypeMayContainAuto*/ false);
3942
3943 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
3944 // This will be used to implement clause 'lastprivate'.
3945 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00003946 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
3947 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003948 SemaRef.AddInitializerToDecl(
3949 ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3950 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3951
3952 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00003953 VarDecl *STDecl =
3954 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
3955 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003956 SemaRef.AddInitializerToDecl(
3957 STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
3958 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3959
3960 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00003961 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00003962 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
3963 UB.get(), LastIteration.get());
3964 ExprResult CondOp = SemaRef.ActOnConditionalOp(
3965 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
3966 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
3967 CondOp.get());
3968 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
Carlo Bertolli9925f152016-06-27 14:55:37 +00003969
3970 // If we have a combined directive that combines 'distribute', 'for' or
3971 // 'simd' we need to be able to access the bounds of the schedule of the
3972 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
3973 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
3974 if (isOpenMPLoopBoundSharingDirective(DKind)) {
3975 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
3976
3977 // We expect to have at least 2 more parameters than the 'parallel'
3978 // directive does - the lower and upper bounds of the previous schedule.
3979 assert(CD->getNumParams() >= 4 &&
3980 "Unexpected number of parameters in loop combined directive");
3981
3982 // Set the proper type for the bounds given what we learned from the
3983 // enclosed loops.
3984 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
3985 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
3986
3987 // Previous lower and upper bounds are obtained from the region
3988 // parameters.
3989 PrevLB =
3990 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
3991 PrevUB =
3992 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
3993 }
Alexander Musmanc6388682014-12-15 07:07:06 +00003994 }
3995
3996 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003997 ExprResult IV;
3998 ExprResult Init;
3999 {
Alexey Bataev7292c292016-04-25 12:22:29 +00004000 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4001 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00004002 Expr *RHS =
4003 (isOpenMPWorksharingDirective(DKind) ||
4004 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4005 ? LB.get()
4006 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004007 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4008 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004009 }
4010
Alexander Musmanc6388682014-12-15 07:07:06 +00004011 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004012 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00004013 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004014 (isOpenMPWorksharingDirective(DKind) ||
4015 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004016 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4017 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4018 NumIterations.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004019
4020 // Loop increment (IV = IV + 1)
4021 SourceLocation IncLoc;
4022 ExprResult Inc =
4023 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4024 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4025 if (!Inc.isUsable())
4026 return 0;
4027 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00004028 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4029 if (!Inc.isUsable())
4030 return 0;
4031
4032 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4033 // Used for directives with static scheduling.
4034 ExprResult NextLB, NextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004035 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4036 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004037 // LB + ST
4038 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4039 if (!NextLB.isUsable())
4040 return 0;
4041 // LB = LB + ST
4042 NextLB =
4043 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4044 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4045 if (!NextLB.isUsable())
4046 return 0;
4047 // UB + ST
4048 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4049 if (!NextUB.isUsable())
4050 return 0;
4051 // UB = UB + ST
4052 NextUB =
4053 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4054 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4055 if (!NextUB.isUsable())
4056 return 0;
4057 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004058
4059 // Build updates and final values of the loop counters.
4060 bool HasErrors = false;
4061 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004062 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004063 Built.Updates.resize(NestedLoopCount);
4064 Built.Finals.resize(NestedLoopCount);
Alexey Bataev8b427062016-05-25 12:36:08 +00004065 SmallVector<Expr *, 4> LoopMultipliers;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004066 {
4067 ExprResult Div;
4068 // Go from inner nested loop to outer.
4069 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4070 LoopIterationSpace &IS = IterSpaces[Cnt];
4071 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4072 // Build: Iter = (IV / Div) % IS.NumIters
4073 // where Div is product of previous iterations' IS.NumIters.
4074 ExprResult Iter;
4075 if (Div.isUsable()) {
4076 Iter =
4077 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4078 } else {
4079 Iter = IV;
4080 assert((Cnt == (int)NestedLoopCount - 1) &&
4081 "unusable div expected on first iteration only");
4082 }
4083
4084 if (Cnt != 0 && Iter.isUsable())
4085 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4086 IS.NumIterations);
4087 if (!Iter.isUsable()) {
4088 HasErrors = true;
4089 break;
4090 }
4091
Alexey Bataev39f915b82015-05-08 10:41:21 +00004092 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004093 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4094 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4095 IS.CounterVar->getExprLoc(),
4096 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004097 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004098 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004099 if (!Init.isUsable()) {
4100 HasErrors = true;
4101 break;
4102 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00004103 ExprResult Update = BuildCounterUpdate(
4104 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4105 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004106 if (!Update.isUsable()) {
4107 HasErrors = true;
4108 break;
4109 }
4110
4111 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4112 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00004113 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004114 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004115 if (!Final.isUsable()) {
4116 HasErrors = true;
4117 break;
4118 }
4119
4120 // Build Div for the next iteration: Div <- Div * IS.NumIters
4121 if (Cnt != 0) {
4122 if (Div.isUnset())
4123 Div = IS.NumIterations;
4124 else
4125 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4126 IS.NumIterations);
4127
4128 // Add parentheses (for debugging purposes only).
4129 if (Div.isUsable())
Alexey Bataev8b427062016-05-25 12:36:08 +00004130 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004131 if (!Div.isUsable()) {
4132 HasErrors = true;
4133 break;
4134 }
Alexey Bataev8b427062016-05-25 12:36:08 +00004135 LoopMultipliers.push_back(Div.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004136 }
4137 if (!Update.isUsable() || !Final.isUsable()) {
4138 HasErrors = true;
4139 break;
4140 }
4141 // Save results
4142 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00004143 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004144 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004145 Built.Updates[Cnt] = Update.get();
4146 Built.Finals[Cnt] = Final.get();
4147 }
4148 }
4149
4150 if (HasErrors)
4151 return 0;
4152
4153 // Save results
4154 Built.IterationVarRef = IV.get();
4155 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00004156 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004157 Built.CalcLastIteration =
4158 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004159 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00004160 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004161 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004162 Built.Init = Init.get();
4163 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004164 Built.LB = LB.get();
4165 Built.UB = UB.get();
4166 Built.IL = IL.get();
4167 Built.ST = ST.get();
4168 Built.EUB = EUB.get();
4169 Built.NLB = NextLB.get();
4170 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004171 Built.PrevLB = PrevLB.get();
4172 Built.PrevUB = PrevUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004173
Alexey Bataev8b427062016-05-25 12:36:08 +00004174 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4175 // Fill data for doacross depend clauses.
4176 for (auto Pair : DSA.getDoacrossDependClauses()) {
4177 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4178 Pair.first->setCounterValue(CounterVal);
4179 else {
4180 if (NestedLoopCount != Pair.second.size() ||
4181 NestedLoopCount != LoopMultipliers.size() + 1) {
4182 // Erroneous case - clause has some problems.
4183 Pair.first->setCounterValue(CounterVal);
4184 continue;
4185 }
4186 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4187 auto I = Pair.second.rbegin();
4188 auto IS = IterSpaces.rbegin();
4189 auto ILM = LoopMultipliers.rbegin();
4190 Expr *UpCounterVal = CounterVal;
4191 Expr *Multiplier = nullptr;
4192 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4193 if (I->first) {
4194 assert(IS->CounterStep);
4195 Expr *NormalizedOffset =
4196 SemaRef
4197 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4198 I->first, IS->CounterStep)
4199 .get();
4200 if (Multiplier) {
4201 NormalizedOffset =
4202 SemaRef
4203 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
4204 NormalizedOffset, Multiplier)
4205 .get();
4206 }
4207 assert(I->second == OO_Plus || I->second == OO_Minus);
4208 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
David Majnemer9d168222016-08-05 17:44:54 +00004209 UpCounterVal = SemaRef
4210 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
4211 UpCounterVal, NormalizedOffset)
4212 .get();
Alexey Bataev8b427062016-05-25 12:36:08 +00004213 }
4214 Multiplier = *ILM;
4215 ++I;
4216 ++IS;
4217 ++ILM;
4218 }
4219 Pair.first->setCounterValue(UpCounterVal);
4220 }
4221 }
4222
Alexey Bataevabfc0692014-06-25 06:52:00 +00004223 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004224}
4225
Alexey Bataev10e775f2015-07-30 11:36:16 +00004226static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004227 auto CollapseClauses =
4228 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4229 if (CollapseClauses.begin() != CollapseClauses.end())
4230 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004231 return nullptr;
4232}
4233
Alexey Bataev10e775f2015-07-30 11:36:16 +00004234static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004235 auto OrderedClauses =
4236 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4237 if (OrderedClauses.begin() != OrderedClauses.end())
4238 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004239 return nullptr;
4240}
4241
Kelvin Lic5609492016-07-15 04:39:07 +00004242static bool checkSimdlenSafelenSpecified(Sema &S,
4243 const ArrayRef<OMPClause *> Clauses) {
4244 OMPSafelenClause *Safelen = nullptr;
4245 OMPSimdlenClause *Simdlen = nullptr;
4246
4247 for (auto *Clause : Clauses) {
4248 if (Clause->getClauseKind() == OMPC_safelen)
4249 Safelen = cast<OMPSafelenClause>(Clause);
4250 else if (Clause->getClauseKind() == OMPC_simdlen)
4251 Simdlen = cast<OMPSimdlenClause>(Clause);
4252 if (Safelen && Simdlen)
4253 break;
4254 }
4255
4256 if (Simdlen && Safelen) {
4257 llvm::APSInt SimdlenRes, SafelenRes;
4258 auto SimdlenLength = Simdlen->getSimdlen();
4259 auto SafelenLength = Safelen->getSafelen();
4260 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
4261 SimdlenLength->isInstantiationDependent() ||
4262 SimdlenLength->containsUnexpandedParameterPack())
4263 return false;
4264 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
4265 SafelenLength->isInstantiationDependent() ||
4266 SafelenLength->containsUnexpandedParameterPack())
4267 return false;
4268 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
4269 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
4270 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
4271 // If both simdlen and safelen clauses are specified, the value of the
4272 // simdlen parameter must be less than or equal to the value of the safelen
4273 // parameter.
4274 if (SimdlenRes > SafelenRes) {
4275 S.Diag(SimdlenLength->getExprLoc(),
4276 diag::err_omp_wrong_simdlen_safelen_values)
4277 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
4278 return true;
4279 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00004280 }
4281 return false;
4282}
4283
Alexey Bataev4acb8592014-07-07 13:01:15 +00004284StmtResult Sema::ActOnOpenMPSimdDirective(
4285 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4286 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004287 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004288 if (!AStmt)
4289 return StmtError();
4290
4291 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004292 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004293 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4294 // define the nested loops number.
4295 unsigned NestedLoopCount = CheckOpenMPLoop(
4296 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4297 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004298 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004299 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004300
Alexander Musmana5f070a2014-10-01 06:03:56 +00004301 assert((CurContext->isDependentContext() || B.builtAll()) &&
4302 "omp simd loop exprs were not built");
4303
Alexander Musman3276a272015-03-21 10:12:56 +00004304 if (!CurContext->isDependentContext()) {
4305 // Finalize the clauses that need pre-built expressions for CodeGen.
4306 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004307 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00004308 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004309 B.NumIterations, *this, CurScope,
4310 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00004311 return StmtError();
4312 }
4313 }
4314
Kelvin Lic5609492016-07-15 04:39:07 +00004315 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004316 return StmtError();
4317
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004318 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004319 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4320 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004321}
4322
Alexey Bataev4acb8592014-07-07 13:01:15 +00004323StmtResult Sema::ActOnOpenMPForDirective(
4324 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4325 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004326 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004327 if (!AStmt)
4328 return StmtError();
4329
4330 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004331 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004332 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4333 // define the nested loops number.
4334 unsigned NestedLoopCount = CheckOpenMPLoop(
4335 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4336 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004337 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00004338 return StmtError();
4339
Alexander Musmana5f070a2014-10-01 06:03:56 +00004340 assert((CurContext->isDependentContext() || B.builtAll()) &&
4341 "omp for loop exprs were not built");
4342
Alexey Bataev54acd402015-08-04 11:18:19 +00004343 if (!CurContext->isDependentContext()) {
4344 // Finalize the clauses that need pre-built expressions for CodeGen.
4345 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004346 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004347 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004348 B.NumIterations, *this, CurScope,
4349 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004350 return StmtError();
4351 }
4352 }
4353
Alexey Bataevf29276e2014-06-18 04:14:57 +00004354 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004355 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004356 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00004357}
4358
Alexander Musmanf82886e2014-09-18 05:12:34 +00004359StmtResult Sema::ActOnOpenMPForSimdDirective(
4360 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4361 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004362 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004363 if (!AStmt)
4364 return StmtError();
4365
4366 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004367 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004368 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4369 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00004370 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004371 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
4372 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4373 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004374 if (NestedLoopCount == 0)
4375 return StmtError();
4376
Alexander Musmanc6388682014-12-15 07:07:06 +00004377 assert((CurContext->isDependentContext() || B.builtAll()) &&
4378 "omp for simd loop exprs were not built");
4379
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004380 if (!CurContext->isDependentContext()) {
4381 // Finalize the clauses that need pre-built expressions for CodeGen.
4382 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004383 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004384 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004385 B.NumIterations, *this, CurScope,
4386 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004387 return StmtError();
4388 }
4389 }
4390
Kelvin Lic5609492016-07-15 04:39:07 +00004391 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004392 return StmtError();
4393
Alexander Musmanf82886e2014-09-18 05:12:34 +00004394 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004395 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4396 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004397}
4398
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004399StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
4400 Stmt *AStmt,
4401 SourceLocation StartLoc,
4402 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004403 if (!AStmt)
4404 return StmtError();
4405
4406 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004407 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004408 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004409 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004410 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004411 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004412 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004413 return StmtError();
4414 // All associated statements must be '#pragma omp section' except for
4415 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004416 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004417 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4418 if (SectionStmt)
4419 Diag(SectionStmt->getLocStart(),
4420 diag::err_omp_sections_substmt_not_section);
4421 return StmtError();
4422 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004423 cast<OMPSectionDirective>(SectionStmt)
4424 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004425 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004426 } else {
4427 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
4428 return StmtError();
4429 }
4430
4431 getCurFunction()->setHasBranchProtectedScope();
4432
Alexey Bataev25e5b442015-09-15 12:52:43 +00004433 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4434 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004435}
4436
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004437StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
4438 SourceLocation StartLoc,
4439 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004440 if (!AStmt)
4441 return StmtError();
4442
4443 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004444
4445 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00004446 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004447
Alexey Bataev25e5b442015-09-15 12:52:43 +00004448 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
4449 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004450}
4451
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004452StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
4453 Stmt *AStmt,
4454 SourceLocation StartLoc,
4455 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004456 if (!AStmt)
4457 return StmtError();
4458
4459 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00004460
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004461 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00004462
Alexey Bataev3255bf32015-01-19 05:20:46 +00004463 // OpenMP [2.7.3, single Construct, Restrictions]
4464 // The copyprivate clause must not be used with the nowait clause.
4465 OMPClause *Nowait = nullptr;
4466 OMPClause *Copyprivate = nullptr;
4467 for (auto *Clause : Clauses) {
4468 if (Clause->getClauseKind() == OMPC_nowait)
4469 Nowait = Clause;
4470 else if (Clause->getClauseKind() == OMPC_copyprivate)
4471 Copyprivate = Clause;
4472 if (Copyprivate && Nowait) {
4473 Diag(Copyprivate->getLocStart(),
4474 diag::err_omp_single_copyprivate_with_nowait);
4475 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
4476 return StmtError();
4477 }
4478 }
4479
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004480 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4481}
4482
Alexander Musman80c22892014-07-17 08:54:58 +00004483StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
4484 SourceLocation StartLoc,
4485 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004486 if (!AStmt)
4487 return StmtError();
4488
4489 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00004490
4491 getCurFunction()->setHasBranchProtectedScope();
4492
4493 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
4494}
4495
Alexey Bataev28c75412015-12-15 08:19:24 +00004496StmtResult Sema::ActOnOpenMPCriticalDirective(
4497 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
4498 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004499 if (!AStmt)
4500 return StmtError();
4501
4502 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004503
Alexey Bataev28c75412015-12-15 08:19:24 +00004504 bool ErrorFound = false;
4505 llvm::APSInt Hint;
4506 SourceLocation HintLoc;
4507 bool DependentHint = false;
4508 for (auto *C : Clauses) {
4509 if (C->getClauseKind() == OMPC_hint) {
4510 if (!DirName.getName()) {
4511 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
4512 ErrorFound = true;
4513 }
4514 Expr *E = cast<OMPHintClause>(C)->getHint();
4515 if (E->isTypeDependent() || E->isValueDependent() ||
4516 E->isInstantiationDependent())
4517 DependentHint = true;
4518 else {
4519 Hint = E->EvaluateKnownConstInt(Context);
4520 HintLoc = C->getLocStart();
4521 }
4522 }
4523 }
4524 if (ErrorFound)
4525 return StmtError();
4526 auto Pair = DSAStack->getCriticalWithHint(DirName);
4527 if (Pair.first && DirName.getName() && !DependentHint) {
4528 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
4529 Diag(StartLoc, diag::err_omp_critical_with_hint);
4530 if (HintLoc.isValid()) {
4531 Diag(HintLoc, diag::note_omp_critical_hint_here)
4532 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
4533 } else
4534 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
4535 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
4536 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
4537 << 1
4538 << C->getHint()->EvaluateKnownConstInt(Context).toString(
4539 /*Radix=*/10, /*Signed=*/false);
4540 } else
4541 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
4542 }
4543 }
4544
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004545 getCurFunction()->setHasBranchProtectedScope();
4546
Alexey Bataev28c75412015-12-15 08:19:24 +00004547 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
4548 Clauses, AStmt);
4549 if (!Pair.first && DirName.getName() && !DependentHint)
4550 DSAStack->addCriticalWithHint(Dir, Hint);
4551 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004552}
4553
Alexey Bataev4acb8592014-07-07 13:01:15 +00004554StmtResult Sema::ActOnOpenMPParallelForDirective(
4555 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4556 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004557 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004558 if (!AStmt)
4559 return StmtError();
4560
Alexey Bataev4acb8592014-07-07 13:01:15 +00004561 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4562 // 1.2.2 OpenMP Language Terminology
4563 // Structured block - An executable statement with a single entry at the
4564 // top and a single exit at the bottom.
4565 // The point of exit cannot be a branch out of the structured block.
4566 // longjmp() and throw() must not violate the entry/exit criteria.
4567 CS->getCapturedDecl()->setNothrow();
4568
Alexander Musmanc6388682014-12-15 07:07:06 +00004569 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004570 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4571 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004572 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004573 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
4574 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4575 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004576 if (NestedLoopCount == 0)
4577 return StmtError();
4578
Alexander Musmana5f070a2014-10-01 06:03:56 +00004579 assert((CurContext->isDependentContext() || B.builtAll()) &&
4580 "omp parallel for loop exprs were not built");
4581
Alexey Bataev54acd402015-08-04 11:18:19 +00004582 if (!CurContext->isDependentContext()) {
4583 // Finalize the clauses that need pre-built expressions for CodeGen.
4584 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004585 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004586 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004587 B.NumIterations, *this, CurScope,
4588 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004589 return StmtError();
4590 }
4591 }
4592
Alexey Bataev4acb8592014-07-07 13:01:15 +00004593 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004594 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004595 NestedLoopCount, Clauses, AStmt, B,
4596 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00004597}
4598
Alexander Musmane4e893b2014-09-23 09:33:00 +00004599StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
4600 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4601 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004602 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004603 if (!AStmt)
4604 return StmtError();
4605
Alexander Musmane4e893b2014-09-23 09:33:00 +00004606 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4607 // 1.2.2 OpenMP Language Terminology
4608 // Structured block - An executable statement with a single entry at the
4609 // top and a single exit at the bottom.
4610 // The point of exit cannot be a branch out of the structured block.
4611 // longjmp() and throw() must not violate the entry/exit criteria.
4612 CS->getCapturedDecl()->setNothrow();
4613
Alexander Musmanc6388682014-12-15 07:07:06 +00004614 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004615 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4616 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00004617 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004618 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
4619 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4620 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004621 if (NestedLoopCount == 0)
4622 return StmtError();
4623
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004624 if (!CurContext->isDependentContext()) {
4625 // Finalize the clauses that need pre-built expressions for CodeGen.
4626 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004627 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004628 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004629 B.NumIterations, *this, CurScope,
4630 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004631 return StmtError();
4632 }
4633 }
4634
Kelvin Lic5609492016-07-15 04:39:07 +00004635 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004636 return StmtError();
4637
Alexander Musmane4e893b2014-09-23 09:33:00 +00004638 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004639 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00004640 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004641}
4642
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004643StmtResult
4644Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
4645 Stmt *AStmt, SourceLocation StartLoc,
4646 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004647 if (!AStmt)
4648 return StmtError();
4649
4650 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004651 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004652 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004653 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004654 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004655 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004656 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004657 return StmtError();
4658 // All associated statements must be '#pragma omp section' except for
4659 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004660 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004661 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4662 if (SectionStmt)
4663 Diag(SectionStmt->getLocStart(),
4664 diag::err_omp_parallel_sections_substmt_not_section);
4665 return StmtError();
4666 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004667 cast<OMPSectionDirective>(SectionStmt)
4668 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004669 }
4670 } else {
4671 Diag(AStmt->getLocStart(),
4672 diag::err_omp_parallel_sections_not_compound_stmt);
4673 return StmtError();
4674 }
4675
4676 getCurFunction()->setHasBranchProtectedScope();
4677
Alexey Bataev25e5b442015-09-15 12:52:43 +00004678 return OMPParallelSectionsDirective::Create(
4679 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004680}
4681
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004682StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
4683 Stmt *AStmt, SourceLocation StartLoc,
4684 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004685 if (!AStmt)
4686 return StmtError();
4687
David Majnemer9d168222016-08-05 17:44:54 +00004688 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004689 // 1.2.2 OpenMP Language Terminology
4690 // Structured block - An executable statement with a single entry at the
4691 // top and a single exit at the bottom.
4692 // The point of exit cannot be a branch out of the structured block.
4693 // longjmp() and throw() must not violate the entry/exit criteria.
4694 CS->getCapturedDecl()->setNothrow();
4695
4696 getCurFunction()->setHasBranchProtectedScope();
4697
Alexey Bataev25e5b442015-09-15 12:52:43 +00004698 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4699 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004700}
4701
Alexey Bataev68446b72014-07-18 07:47:19 +00004702StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
4703 SourceLocation EndLoc) {
4704 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
4705}
4706
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004707StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
4708 SourceLocation EndLoc) {
4709 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
4710}
4711
Alexey Bataev2df347a2014-07-18 10:17:07 +00004712StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
4713 SourceLocation EndLoc) {
4714 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
4715}
4716
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004717StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
4718 SourceLocation StartLoc,
4719 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004720 if (!AStmt)
4721 return StmtError();
4722
4723 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004724
4725 getCurFunction()->setHasBranchProtectedScope();
4726
4727 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
4728}
4729
Alexey Bataev6125da92014-07-21 11:26:11 +00004730StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
4731 SourceLocation StartLoc,
4732 SourceLocation EndLoc) {
4733 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
4734 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
4735}
4736
Alexey Bataev346265e2015-09-25 10:37:12 +00004737StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
4738 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004739 SourceLocation StartLoc,
4740 SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00004741 OMPClause *DependFound = nullptr;
4742 OMPClause *DependSourceClause = nullptr;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004743 OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00004744 bool ErrorFound = false;
Alexey Bataev346265e2015-09-25 10:37:12 +00004745 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004746 OMPSIMDClause *SC = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00004747 for (auto *C : Clauses) {
4748 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
4749 DependFound = C;
4750 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
4751 if (DependSourceClause) {
4752 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
4753 << getOpenMPDirectiveName(OMPD_ordered)
4754 << getOpenMPClauseName(OMPC_depend) << 2;
4755 ErrorFound = true;
4756 } else
4757 DependSourceClause = C;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004758 if (DependSinkClause) {
4759 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4760 << 0;
4761 ErrorFound = true;
4762 }
4763 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
4764 if (DependSourceClause) {
4765 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4766 << 1;
4767 ErrorFound = true;
4768 }
4769 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00004770 }
4771 } else if (C->getClauseKind() == OMPC_threads)
Alexey Bataev346265e2015-09-25 10:37:12 +00004772 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004773 else if (C->getClauseKind() == OMPC_simd)
4774 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00004775 }
Alexey Bataeveb482352015-12-18 05:05:56 +00004776 if (!ErrorFound && !SC &&
4777 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004778 // OpenMP [2.8.1,simd Construct, Restrictions]
4779 // An ordered construct with the simd clause is the only OpenMP construct
4780 // that can appear in the simd region.
4781 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00004782 ErrorFound = true;
4783 } else if (DependFound && (TC || SC)) {
4784 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
4785 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
4786 ErrorFound = true;
4787 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
4788 Diag(DependFound->getLocStart(),
4789 diag::err_omp_ordered_directive_without_param);
4790 ErrorFound = true;
4791 } else if (TC || Clauses.empty()) {
4792 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
4793 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
4794 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
4795 << (TC != nullptr);
4796 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
4797 ErrorFound = true;
4798 }
4799 }
4800 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004801 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00004802
4803 if (AStmt) {
4804 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4805
4806 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004807 }
Alexey Bataev346265e2015-09-25 10:37:12 +00004808
4809 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004810}
4811
Alexey Bataev1d160b12015-03-13 12:27:31 +00004812namespace {
4813/// \brief Helper class for checking expression in 'omp atomic [update]'
4814/// construct.
4815class OpenMPAtomicUpdateChecker {
4816 /// \brief Error results for atomic update expressions.
4817 enum ExprAnalysisErrorCode {
4818 /// \brief A statement is not an expression statement.
4819 NotAnExpression,
4820 /// \brief Expression is not builtin binary or unary operation.
4821 NotABinaryOrUnaryExpression,
4822 /// \brief Unary operation is not post-/pre- increment/decrement operation.
4823 NotAnUnaryIncDecExpression,
4824 /// \brief An expression is not of scalar type.
4825 NotAScalarType,
4826 /// \brief A binary operation is not an assignment operation.
4827 NotAnAssignmentOp,
4828 /// \brief RHS part of the binary operation is not a binary expression.
4829 NotABinaryExpression,
4830 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
4831 /// expression.
4832 NotABinaryOperator,
4833 /// \brief RHS binary operation does not have reference to the updated LHS
4834 /// part.
4835 NotAnUpdateExpression,
4836 /// \brief No errors is found.
4837 NoError
4838 };
4839 /// \brief Reference to Sema.
4840 Sema &SemaRef;
4841 /// \brief A location for note diagnostics (when error is found).
4842 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004843 /// \brief 'x' lvalue part of the source atomic expression.
4844 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004845 /// \brief 'expr' rvalue part of the source atomic expression.
4846 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004847 /// \brief Helper expression of the form
4848 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4849 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4850 Expr *UpdateExpr;
4851 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
4852 /// important for non-associative operations.
4853 bool IsXLHSInRHSPart;
4854 BinaryOperatorKind Op;
4855 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00004856 /// \brief true if the source expression is a postfix unary operation, false
4857 /// if it is a prefix unary operation.
4858 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004859
4860public:
4861 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00004862 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00004863 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00004864 /// \brief Check specified statement that it is suitable for 'atomic update'
4865 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00004866 /// expression. If DiagId and NoteId == 0, then only check is performed
4867 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00004868 /// \param DiagId Diagnostic which should be emitted if error is found.
4869 /// \param NoteId Diagnostic note for the main error message.
4870 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00004871 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00004872 /// \brief Return the 'x' lvalue part of the source atomic expression.
4873 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00004874 /// \brief Return the 'expr' rvalue part of the source atomic expression.
4875 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00004876 /// \brief Return the update expression used in calculation of the updated
4877 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4878 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4879 Expr *getUpdateExpr() const { return UpdateExpr; }
4880 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
4881 /// false otherwise.
4882 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
4883
Alexey Bataevb78ca832015-04-01 03:33:17 +00004884 /// \brief true if the source expression is a postfix unary operation, false
4885 /// if it is a prefix unary operation.
4886 bool isPostfixUpdate() const { return IsPostfixUpdate; }
4887
Alexey Bataev1d160b12015-03-13 12:27:31 +00004888private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00004889 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
4890 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00004891};
4892} // namespace
4893
4894bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
4895 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
4896 ExprAnalysisErrorCode ErrorFound = NoError;
4897 SourceLocation ErrorLoc, NoteLoc;
4898 SourceRange ErrorRange, NoteRange;
4899 // Allowed constructs are:
4900 // x = x binop expr;
4901 // x = expr binop x;
4902 if (AtomicBinOp->getOpcode() == BO_Assign) {
4903 X = AtomicBinOp->getLHS();
4904 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
4905 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
4906 if (AtomicInnerBinOp->isMultiplicativeOp() ||
4907 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
4908 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00004909 Op = AtomicInnerBinOp->getOpcode();
4910 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00004911 auto *LHS = AtomicInnerBinOp->getLHS();
4912 auto *RHS = AtomicInnerBinOp->getRHS();
4913 llvm::FoldingSetNodeID XId, LHSId, RHSId;
4914 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
4915 /*Canonical=*/true);
4916 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
4917 /*Canonical=*/true);
4918 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
4919 /*Canonical=*/true);
4920 if (XId == LHSId) {
4921 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004922 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004923 } else if (XId == RHSId) {
4924 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004925 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004926 } else {
4927 ErrorLoc = AtomicInnerBinOp->getExprLoc();
4928 ErrorRange = AtomicInnerBinOp->getSourceRange();
4929 NoteLoc = X->getExprLoc();
4930 NoteRange = X->getSourceRange();
4931 ErrorFound = NotAnUpdateExpression;
4932 }
4933 } else {
4934 ErrorLoc = AtomicInnerBinOp->getExprLoc();
4935 ErrorRange = AtomicInnerBinOp->getSourceRange();
4936 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
4937 NoteRange = SourceRange(NoteLoc, NoteLoc);
4938 ErrorFound = NotABinaryOperator;
4939 }
4940 } else {
4941 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
4942 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
4943 ErrorFound = NotABinaryExpression;
4944 }
4945 } else {
4946 ErrorLoc = AtomicBinOp->getExprLoc();
4947 ErrorRange = AtomicBinOp->getSourceRange();
4948 NoteLoc = AtomicBinOp->getOperatorLoc();
4949 NoteRange = SourceRange(NoteLoc, NoteLoc);
4950 ErrorFound = NotAnAssignmentOp;
4951 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00004952 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00004953 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
4954 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
4955 return true;
4956 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00004957 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00004958 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004959}
4960
4961bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
4962 unsigned NoteId) {
4963 ExprAnalysisErrorCode ErrorFound = NoError;
4964 SourceLocation ErrorLoc, NoteLoc;
4965 SourceRange ErrorRange, NoteRange;
4966 // Allowed constructs are:
4967 // x++;
4968 // x--;
4969 // ++x;
4970 // --x;
4971 // x binop= expr;
4972 // x = x binop expr;
4973 // x = expr binop x;
4974 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
4975 AtomicBody = AtomicBody->IgnoreParenImpCasts();
4976 if (AtomicBody->getType()->isScalarType() ||
4977 AtomicBody->isInstantiationDependent()) {
4978 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
4979 AtomicBody->IgnoreParenImpCasts())) {
4980 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00004981 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00004982 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00004983 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00004984 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00004985 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00004986 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004987 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
4988 AtomicBody->IgnoreParenImpCasts())) {
4989 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00004990 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00004991 return true;
David Majnemer9d168222016-08-05 17:44:54 +00004992 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
4993 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00004994 // Check for Unary Operation
4995 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00004996 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00004997 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
4998 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00004999 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005000 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5001 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005002 } else {
5003 ErrorFound = NotAnUnaryIncDecExpression;
5004 ErrorLoc = AtomicUnaryOp->getExprLoc();
5005 ErrorRange = AtomicUnaryOp->getSourceRange();
5006 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5007 NoteRange = SourceRange(NoteLoc, NoteLoc);
5008 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005009 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005010 ErrorFound = NotABinaryOrUnaryExpression;
5011 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5012 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5013 }
5014 } else {
5015 ErrorFound = NotAScalarType;
5016 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5017 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5018 }
5019 } else {
5020 ErrorFound = NotAnExpression;
5021 NoteLoc = ErrorLoc = S->getLocStart();
5022 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5023 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005024 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005025 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5026 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5027 return true;
5028 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005029 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005030 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005031 // Build an update expression of form 'OpaqueValueExpr(x) binop
5032 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5033 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5034 auto *OVEX = new (SemaRef.getASTContext())
5035 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5036 auto *OVEExpr = new (SemaRef.getASTContext())
5037 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5038 auto Update =
5039 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5040 IsXLHSInRHSPart ? OVEExpr : OVEX);
5041 if (Update.isInvalid())
5042 return true;
5043 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5044 Sema::AA_Casting);
5045 if (Update.isInvalid())
5046 return true;
5047 UpdateExpr = Update.get();
5048 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00005049 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005050}
5051
Alexey Bataev0162e452014-07-22 10:10:35 +00005052StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5053 Stmt *AStmt,
5054 SourceLocation StartLoc,
5055 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005056 if (!AStmt)
5057 return StmtError();
5058
David Majnemer9d168222016-08-05 17:44:54 +00005059 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00005060 // 1.2.2 OpenMP Language Terminology
5061 // Structured block - An executable statement with a single entry at the
5062 // top and a single exit at the bottom.
5063 // The point of exit cannot be a branch out of the structured block.
5064 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00005065 OpenMPClauseKind AtomicKind = OMPC_unknown;
5066 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005067 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00005068 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00005069 C->getClauseKind() == OMPC_update ||
5070 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00005071 if (AtomicKind != OMPC_unknown) {
5072 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5073 << SourceRange(C->getLocStart(), C->getLocEnd());
5074 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5075 << getOpenMPClauseName(AtomicKind);
5076 } else {
5077 AtomicKind = C->getClauseKind();
5078 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005079 }
5080 }
5081 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005082
Alexey Bataev459dec02014-07-24 06:46:57 +00005083 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00005084 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5085 Body = EWC->getSubExpr();
5086
Alexey Bataev62cec442014-11-18 10:14:22 +00005087 Expr *X = nullptr;
5088 Expr *V = nullptr;
5089 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005090 Expr *UE = nullptr;
5091 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005092 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00005093 // OpenMP [2.12.6, atomic Construct]
5094 // In the next expressions:
5095 // * x and v (as applicable) are both l-value expressions with scalar type.
5096 // * During the execution of an atomic region, multiple syntactic
5097 // occurrences of x must designate the same storage location.
5098 // * Neither of v and expr (as applicable) may access the storage location
5099 // designated by x.
5100 // * Neither of x and expr (as applicable) may access the storage location
5101 // designated by v.
5102 // * expr is an expression with scalar type.
5103 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5104 // * binop, binop=, ++, and -- are not overloaded operators.
5105 // * The expression x binop expr must be numerically equivalent to x binop
5106 // (expr). This requirement is satisfied if the operators in expr have
5107 // precedence greater than binop, or by using parentheses around expr or
5108 // subexpressions of expr.
5109 // * The expression expr binop x must be numerically equivalent to (expr)
5110 // binop x. This requirement is satisfied if the operators in expr have
5111 // precedence equal to or greater than binop, or by using parentheses around
5112 // expr or subexpressions of expr.
5113 // * For forms that allow multiple occurrences of x, the number of times
5114 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00005115 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005116 enum {
5117 NotAnExpression,
5118 NotAnAssignmentOp,
5119 NotAScalarType,
5120 NotAnLValue,
5121 NoError
5122 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00005123 SourceLocation ErrorLoc, NoteLoc;
5124 SourceRange ErrorRange, NoteRange;
5125 // If clause is read:
5126 // v = x;
David Majnemer9d168222016-08-05 17:44:54 +00005127 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5128 auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00005129 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5130 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5131 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5132 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5133 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5134 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5135 if (!X->isLValue() || !V->isLValue()) {
5136 auto NotLValueExpr = X->isLValue() ? V : X;
5137 ErrorFound = NotAnLValue;
5138 ErrorLoc = AtomicBinOp->getExprLoc();
5139 ErrorRange = AtomicBinOp->getSourceRange();
5140 NoteLoc = NotLValueExpr->getExprLoc();
5141 NoteRange = NotLValueExpr->getSourceRange();
5142 }
5143 } else if (!X->isInstantiationDependent() ||
5144 !V->isInstantiationDependent()) {
5145 auto NotScalarExpr =
5146 (X->isInstantiationDependent() || X->getType()->isScalarType())
5147 ? V
5148 : X;
5149 ErrorFound = NotAScalarType;
5150 ErrorLoc = AtomicBinOp->getExprLoc();
5151 ErrorRange = AtomicBinOp->getSourceRange();
5152 NoteLoc = NotScalarExpr->getExprLoc();
5153 NoteRange = NotScalarExpr->getSourceRange();
5154 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005155 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00005156 ErrorFound = NotAnAssignmentOp;
5157 ErrorLoc = AtomicBody->getExprLoc();
5158 ErrorRange = AtomicBody->getSourceRange();
5159 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5160 : AtomicBody->getExprLoc();
5161 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5162 : AtomicBody->getSourceRange();
5163 }
5164 } else {
5165 ErrorFound = NotAnExpression;
5166 NoteLoc = ErrorLoc = Body->getLocStart();
5167 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005168 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005169 if (ErrorFound != NoError) {
5170 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5171 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005172 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5173 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00005174 return StmtError();
5175 } else if (CurContext->isDependentContext())
5176 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00005177 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005178 enum {
5179 NotAnExpression,
5180 NotAnAssignmentOp,
5181 NotAScalarType,
5182 NotAnLValue,
5183 NoError
5184 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005185 SourceLocation ErrorLoc, NoteLoc;
5186 SourceRange ErrorRange, NoteRange;
5187 // If clause is write:
5188 // x = expr;
David Majnemer9d168222016-08-05 17:44:54 +00005189 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5190 auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00005191 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5192 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00005193 X = AtomicBinOp->getLHS();
5194 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00005195 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5196 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5197 if (!X->isLValue()) {
5198 ErrorFound = NotAnLValue;
5199 ErrorLoc = AtomicBinOp->getExprLoc();
5200 ErrorRange = AtomicBinOp->getSourceRange();
5201 NoteLoc = X->getExprLoc();
5202 NoteRange = X->getSourceRange();
5203 }
5204 } else if (!X->isInstantiationDependent() ||
5205 !E->isInstantiationDependent()) {
5206 auto NotScalarExpr =
5207 (X->isInstantiationDependent() || X->getType()->isScalarType())
5208 ? E
5209 : X;
5210 ErrorFound = NotAScalarType;
5211 ErrorLoc = AtomicBinOp->getExprLoc();
5212 ErrorRange = AtomicBinOp->getSourceRange();
5213 NoteLoc = NotScalarExpr->getExprLoc();
5214 NoteRange = NotScalarExpr->getSourceRange();
5215 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005216 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00005217 ErrorFound = NotAnAssignmentOp;
5218 ErrorLoc = AtomicBody->getExprLoc();
5219 ErrorRange = AtomicBody->getSourceRange();
5220 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5221 : AtomicBody->getExprLoc();
5222 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5223 : AtomicBody->getSourceRange();
5224 }
5225 } else {
5226 ErrorFound = NotAnExpression;
5227 NoteLoc = ErrorLoc = Body->getLocStart();
5228 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005229 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00005230 if (ErrorFound != NoError) {
5231 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
5232 << ErrorRange;
5233 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5234 << NoteRange;
5235 return StmtError();
5236 } else if (CurContext->isDependentContext())
5237 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00005238 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005239 // If clause is update:
5240 // x++;
5241 // x--;
5242 // ++x;
5243 // --x;
5244 // x binop= expr;
5245 // x = x binop expr;
5246 // x = expr binop x;
5247 OpenMPAtomicUpdateChecker Checker(*this);
5248 if (Checker.checkStatement(
5249 Body, (AtomicKind == OMPC_update)
5250 ? diag::err_omp_atomic_update_not_expression_statement
5251 : diag::err_omp_atomic_not_expression_statement,
5252 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00005253 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005254 if (!CurContext->isDependentContext()) {
5255 E = Checker.getExpr();
5256 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005257 UE = Checker.getUpdateExpr();
5258 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00005259 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005260 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005261 enum {
5262 NotAnAssignmentOp,
5263 NotACompoundStatement,
5264 NotTwoSubstatements,
5265 NotASpecificExpression,
5266 NoError
5267 } ErrorFound = NoError;
5268 SourceLocation ErrorLoc, NoteLoc;
5269 SourceRange ErrorRange, NoteRange;
5270 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5271 // If clause is a capture:
5272 // v = x++;
5273 // v = x--;
5274 // v = ++x;
5275 // v = --x;
5276 // v = x binop= expr;
5277 // v = x = x binop expr;
5278 // v = x = expr binop x;
5279 auto *AtomicBinOp =
5280 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5281 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5282 V = AtomicBinOp->getLHS();
5283 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5284 OpenMPAtomicUpdateChecker Checker(*this);
5285 if (Checker.checkStatement(
5286 Body, diag::err_omp_atomic_capture_not_expression_statement,
5287 diag::note_omp_atomic_update))
5288 return StmtError();
5289 E = Checker.getExpr();
5290 X = Checker.getX();
5291 UE = Checker.getUpdateExpr();
5292 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5293 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00005294 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005295 ErrorLoc = AtomicBody->getExprLoc();
5296 ErrorRange = AtomicBody->getSourceRange();
5297 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5298 : AtomicBody->getExprLoc();
5299 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5300 : AtomicBody->getSourceRange();
5301 ErrorFound = NotAnAssignmentOp;
5302 }
5303 if (ErrorFound != NoError) {
5304 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
5305 << ErrorRange;
5306 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5307 return StmtError();
5308 } else if (CurContext->isDependentContext()) {
5309 UE = V = E = X = nullptr;
5310 }
5311 } else {
5312 // If clause is a capture:
5313 // { v = x; x = expr; }
5314 // { v = x; x++; }
5315 // { v = x; x--; }
5316 // { v = x; ++x; }
5317 // { v = x; --x; }
5318 // { v = x; x binop= expr; }
5319 // { v = x; x = x binop expr; }
5320 // { v = x; x = expr binop x; }
5321 // { x++; v = x; }
5322 // { x--; v = x; }
5323 // { ++x; v = x; }
5324 // { --x; v = x; }
5325 // { x binop= expr; v = x; }
5326 // { x = x binop expr; v = x; }
5327 // { x = expr binop x; v = x; }
5328 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
5329 // Check that this is { expr1; expr2; }
5330 if (CS->size() == 2) {
5331 auto *First = CS->body_front();
5332 auto *Second = CS->body_back();
5333 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
5334 First = EWC->getSubExpr()->IgnoreParenImpCasts();
5335 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
5336 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
5337 // Need to find what subexpression is 'v' and what is 'x'.
5338 OpenMPAtomicUpdateChecker Checker(*this);
5339 bool IsUpdateExprFound = !Checker.checkStatement(Second);
5340 BinaryOperator *BinOp = nullptr;
5341 if (IsUpdateExprFound) {
5342 BinOp = dyn_cast<BinaryOperator>(First);
5343 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5344 }
5345 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5346 // { v = x; x++; }
5347 // { v = x; x--; }
5348 // { v = x; ++x; }
5349 // { v = x; --x; }
5350 // { v = x; x binop= expr; }
5351 // { v = x; x = x binop expr; }
5352 // { v = x; x = expr binop x; }
5353 // Check that the first expression has form v = x.
5354 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5355 llvm::FoldingSetNodeID XId, PossibleXId;
5356 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5357 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5358 IsUpdateExprFound = XId == PossibleXId;
5359 if (IsUpdateExprFound) {
5360 V = BinOp->getLHS();
5361 X = Checker.getX();
5362 E = Checker.getExpr();
5363 UE = Checker.getUpdateExpr();
5364 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005365 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005366 }
5367 }
5368 if (!IsUpdateExprFound) {
5369 IsUpdateExprFound = !Checker.checkStatement(First);
5370 BinOp = nullptr;
5371 if (IsUpdateExprFound) {
5372 BinOp = dyn_cast<BinaryOperator>(Second);
5373 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5374 }
5375 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5376 // { x++; v = x; }
5377 // { x--; v = x; }
5378 // { ++x; v = x; }
5379 // { --x; v = x; }
5380 // { x binop= expr; v = x; }
5381 // { x = x binop expr; v = x; }
5382 // { x = expr binop x; v = x; }
5383 // Check that the second expression has form v = x.
5384 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5385 llvm::FoldingSetNodeID XId, PossibleXId;
5386 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5387 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5388 IsUpdateExprFound = XId == PossibleXId;
5389 if (IsUpdateExprFound) {
5390 V = BinOp->getLHS();
5391 X = Checker.getX();
5392 E = Checker.getExpr();
5393 UE = Checker.getUpdateExpr();
5394 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005395 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005396 }
5397 }
5398 }
5399 if (!IsUpdateExprFound) {
5400 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00005401 auto *FirstExpr = dyn_cast<Expr>(First);
5402 auto *SecondExpr = dyn_cast<Expr>(Second);
5403 if (!FirstExpr || !SecondExpr ||
5404 !(FirstExpr->isInstantiationDependent() ||
5405 SecondExpr->isInstantiationDependent())) {
5406 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
5407 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005408 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00005409 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
5410 : First->getLocStart();
5411 NoteRange = ErrorRange = FirstBinOp
5412 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00005413 : SourceRange(ErrorLoc, ErrorLoc);
5414 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005415 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
5416 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
5417 ErrorFound = NotAnAssignmentOp;
5418 NoteLoc = ErrorLoc = SecondBinOp
5419 ? SecondBinOp->getOperatorLoc()
5420 : Second->getLocStart();
5421 NoteRange = ErrorRange =
5422 SecondBinOp ? SecondBinOp->getSourceRange()
5423 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00005424 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005425 auto *PossibleXRHSInFirst =
5426 FirstBinOp->getRHS()->IgnoreParenImpCasts();
5427 auto *PossibleXLHSInSecond =
5428 SecondBinOp->getLHS()->IgnoreParenImpCasts();
5429 llvm::FoldingSetNodeID X1Id, X2Id;
5430 PossibleXRHSInFirst->Profile(X1Id, Context,
5431 /*Canonical=*/true);
5432 PossibleXLHSInSecond->Profile(X2Id, Context,
5433 /*Canonical=*/true);
5434 IsUpdateExprFound = X1Id == X2Id;
5435 if (IsUpdateExprFound) {
5436 V = FirstBinOp->getLHS();
5437 X = SecondBinOp->getLHS();
5438 E = SecondBinOp->getRHS();
5439 UE = nullptr;
5440 IsXLHSInRHSPart = false;
5441 IsPostfixUpdate = true;
5442 } else {
5443 ErrorFound = NotASpecificExpression;
5444 ErrorLoc = FirstBinOp->getExprLoc();
5445 ErrorRange = FirstBinOp->getSourceRange();
5446 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
5447 NoteRange = SecondBinOp->getRHS()->getSourceRange();
5448 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005449 }
5450 }
5451 }
5452 }
5453 } else {
5454 NoteLoc = ErrorLoc = Body->getLocStart();
5455 NoteRange = ErrorRange =
5456 SourceRange(Body->getLocStart(), Body->getLocStart());
5457 ErrorFound = NotTwoSubstatements;
5458 }
5459 } else {
5460 NoteLoc = ErrorLoc = Body->getLocStart();
5461 NoteRange = ErrorRange =
5462 SourceRange(Body->getLocStart(), Body->getLocStart());
5463 ErrorFound = NotACompoundStatement;
5464 }
5465 if (ErrorFound != NoError) {
5466 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
5467 << ErrorRange;
5468 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5469 return StmtError();
5470 } else if (CurContext->isDependentContext()) {
5471 UE = V = E = X = nullptr;
5472 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005473 }
Alexey Bataevdea47612014-07-23 07:46:59 +00005474 }
Alexey Bataev0162e452014-07-22 10:10:35 +00005475
5476 getCurFunction()->setHasBranchProtectedScope();
5477
Alexey Bataev62cec442014-11-18 10:14:22 +00005478 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00005479 X, V, E, UE, IsXLHSInRHSPart,
5480 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00005481}
5482
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005483StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
5484 Stmt *AStmt,
5485 SourceLocation StartLoc,
5486 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005487 if (!AStmt)
5488 return StmtError();
5489
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005490 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5491 // 1.2.2 OpenMP Language Terminology
5492 // Structured block - An executable statement with a single entry at the
5493 // top and a single exit at the bottom.
5494 // The point of exit cannot be a branch out of the structured block.
5495 // longjmp() and throw() must not violate the entry/exit criteria.
5496 CS->getCapturedDecl()->setNothrow();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005497
Alexey Bataev13314bf2014-10-09 04:18:56 +00005498 // OpenMP [2.16, Nesting of Regions]
5499 // If specified, a teams construct must be contained within a target
5500 // construct. That target construct must contain no statements or directives
5501 // outside of the teams construct.
5502 if (DSAStack->hasInnerTeamsRegion()) {
5503 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
5504 bool OMPTeamsFound = true;
5505 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
5506 auto I = CS->body_begin();
5507 while (I != CS->body_end()) {
David Majnemer9d168222016-08-05 17:44:54 +00005508 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00005509 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
5510 OMPTeamsFound = false;
5511 break;
5512 }
5513 ++I;
5514 }
5515 assert(I != CS->body_end() && "Not found statement");
5516 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00005517 } else {
5518 auto *OED = dyn_cast<OMPExecutableDirective>(S);
5519 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00005520 }
5521 if (!OMPTeamsFound) {
5522 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
5523 Diag(DSAStack->getInnerTeamsRegionLoc(),
5524 diag::note_omp_nested_teams_construct_here);
5525 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
5526 << isa<OMPExecutableDirective>(S);
5527 return StmtError();
5528 }
5529 }
5530
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005531 getCurFunction()->setHasBranchProtectedScope();
5532
5533 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5534}
5535
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005536StmtResult
5537Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
5538 Stmt *AStmt, SourceLocation StartLoc,
5539 SourceLocation EndLoc) {
5540 if (!AStmt)
5541 return StmtError();
5542
5543 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5544 // 1.2.2 OpenMP Language Terminology
5545 // Structured block - An executable statement with a single entry at the
5546 // top and a single exit at the bottom.
5547 // The point of exit cannot be a branch out of the structured block.
5548 // longjmp() and throw() must not violate the entry/exit criteria.
5549 CS->getCapturedDecl()->setNothrow();
5550
5551 getCurFunction()->setHasBranchProtectedScope();
5552
5553 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5554 AStmt);
5555}
5556
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005557StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
5558 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5559 SourceLocation EndLoc,
5560 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5561 if (!AStmt)
5562 return StmtError();
5563
5564 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5565 // 1.2.2 OpenMP Language Terminology
5566 // Structured block - An executable statement with a single entry at the
5567 // top and a single exit at the bottom.
5568 // The point of exit cannot be a branch out of the structured block.
5569 // longjmp() and throw() must not violate the entry/exit criteria.
5570 CS->getCapturedDecl()->setNothrow();
5571
5572 OMPLoopDirective::HelperExprs B;
5573 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5574 // define the nested loops number.
5575 unsigned NestedLoopCount =
5576 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
5577 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5578 VarsWithImplicitDSA, B);
5579 if (NestedLoopCount == 0)
5580 return StmtError();
5581
5582 assert((CurContext->isDependentContext() || B.builtAll()) &&
5583 "omp target parallel for loop exprs were not built");
5584
5585 if (!CurContext->isDependentContext()) {
5586 // Finalize the clauses that need pre-built expressions for CodeGen.
5587 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005588 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005589 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005590 B.NumIterations, *this, CurScope,
5591 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005592 return StmtError();
5593 }
5594 }
5595
5596 getCurFunction()->setHasBranchProtectedScope();
5597 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
5598 NestedLoopCount, Clauses, AStmt,
5599 B, DSAStack->isCancelRegion());
5600}
5601
Samuel Antaodf67fc42016-01-19 19:15:56 +00005602/// \brief Check for existence of a map clause in the list of clauses.
5603static bool HasMapClause(ArrayRef<OMPClause *> Clauses) {
5604 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
5605 I != E; ++I) {
5606 if (*I != nullptr && (*I)->getClauseKind() == OMPC_map) {
5607 return true;
5608 }
5609 }
5610
5611 return false;
5612}
5613
Michael Wong65f367f2015-07-21 13:44:28 +00005614StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
5615 Stmt *AStmt,
5616 SourceLocation StartLoc,
5617 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005618 if (!AStmt)
5619 return StmtError();
5620
5621 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5622
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005623 // OpenMP [2.10.1, Restrictions, p. 97]
5624 // At least one map clause must appear on the directive.
5625 if (!HasMapClause(Clauses)) {
David Majnemer9d168222016-08-05 17:44:54 +00005626 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5627 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005628 return StmtError();
5629 }
5630
Michael Wong65f367f2015-07-21 13:44:28 +00005631 getCurFunction()->setHasBranchProtectedScope();
5632
5633 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
5634 AStmt);
5635}
5636
Samuel Antaodf67fc42016-01-19 19:15:56 +00005637StmtResult
5638Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
5639 SourceLocation StartLoc,
5640 SourceLocation EndLoc) {
5641 // OpenMP [2.10.2, Restrictions, p. 99]
5642 // At least one map clause must appear on the directive.
5643 if (!HasMapClause(Clauses)) {
5644 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5645 << getOpenMPDirectiveName(OMPD_target_enter_data);
5646 return StmtError();
5647 }
5648
5649 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
5650 Clauses);
5651}
5652
Samuel Antao72590762016-01-19 20:04:50 +00005653StmtResult
5654Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
5655 SourceLocation StartLoc,
5656 SourceLocation EndLoc) {
5657 // OpenMP [2.10.3, Restrictions, p. 102]
5658 // At least one map clause must appear on the directive.
5659 if (!HasMapClause(Clauses)) {
5660 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5661 << getOpenMPDirectiveName(OMPD_target_exit_data);
5662 return StmtError();
5663 }
5664
5665 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
5666}
5667
Samuel Antao686c70c2016-05-26 17:30:50 +00005668StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
5669 SourceLocation StartLoc,
5670 SourceLocation EndLoc) {
Samuel Antao686c70c2016-05-26 17:30:50 +00005671 bool seenMotionClause = false;
Samuel Antao661c0902016-05-26 17:39:58 +00005672 for (auto *C : Clauses) {
Samuel Antaoec172c62016-05-26 17:49:04 +00005673 if (C->getClauseKind() == OMPC_to || C->getClauseKind() == OMPC_from)
Samuel Antao661c0902016-05-26 17:39:58 +00005674 seenMotionClause = true;
5675 }
Samuel Antao686c70c2016-05-26 17:30:50 +00005676 if (!seenMotionClause) {
5677 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
5678 return StmtError();
5679 }
5680 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses);
5681}
5682
Alexey Bataev13314bf2014-10-09 04:18:56 +00005683StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
5684 Stmt *AStmt, SourceLocation StartLoc,
5685 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005686 if (!AStmt)
5687 return StmtError();
5688
Alexey Bataev13314bf2014-10-09 04:18:56 +00005689 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5690 // 1.2.2 OpenMP Language Terminology
5691 // Structured block - An executable statement with a single entry at the
5692 // top and a single exit at the bottom.
5693 // The point of exit cannot be a branch out of the structured block.
5694 // longjmp() and throw() must not violate the entry/exit criteria.
5695 CS->getCapturedDecl()->setNothrow();
5696
5697 getCurFunction()->setHasBranchProtectedScope();
5698
5699 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5700}
5701
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005702StmtResult
5703Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
5704 SourceLocation EndLoc,
5705 OpenMPDirectiveKind CancelRegion) {
5706 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5707 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5708 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5709 << getOpenMPDirectiveName(CancelRegion);
5710 return StmtError();
5711 }
5712 if (DSAStack->isParentNowaitRegion()) {
5713 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
5714 return StmtError();
5715 }
5716 if (DSAStack->isParentOrderedRegion()) {
5717 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
5718 return StmtError();
5719 }
5720 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
5721 CancelRegion);
5722}
5723
Alexey Bataev87933c72015-09-18 08:07:34 +00005724StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
5725 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00005726 SourceLocation EndLoc,
5727 OpenMPDirectiveKind CancelRegion) {
5728 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5729 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5730 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5731 << getOpenMPDirectiveName(CancelRegion);
5732 return StmtError();
5733 }
5734 if (DSAStack->isParentNowaitRegion()) {
5735 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
5736 return StmtError();
5737 }
5738 if (DSAStack->isParentOrderedRegion()) {
5739 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
5740 return StmtError();
5741 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005742 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00005743 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5744 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00005745}
5746
Alexey Bataev382967a2015-12-08 12:06:20 +00005747static bool checkGrainsizeNumTasksClauses(Sema &S,
5748 ArrayRef<OMPClause *> Clauses) {
5749 OMPClause *PrevClause = nullptr;
5750 bool ErrorFound = false;
5751 for (auto *C : Clauses) {
5752 if (C->getClauseKind() == OMPC_grainsize ||
5753 C->getClauseKind() == OMPC_num_tasks) {
5754 if (!PrevClause)
5755 PrevClause = C;
5756 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
5757 S.Diag(C->getLocStart(),
5758 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
5759 << getOpenMPClauseName(C->getClauseKind())
5760 << getOpenMPClauseName(PrevClause->getClauseKind());
5761 S.Diag(PrevClause->getLocStart(),
5762 diag::note_omp_previous_grainsize_num_tasks)
5763 << getOpenMPClauseName(PrevClause->getClauseKind());
5764 ErrorFound = true;
5765 }
5766 }
5767 }
5768 return ErrorFound;
5769}
5770
Alexey Bataev49f6e782015-12-01 04:18:41 +00005771StmtResult Sema::ActOnOpenMPTaskLoopDirective(
5772 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5773 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005774 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00005775 if (!AStmt)
5776 return StmtError();
5777
5778 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5779 OMPLoopDirective::HelperExprs B;
5780 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5781 // define the nested loops number.
5782 unsigned NestedLoopCount =
5783 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005784 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00005785 VarsWithImplicitDSA, B);
5786 if (NestedLoopCount == 0)
5787 return StmtError();
5788
5789 assert((CurContext->isDependentContext() || B.builtAll()) &&
5790 "omp for loop exprs were not built");
5791
Alexey Bataev382967a2015-12-08 12:06:20 +00005792 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5793 // The grainsize clause and num_tasks clause are mutually exclusive and may
5794 // not appear on the same taskloop directive.
5795 if (checkGrainsizeNumTasksClauses(*this, Clauses))
5796 return StmtError();
5797
Alexey Bataev49f6e782015-12-01 04:18:41 +00005798 getCurFunction()->setHasBranchProtectedScope();
5799 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
5800 NestedLoopCount, Clauses, AStmt, B);
5801}
5802
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005803StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
5804 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5805 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005806 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005807 if (!AStmt)
5808 return StmtError();
5809
5810 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5811 OMPLoopDirective::HelperExprs B;
5812 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5813 // define the nested loops number.
5814 unsigned NestedLoopCount =
5815 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
5816 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
5817 VarsWithImplicitDSA, B);
5818 if (NestedLoopCount == 0)
5819 return StmtError();
5820
5821 assert((CurContext->isDependentContext() || B.builtAll()) &&
5822 "omp for loop exprs were not built");
5823
Alexey Bataev5a3af132016-03-29 08:58:54 +00005824 if (!CurContext->isDependentContext()) {
5825 // Finalize the clauses that need pre-built expressions for CodeGen.
5826 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005827 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00005828 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005829 B.NumIterations, *this, CurScope,
5830 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00005831 return StmtError();
5832 }
5833 }
5834
Alexey Bataev382967a2015-12-08 12:06:20 +00005835 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5836 // The grainsize clause and num_tasks clause are mutually exclusive and may
5837 // not appear on the same taskloop directive.
5838 if (checkGrainsizeNumTasksClauses(*this, Clauses))
5839 return StmtError();
5840
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005841 getCurFunction()->setHasBranchProtectedScope();
5842 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
5843 NestedLoopCount, Clauses, AStmt, B);
5844}
5845
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005846StmtResult Sema::ActOnOpenMPDistributeDirective(
5847 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5848 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005849 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005850 if (!AStmt)
5851 return StmtError();
5852
5853 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5854 OMPLoopDirective::HelperExprs B;
5855 // In presence of clause 'collapse' with number of loops, it will
5856 // define the nested loops number.
5857 unsigned NestedLoopCount =
5858 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
5859 nullptr /*ordered not a clause on distribute*/, AStmt,
5860 *this, *DSAStack, VarsWithImplicitDSA, B);
5861 if (NestedLoopCount == 0)
5862 return StmtError();
5863
5864 assert((CurContext->isDependentContext() || B.builtAll()) &&
5865 "omp for loop exprs were not built");
5866
5867 getCurFunction()->setHasBranchProtectedScope();
5868 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
5869 NestedLoopCount, Clauses, AStmt, B);
5870}
5871
Carlo Bertolli9925f152016-06-27 14:55:37 +00005872StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
5873 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5874 SourceLocation EndLoc,
5875 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5876 if (!AStmt)
5877 return StmtError();
5878
5879 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5880 // 1.2.2 OpenMP Language Terminology
5881 // Structured block - An executable statement with a single entry at the
5882 // top and a single exit at the bottom.
5883 // The point of exit cannot be a branch out of the structured block.
5884 // longjmp() and throw() must not violate the entry/exit criteria.
5885 CS->getCapturedDecl()->setNothrow();
5886
5887 OMPLoopDirective::HelperExprs B;
5888 // In presence of clause 'collapse' with number of loops, it will
5889 // define the nested loops number.
5890 unsigned NestedLoopCount = CheckOpenMPLoop(
5891 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
5892 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
5893 VarsWithImplicitDSA, B);
5894 if (NestedLoopCount == 0)
5895 return StmtError();
5896
5897 assert((CurContext->isDependentContext() || B.builtAll()) &&
5898 "omp for loop exprs were not built");
5899
5900 getCurFunction()->setHasBranchProtectedScope();
5901 return OMPDistributeParallelForDirective::Create(
5902 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
5903}
5904
Kelvin Li4a39add2016-07-05 05:00:15 +00005905StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
5906 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5907 SourceLocation EndLoc,
5908 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5909 if (!AStmt)
5910 return StmtError();
5911
5912 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5913 // 1.2.2 OpenMP Language Terminology
5914 // Structured block - An executable statement with a single entry at the
5915 // top and a single exit at the bottom.
5916 // The point of exit cannot be a branch out of the structured block.
5917 // longjmp() and throw() must not violate the entry/exit criteria.
5918 CS->getCapturedDecl()->setNothrow();
5919
5920 OMPLoopDirective::HelperExprs B;
5921 // In presence of clause 'collapse' with number of loops, it will
5922 // define the nested loops number.
5923 unsigned NestedLoopCount = CheckOpenMPLoop(
5924 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
5925 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
5926 VarsWithImplicitDSA, B);
5927 if (NestedLoopCount == 0)
5928 return StmtError();
5929
5930 assert((CurContext->isDependentContext() || B.builtAll()) &&
5931 "omp for loop exprs were not built");
5932
Kelvin Lic5609492016-07-15 04:39:07 +00005933 if (checkSimdlenSafelenSpecified(*this, Clauses))
5934 return StmtError();
5935
Kelvin Li4a39add2016-07-05 05:00:15 +00005936 getCurFunction()->setHasBranchProtectedScope();
5937 return OMPDistributeParallelForSimdDirective::Create(
5938 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
5939}
5940
Kelvin Li787f3fc2016-07-06 04:45:38 +00005941StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
5942 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5943 SourceLocation EndLoc,
5944 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5945 if (!AStmt)
5946 return StmtError();
5947
5948 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5949 // 1.2.2 OpenMP Language Terminology
5950 // Structured block - An executable statement with a single entry at the
5951 // top and a single exit at the bottom.
5952 // The point of exit cannot be a branch out of the structured block.
5953 // longjmp() and throw() must not violate the entry/exit criteria.
5954 CS->getCapturedDecl()->setNothrow();
5955
5956 OMPLoopDirective::HelperExprs B;
5957 // In presence of clause 'collapse' with number of loops, it will
5958 // define the nested loops number.
5959 unsigned NestedLoopCount =
5960 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
5961 nullptr /*ordered not a clause on distribute*/, AStmt,
5962 *this, *DSAStack, VarsWithImplicitDSA, B);
5963 if (NestedLoopCount == 0)
5964 return StmtError();
5965
5966 assert((CurContext->isDependentContext() || B.builtAll()) &&
5967 "omp for loop exprs were not built");
5968
Kelvin Lic5609492016-07-15 04:39:07 +00005969 if (checkSimdlenSafelenSpecified(*this, Clauses))
5970 return StmtError();
5971
Kelvin Li787f3fc2016-07-06 04:45:38 +00005972 getCurFunction()->setHasBranchProtectedScope();
5973 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
5974 NestedLoopCount, Clauses, AStmt, B);
5975}
5976
Kelvin Lia579b912016-07-14 02:54:56 +00005977StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
5978 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5979 SourceLocation EndLoc,
5980 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5981 if (!AStmt)
5982 return StmtError();
5983
5984 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5985 // 1.2.2 OpenMP Language Terminology
5986 // Structured block - An executable statement with a single entry at the
5987 // top and a single exit at the bottom.
5988 // The point of exit cannot be a branch out of the structured block.
5989 // longjmp() and throw() must not violate the entry/exit criteria.
5990 CS->getCapturedDecl()->setNothrow();
5991
5992 OMPLoopDirective::HelperExprs B;
5993 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5994 // define the nested loops number.
5995 unsigned NestedLoopCount = CheckOpenMPLoop(
5996 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
5997 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5998 VarsWithImplicitDSA, B);
5999 if (NestedLoopCount == 0)
6000 return StmtError();
6001
6002 assert((CurContext->isDependentContext() || B.builtAll()) &&
6003 "omp target parallel for simd loop exprs were not built");
6004
6005 if (!CurContext->isDependentContext()) {
6006 // Finalize the clauses that need pre-built expressions for CodeGen.
6007 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006008 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00006009 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6010 B.NumIterations, *this, CurScope,
6011 DSAStack))
6012 return StmtError();
6013 }
6014 }
Kelvin Lic5609492016-07-15 04:39:07 +00006015 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00006016 return StmtError();
6017
6018 getCurFunction()->setHasBranchProtectedScope();
6019 return OMPTargetParallelForSimdDirective::Create(
6020 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6021}
6022
Kelvin Li986330c2016-07-20 22:57:10 +00006023StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6024 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6025 SourceLocation EndLoc,
6026 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6027 if (!AStmt)
6028 return StmtError();
6029
6030 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6031 // 1.2.2 OpenMP Language Terminology
6032 // Structured block - An executable statement with a single entry at the
6033 // top and a single exit at the bottom.
6034 // The point of exit cannot be a branch out of the structured block.
6035 // longjmp() and throw() must not violate the entry/exit criteria.
6036 CS->getCapturedDecl()->setNothrow();
6037
6038 OMPLoopDirective::HelperExprs B;
6039 // In presence of clause 'collapse' with number of loops, it will define the
6040 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00006041 unsigned NestedLoopCount =
Kelvin Li986330c2016-07-20 22:57:10 +00006042 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
6043 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6044 VarsWithImplicitDSA, B);
6045 if (NestedLoopCount == 0)
6046 return StmtError();
6047
6048 assert((CurContext->isDependentContext() || B.builtAll()) &&
6049 "omp target simd loop exprs were not built");
6050
6051 if (!CurContext->isDependentContext()) {
6052 // Finalize the clauses that need pre-built expressions for CodeGen.
6053 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006054 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00006055 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6056 B.NumIterations, *this, CurScope,
6057 DSAStack))
6058 return StmtError();
6059 }
6060 }
6061
6062 if (checkSimdlenSafelenSpecified(*this, Clauses))
6063 return StmtError();
6064
6065 getCurFunction()->setHasBranchProtectedScope();
6066 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
6067 NestedLoopCount, Clauses, AStmt, B);
6068}
6069
Kelvin Li02532872016-08-05 14:37:37 +00006070StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
6071 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6072 SourceLocation EndLoc,
6073 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6074 if (!AStmt)
6075 return StmtError();
6076
6077 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6078 // 1.2.2 OpenMP Language Terminology
6079 // Structured block - An executable statement with a single entry at the
6080 // top and a single exit at the bottom.
6081 // The point of exit cannot be a branch out of the structured block.
6082 // longjmp() and throw() must not violate the entry/exit criteria.
6083 CS->getCapturedDecl()->setNothrow();
6084
6085 OMPLoopDirective::HelperExprs B;
6086 // In presence of clause 'collapse' with number of loops, it will
6087 // define the nested loops number.
6088 unsigned NestedLoopCount =
6089 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
6090 nullptr /*ordered not a clause on distribute*/, AStmt,
6091 *this, *DSAStack, VarsWithImplicitDSA, B);
6092 if (NestedLoopCount == 0)
6093 return StmtError();
6094
6095 assert((CurContext->isDependentContext() || B.builtAll()) &&
6096 "omp teams distribute loop exprs were not built");
6097
6098 getCurFunction()->setHasBranchProtectedScope();
David Majnemer9d168222016-08-05 17:44:54 +00006099 return OMPTeamsDistributeDirective::Create(
6100 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00006101}
6102
Kelvin Li4e325f72016-10-25 12:50:55 +00006103StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
6104 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6105 SourceLocation EndLoc,
6106 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6107 if (!AStmt)
6108 return StmtError();
6109
6110 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6111 // 1.2.2 OpenMP Language Terminology
6112 // Structured block - An executable statement with a single entry at the
6113 // top and a single exit at the bottom.
6114 // The point of exit cannot be a branch out of the structured block.
6115 // longjmp() and throw() must not violate the entry/exit criteria.
6116 CS->getCapturedDecl()->setNothrow();
6117
6118 OMPLoopDirective::HelperExprs B;
6119 // In presence of clause 'collapse' with number of loops, it will
6120 // define the nested loops number.
6121 unsigned NestedLoopCount =
6122 CheckOpenMPLoop(OMPD_teams_distribute_simd,
6123 getCollapseNumberExpr(Clauses),
6124 nullptr /*ordered not a clause on distribute*/, AStmt,
6125 *this, *DSAStack, VarsWithImplicitDSA, B);
6126
6127 if (NestedLoopCount == 0)
6128 return StmtError();
6129
6130 assert((CurContext->isDependentContext() || B.builtAll()) &&
6131 "omp teams distribute simd loop exprs were not built");
6132
6133 if (!CurContext->isDependentContext()) {
6134 // Finalize the clauses that need pre-built expressions for CodeGen.
6135 for (auto C : Clauses) {
6136 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6137 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6138 B.NumIterations, *this, CurScope,
6139 DSAStack))
6140 return StmtError();
6141 }
6142 }
6143
6144 if (checkSimdlenSafelenSpecified(*this, Clauses))
6145 return StmtError();
6146
6147 getCurFunction()->setHasBranchProtectedScope();
6148 return OMPTeamsDistributeSimdDirective::Create(
6149 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6150}
6151
Kelvin Li579e41c2016-11-30 23:51:03 +00006152StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6153 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6154 SourceLocation EndLoc,
6155 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6156 if (!AStmt)
6157 return StmtError();
6158
6159 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6160 // 1.2.2 OpenMP Language Terminology
6161 // Structured block - An executable statement with a single entry at the
6162 // top and a single exit at the bottom.
6163 // The point of exit cannot be a branch out of the structured block.
6164 // longjmp() and throw() must not violate the entry/exit criteria.
6165 CS->getCapturedDecl()->setNothrow();
6166
6167 OMPLoopDirective::HelperExprs B;
6168 // In presence of clause 'collapse' with number of loops, it will
6169 // define the nested loops number.
6170 auto NestedLoopCount = CheckOpenMPLoop(
6171 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6172 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6173 VarsWithImplicitDSA, B);
6174
6175 if (NestedLoopCount == 0)
6176 return StmtError();
6177
6178 assert((CurContext->isDependentContext() || B.builtAll()) &&
6179 "omp for loop exprs were not built");
6180
6181 if (!CurContext->isDependentContext()) {
6182 // Finalize the clauses that need pre-built expressions for CodeGen.
6183 for (auto C : Clauses) {
6184 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6185 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6186 B.NumIterations, *this, CurScope,
6187 DSAStack))
6188 return StmtError();
6189 }
6190 }
6191
6192 if (checkSimdlenSafelenSpecified(*this, Clauses))
6193 return StmtError();
6194
6195 getCurFunction()->setHasBranchProtectedScope();
6196 return OMPTeamsDistributeParallelForSimdDirective::Create(
6197 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6198}
6199
Alexey Bataeved09d242014-05-28 05:53:51 +00006200OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006201 SourceLocation StartLoc,
6202 SourceLocation LParenLoc,
6203 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006204 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006205 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00006206 case OMPC_final:
6207 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
6208 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00006209 case OMPC_num_threads:
6210 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
6211 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006212 case OMPC_safelen:
6213 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
6214 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00006215 case OMPC_simdlen:
6216 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
6217 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00006218 case OMPC_collapse:
6219 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
6220 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006221 case OMPC_ordered:
6222 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
6223 break;
Michael Wonge710d542015-08-07 16:16:36 +00006224 case OMPC_device:
6225 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
6226 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00006227 case OMPC_num_teams:
6228 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
6229 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006230 case OMPC_thread_limit:
6231 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
6232 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00006233 case OMPC_priority:
6234 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
6235 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006236 case OMPC_grainsize:
6237 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
6238 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00006239 case OMPC_num_tasks:
6240 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
6241 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00006242 case OMPC_hint:
6243 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
6244 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006245 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006246 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006247 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006248 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006249 case OMPC_private:
6250 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00006251 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006252 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00006253 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00006254 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006255 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006256 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006257 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00006258 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006259 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006260 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006261 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006262 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006263 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006264 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006265 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006266 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006267 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006268 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00006269 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006270 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006271 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00006272 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00006273 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006274 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006275 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006276 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006277 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006278 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006279 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006280 case OMPC_is_device_ptr:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006281 llvm_unreachable("Clause is not allowed.");
6282 }
6283 return Res;
6284}
6285
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006286OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
6287 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006288 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006289 SourceLocation NameModifierLoc,
6290 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006291 SourceLocation EndLoc) {
6292 Expr *ValExpr = Condition;
6293 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6294 !Condition->isInstantiationDependent() &&
6295 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00006296 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006297 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006298 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006299
Richard Smith03a4aa32016-06-23 19:02:52 +00006300 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006301 }
6302
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006303 return new (Context) OMPIfClause(NameModifier, ValExpr, StartLoc, LParenLoc,
6304 NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006305}
6306
Alexey Bataev3778b602014-07-17 07:32:53 +00006307OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
6308 SourceLocation StartLoc,
6309 SourceLocation LParenLoc,
6310 SourceLocation EndLoc) {
6311 Expr *ValExpr = Condition;
6312 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6313 !Condition->isInstantiationDependent() &&
6314 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00006315 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00006316 if (Val.isInvalid())
6317 return nullptr;
6318
Richard Smith03a4aa32016-06-23 19:02:52 +00006319 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00006320 }
6321
6322 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
6323}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006324ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
6325 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00006326 if (!Op)
6327 return ExprError();
6328
6329 class IntConvertDiagnoser : public ICEConvertDiagnoser {
6330 public:
6331 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00006332 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00006333 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
6334 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006335 return S.Diag(Loc, diag::err_omp_not_integral) << T;
6336 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006337 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
6338 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006339 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
6340 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006341 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
6342 QualType T,
6343 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006344 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
6345 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006346 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
6347 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006348 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00006349 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00006350 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006351 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
6352 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006353 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
6354 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006355 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
6356 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006357 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00006358 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00006359 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006360 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
6361 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006362 llvm_unreachable("conversion functions are permitted");
6363 }
6364 } ConvertDiagnoser;
6365 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
6366}
6367
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006368static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00006369 OpenMPClauseKind CKind,
6370 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006371 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
6372 !ValExpr->isInstantiationDependent()) {
6373 SourceLocation Loc = ValExpr->getExprLoc();
6374 ExprResult Value =
6375 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
6376 if (Value.isInvalid())
6377 return false;
6378
6379 ValExpr = Value.get();
6380 // The expression must evaluate to a non-negative integer value.
6381 llvm::APSInt Result;
6382 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00006383 Result.isSigned() &&
6384 !((!StrictlyPositive && Result.isNonNegative()) ||
6385 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006386 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00006387 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
6388 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006389 return false;
6390 }
6391 }
6392 return true;
6393}
6394
Alexey Bataev568a8332014-03-06 06:15:19 +00006395OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
6396 SourceLocation StartLoc,
6397 SourceLocation LParenLoc,
6398 SourceLocation EndLoc) {
6399 Expr *ValExpr = NumThreads;
Alexey Bataev568a8332014-03-06 06:15:19 +00006400
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006401 // OpenMP [2.5, Restrictions]
6402 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00006403 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
6404 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006405 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00006406
Alexey Bataeved09d242014-05-28 05:53:51 +00006407 return new (Context)
6408 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00006409}
6410
Alexey Bataev62c87d22014-03-21 04:51:18 +00006411ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006412 OpenMPClauseKind CKind,
6413 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00006414 if (!E)
6415 return ExprError();
6416 if (E->isValueDependent() || E->isTypeDependent() ||
6417 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006418 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006419 llvm::APSInt Result;
6420 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
6421 if (ICE.isInvalid())
6422 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006423 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
6424 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00006425 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006426 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
6427 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00006428 return ExprError();
6429 }
Alexander Musman09184fe2014-09-30 05:29:28 +00006430 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
6431 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
6432 << E->getSourceRange();
6433 return ExprError();
6434 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006435 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
6436 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00006437 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006438 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00006439 return ICE;
6440}
6441
6442OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
6443 SourceLocation LParenLoc,
6444 SourceLocation EndLoc) {
6445 // OpenMP [2.8.1, simd construct, Description]
6446 // The parameter of the safelen clause must be a constant
6447 // positive integer expression.
6448 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
6449 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006450 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006451 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006452 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00006453}
6454
Alexey Bataev66b15b52015-08-21 11:14:16 +00006455OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
6456 SourceLocation LParenLoc,
6457 SourceLocation EndLoc) {
6458 // OpenMP [2.8.1, simd construct, Description]
6459 // The parameter of the simdlen clause must be a constant
6460 // positive integer expression.
6461 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
6462 if (Simdlen.isInvalid())
6463 return nullptr;
6464 return new (Context)
6465 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
6466}
6467
Alexander Musman64d33f12014-06-04 07:53:32 +00006468OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
6469 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00006470 SourceLocation LParenLoc,
6471 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00006472 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00006473 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00006474 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00006475 // The parameter of the collapse clause must be a constant
6476 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00006477 ExprResult NumForLoopsResult =
6478 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
6479 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00006480 return nullptr;
6481 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00006482 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00006483}
6484
Alexey Bataev10e775f2015-07-30 11:36:16 +00006485OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
6486 SourceLocation EndLoc,
6487 SourceLocation LParenLoc,
6488 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00006489 // OpenMP [2.7.1, loop construct, Description]
6490 // OpenMP [2.8.1, simd construct, Description]
6491 // OpenMP [2.9.6, distribute construct, Description]
6492 // The parameter of the ordered clause must be a constant
6493 // positive integer expression if any.
6494 if (NumForLoops && LParenLoc.isValid()) {
6495 ExprResult NumForLoopsResult =
6496 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
6497 if (NumForLoopsResult.isInvalid())
6498 return nullptr;
6499 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00006500 } else
6501 NumForLoops = nullptr;
6502 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00006503 return new (Context)
6504 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
6505}
6506
Alexey Bataeved09d242014-05-28 05:53:51 +00006507OMPClause *Sema::ActOnOpenMPSimpleClause(
6508 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
6509 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006510 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006511 switch (Kind) {
6512 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00006513 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00006514 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
6515 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006516 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006517 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00006518 Res = ActOnOpenMPProcBindClause(
6519 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
6520 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006521 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006522 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00006523 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00006524 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00006525 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00006526 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00006527 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006528 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006529 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006530 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00006531 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00006532 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00006533 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00006534 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006535 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006536 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006537 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006538 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00006539 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006540 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006541 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006542 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006543 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006544 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006545 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006546 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006547 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006548 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006549 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00006550 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00006551 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006552 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006553 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00006554 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006555 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00006556 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006557 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00006558 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00006559 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00006560 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00006561 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006562 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006563 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006564 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006565 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006566 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006567 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006568 case OMPC_is_device_ptr:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006569 llvm_unreachable("Clause is not allowed.");
6570 }
6571 return Res;
6572}
6573
Alexey Bataev6402bca2015-12-28 07:25:51 +00006574static std::string
6575getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
6576 ArrayRef<unsigned> Exclude = llvm::None) {
6577 std::string Values;
6578 unsigned Bound = Last >= 2 ? Last - 2 : 0;
6579 unsigned Skipped = Exclude.size();
6580 auto S = Exclude.begin(), E = Exclude.end();
6581 for (unsigned i = First; i < Last; ++i) {
6582 if (std::find(S, E, i) != E) {
6583 --Skipped;
6584 continue;
6585 }
6586 Values += "'";
6587 Values += getOpenMPSimpleClauseTypeName(K, i);
6588 Values += "'";
6589 if (i == Bound - Skipped)
6590 Values += " or ";
6591 else if (i != Bound + 1 - Skipped)
6592 Values += ", ";
6593 }
6594 return Values;
6595}
6596
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006597OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
6598 SourceLocation KindKwLoc,
6599 SourceLocation StartLoc,
6600 SourceLocation LParenLoc,
6601 SourceLocation EndLoc) {
6602 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00006603 static_assert(OMPC_DEFAULT_unknown > 0,
6604 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006605 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00006606 << getListOfPossibleValues(OMPC_default, /*First=*/0,
6607 /*Last=*/OMPC_DEFAULT_unknown)
6608 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006609 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006610 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00006611 switch (Kind) {
6612 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006613 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00006614 break;
6615 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006616 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00006617 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006618 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006619 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00006620 break;
6621 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006622 return new (Context)
6623 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006624}
6625
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006626OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
6627 SourceLocation KindKwLoc,
6628 SourceLocation StartLoc,
6629 SourceLocation LParenLoc,
6630 SourceLocation EndLoc) {
6631 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006632 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00006633 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
6634 /*Last=*/OMPC_PROC_BIND_unknown)
6635 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006636 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006637 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006638 return new (Context)
6639 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006640}
6641
Alexey Bataev56dafe82014-06-20 07:16:17 +00006642OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00006643 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00006644 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00006645 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00006646 SourceLocation EndLoc) {
6647 OMPClause *Res = nullptr;
6648 switch (Kind) {
6649 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00006650 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
6651 assert(Argument.size() == NumberOfElements &&
6652 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00006653 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00006654 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
6655 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
6656 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
6657 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
6658 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00006659 break;
6660 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00006661 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
6662 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
6663 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
6664 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006665 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00006666 case OMPC_dist_schedule:
6667 Res = ActOnOpenMPDistScheduleClause(
6668 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
6669 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
6670 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006671 case OMPC_defaultmap:
6672 enum { Modifier, DefaultmapKind };
6673 Res = ActOnOpenMPDefaultmapClause(
6674 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
6675 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00006676 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
6677 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006678 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00006679 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006680 case OMPC_num_threads:
6681 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00006682 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006683 case OMPC_collapse:
6684 case OMPC_default:
6685 case OMPC_proc_bind:
6686 case OMPC_private:
6687 case OMPC_firstprivate:
6688 case OMPC_lastprivate:
6689 case OMPC_shared:
6690 case OMPC_reduction:
6691 case OMPC_linear:
6692 case OMPC_aligned:
6693 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006694 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006695 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00006696 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006697 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006698 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006699 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006700 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006701 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006702 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006703 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006704 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006705 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006706 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00006707 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00006708 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006709 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006710 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00006711 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006712 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00006713 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006714 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00006715 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00006716 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00006717 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006718 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006719 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006720 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006721 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006722 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006723 case OMPC_is_device_ptr:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006724 llvm_unreachable("Clause is not allowed.");
6725 }
6726 return Res;
6727}
6728
Alexey Bataev6402bca2015-12-28 07:25:51 +00006729static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
6730 OpenMPScheduleClauseModifier M2,
6731 SourceLocation M1Loc, SourceLocation M2Loc) {
6732 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
6733 SmallVector<unsigned, 2> Excluded;
6734 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
6735 Excluded.push_back(M2);
6736 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
6737 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
6738 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
6739 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
6740 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
6741 << getListOfPossibleValues(OMPC_schedule,
6742 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
6743 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
6744 Excluded)
6745 << getOpenMPClauseName(OMPC_schedule);
6746 return true;
6747 }
6748 return false;
6749}
6750
Alexey Bataev56dafe82014-06-20 07:16:17 +00006751OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00006752 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00006753 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00006754 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
6755 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
6756 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
6757 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
6758 return nullptr;
6759 // OpenMP, 2.7.1, Loop Construct, Restrictions
6760 // Either the monotonic modifier or the nonmonotonic modifier can be specified
6761 // but not both.
6762 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
6763 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
6764 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
6765 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
6766 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
6767 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
6768 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
6769 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
6770 return nullptr;
6771 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00006772 if (Kind == OMPC_SCHEDULE_unknown) {
6773 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00006774 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
6775 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
6776 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
6777 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
6778 Exclude);
6779 } else {
6780 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
6781 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00006782 }
6783 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
6784 << Values << getOpenMPClauseName(OMPC_schedule);
6785 return nullptr;
6786 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00006787 // OpenMP, 2.7.1, Loop Construct, Restrictions
6788 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
6789 // schedule(guided).
6790 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
6791 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
6792 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
6793 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
6794 diag::err_omp_schedule_nonmonotonic_static);
6795 return nullptr;
6796 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00006797 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00006798 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00006799 if (ChunkSize) {
6800 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
6801 !ChunkSize->isInstantiationDependent() &&
6802 !ChunkSize->containsUnexpandedParameterPack()) {
6803 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
6804 ExprResult Val =
6805 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
6806 if (Val.isInvalid())
6807 return nullptr;
6808
6809 ValExpr = Val.get();
6810
6811 // OpenMP [2.7.1, Restrictions]
6812 // chunk_size must be a loop invariant integer expression with a positive
6813 // value.
6814 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00006815 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
6816 if (Result.isSigned() && !Result.isStrictlyPositive()) {
6817 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00006818 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00006819 return nullptr;
6820 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +00006821 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
6822 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00006823 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
6824 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
6825 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00006826 }
6827 }
6828 }
6829
Alexey Bataev6402bca2015-12-28 07:25:51 +00006830 return new (Context)
6831 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00006832 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00006833}
6834
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006835OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
6836 SourceLocation StartLoc,
6837 SourceLocation EndLoc) {
6838 OMPClause *Res = nullptr;
6839 switch (Kind) {
6840 case OMPC_ordered:
6841 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
6842 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00006843 case OMPC_nowait:
6844 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
6845 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006846 case OMPC_untied:
6847 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
6848 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006849 case OMPC_mergeable:
6850 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
6851 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006852 case OMPC_read:
6853 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
6854 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00006855 case OMPC_write:
6856 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
6857 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00006858 case OMPC_update:
6859 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
6860 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00006861 case OMPC_capture:
6862 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
6863 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006864 case OMPC_seq_cst:
6865 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
6866 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00006867 case OMPC_threads:
6868 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
6869 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006870 case OMPC_simd:
6871 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
6872 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00006873 case OMPC_nogroup:
6874 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
6875 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006876 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00006877 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006878 case OMPC_num_threads:
6879 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00006880 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006881 case OMPC_collapse:
6882 case OMPC_schedule:
6883 case OMPC_private:
6884 case OMPC_firstprivate:
6885 case OMPC_lastprivate:
6886 case OMPC_shared:
6887 case OMPC_reduction:
6888 case OMPC_linear:
6889 case OMPC_aligned:
6890 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006891 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006892 case OMPC_default:
6893 case OMPC_proc_bind:
6894 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006895 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006896 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00006897 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006898 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00006899 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006900 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00006901 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006902 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00006903 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00006904 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00006905 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006906 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006907 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006908 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006909 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006910 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006911 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006912 case OMPC_is_device_ptr:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006913 llvm_unreachable("Clause is not allowed.");
6914 }
6915 return Res;
6916}
6917
Alexey Bataev236070f2014-06-20 11:19:47 +00006918OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
6919 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006920 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00006921 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
6922}
6923
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006924OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
6925 SourceLocation EndLoc) {
6926 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
6927}
6928
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006929OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
6930 SourceLocation EndLoc) {
6931 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
6932}
6933
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006934OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
6935 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006936 return new (Context) OMPReadClause(StartLoc, EndLoc);
6937}
6938
Alexey Bataevdea47612014-07-23 07:46:59 +00006939OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
6940 SourceLocation EndLoc) {
6941 return new (Context) OMPWriteClause(StartLoc, EndLoc);
6942}
6943
Alexey Bataev67a4f222014-07-23 10:25:33 +00006944OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
6945 SourceLocation EndLoc) {
6946 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
6947}
6948
Alexey Bataev459dec02014-07-24 06:46:57 +00006949OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
6950 SourceLocation EndLoc) {
6951 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
6952}
6953
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006954OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
6955 SourceLocation EndLoc) {
6956 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
6957}
6958
Alexey Bataev346265e2015-09-25 10:37:12 +00006959OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
6960 SourceLocation EndLoc) {
6961 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
6962}
6963
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006964OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
6965 SourceLocation EndLoc) {
6966 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
6967}
6968
Alexey Bataevb825de12015-12-07 10:51:44 +00006969OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
6970 SourceLocation EndLoc) {
6971 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
6972}
6973
Alexey Bataevc5e02582014-06-16 07:08:35 +00006974OMPClause *Sema::ActOnOpenMPVarListClause(
6975 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
6976 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
6977 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006978 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00006979 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
6980 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
6981 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006982 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006983 switch (Kind) {
6984 case OMPC_private:
6985 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
6986 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006987 case OMPC_firstprivate:
6988 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
6989 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00006990 case OMPC_lastprivate:
6991 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
6992 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00006993 case OMPC_shared:
6994 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
6995 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006996 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00006997 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
6998 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00006999 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00007000 case OMPC_linear:
7001 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00007002 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00007003 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007004 case OMPC_aligned:
7005 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
7006 ColonLoc, EndLoc);
7007 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007008 case OMPC_copyin:
7009 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
7010 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00007011 case OMPC_copyprivate:
7012 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7013 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00007014 case OMPC_flush:
7015 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
7016 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007017 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00007018 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00007019 StartLoc, LParenLoc, EndLoc);
7020 break;
7021 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00007022 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
7023 DepLinMapLoc, ColonLoc, VarList, StartLoc,
7024 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007025 break;
Samuel Antao661c0902016-05-26 17:39:58 +00007026 case OMPC_to:
7027 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
7028 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00007029 case OMPC_from:
7030 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
7031 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00007032 case OMPC_use_device_ptr:
7033 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7034 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00007035 case OMPC_is_device_ptr:
7036 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7037 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007038 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007039 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00007040 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00007041 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007042 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00007043 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007044 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007045 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007046 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007047 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007048 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007049 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007050 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007051 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007052 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007053 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007054 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007055 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007056 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00007057 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007058 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007059 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007060 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007061 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007062 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007063 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007064 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007065 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007066 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007067 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007068 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007069 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007070 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007071 llvm_unreachable("Clause is not allowed.");
7072 }
7073 return Res;
7074}
7075
Alexey Bataev90c228f2016-02-08 09:29:13 +00007076ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00007077 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00007078 ExprResult Res = BuildDeclRefExpr(
7079 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
7080 if (!Res.isUsable())
7081 return ExprError();
7082 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
7083 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
7084 if (!Res.isUsable())
7085 return ExprError();
7086 }
7087 if (VK != VK_LValue && Res.get()->isGLValue()) {
7088 Res = DefaultLvalueConversion(Res.get());
7089 if (!Res.isUsable())
7090 return ExprError();
7091 }
7092 return Res;
7093}
7094
Alexey Bataev60da77e2016-02-29 05:54:20 +00007095static std::pair<ValueDecl *, bool>
7096getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
7097 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007098 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
7099 RefExpr->containsUnexpandedParameterPack())
7100 return std::make_pair(nullptr, true);
7101
Alexey Bataevd985eda2016-02-10 11:29:16 +00007102 // OpenMP [3.1, C/C++]
7103 // A list item is a variable name.
7104 // OpenMP [2.9.3.3, Restrictions, p.1]
7105 // A variable that is part of another variable (as an array or
7106 // structure element) cannot appear in a private clause.
7107 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00007108 enum {
7109 NoArrayExpr = -1,
7110 ArraySubscript = 0,
7111 OMPArraySection = 1
7112 } IsArrayExpr = NoArrayExpr;
7113 if (AllowArraySection) {
7114 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
7115 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
7116 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7117 Base = TempASE->getBase()->IgnoreParenImpCasts();
7118 RefExpr = Base;
7119 IsArrayExpr = ArraySubscript;
7120 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
7121 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
7122 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
7123 Base = TempOASE->getBase()->IgnoreParenImpCasts();
7124 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7125 Base = TempASE->getBase()->IgnoreParenImpCasts();
7126 RefExpr = Base;
7127 IsArrayExpr = OMPArraySection;
7128 }
7129 }
7130 ELoc = RefExpr->getExprLoc();
7131 ERange = RefExpr->getSourceRange();
7132 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00007133 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
7134 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
7135 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
7136 (S.getCurrentThisType().isNull() || !ME ||
7137 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
7138 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00007139 if (IsArrayExpr != NoArrayExpr)
7140 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
7141 << ERange;
7142 else {
7143 S.Diag(ELoc,
7144 AllowArraySection
7145 ? diag::err_omp_expected_var_name_member_expr_or_array_item
7146 : diag::err_omp_expected_var_name_member_expr)
7147 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
7148 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007149 return std::make_pair(nullptr, false);
7150 }
7151 return std::make_pair(DE ? DE->getDecl() : ME->getMemberDecl(), false);
7152}
7153
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007154OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
7155 SourceLocation StartLoc,
7156 SourceLocation LParenLoc,
7157 SourceLocation EndLoc) {
7158 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00007159 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00007160 for (auto &RefExpr : VarList) {
7161 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007162 SourceLocation ELoc;
7163 SourceRange ERange;
7164 Expr *SimpleRefExpr = RefExpr;
7165 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007166 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007167 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007168 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007169 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007170 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007171 ValueDecl *D = Res.first;
7172 if (!D)
7173 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007174
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007175 QualType Type = D->getType();
7176 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007177
7178 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7179 // A variable that appears in a private clause must not have an incomplete
7180 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007181 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007182 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007183 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007184
Alexey Bataev758e55e2013-09-06 18:03:48 +00007185 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7186 // in a Construct]
7187 // Variables with the predetermined data-sharing attributes may not be
7188 // listed in data-sharing attributes clauses, except for the cases
7189 // listed below. For these exceptions only, listing a predetermined
7190 // variable in a data-sharing attribute clause is allowed and overrides
7191 // the variable's predetermined data-sharing attributes.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007192 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007193 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00007194 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7195 << getOpenMPClauseName(OMPC_private);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007196 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007197 continue;
7198 }
7199
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007200 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00007201 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00007202 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007203 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7204 << getOpenMPClauseName(OMPC_private) << Type
7205 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7206 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007207 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007208 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007209 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007210 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007211 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007212 continue;
7213 }
7214
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007215 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
7216 // A list item cannot appear in both a map clause and a data-sharing
7217 // attribute clause on the same construct
7218 if (DSAStack->getCurrentDirective() == OMPD_target) {
Samuel Antao6890b092016-07-28 14:25:09 +00007219 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00007220 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00007221 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00007222 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
7223 OpenMPClauseKind WhereFoundClauseKind) -> bool {
7224 ConflictKind = WhereFoundClauseKind;
7225 return true;
7226 })) {
7227 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007228 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00007229 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007230 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7231 ReportOriginalDSA(*this, DSAStack, D, DVar);
7232 continue;
7233 }
7234 }
7235
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007236 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
7237 // A variable of class type (or array thereof) that appears in a private
7238 // clause requires an accessible, unambiguous default constructor for the
7239 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00007240 // Generate helper private variable and initialize it with the default
7241 // value. The address of the original variable is replaced by the address of
7242 // the new private variable in CodeGen. This new variable is not added to
7243 // IdResolver, so the code in the OpenMP region uses original variable for
7244 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007245 Type = Type.getUnqualifiedType();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007246 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7247 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00007248 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007249 if (VDPrivate->isInvalidDecl())
7250 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007251 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007252 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007253
Alexey Bataev90c228f2016-02-08 09:29:13 +00007254 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007255 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00007256 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00007257 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007258 Vars.push_back((VD || CurContext->isDependentContext())
7259 ? RefExpr->IgnoreParens()
7260 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007261 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007262 }
7263
Alexey Bataeved09d242014-05-28 05:53:51 +00007264 if (Vars.empty())
7265 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007266
Alexey Bataev03b340a2014-10-21 03:16:40 +00007267 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
7268 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007269}
7270
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007271namespace {
7272class DiagsUninitializedSeveretyRAII {
7273private:
7274 DiagnosticsEngine &Diags;
7275 SourceLocation SavedLoc;
7276 bool IsIgnored;
7277
7278public:
7279 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
7280 bool IsIgnored)
7281 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
7282 if (!IsIgnored) {
7283 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
7284 /*Map*/ diag::Severity::Ignored, Loc);
7285 }
7286 }
7287 ~DiagsUninitializedSeveretyRAII() {
7288 if (!IsIgnored)
7289 Diags.popMappings(SavedLoc);
7290 }
7291};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007292}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007293
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007294OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
7295 SourceLocation StartLoc,
7296 SourceLocation LParenLoc,
7297 SourceLocation EndLoc) {
7298 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007299 SmallVector<Expr *, 8> PrivateCopies;
7300 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00007301 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007302 bool IsImplicitClause =
7303 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
7304 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
7305
Alexey Bataeved09d242014-05-28 05:53:51 +00007306 for (auto &RefExpr : VarList) {
7307 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007308 SourceLocation ELoc;
7309 SourceRange ERange;
7310 Expr *SimpleRefExpr = RefExpr;
7311 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007312 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007313 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007314 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007315 PrivateCopies.push_back(nullptr);
7316 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007317 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007318 ValueDecl *D = Res.first;
7319 if (!D)
7320 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007321
Alexey Bataev60da77e2016-02-29 05:54:20 +00007322 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00007323 QualType Type = D->getType();
7324 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007325
7326 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7327 // A variable that appears in a private clause must not have an incomplete
7328 // type or a reference type.
7329 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00007330 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007331 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007332 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007333
7334 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
7335 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00007336 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007337 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007338 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007339
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007340 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00007341 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007342 if (!IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007343 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev005248a2016-02-25 05:25:57 +00007344 TopDVar = DVar;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007345 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007346 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
7347 // A list item that specifies a given variable may not appear in more
7348 // than one clause on the same directive, except that a variable may be
7349 // specified in both firstprivate and lastprivate clauses.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007350 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevf29276e2014-06-18 04:14:57 +00007351 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007352 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00007353 << getOpenMPClauseName(DVar.CKind)
7354 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007355 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007356 continue;
7357 }
7358
7359 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7360 // in a Construct]
7361 // Variables with the predetermined data-sharing attributes may not be
7362 // listed in data-sharing attributes clauses, except for the cases
7363 // listed below. For these exceptions only, listing a predetermined
7364 // variable in a data-sharing attribute clause is allowed and overrides
7365 // the variable's predetermined data-sharing attributes.
7366 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7367 // in a Construct, C/C++, p.2]
7368 // Variables with const-qualified type having no mutable member may be
7369 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00007370 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007371 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
7372 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00007373 << getOpenMPClauseName(DVar.CKind)
7374 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007375 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007376 continue;
7377 }
7378
Alexey Bataevf29276e2014-06-18 04:14:57 +00007379 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007380 // OpenMP [2.9.3.4, Restrictions, p.2]
7381 // A list item that is private within a parallel region must not appear
7382 // in a firstprivate clause on a worksharing construct if any of the
7383 // worksharing regions arising from the worksharing construct ever bind
7384 // to any of the parallel regions arising from the parallel construct.
Alexey Bataev549210e2014-06-24 04:39:47 +00007385 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00007386 !isOpenMPParallelDirective(CurrDir) &&
7387 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007388 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007389 if (DVar.CKind != OMPC_shared &&
7390 (isOpenMPParallelDirective(DVar.DKind) ||
7391 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00007392 Diag(ELoc, diag::err_omp_required_access)
7393 << getOpenMPClauseName(OMPC_firstprivate)
7394 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007395 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00007396 continue;
7397 }
7398 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007399 // OpenMP [2.9.3.4, Restrictions, p.3]
7400 // A list item that appears in a reduction clause of a parallel construct
7401 // must not appear in a firstprivate clause on a worksharing or task
7402 // construct if any of the worksharing or task regions arising from the
7403 // worksharing or task construct ever bind to any of the parallel regions
7404 // arising from the parallel construct.
7405 // OpenMP [2.9.3.4, Restrictions, p.4]
7406 // A list item that appears in a reduction clause in worksharing
7407 // construct must not appear in a firstprivate clause in a task construct
7408 // encountered during execution of any of the worksharing regions arising
7409 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00007410 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007411 DVar = DSAStack->hasInnermostDSA(
7412 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
7413 [](OpenMPDirectiveKind K) -> bool {
7414 return isOpenMPParallelDirective(K) ||
7415 isOpenMPWorksharingDirective(K);
7416 },
7417 false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007418 if (DVar.CKind == OMPC_reduction &&
7419 (isOpenMPParallelDirective(DVar.DKind) ||
7420 isOpenMPWorksharingDirective(DVar.DKind))) {
7421 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
7422 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007423 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007424 continue;
7425 }
7426 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007427
7428 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
7429 // A list item that is private within a teams region must not appear in a
7430 // firstprivate clause on a distribute construct if any of the distribute
7431 // regions arising from the distribute construct ever bind to any of the
7432 // teams regions arising from the teams construct.
7433 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
7434 // A list item that appears in a reduction clause of a teams construct
7435 // must not appear in a firstprivate clause on a distribute construct if
7436 // any of the distribute regions arising from the distribute construct
7437 // ever bind to any of the teams regions arising from the teams construct.
7438 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
7439 // A list item may appear in a firstprivate or lastprivate clause but not
7440 // both.
7441 if (CurrDir == OMPD_distribute) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007442 DVar = DSAStack->hasInnermostDSA(
7443 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_private; },
7444 [](OpenMPDirectiveKind K) -> bool {
7445 return isOpenMPTeamsDirective(K);
7446 },
7447 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007448 if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) {
7449 Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007450 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007451 continue;
7452 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007453 DVar = DSAStack->hasInnermostDSA(
7454 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
7455 [](OpenMPDirectiveKind K) -> bool {
7456 return isOpenMPTeamsDirective(K);
7457 },
7458 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007459 if (DVar.CKind == OMPC_reduction &&
7460 isOpenMPTeamsDirective(DVar.DKind)) {
7461 Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007462 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007463 continue;
7464 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007465 DVar = DSAStack->getTopDSA(D, false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007466 if (DVar.CKind == OMPC_lastprivate) {
7467 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007468 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007469 continue;
7470 }
7471 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007472 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
7473 // A list item cannot appear in both a map clause and a data-sharing
7474 // attribute clause on the same construct
7475 if (CurrDir == OMPD_target) {
Samuel Antao6890b092016-07-28 14:25:09 +00007476 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00007477 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00007478 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00007479 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
7480 OpenMPClauseKind WhereFoundClauseKind) -> bool {
7481 ConflictKind = WhereFoundClauseKind;
7482 return true;
7483 })) {
7484 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007485 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +00007486 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007487 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7488 ReportOriginalDSA(*this, DSAStack, D, DVar);
7489 continue;
7490 }
7491 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007492 }
7493
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007494 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00007495 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00007496 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007497 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7498 << getOpenMPClauseName(OMPC_firstprivate) << Type
7499 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7500 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00007501 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007502 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00007503 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007504 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00007505 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007506 continue;
7507 }
7508
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007509 Type = Type.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00007510 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7511 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007512 // Generate helper private variable and initialize it with the value of the
7513 // original variable. The address of the original variable is replaced by
7514 // the address of the new private variable in the CodeGen. This new variable
7515 // is not added to IdResolver, so the code in the OpenMP region uses
7516 // original variable for proper diagnostics and variable capturing.
7517 Expr *VDInitRefExpr = nullptr;
7518 // For arrays generate initializer for single element and replace it by the
7519 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007520 if (Type->isArrayType()) {
7521 auto VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00007522 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007523 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007524 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007525 ElemType = ElemType.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00007526 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007527 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00007528 InitializedEntity Entity =
7529 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007530 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
7531
7532 InitializationSequence InitSeq(*this, Entity, Kind, Init);
7533 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
7534 if (Result.isInvalid())
7535 VDPrivate->setInvalidDecl();
7536 else
7537 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00007538 // Remove temp variable declaration.
7539 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007540 } else {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007541 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
7542 ".firstprivate.temp");
7543 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
7544 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00007545 AddInitializerToDecl(VDPrivate,
7546 DefaultLvalueConversion(VDInitRefExpr).get(),
7547 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007548 }
7549 if (VDPrivate->isInvalidDecl()) {
7550 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007551 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007552 diag::note_omp_task_predetermined_firstprivate_here);
7553 }
7554 continue;
7555 }
7556 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00007557 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00007558 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
7559 RefExpr->getExprLoc());
7560 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007561 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00007562 if (TopDVar.CKind == OMPC_lastprivate)
7563 Ref = TopDVar.PrivateCopy;
7564 else {
Alexey Bataev61205072016-03-02 04:57:40 +00007565 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataev005248a2016-02-25 05:25:57 +00007566 if (!IsOpenMPCapturedDecl(D))
7567 ExprCaptures.push_back(Ref->getDecl());
7568 }
Alexey Bataev417089f2016-02-17 13:19:37 +00007569 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007570 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007571 Vars.push_back((VD || CurContext->isDependentContext())
7572 ? RefExpr->IgnoreParens()
7573 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007574 PrivateCopies.push_back(VDPrivateRefExpr);
7575 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007576 }
7577
Alexey Bataeved09d242014-05-28 05:53:51 +00007578 if (Vars.empty())
7579 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007580
7581 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00007582 Vars, PrivateCopies, Inits,
7583 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007584}
7585
Alexander Musman1bb328c2014-06-04 13:06:39 +00007586OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
7587 SourceLocation StartLoc,
7588 SourceLocation LParenLoc,
7589 SourceLocation EndLoc) {
7590 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00007591 SmallVector<Expr *, 8> SrcExprs;
7592 SmallVector<Expr *, 8> DstExprs;
7593 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00007594 SmallVector<Decl *, 4> ExprCaptures;
7595 SmallVector<Expr *, 4> ExprPostUpdates;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007596 for (auto &RefExpr : VarList) {
7597 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007598 SourceLocation ELoc;
7599 SourceRange ERange;
7600 Expr *SimpleRefExpr = RefExpr;
7601 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00007602 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00007603 // It will be analyzed later.
7604 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00007605 SrcExprs.push_back(nullptr);
7606 DstExprs.push_back(nullptr);
7607 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007608 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00007609 ValueDecl *D = Res.first;
7610 if (!D)
7611 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007612
Alexey Bataev74caaf22016-02-20 04:09:36 +00007613 QualType Type = D->getType();
7614 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007615
7616 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
7617 // A variable that appears in a lastprivate clause must not have an
7618 // incomplete type or a reference type.
7619 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00007620 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00007621 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007622 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00007623
7624 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
7625 // in a Construct]
7626 // Variables with the predetermined data-sharing attributes may not be
7627 // listed in data-sharing attributes clauses, except for the cases
7628 // listed below.
Alexey Bataev74caaf22016-02-20 04:09:36 +00007629 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007630 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
7631 DVar.CKind != OMPC_firstprivate &&
7632 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
7633 Diag(ELoc, diag::err_omp_wrong_dsa)
7634 << getOpenMPClauseName(DVar.CKind)
7635 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev74caaf22016-02-20 04:09:36 +00007636 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007637 continue;
7638 }
7639
Alexey Bataevf29276e2014-06-18 04:14:57 +00007640 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
7641 // OpenMP [2.14.3.5, Restrictions, p.2]
7642 // A list item that is private within a parallel region, or that appears in
7643 // the reduction clause of a parallel construct, must not appear in a
7644 // lastprivate clause on a worksharing construct if any of the corresponding
7645 // worksharing regions ever binds to any of the corresponding parallel
7646 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00007647 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00007648 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00007649 !isOpenMPParallelDirective(CurrDir) &&
7650 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00007651 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00007652 if (DVar.CKind != OMPC_shared) {
7653 Diag(ELoc, diag::err_omp_required_access)
7654 << getOpenMPClauseName(OMPC_lastprivate)
7655 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev74caaf22016-02-20 04:09:36 +00007656 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00007657 continue;
7658 }
7659 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00007660
7661 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
7662 // A list item may appear in a firstprivate or lastprivate clause but not
7663 // both.
7664 if (CurrDir == OMPD_distribute) {
7665 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
7666 if (DVar.CKind == OMPC_firstprivate) {
7667 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
7668 ReportOriginalDSA(*this, DSAStack, D, DVar);
7669 continue;
7670 }
7671 }
7672
Alexander Musman1bb328c2014-06-04 13:06:39 +00007673 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00007674 // A variable of class type (or array thereof) that appears in a
7675 // lastprivate clause requires an accessible, unambiguous default
7676 // constructor for the class type, unless the list item is also specified
7677 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00007678 // A variable of class type (or array thereof) that appears in a
7679 // lastprivate clause requires an accessible, unambiguous copy assignment
7680 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00007681 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00007682 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00007683 Type.getUnqualifiedType(), ".lastprivate.src",
Alexey Bataev74caaf22016-02-20 04:09:36 +00007684 D->hasAttrs() ? &D->getAttrs() : nullptr);
7685 auto *PseudoSrcExpr =
7686 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00007687 auto *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00007688 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00007689 D->hasAttrs() ? &D->getAttrs() : nullptr);
7690 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00007691 // For arrays generate assignment operation for single element and replace
7692 // it by the original array element in CodeGen.
Alexey Bataev74caaf22016-02-20 04:09:36 +00007693 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
Alexey Bataev38e89532015-04-16 04:54:05 +00007694 PseudoDstExpr, PseudoSrcExpr);
7695 if (AssignmentOp.isInvalid())
7696 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00007697 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00007698 /*DiscardedValue=*/true);
7699 if (AssignmentOp.isInvalid())
7700 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007701
Alexey Bataev74caaf22016-02-20 04:09:36 +00007702 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007703 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00007704 if (TopDVar.CKind == OMPC_firstprivate)
7705 Ref = TopDVar.PrivateCopy;
7706 else {
Alexey Bataev61205072016-03-02 04:57:40 +00007707 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00007708 if (!IsOpenMPCapturedDecl(D))
7709 ExprCaptures.push_back(Ref->getDecl());
7710 }
7711 if (TopDVar.CKind == OMPC_firstprivate ||
7712 (!IsOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00007713 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00007714 ExprResult RefRes = DefaultLvalueConversion(Ref);
7715 if (!RefRes.isUsable())
7716 continue;
7717 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00007718 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
7719 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00007720 if (!PostUpdateRes.isUsable())
7721 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00007722 ExprPostUpdates.push_back(
7723 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00007724 }
7725 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007726 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007727 Vars.push_back((VD || CurContext->isDependentContext())
7728 ? RefExpr->IgnoreParens()
7729 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00007730 SrcExprs.push_back(PseudoSrcExpr);
7731 DstExprs.push_back(PseudoDstExpr);
7732 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00007733 }
7734
7735 if (Vars.empty())
7736 return nullptr;
7737
7738 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00007739 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00007740 buildPreInits(Context, ExprCaptures),
7741 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00007742}
7743
Alexey Bataev758e55e2013-09-06 18:03:48 +00007744OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
7745 SourceLocation StartLoc,
7746 SourceLocation LParenLoc,
7747 SourceLocation EndLoc) {
7748 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00007749 for (auto &RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007750 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007751 SourceLocation ELoc;
7752 SourceRange ERange;
7753 Expr *SimpleRefExpr = RefExpr;
7754 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007755 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00007756 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007757 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007758 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007759 ValueDecl *D = Res.first;
7760 if (!D)
7761 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00007762
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007763 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007764 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7765 // in a Construct]
7766 // Variables with the predetermined data-sharing attributes may not be
7767 // listed in data-sharing attributes clauses, except for the cases
7768 // listed below. For these exceptions only, listing a predetermined
7769 // variable in a data-sharing attribute clause is allowed and overrides
7770 // the variable's predetermined data-sharing attributes.
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007771 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00007772 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
7773 DVar.RefExpr) {
7774 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7775 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007776 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007777 continue;
7778 }
7779
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007780 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007781 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00007782 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007783 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007784 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
7785 ? RefExpr->IgnoreParens()
7786 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007787 }
7788
Alexey Bataeved09d242014-05-28 05:53:51 +00007789 if (Vars.empty())
7790 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00007791
7792 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
7793}
7794
Alexey Bataevc5e02582014-06-16 07:08:35 +00007795namespace {
7796class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
7797 DSAStackTy *Stack;
7798
7799public:
7800 bool VisitDeclRefExpr(DeclRefExpr *E) {
7801 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007802 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00007803 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
7804 return false;
7805 if (DVar.CKind != OMPC_unknown)
7806 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007807 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
7808 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
7809 false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00007810 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00007811 return true;
7812 return false;
7813 }
7814 return false;
7815 }
7816 bool VisitStmt(Stmt *S) {
7817 for (auto Child : S->children()) {
7818 if (Child && Visit(Child))
7819 return true;
7820 }
7821 return false;
7822 }
Alexey Bataev23b69422014-06-18 07:08:49 +00007823 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00007824};
Alexey Bataev23b69422014-06-18 07:08:49 +00007825} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00007826
Alexey Bataev60da77e2016-02-29 05:54:20 +00007827namespace {
7828// Transform MemberExpression for specified FieldDecl of current class to
7829// DeclRefExpr to specified OMPCapturedExprDecl.
7830class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
7831 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
7832 ValueDecl *Field;
7833 DeclRefExpr *CapturedExpr;
7834
7835public:
7836 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
7837 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
7838
7839 ExprResult TransformMemberExpr(MemberExpr *E) {
7840 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
7841 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00007842 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00007843 return CapturedExpr;
7844 }
7845 return BaseTransform::TransformMemberExpr(E);
7846 }
7847 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
7848};
7849} // namespace
7850
Alexey Bataeva839ddd2016-03-17 10:19:46 +00007851template <typename T>
7852static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
7853 const llvm::function_ref<T(ValueDecl *)> &Gen) {
7854 for (auto &Set : Lookups) {
7855 for (auto *D : Set) {
7856 if (auto Res = Gen(cast<ValueDecl>(D)))
7857 return Res;
7858 }
7859 }
7860 return T();
7861}
7862
7863static ExprResult
7864buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
7865 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
7866 const DeclarationNameInfo &ReductionId, QualType Ty,
7867 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
7868 if (ReductionIdScopeSpec.isInvalid())
7869 return ExprError();
7870 SmallVector<UnresolvedSet<8>, 4> Lookups;
7871 if (S) {
7872 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
7873 Lookup.suppressDiagnostics();
7874 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
7875 auto *D = Lookup.getRepresentativeDecl();
7876 do {
7877 S = S->getParent();
7878 } while (S && !S->isDeclScope(D));
7879 if (S)
7880 S = S->getParent();
7881 Lookups.push_back(UnresolvedSet<8>());
7882 Lookups.back().append(Lookup.begin(), Lookup.end());
7883 Lookup.clear();
7884 }
7885 } else if (auto *ULE =
7886 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
7887 Lookups.push_back(UnresolvedSet<8>());
7888 Decl *PrevD = nullptr;
David Majnemer9d168222016-08-05 17:44:54 +00007889 for (auto *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00007890 if (D == PrevD)
7891 Lookups.push_back(UnresolvedSet<8>());
7892 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
7893 Lookups.back().addDecl(DRD);
7894 PrevD = D;
7895 }
7896 }
7897 if (Ty->isDependentType() || Ty->isInstantiationDependentType() ||
7898 Ty->containsUnexpandedParameterPack() ||
7899 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
7900 return !D->isInvalidDecl() &&
7901 (D->getType()->isDependentType() ||
7902 D->getType()->isInstantiationDependentType() ||
7903 D->getType()->containsUnexpandedParameterPack());
7904 })) {
7905 UnresolvedSet<8> ResSet;
7906 for (auto &Set : Lookups) {
7907 ResSet.append(Set.begin(), Set.end());
7908 // The last item marks the end of all declarations at the specified scope.
7909 ResSet.addDecl(Set[Set.size() - 1]);
7910 }
7911 return UnresolvedLookupExpr::Create(
7912 SemaRef.Context, /*NamingClass=*/nullptr,
7913 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
7914 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
7915 }
7916 if (auto *VD = filterLookupForUDR<ValueDecl *>(
7917 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
7918 if (!D->isInvalidDecl() &&
7919 SemaRef.Context.hasSameType(D->getType(), Ty))
7920 return D;
7921 return nullptr;
7922 }))
7923 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
7924 if (auto *VD = filterLookupForUDR<ValueDecl *>(
7925 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
7926 if (!D->isInvalidDecl() &&
7927 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
7928 !Ty.isMoreQualifiedThan(D->getType()))
7929 return D;
7930 return nullptr;
7931 })) {
7932 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
7933 /*DetectVirtual=*/false);
7934 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
7935 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
7936 VD->getType().getUnqualifiedType()))) {
7937 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
7938 /*DiagID=*/0) !=
7939 Sema::AR_inaccessible) {
7940 SemaRef.BuildBasePathArray(Paths, BasePath);
7941 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
7942 }
7943 }
7944 }
7945 }
7946 if (ReductionIdScopeSpec.isSet()) {
7947 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
7948 return ExprError();
7949 }
7950 return ExprEmpty();
7951}
7952
Alexey Bataevc5e02582014-06-16 07:08:35 +00007953OMPClause *Sema::ActOnOpenMPReductionClause(
7954 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
7955 SourceLocation ColonLoc, SourceLocation EndLoc,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00007956 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
7957 ArrayRef<Expr *> UnresolvedReductions) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00007958 auto DN = ReductionId.getName();
7959 auto OOK = DN.getCXXOverloadedOperator();
7960 BinaryOperatorKind BOK = BO_Comma;
7961
7962 // OpenMP [2.14.3.6, reduction clause]
7963 // C
7964 // reduction-identifier is either an identifier or one of the following
7965 // operators: +, -, *, &, |, ^, && and ||
7966 // C++
7967 // reduction-identifier is either an id-expression or one of the following
7968 // operators: +, -, *, &, |, ^, && and ||
7969 // FIXME: Only 'min' and 'max' identifiers are supported for now.
7970 switch (OOK) {
7971 case OO_Plus:
7972 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00007973 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00007974 break;
7975 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00007976 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00007977 break;
7978 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00007979 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00007980 break;
7981 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00007982 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00007983 break;
7984 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00007985 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00007986 break;
7987 case OO_AmpAmp:
7988 BOK = BO_LAnd;
7989 break;
7990 case OO_PipePipe:
7991 BOK = BO_LOr;
7992 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00007993 case OO_New:
7994 case OO_Delete:
7995 case OO_Array_New:
7996 case OO_Array_Delete:
7997 case OO_Slash:
7998 case OO_Percent:
7999 case OO_Tilde:
8000 case OO_Exclaim:
8001 case OO_Equal:
8002 case OO_Less:
8003 case OO_Greater:
8004 case OO_LessEqual:
8005 case OO_GreaterEqual:
8006 case OO_PlusEqual:
8007 case OO_MinusEqual:
8008 case OO_StarEqual:
8009 case OO_SlashEqual:
8010 case OO_PercentEqual:
8011 case OO_CaretEqual:
8012 case OO_AmpEqual:
8013 case OO_PipeEqual:
8014 case OO_LessLess:
8015 case OO_GreaterGreater:
8016 case OO_LessLessEqual:
8017 case OO_GreaterGreaterEqual:
8018 case OO_EqualEqual:
8019 case OO_ExclaimEqual:
8020 case OO_PlusPlus:
8021 case OO_MinusMinus:
8022 case OO_Comma:
8023 case OO_ArrowStar:
8024 case OO_Arrow:
8025 case OO_Call:
8026 case OO_Subscript:
8027 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +00008028 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008029 case NUM_OVERLOADED_OPERATORS:
8030 llvm_unreachable("Unexpected reduction identifier");
8031 case OO_None:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008032 if (auto II = DN.getAsIdentifierInfo()) {
8033 if (II->isStr("max"))
8034 BOK = BO_GT;
8035 else if (II->isStr("min"))
8036 BOK = BO_LT;
8037 }
8038 break;
8039 }
8040 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008041 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +00008042 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008043 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008044
8045 SmallVector<Expr *, 8> Vars;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008046 SmallVector<Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008047 SmallVector<Expr *, 8> LHSs;
8048 SmallVector<Expr *, 8> RHSs;
8049 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev61205072016-03-02 04:57:40 +00008050 SmallVector<Decl *, 4> ExprCaptures;
8051 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008052 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
8053 bool FirstIter = true;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008054 for (auto RefExpr : VarList) {
8055 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +00008056 // OpenMP [2.1, C/C++]
8057 // A list item is a variable or array section, subject to the restrictions
8058 // specified in Section 2.4 on page 42 and in each of the sections
8059 // describing clauses and directives for which a list appears.
8060 // OpenMP [2.14.3.3, Restrictions, p.1]
8061 // A variable that is part of another variable (as an array or
8062 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008063 if (!FirstIter && IR != ER)
8064 ++IR;
8065 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008066 SourceLocation ELoc;
8067 SourceRange ERange;
8068 Expr *SimpleRefExpr = RefExpr;
8069 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8070 /*AllowArraySection=*/true);
8071 if (Res.second) {
8072 // It will be analyzed later.
8073 Vars.push_back(RefExpr);
8074 Privates.push_back(nullptr);
8075 LHSs.push_back(nullptr);
8076 RHSs.push_back(nullptr);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008077 // Try to find 'declare reduction' corresponding construct before using
8078 // builtin/overloaded operators.
8079 QualType Type = Context.DependentTy;
8080 CXXCastPath BasePath;
8081 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8082 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8083 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8084 if (CurContext->isDependentContext() &&
8085 (DeclareReductionRef.isUnset() ||
8086 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
8087 ReductionOps.push_back(DeclareReductionRef.get());
8088 else
8089 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008090 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00008091 ValueDecl *D = Res.first;
8092 if (!D)
8093 continue;
8094
Alexey Bataeva1764212015-09-30 09:22:36 +00008095 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008096 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
8097 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
8098 if (ASE)
Alexey Bataev31300ed2016-02-04 11:27:03 +00008099 Type = ASE->getType().getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008100 else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008101 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
8102 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
8103 Type = ATy->getElementType();
8104 else
8105 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00008106 Type = Type.getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008107 } else
8108 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
8109 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +00008110
Alexey Bataevc5e02582014-06-16 07:08:35 +00008111 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8112 // A variable that appears in a private clause must not have an incomplete
8113 // type or a reference type.
8114 if (RequireCompleteType(ELoc, Type,
8115 diag::err_omp_reduction_incomplete_type))
8116 continue;
8117 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +00008118 // A list item that appears in a reduction clause must not be
8119 // const-qualified.
8120 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008121 Diag(ELoc, diag::err_omp_const_reduction_list_item)
Alexey Bataevc5e02582014-06-16 07:08:35 +00008122 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008123 if (!ASE && !OASE) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008124 bool IsDecl = !VD ||
8125 VD->isThisDeclarationADefinition(Context) ==
8126 VarDecl::DeclarationOnly;
8127 Diag(D->getLocation(),
Alexey Bataeva1764212015-09-30 09:22:36 +00008128 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +00008129 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +00008130 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00008131 continue;
8132 }
8133 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
8134 // If a list-item is a reference type then it must bind to the same object
8135 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +00008136 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008137 VarDecl *VDDef = VD->getDefinition();
David Sheinkman92589992016-10-04 14:41:36 +00008138 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008139 DSARefChecker Check(DSAStack);
8140 if (Check.Visit(VDDef->getInit())) {
8141 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
8142 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
8143 continue;
8144 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00008145 }
8146 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008147
Alexey Bataevc5e02582014-06-16 07:08:35 +00008148 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8149 // in a Construct]
8150 // Variables with the predetermined data-sharing attributes may not be
8151 // listed in data-sharing attributes clauses, except for the cases
8152 // listed below. For these exceptions only, listing a predetermined
8153 // variable in a data-sharing attribute clause is allowed and overrides
8154 // the variable's predetermined data-sharing attributes.
8155 // OpenMP [2.14.3.6, Restrictions, p.3]
8156 // Any number of reduction clauses can be specified on the directive,
8157 // but a list item can appear only once in the reduction clauses for that
8158 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +00008159 DSAStackTy::DSAVarData DVar;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008160 DVar = DSAStack->getTopDSA(D, false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008161 if (DVar.CKind == OMPC_reduction) {
8162 Diag(ELoc, diag::err_omp_once_referenced)
8163 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008164 if (DVar.RefExpr)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008165 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008166 } else if (DVar.CKind != OMPC_unknown) {
8167 Diag(ELoc, diag::err_omp_wrong_dsa)
8168 << getOpenMPClauseName(DVar.CKind)
8169 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008170 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008171 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008172 }
8173
8174 // OpenMP [2.14.3.6, Restrictions, p.1]
8175 // A list item that appears in a reduction clause of a worksharing
8176 // construct must be shared in the parallel regions to which any of the
8177 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008178 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8179 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008180 !isOpenMPParallelDirective(CurrDir) &&
8181 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008182 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008183 if (DVar.CKind != OMPC_shared) {
8184 Diag(ELoc, diag::err_omp_required_access)
8185 << getOpenMPClauseName(OMPC_reduction)
8186 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008187 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008188 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +00008189 }
8190 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008191
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008192 // Try to find 'declare reduction' corresponding construct before using
8193 // builtin/overloaded operators.
8194 CXXCastPath BasePath;
8195 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8196 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8197 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8198 if (DeclareReductionRef.isInvalid())
8199 continue;
8200 if (CurContext->isDependentContext() &&
8201 (DeclareReductionRef.isUnset() ||
8202 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
8203 Vars.push_back(RefExpr);
8204 Privates.push_back(nullptr);
8205 LHSs.push_back(nullptr);
8206 RHSs.push_back(nullptr);
8207 ReductionOps.push_back(DeclareReductionRef.get());
8208 continue;
8209 }
8210 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
8211 // Not allowed reduction identifier is found.
8212 Diag(ReductionId.getLocStart(),
8213 diag::err_omp_unknown_reduction_identifier)
8214 << Type << ReductionIdRange;
8215 continue;
8216 }
8217
8218 // OpenMP [2.14.3.6, reduction clause, Restrictions]
8219 // The type of a list item that appears in a reduction clause must be valid
8220 // for the reduction-identifier. For a max or min reduction in C, the type
8221 // of the list item must be an allowed arithmetic data type: char, int,
8222 // float, double, or _Bool, possibly modified with long, short, signed, or
8223 // unsigned. For a max or min reduction in C++, the type of the list item
8224 // must be an allowed arithmetic data type: char, wchar_t, int, float,
8225 // double, or bool, possibly modified with long, short, signed, or unsigned.
8226 if (DeclareReductionRef.isUnset()) {
8227 if ((BOK == BO_GT || BOK == BO_LT) &&
8228 !(Type->isScalarType() ||
8229 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
8230 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
8231 << getLangOpts().CPlusPlus;
8232 if (!ASE && !OASE) {
8233 bool IsDecl = !VD ||
8234 VD->isThisDeclarationADefinition(Context) ==
8235 VarDecl::DeclarationOnly;
8236 Diag(D->getLocation(),
8237 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8238 << D;
8239 }
8240 continue;
8241 }
8242 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
8243 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
8244 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
8245 if (!ASE && !OASE) {
8246 bool IsDecl = !VD ||
8247 VD->isThisDeclarationADefinition(Context) ==
8248 VarDecl::DeclarationOnly;
8249 Diag(D->getLocation(),
8250 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8251 << D;
8252 }
8253 continue;
8254 }
8255 }
8256
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008257 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008258 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
Alexey Bataev60da77e2016-02-29 05:54:20 +00008259 D->hasAttrs() ? &D->getAttrs() : nullptr);
8260 auto *RHSVD = buildVarDecl(*this, ELoc, Type, D->getName(),
8261 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008262 auto PrivateTy = Type;
Alexey Bataev1189bd02016-01-26 12:20:39 +00008263 if (OASE ||
Alexey Bataev60da77e2016-02-29 05:54:20 +00008264 (!ASE &&
8265 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
David Majnemer9d168222016-08-05 17:44:54 +00008266 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008267 // Create pseudo array type for private copy. The size for this array will
8268 // be generated during codegen.
8269 // For array subscripts or single variables Private Ty is the same as Type
8270 // (type of the variable or single array element).
8271 PrivateTy = Context.getVariableArrayType(
8272 Type, new (Context) OpaqueValueExpr(SourceLocation(),
8273 Context.getSizeType(), VK_RValue),
8274 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +00008275 } else if (!ASE && !OASE &&
8276 Context.getAsArrayType(D->getType().getNonReferenceType()))
8277 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008278 // Private copy.
Alexey Bataev60da77e2016-02-29 05:54:20 +00008279 auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, D->getName(),
8280 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008281 // Add initializer for private variable.
8282 Expr *Init = nullptr;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008283 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
8284 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
8285 if (DeclareReductionRef.isUsable()) {
8286 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
8287 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
8288 if (DRD->getInitializer()) {
8289 Init = DRDRef;
8290 RHSVD->setInit(DRDRef);
8291 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008292 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008293 } else {
8294 switch (BOK) {
8295 case BO_Add:
8296 case BO_Xor:
8297 case BO_Or:
8298 case BO_LOr:
8299 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
8300 if (Type->isScalarType() || Type->isAnyComplexType())
8301 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
8302 break;
8303 case BO_Mul:
8304 case BO_LAnd:
8305 if (Type->isScalarType() || Type->isAnyComplexType()) {
8306 // '*' and '&&' reduction ops - initializer is '1'.
8307 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00008308 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008309 break;
8310 case BO_And: {
8311 // '&' reduction op - initializer is '~0'.
8312 QualType OrigType = Type;
8313 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
8314 Type = ComplexTy->getElementType();
8315 if (Type->isRealFloatingType()) {
8316 llvm::APFloat InitValue =
8317 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
8318 /*isIEEE=*/true);
8319 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
8320 Type, ELoc);
8321 } else if (Type->isScalarType()) {
8322 auto Size = Context.getTypeSize(Type);
8323 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
8324 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
8325 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
8326 }
8327 if (Init && OrigType->isAnyComplexType()) {
8328 // Init = 0xFFFF + 0xFFFFi;
8329 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
8330 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
8331 }
8332 Type = OrigType;
8333 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008334 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008335 case BO_LT:
8336 case BO_GT: {
8337 // 'min' reduction op - initializer is 'Largest representable number in
8338 // the reduction list item type'.
8339 // 'max' reduction op - initializer is 'Least representable number in
8340 // the reduction list item type'.
8341 if (Type->isIntegerType() || Type->isPointerType()) {
8342 bool IsSigned = Type->hasSignedIntegerRepresentation();
8343 auto Size = Context.getTypeSize(Type);
8344 QualType IntTy =
8345 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
8346 llvm::APInt InitValue =
8347 (BOK != BO_LT)
8348 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
8349 : llvm::APInt::getMinValue(Size)
8350 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
8351 : llvm::APInt::getMaxValue(Size);
8352 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
8353 if (Type->isPointerType()) {
8354 // Cast to pointer type.
8355 auto CastExpr = BuildCStyleCastExpr(
8356 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
8357 SourceLocation(), Init);
8358 if (CastExpr.isInvalid())
8359 continue;
8360 Init = CastExpr.get();
8361 }
8362 } else if (Type->isRealFloatingType()) {
8363 llvm::APFloat InitValue = llvm::APFloat::getLargest(
8364 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
8365 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
8366 Type, ELoc);
8367 }
8368 break;
8369 }
8370 case BO_PtrMemD:
8371 case BO_PtrMemI:
8372 case BO_MulAssign:
8373 case BO_Div:
8374 case BO_Rem:
8375 case BO_Sub:
8376 case BO_Shl:
8377 case BO_Shr:
8378 case BO_LE:
8379 case BO_GE:
8380 case BO_EQ:
8381 case BO_NE:
8382 case BO_AndAssign:
8383 case BO_XorAssign:
8384 case BO_OrAssign:
8385 case BO_Assign:
8386 case BO_AddAssign:
8387 case BO_SubAssign:
8388 case BO_DivAssign:
8389 case BO_RemAssign:
8390 case BO_ShlAssign:
8391 case BO_ShrAssign:
8392 case BO_Comma:
8393 llvm_unreachable("Unexpected reduction operation");
8394 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008395 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008396 if (Init && DeclareReductionRef.isUnset()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008397 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
8398 /*TypeMayContainAuto=*/false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008399 } else if (!Init)
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008400 ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008401 if (RHSVD->isInvalidDecl())
8402 continue;
8403 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008404 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
8405 << ReductionIdRange;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008406 bool IsDecl =
8407 !VD ||
8408 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8409 Diag(D->getLocation(),
8410 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8411 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008412 continue;
8413 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008414 // Store initializer for single element in private copy. Will be used during
8415 // codegen.
8416 PrivateVD->setInit(RHSVD->getInit());
8417 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008418 auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008419 ExprResult ReductionOp;
8420 if (DeclareReductionRef.isUsable()) {
8421 QualType RedTy = DeclareReductionRef.get()->getType();
8422 QualType PtrRedTy = Context.getPointerType(RedTy);
8423 ExprResult LHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
8424 ExprResult RHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
8425 if (!BasePath.empty()) {
8426 LHS = DefaultLvalueConversion(LHS.get());
8427 RHS = DefaultLvalueConversion(RHS.get());
8428 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
8429 CK_UncheckedDerivedToBase, LHS.get(),
8430 &BasePath, LHS.get()->getValueKind());
8431 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
8432 CK_UncheckedDerivedToBase, RHS.get(),
8433 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008434 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008435 FunctionProtoType::ExtProtoInfo EPI;
8436 QualType Params[] = {PtrRedTy, PtrRedTy};
8437 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
8438 auto *OVE = new (Context) OpaqueValueExpr(
8439 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
8440 DefaultLvalueConversion(DeclareReductionRef.get()).get());
8441 Expr *Args[] = {LHS.get(), RHS.get()};
8442 ReductionOp = new (Context)
8443 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
8444 } else {
8445 ReductionOp = BuildBinOp(DSAStack->getCurScope(),
8446 ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
8447 if (ReductionOp.isUsable()) {
8448 if (BOK != BO_LT && BOK != BO_GT) {
8449 ReductionOp =
8450 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
8451 BO_Assign, LHSDRE, ReductionOp.get());
8452 } else {
8453 auto *ConditionalOp = new (Context) ConditionalOperator(
8454 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
8455 RHSDRE, Type, VK_LValue, OK_Ordinary);
8456 ReductionOp =
8457 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
8458 BO_Assign, LHSDRE, ConditionalOp);
8459 }
8460 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
8461 }
8462 if (ReductionOp.isInvalid())
8463 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008464 }
8465
Alexey Bataev60da77e2016-02-29 05:54:20 +00008466 DeclRefExpr *Ref = nullptr;
8467 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008468 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008469 if (ASE || OASE) {
8470 TransformExprToCaptures RebuildToCapture(*this, D);
8471 VarsExpr =
8472 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
8473 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +00008474 } else {
8475 VarsExpr = Ref =
8476 buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +00008477 }
8478 if (!IsOpenMPCapturedDecl(D)) {
8479 ExprCaptures.push_back(Ref->getDecl());
8480 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
8481 ExprResult RefRes = DefaultLvalueConversion(Ref);
8482 if (!RefRes.isUsable())
8483 continue;
8484 ExprResult PostUpdateRes =
8485 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
8486 SimpleRefExpr, RefRes.get());
8487 if (!PostUpdateRes.isUsable())
8488 continue;
8489 ExprPostUpdates.push_back(
8490 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +00008491 }
8492 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00008493 }
8494 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
8495 Vars.push_back(VarsExpr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008496 Privates.push_back(PrivateDRE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008497 LHSs.push_back(LHSDRE);
8498 RHSs.push_back(RHSDRE);
8499 ReductionOps.push_back(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008500 }
8501
8502 if (Vars.empty())
8503 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +00008504
Alexey Bataevc5e02582014-06-16 07:08:35 +00008505 return OMPReductionClause::Create(
8506 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008507 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008508 LHSs, RHSs, ReductionOps, buildPreInits(Context, ExprCaptures),
8509 buildPostUpdate(*this, ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +00008510}
8511
Alexey Bataevecba70f2016-04-12 11:02:11 +00008512bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
8513 SourceLocation LinLoc) {
8514 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
8515 LinKind == OMPC_LINEAR_unknown) {
8516 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
8517 return true;
8518 }
8519 return false;
8520}
8521
8522bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
8523 OpenMPLinearClauseKind LinKind,
8524 QualType Type) {
8525 auto *VD = dyn_cast_or_null<VarDecl>(D);
8526 // A variable must not have an incomplete type or a reference type.
8527 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
8528 return true;
8529 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
8530 !Type->isReferenceType()) {
8531 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
8532 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
8533 return true;
8534 }
8535 Type = Type.getNonReferenceType();
8536
8537 // A list item must not be const-qualified.
8538 if (Type.isConstant(Context)) {
8539 Diag(ELoc, diag::err_omp_const_variable)
8540 << getOpenMPClauseName(OMPC_linear);
8541 if (D) {
8542 bool IsDecl =
8543 !VD ||
8544 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8545 Diag(D->getLocation(),
8546 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8547 << D;
8548 }
8549 return true;
8550 }
8551
8552 // A list item must be of integral or pointer type.
8553 Type = Type.getUnqualifiedType().getCanonicalType();
8554 const auto *Ty = Type.getTypePtrOrNull();
8555 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
8556 !Ty->isPointerType())) {
8557 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
8558 if (D) {
8559 bool IsDecl =
8560 !VD ||
8561 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8562 Diag(D->getLocation(),
8563 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8564 << D;
8565 }
8566 return true;
8567 }
8568 return false;
8569}
8570
Alexey Bataev182227b2015-08-20 10:54:39 +00008571OMPClause *Sema::ActOnOpenMPLinearClause(
8572 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
8573 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
8574 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +00008575 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008576 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +00008577 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +00008578 SmallVector<Decl *, 4> ExprCaptures;
8579 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +00008580 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +00008581 LinKind = OMPC_LINEAR_val;
Alexey Bataeved09d242014-05-28 05:53:51 +00008582 for (auto &RefExpr : VarList) {
8583 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008584 SourceLocation ELoc;
8585 SourceRange ERange;
8586 Expr *SimpleRefExpr = RefExpr;
8587 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8588 /*AllowArraySection=*/false);
8589 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +00008590 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008591 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008592 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +00008593 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00008594 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008595 ValueDecl *D = Res.first;
8596 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +00008597 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +00008598
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008599 QualType Type = D->getType();
8600 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +00008601
8602 // OpenMP [2.14.3.7, linear clause]
8603 // A list-item cannot appear in more than one linear clause.
8604 // A list-item that appears in a linear clause cannot appear in any
8605 // other data-sharing attribute clause.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008606 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00008607 if (DVar.RefExpr) {
8608 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8609 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008610 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00008611 continue;
8612 }
8613
Alexey Bataevecba70f2016-04-12 11:02:11 +00008614 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +00008615 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00008616 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +00008617
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008618 // Build private copy of original var.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008619 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
8620 D->hasAttrs() ? &D->getAttrs() : nullptr);
8621 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +00008622 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008623 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008624 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008625 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008626 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +00008627 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
8628 if (!IsOpenMPCapturedDecl(D)) {
8629 ExprCaptures.push_back(Ref->getDecl());
8630 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
8631 ExprResult RefRes = DefaultLvalueConversion(Ref);
8632 if (!RefRes.isUsable())
8633 continue;
8634 ExprResult PostUpdateRes =
8635 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
8636 SimpleRefExpr, RefRes.get());
8637 if (!PostUpdateRes.isUsable())
8638 continue;
8639 ExprPostUpdates.push_back(
8640 IgnoredValueConversions(PostUpdateRes.get()).get());
8641 }
8642 }
8643 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008644 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008645 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008646 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008647 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008648 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008649 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
8650 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
8651
8652 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008653 Vars.push_back((VD || CurContext->isDependentContext())
8654 ? RefExpr->IgnoreParens()
8655 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008656 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +00008657 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00008658 }
8659
8660 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008661 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00008662
8663 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00008664 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00008665 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
8666 !Step->isInstantiationDependent() &&
8667 !Step->containsUnexpandedParameterPack()) {
8668 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00008669 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00008670 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008671 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008672 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00008673
Alexander Musman3276a272015-03-21 10:12:56 +00008674 // Build var to save the step value.
8675 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00008676 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +00008677 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +00008678 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +00008679 ExprResult CalcStep =
8680 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008681 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +00008682
Alexander Musman8dba6642014-04-22 13:09:42 +00008683 // Warn about zero linear step (it would be probably better specified as
8684 // making corresponding variables 'const').
8685 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00008686 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
8687 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00008688 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
8689 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00008690 if (!IsConstant && CalcStep.isUsable()) {
8691 // Calculate the step beforehand instead of doing this on each iteration.
8692 // (This is not used if the number of iterations may be kfold-ed).
8693 CalcStepExpr = CalcStep.get();
8694 }
Alexander Musman8dba6642014-04-22 13:09:42 +00008695 }
8696
Alexey Bataev182227b2015-08-20 10:54:39 +00008697 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
8698 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008699 StepExpr, CalcStepExpr,
8700 buildPreInits(Context, ExprCaptures),
8701 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +00008702}
8703
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008704static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
8705 Expr *NumIterations, Sema &SemaRef,
8706 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +00008707 // Walk the vars and build update/final expressions for the CodeGen.
8708 SmallVector<Expr *, 8> Updates;
8709 SmallVector<Expr *, 8> Finals;
8710 Expr *Step = Clause.getStep();
8711 Expr *CalcStep = Clause.getCalcStep();
8712 // OpenMP [2.14.3.7, linear clause]
8713 // If linear-step is not specified it is assumed to be 1.
8714 if (Step == nullptr)
8715 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00008716 else if (CalcStep) {
Alexander Musman3276a272015-03-21 10:12:56 +00008717 Step = cast<BinaryOperator>(CalcStep)->getLHS();
Alexey Bataev5a3af132016-03-29 08:58:54 +00008718 }
Alexander Musman3276a272015-03-21 10:12:56 +00008719 bool HasErrors = false;
8720 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008721 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008722 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +00008723 for (auto &RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008724 SourceLocation ELoc;
8725 SourceRange ERange;
8726 Expr *SimpleRefExpr = RefExpr;
8727 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
8728 /*AllowArraySection=*/false);
8729 ValueDecl *D = Res.first;
8730 if (Res.second || !D) {
8731 Updates.push_back(nullptr);
8732 Finals.push_back(nullptr);
8733 HasErrors = true;
8734 continue;
8735 }
8736 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) {
8737 D = cast<MemberExpr>(CED->getInit()->IgnoreParenImpCasts())
8738 ->getMemberDecl();
8739 }
8740 auto &&Info = Stack->isLoopControlVariable(D);
Alexander Musman3276a272015-03-21 10:12:56 +00008741 Expr *InitExpr = *CurInit;
8742
8743 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +00008744 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008745 Expr *CapturedRef;
8746 if (LinKind == OMPC_LINEAR_uval)
8747 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
8748 else
8749 CapturedRef =
8750 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
8751 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
8752 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00008753
8754 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008755 ExprResult Update;
8756 if (!Info.first) {
8757 Update =
8758 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
8759 InitExpr, IV, Step, /* Subtract */ false);
8760 } else
8761 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008762 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
8763 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00008764
8765 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008766 ExprResult Final;
8767 if (!Info.first) {
8768 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
8769 InitExpr, NumIterations, Step,
8770 /* Subtract */ false);
8771 } else
8772 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008773 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
8774 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008775
Alexander Musman3276a272015-03-21 10:12:56 +00008776 if (!Update.isUsable() || !Final.isUsable()) {
8777 Updates.push_back(nullptr);
8778 Finals.push_back(nullptr);
8779 HasErrors = true;
8780 } else {
8781 Updates.push_back(Update.get());
8782 Finals.push_back(Final.get());
8783 }
Richard Trieucc3949d2016-02-18 22:34:54 +00008784 ++CurInit;
8785 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00008786 }
8787 Clause.setUpdates(Updates);
8788 Clause.setFinals(Finals);
8789 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00008790}
8791
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008792OMPClause *Sema::ActOnOpenMPAlignedClause(
8793 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
8794 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
8795
8796 SmallVector<Expr *, 8> Vars;
8797 for (auto &RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +00008798 assert(RefExpr && "NULL expr in OpenMP linear clause.");
8799 SourceLocation ELoc;
8800 SourceRange ERange;
8801 Expr *SimpleRefExpr = RefExpr;
8802 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8803 /*AllowArraySection=*/false);
8804 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008805 // It will be analyzed later.
8806 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008807 }
Alexey Bataev1efd1662016-03-29 10:59:56 +00008808 ValueDecl *D = Res.first;
8809 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008810 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008811
Alexey Bataev1efd1662016-03-29 10:59:56 +00008812 QualType QType = D->getType();
8813 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008814
8815 // OpenMP [2.8.1, simd construct, Restrictions]
8816 // The type of list items appearing in the aligned clause must be
8817 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008818 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008819 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +00008820 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008821 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +00008822 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008823 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +00008824 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008825 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +00008826 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008827 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +00008828 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008829 continue;
8830 }
8831
8832 // OpenMP [2.8.1, simd construct, Restrictions]
8833 // A list-item cannot appear in more than one aligned clause.
Alexey Bataev1efd1662016-03-29 10:59:56 +00008834 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00008835 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008836 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
8837 << getOpenMPClauseName(OMPC_aligned);
8838 continue;
8839 }
8840
Alexey Bataev1efd1662016-03-29 10:59:56 +00008841 DeclRefExpr *Ref = nullptr;
8842 if (!VD && IsOpenMPCapturedDecl(D))
8843 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
8844 Vars.push_back(DefaultFunctionArrayConversion(
8845 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
8846 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008847 }
8848
8849 // OpenMP [2.8.1, simd construct, Description]
8850 // The parameter of the aligned clause, alignment, must be a constant
8851 // positive integer expression.
8852 // If no optional parameter is specified, implementation-defined default
8853 // alignments for SIMD instructions on the target platforms are assumed.
8854 if (Alignment != nullptr) {
8855 ExprResult AlignResult =
8856 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
8857 if (AlignResult.isInvalid())
8858 return nullptr;
8859 Alignment = AlignResult.get();
8860 }
8861 if (Vars.empty())
8862 return nullptr;
8863
8864 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
8865 EndLoc, Vars, Alignment);
8866}
8867
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008868OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
8869 SourceLocation StartLoc,
8870 SourceLocation LParenLoc,
8871 SourceLocation EndLoc) {
8872 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +00008873 SmallVector<Expr *, 8> SrcExprs;
8874 SmallVector<Expr *, 8> DstExprs;
8875 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +00008876 for (auto &RefExpr : VarList) {
8877 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
8878 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008879 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008880 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00008881 SrcExprs.push_back(nullptr);
8882 DstExprs.push_back(nullptr);
8883 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008884 continue;
8885 }
8886
Alexey Bataeved09d242014-05-28 05:53:51 +00008887 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008888 // OpenMP [2.1, C/C++]
8889 // A list item is a variable name.
8890 // OpenMP [2.14.4.1, Restrictions, p.1]
8891 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +00008892 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008893 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008894 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
8895 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008896 continue;
8897 }
8898
8899 Decl *D = DE->getDecl();
8900 VarDecl *VD = cast<VarDecl>(D);
8901
8902 QualType Type = VD->getType();
8903 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
8904 // It will be analyzed later.
8905 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00008906 SrcExprs.push_back(nullptr);
8907 DstExprs.push_back(nullptr);
8908 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008909 continue;
8910 }
8911
8912 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
8913 // A list item that appears in a copyin clause must be threadprivate.
8914 if (!DSAStack->isThreadPrivate(VD)) {
8915 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +00008916 << getOpenMPClauseName(OMPC_copyin)
8917 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008918 continue;
8919 }
8920
8921 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
8922 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +00008923 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008924 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008925 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00008926 auto *SrcVD =
8927 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
8928 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00008929 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008930 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
8931 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00008932 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
8933 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00008934 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008935 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +00008936 // For arrays generate assignment operation for single element and replace
8937 // it by the original array element in CodeGen.
8938 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
8939 PseudoDstExpr, PseudoSrcExpr);
8940 if (AssignmentOp.isInvalid())
8941 continue;
8942 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
8943 /*DiscardedValue=*/true);
8944 if (AssignmentOp.isInvalid())
8945 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008946
8947 DSAStack->addDSA(VD, DE, OMPC_copyin);
8948 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00008949 SrcExprs.push_back(PseudoSrcExpr);
8950 DstExprs.push_back(PseudoDstExpr);
8951 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008952 }
8953
Alexey Bataeved09d242014-05-28 05:53:51 +00008954 if (Vars.empty())
8955 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008956
Alexey Bataevf56f98c2015-04-16 05:39:01 +00008957 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
8958 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008959}
8960
Alexey Bataevbae9a792014-06-27 10:37:06 +00008961OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
8962 SourceLocation StartLoc,
8963 SourceLocation LParenLoc,
8964 SourceLocation EndLoc) {
8965 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +00008966 SmallVector<Expr *, 8> SrcExprs;
8967 SmallVector<Expr *, 8> DstExprs;
8968 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +00008969 for (auto &RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +00008970 assert(RefExpr && "NULL expr in OpenMP linear clause.");
8971 SourceLocation ELoc;
8972 SourceRange ERange;
8973 Expr *SimpleRefExpr = RefExpr;
8974 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8975 /*AllowArraySection=*/false);
8976 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00008977 // It will be analyzed later.
8978 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +00008979 SrcExprs.push_back(nullptr);
8980 DstExprs.push_back(nullptr);
8981 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00008982 }
Alexey Bataeve122da12016-03-17 10:50:17 +00008983 ValueDecl *D = Res.first;
8984 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +00008985 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00008986
Alexey Bataeve122da12016-03-17 10:50:17 +00008987 QualType Type = D->getType();
8988 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +00008989
8990 // OpenMP [2.14.4.2, Restrictions, p.2]
8991 // A list item that appears in a copyprivate clause may not appear in a
8992 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +00008993 if (!VD || !DSAStack->isThreadPrivate(VD)) {
8994 auto DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +00008995 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
8996 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00008997 Diag(ELoc, diag::err_omp_wrong_dsa)
8998 << getOpenMPClauseName(DVar.CKind)
8999 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve122da12016-03-17 10:50:17 +00009000 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009001 continue;
9002 }
9003
9004 // OpenMP [2.11.4.2, Restrictions, p.1]
9005 // All list items that appear in a copyprivate clause must be either
9006 // threadprivate or private in the enclosing context.
9007 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +00009008 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009009 if (DVar.CKind == OMPC_shared) {
9010 Diag(ELoc, diag::err_omp_required_access)
9011 << getOpenMPClauseName(OMPC_copyprivate)
9012 << "threadprivate or private in the enclosing context";
Alexey Bataeve122da12016-03-17 10:50:17 +00009013 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009014 continue;
9015 }
9016 }
9017 }
9018
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009019 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009020 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009021 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009022 << getOpenMPClauseName(OMPC_copyprivate) << Type
9023 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009024 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +00009025 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009026 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +00009027 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009028 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +00009029 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009030 continue;
9031 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009032
Alexey Bataevbae9a792014-06-27 10:37:06 +00009033 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9034 // A variable of class type (or array thereof) that appears in a
9035 // copyin clause requires an accessible, unambiguous copy assignment
9036 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009037 Type = Context.getBaseElementType(Type.getNonReferenceType())
9038 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +00009039 auto *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +00009040 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
9041 D->hasAttrs() ? &D->getAttrs() : nullptr);
9042 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
Alexey Bataev420d45b2015-04-14 05:11:24 +00009043 auto *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +00009044 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
9045 D->hasAttrs() ? &D->getAttrs() : nullptr);
David Majnemer9d168222016-08-05 17:44:54 +00009046 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataeve122da12016-03-17 10:50:17 +00009047 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
Alexey Bataeva63048e2015-03-23 06:18:07 +00009048 PseudoDstExpr, PseudoSrcExpr);
9049 if (AssignmentOp.isInvalid())
9050 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +00009051 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +00009052 /*DiscardedValue=*/true);
9053 if (AssignmentOp.isInvalid())
9054 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009055
9056 // No need to mark vars as copyprivate, they are already threadprivate or
9057 // implicitly private.
Alexey Bataeve122da12016-03-17 10:50:17 +00009058 assert(VD || IsOpenMPCapturedDecl(D));
9059 Vars.push_back(
9060 VD ? RefExpr->IgnoreParens()
9061 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +00009062 SrcExprs.push_back(PseudoSrcExpr);
9063 DstExprs.push_back(PseudoDstExpr);
9064 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +00009065 }
9066
9067 if (Vars.empty())
9068 return nullptr;
9069
Alexey Bataeva63048e2015-03-23 06:18:07 +00009070 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9071 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009072}
9073
Alexey Bataev6125da92014-07-21 11:26:11 +00009074OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
9075 SourceLocation StartLoc,
9076 SourceLocation LParenLoc,
9077 SourceLocation EndLoc) {
9078 if (VarList.empty())
9079 return nullptr;
9080
9081 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
9082}
Alexey Bataevdea47612014-07-23 07:46:59 +00009083
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009084OMPClause *
9085Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
9086 SourceLocation DepLoc, SourceLocation ColonLoc,
9087 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9088 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00009089 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009090 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +00009091 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009092 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +00009093 return nullptr;
9094 }
9095 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009096 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
9097 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +00009098 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009099 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009100 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
9101 /*Last=*/OMPC_DEPEND_unknown, Except)
9102 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009103 return nullptr;
9104 }
9105 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +00009106 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009107 llvm::APSInt DepCounter(/*BitWidth=*/32);
9108 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
9109 if (DepKind == OMPC_DEPEND_sink) {
9110 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
9111 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
9112 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009113 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009114 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009115 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
9116 DSAStack->getParentOrderedRegionParam()) {
9117 for (auto &RefExpr : VarList) {
9118 assert(RefExpr && "NULL expr in OpenMP shared clause.");
Alexey Bataev8b427062016-05-25 12:36:08 +00009119 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009120 // It will be analyzed later.
9121 Vars.push_back(RefExpr);
9122 continue;
9123 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009124
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009125 SourceLocation ELoc = RefExpr->getExprLoc();
9126 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
9127 if (DepKind == OMPC_DEPEND_sink) {
9128 if (DepCounter >= TotalDepCount) {
9129 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
9130 continue;
9131 }
9132 ++DepCounter;
9133 // OpenMP [2.13.9, Summary]
9134 // depend(dependence-type : vec), where dependence-type is:
9135 // 'sink' and where vec is the iteration vector, which has the form:
9136 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
9137 // where n is the value specified by the ordered clause in the loop
9138 // directive, xi denotes the loop iteration variable of the i-th nested
9139 // loop associated with the loop directive, and di is a constant
9140 // non-negative integer.
Alexey Bataev8b427062016-05-25 12:36:08 +00009141 if (CurContext->isDependentContext()) {
9142 // It will be analyzed later.
9143 Vars.push_back(RefExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009144 continue;
9145 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009146 SimpleExpr = SimpleExpr->IgnoreImplicit();
9147 OverloadedOperatorKind OOK = OO_None;
9148 SourceLocation OOLoc;
9149 Expr *LHS = SimpleExpr;
9150 Expr *RHS = nullptr;
9151 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
9152 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
9153 OOLoc = BO->getOperatorLoc();
9154 LHS = BO->getLHS()->IgnoreParenImpCasts();
9155 RHS = BO->getRHS()->IgnoreParenImpCasts();
9156 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
9157 OOK = OCE->getOperator();
9158 OOLoc = OCE->getOperatorLoc();
9159 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9160 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
9161 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
9162 OOK = MCE->getMethodDecl()
9163 ->getNameInfo()
9164 .getName()
9165 .getCXXOverloadedOperator();
9166 OOLoc = MCE->getCallee()->getExprLoc();
9167 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
9168 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9169 }
9170 SourceLocation ELoc;
9171 SourceRange ERange;
9172 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
9173 /*AllowArraySection=*/false);
9174 if (Res.second) {
9175 // It will be analyzed later.
9176 Vars.push_back(RefExpr);
9177 }
9178 ValueDecl *D = Res.first;
9179 if (!D)
9180 continue;
9181
9182 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
9183 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
9184 continue;
9185 }
9186 if (RHS) {
9187 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
9188 RHS, OMPC_depend, /*StrictlyPositive=*/false);
9189 if (RHSRes.isInvalid())
9190 continue;
9191 }
9192 if (!CurContext->isDependentContext() &&
9193 DSAStack->getParentOrderedRegionParam() &&
9194 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
9195 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
9196 << DSAStack->getParentLoopControlVariable(
9197 DepCounter.getZExtValue());
9198 continue;
9199 }
9200 OpsOffs.push_back({RHS, OOK});
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009201 } else {
9202 // OpenMP [2.11.1.1, Restrictions, p.3]
9203 // A variable that is part of another variable (such as a field of a
9204 // structure) but is not an array element or an array section cannot
9205 // appear in a depend clause.
9206 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
9207 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
9208 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
9209 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
9210 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
Alexey Bataev31300ed2016-02-04 11:27:03 +00009211 (ASE &&
9212 !ASE->getBase()
9213 ->getType()
9214 .getNonReferenceType()
9215 ->isPointerType() &&
9216 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009217 Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item)
9218 << 0 << RefExpr->getSourceRange();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009219 continue;
9220 }
9221 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009222 Vars.push_back(RefExpr->IgnoreParenImpCasts());
9223 }
9224
9225 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
9226 TotalDepCount > VarList.size() &&
9227 DSAStack->getParentOrderedRegionParam()) {
9228 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
9229 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
9230 }
9231 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
9232 Vars.empty())
9233 return nullptr;
9234 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009235 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9236 DepKind, DepLoc, ColonLoc, Vars);
9237 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
9238 DSAStack->addDoacrossDependClause(C, OpsOffs);
9239 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009240}
Michael Wonge710d542015-08-07 16:16:36 +00009241
9242OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
9243 SourceLocation LParenLoc,
9244 SourceLocation EndLoc) {
9245 Expr *ValExpr = Device;
Michael Wonge710d542015-08-07 16:16:36 +00009246
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009247 // OpenMP [2.9.1, Restrictions]
9248 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00009249 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
9250 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009251 return nullptr;
9252
Michael Wonge710d542015-08-07 16:16:36 +00009253 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9254}
Kelvin Li0bff7af2015-11-23 05:32:03 +00009255
9256static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
9257 DSAStackTy *Stack, CXXRecordDecl *RD) {
9258 if (!RD || RD->isInvalidDecl())
9259 return true;
9260
9261 auto QTy = SemaRef.Context.getRecordType(RD);
9262 if (RD->isDynamicClass()) {
9263 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9264 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
9265 return false;
9266 }
9267 auto *DC = RD;
9268 bool IsCorrect = true;
9269 for (auto *I : DC->decls()) {
9270 if (I) {
9271 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
9272 if (MD->isStatic()) {
9273 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9274 SemaRef.Diag(MD->getLocation(),
9275 diag::note_omp_static_member_in_target);
9276 IsCorrect = false;
9277 }
9278 } else if (auto *VD = dyn_cast<VarDecl>(I)) {
9279 if (VD->isStaticDataMember()) {
9280 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9281 SemaRef.Diag(VD->getLocation(),
9282 diag::note_omp_static_member_in_target);
9283 IsCorrect = false;
9284 }
9285 }
9286 }
9287 }
9288
9289 for (auto &I : RD->bases()) {
9290 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
9291 I.getType()->getAsCXXRecordDecl()))
9292 IsCorrect = false;
9293 }
9294 return IsCorrect;
9295}
9296
9297static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
9298 DSAStackTy *Stack, QualType QTy) {
9299 NamedDecl *ND;
9300 if (QTy->isIncompleteType(&ND)) {
9301 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
9302 return false;
9303 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
David Majnemer9d168222016-08-05 17:44:54 +00009304 if (!RD->isInvalidDecl() && !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
Kelvin Li0bff7af2015-11-23 05:32:03 +00009305 return false;
9306 }
9307 return true;
9308}
9309
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009310/// \brief Return true if it can be proven that the provided array expression
9311/// (array section or array subscript) does NOT specify the whole size of the
9312/// array whose base type is \a BaseQTy.
9313static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
9314 const Expr *E,
9315 QualType BaseQTy) {
9316 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
9317
9318 // If this is an array subscript, it refers to the whole size if the size of
9319 // the dimension is constant and equals 1. Also, an array section assumes the
9320 // format of an array subscript if no colon is used.
9321 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
9322 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
9323 return ATy->getSize().getSExtValue() != 1;
9324 // Size can't be evaluated statically.
9325 return false;
9326 }
9327
9328 assert(OASE && "Expecting array section if not an array subscript.");
9329 auto *LowerBound = OASE->getLowerBound();
9330 auto *Length = OASE->getLength();
9331
9332 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +00009333 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009334 if (LowerBound) {
9335 llvm::APSInt ConstLowerBound;
9336 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
9337 return false; // Can't get the integer value as a constant.
9338 if (ConstLowerBound.getSExtValue())
9339 return true;
9340 }
9341
9342 // If we don't have a length we covering the whole dimension.
9343 if (!Length)
9344 return false;
9345
9346 // If the base is a pointer, we don't have a way to get the size of the
9347 // pointee.
9348 if (BaseQTy->isPointerType())
9349 return false;
9350
9351 // We can only check if the length is the same as the size of the dimension
9352 // if we have a constant array.
9353 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
9354 if (!CATy)
9355 return false;
9356
9357 llvm::APSInt ConstLength;
9358 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
9359 return false; // Can't get the integer value as a constant.
9360
9361 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
9362}
9363
9364// Return true if it can be proven that the provided array expression (array
9365// section or array subscript) does NOT specify a single element of the array
9366// whose base type is \a BaseQTy.
9367static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +00009368 const Expr *E,
9369 QualType BaseQTy) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009370 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
9371
9372 // An array subscript always refer to a single element. Also, an array section
9373 // assumes the format of an array subscript if no colon is used.
9374 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
9375 return false;
9376
9377 assert(OASE && "Expecting array section if not an array subscript.");
9378 auto *Length = OASE->getLength();
9379
9380 // If we don't have a length we have to check if the array has unitary size
9381 // for this dimension. Also, we should always expect a length if the base type
9382 // is pointer.
9383 if (!Length) {
9384 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
9385 return ATy->getSize().getSExtValue() != 1;
9386 // We cannot assume anything.
9387 return false;
9388 }
9389
9390 // Check if the length evaluates to 1.
9391 llvm::APSInt ConstLength;
9392 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
9393 return false; // Can't get the integer value as a constant.
9394
9395 return ConstLength.getSExtValue() != 1;
9396}
9397
Samuel Antao661c0902016-05-26 17:39:58 +00009398// Return the expression of the base of the mappable expression or null if it
9399// cannot be determined and do all the necessary checks to see if the expression
9400// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +00009401// components of the expression.
9402static Expr *CheckMapClauseExpressionBase(
9403 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +00009404 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
9405 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009406 SourceLocation ELoc = E->getExprLoc();
9407 SourceRange ERange = E->getSourceRange();
9408
9409 // The base of elements of list in a map clause have to be either:
9410 // - a reference to variable or field.
9411 // - a member expression.
9412 // - an array expression.
9413 //
9414 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
9415 // reference to 'r'.
9416 //
9417 // If we have:
9418 //
9419 // struct SS {
9420 // Bla S;
9421 // foo() {
9422 // #pragma omp target map (S.Arr[:12]);
9423 // }
9424 // }
9425 //
9426 // We want to retrieve the member expression 'this->S';
9427
9428 Expr *RelevantExpr = nullptr;
9429
Samuel Antao5de996e2016-01-22 20:21:36 +00009430 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
9431 // If a list item is an array section, it must specify contiguous storage.
9432 //
9433 // For this restriction it is sufficient that we make sure only references
9434 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009435 // exist except in the rightmost expression (unless they cover the whole
9436 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +00009437 //
9438 // r.ArrS[3:5].Arr[6:7]
9439 //
9440 // r.ArrS[3:5].x
9441 //
9442 // but these would be valid:
9443 // r.ArrS[3].Arr[6:7]
9444 //
9445 // r.ArrS[3].x
9446
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009447 bool AllowUnitySizeArraySection = true;
9448 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +00009449
Dmitry Polukhin644a9252016-03-11 07:58:34 +00009450 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009451 E = E->IgnoreParenImpCasts();
9452
9453 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
9454 if (!isa<VarDecl>(CurE->getDecl()))
9455 break;
9456
9457 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009458
9459 // If we got a reference to a declaration, we should not expect any array
9460 // section before that.
9461 AllowUnitySizeArraySection = false;
9462 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +00009463
9464 // Record the component.
9465 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
9466 CurE, CurE->getDecl()));
Samuel Antao5de996e2016-01-22 20:21:36 +00009467 continue;
9468 }
9469
9470 if (auto *CurE = dyn_cast<MemberExpr>(E)) {
9471 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
9472
9473 if (isa<CXXThisExpr>(BaseE))
9474 // We found a base expression: this->Val.
9475 RelevantExpr = CurE;
9476 else
9477 E = BaseE;
9478
9479 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
9480 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
9481 << CurE->getSourceRange();
9482 break;
9483 }
9484
9485 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
9486
9487 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
9488 // A bit-field cannot appear in a map clause.
9489 //
9490 if (FD->isBitField()) {
Samuel Antao661c0902016-05-26 17:39:58 +00009491 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
9492 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +00009493 break;
9494 }
9495
9496 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9497 // If the type of a list item is a reference to a type T then the type
9498 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009499 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +00009500
9501 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
9502 // A list item cannot be a variable that is a member of a structure with
9503 // a union type.
9504 //
9505 if (auto *RT = CurType->getAs<RecordType>())
9506 if (RT->isUnionType()) {
9507 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
9508 << CurE->getSourceRange();
9509 break;
9510 }
9511
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009512 // If we got a member expression, we should not expect any array section
9513 // before that:
9514 //
9515 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
9516 // If a list item is an element of a structure, only the rightmost symbol
9517 // of the variable reference can be an array section.
9518 //
9519 AllowUnitySizeArraySection = false;
9520 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +00009521
9522 // Record the component.
9523 CurComponents.push_back(
9524 OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
Samuel Antao5de996e2016-01-22 20:21:36 +00009525 continue;
9526 }
9527
9528 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
9529 E = CurE->getBase()->IgnoreParenImpCasts();
9530
9531 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
9532 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
9533 << 0 << CurE->getSourceRange();
9534 break;
9535 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009536
9537 // If we got an array subscript that express the whole dimension we
9538 // can have any array expressions before. If it only expressing part of
9539 // the dimension, we can only have unitary-size array expressions.
9540 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
9541 E->getType()))
9542 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +00009543
9544 // Record the component - we don't have any declaration associated.
9545 CurComponents.push_back(
9546 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +00009547 continue;
9548 }
9549
9550 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009551 E = CurE->getBase()->IgnoreParenImpCasts();
9552
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009553 auto CurType =
9554 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
9555
Samuel Antao5de996e2016-01-22 20:21:36 +00009556 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9557 // If the type of a list item is a reference to a type T then the type
9558 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +00009559 if (CurType->isReferenceType())
9560 CurType = CurType->getPointeeType();
9561
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009562 bool IsPointer = CurType->isAnyPointerType();
9563
9564 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009565 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
9566 << 0 << CurE->getSourceRange();
9567 break;
9568 }
9569
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009570 bool NotWhole =
9571 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
9572 bool NotUnity =
9573 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
9574
Samuel Antaodab51bb2016-07-18 23:22:11 +00009575 if (AllowWholeSizeArraySection) {
9576 // Any array section is currently allowed. Allowing a whole size array
9577 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009578 //
9579 // If this array section refers to the whole dimension we can still
9580 // accept other array sections before this one, except if the base is a
9581 // pointer. Otherwise, only unitary sections are accepted.
9582 if (NotWhole || IsPointer)
9583 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +00009584 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009585 // A unity or whole array section is not allowed and that is not
9586 // compatible with the properties of the current array section.
9587 SemaRef.Diag(
9588 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
9589 << CurE->getSourceRange();
9590 break;
9591 }
Samuel Antao90927002016-04-26 14:54:23 +00009592
9593 // Record the component - we don't have any declaration associated.
9594 CurComponents.push_back(
9595 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +00009596 continue;
9597 }
9598
9599 // If nothing else worked, this is not a valid map clause expression.
9600 SemaRef.Diag(ELoc,
9601 diag::err_omp_expected_named_var_member_or_array_expression)
9602 << ERange;
9603 break;
9604 }
9605
9606 return RelevantExpr;
9607}
9608
9609// Return true if expression E associated with value VD has conflicts with other
9610// map information.
Samuel Antao90927002016-04-26 14:54:23 +00009611static bool CheckMapConflicts(
9612 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
9613 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +00009614 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
9615 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009616 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +00009617 SourceLocation ELoc = E->getExprLoc();
9618 SourceRange ERange = E->getSourceRange();
9619
9620 // In order to easily check the conflicts we need to match each component of
9621 // the expression under test with the components of the expressions that are
9622 // already in the stack.
9623
Samuel Antao5de996e2016-01-22 20:21:36 +00009624 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +00009625 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +00009626 "Map clause expression with unexpected base!");
9627
9628 // Variables to help detecting enclosing problems in data environment nests.
9629 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +00009630 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +00009631
Samuel Antao90927002016-04-26 14:54:23 +00009632 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
9633 VD, CurrentRegionOnly,
9634 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00009635 StackComponents,
9636 OpenMPClauseKind) -> bool {
Samuel Antao90927002016-04-26 14:54:23 +00009637
Samuel Antao5de996e2016-01-22 20:21:36 +00009638 assert(!StackComponents.empty() &&
9639 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +00009640 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +00009641 "Map clause expression with unexpected base!");
9642
Samuel Antao90927002016-04-26 14:54:23 +00009643 // The whole expression in the stack.
9644 auto *RE = StackComponents.front().getAssociatedExpression();
9645
Samuel Antao5de996e2016-01-22 20:21:36 +00009646 // Expressions must start from the same base. Here we detect at which
9647 // point both expressions diverge from each other and see if we can
9648 // detect if the memory referred to both expressions is contiguous and
9649 // do not overlap.
9650 auto CI = CurComponents.rbegin();
9651 auto CE = CurComponents.rend();
9652 auto SI = StackComponents.rbegin();
9653 auto SE = StackComponents.rend();
9654 for (; CI != CE && SI != SE; ++CI, ++SI) {
9655
9656 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
9657 // At most one list item can be an array item derived from a given
9658 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +00009659 if (CurrentRegionOnly &&
9660 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
9661 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
9662 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
9663 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
9664 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +00009665 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +00009666 << CI->getAssociatedExpression()->getSourceRange();
9667 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
9668 diag::note_used_here)
9669 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +00009670 return true;
9671 }
9672
9673 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +00009674 if (CI->getAssociatedExpression()->getStmtClass() !=
9675 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +00009676 break;
9677
9678 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +00009679 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +00009680 break;
9681 }
Kelvin Li9f645ae2016-07-18 22:49:16 +00009682 // Check if the extra components of the expressions in the enclosing
9683 // data environment are redundant for the current base declaration.
9684 // If they are, the maps completely overlap, which is legal.
9685 for (; SI != SE; ++SI) {
9686 QualType Type;
9687 if (auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +00009688 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +00009689 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
David Majnemer9d168222016-08-05 17:44:54 +00009690 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
9691 SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +00009692 auto *E = OASE->getBase()->IgnoreParenImpCasts();
9693 Type =
9694 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
9695 }
9696 if (Type.isNull() || Type->isAnyPointerType() ||
9697 CheckArrayExpressionDoesNotReferToWholeSize(
9698 SemaRef, SI->getAssociatedExpression(), Type))
9699 break;
9700 }
Samuel Antao5de996e2016-01-22 20:21:36 +00009701
9702 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
9703 // List items of map clauses in the same construct must not share
9704 // original storage.
9705 //
9706 // If the expressions are exactly the same or one is a subset of the
9707 // other, it means they are sharing storage.
9708 if (CI == CE && SI == SE) {
9709 if (CurrentRegionOnly) {
Samuel Antao661c0902016-05-26 17:39:58 +00009710 if (CKind == OMPC_map)
9711 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
9712 else {
Samuel Antaoec172c62016-05-26 17:49:04 +00009713 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +00009714 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
9715 << ERange;
9716 }
Samuel Antao5de996e2016-01-22 20:21:36 +00009717 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
9718 << RE->getSourceRange();
9719 return true;
9720 } else {
9721 // If we find the same expression in the enclosing data environment,
9722 // that is legal.
9723 IsEnclosedByDataEnvironmentExpr = true;
9724 return false;
9725 }
9726 }
9727
Samuel Antao90927002016-04-26 14:54:23 +00009728 QualType DerivedType =
9729 std::prev(CI)->getAssociatedDeclaration()->getType();
9730 SourceLocation DerivedLoc =
9731 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +00009732
9733 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9734 // If the type of a list item is a reference to a type T then the type
9735 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +00009736 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +00009737
9738 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
9739 // A variable for which the type is pointer and an array section
9740 // derived from that variable must not appear as list items of map
9741 // clauses of the same construct.
9742 //
9743 // Also, cover one of the cases in:
9744 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
9745 // If any part of the original storage of a list item has corresponding
9746 // storage in the device data environment, all of the original storage
9747 // must have corresponding storage in the device data environment.
9748 //
9749 if (DerivedType->isAnyPointerType()) {
9750 if (CI == CE || SI == SE) {
9751 SemaRef.Diag(
9752 DerivedLoc,
9753 diag::err_omp_pointer_mapped_along_with_derived_section)
9754 << DerivedLoc;
9755 } else {
9756 assert(CI != CE && SI != SE);
9757 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
9758 << DerivedLoc;
9759 }
9760 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
9761 << RE->getSourceRange();
9762 return true;
9763 }
9764
9765 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
9766 // List items of map clauses in the same construct must not share
9767 // original storage.
9768 //
9769 // An expression is a subset of the other.
9770 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Samuel Antao661c0902016-05-26 17:39:58 +00009771 if (CKind == OMPC_map)
9772 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
9773 else {
Samuel Antaoec172c62016-05-26 17:49:04 +00009774 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +00009775 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
9776 << ERange;
9777 }
Samuel Antao5de996e2016-01-22 20:21:36 +00009778 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
9779 << RE->getSourceRange();
9780 return true;
9781 }
9782
9783 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +00009784 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +00009785 if (!CurrentRegionOnly && SI != SE)
9786 EnclosingExpr = RE;
9787
9788 // The current expression is a subset of the expression in the data
9789 // environment.
9790 IsEnclosedByDataEnvironmentExpr |=
9791 (!CurrentRegionOnly && CI != CE && SI == SE);
9792
9793 return false;
9794 });
9795
9796 if (CurrentRegionOnly)
9797 return FoundError;
9798
9799 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
9800 // If any part of the original storage of a list item has corresponding
9801 // storage in the device data environment, all of the original storage must
9802 // have corresponding storage in the device data environment.
9803 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
9804 // If a list item is an element of a structure, and a different element of
9805 // the structure has a corresponding list item in the device data environment
9806 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +00009807 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +00009808 // data environment prior to the task encountering the construct.
9809 //
9810 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
9811 SemaRef.Diag(ELoc,
9812 diag::err_omp_original_storage_is_shared_and_does_not_contain)
9813 << ERange;
9814 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
9815 << EnclosingExpr->getSourceRange();
9816 return true;
9817 }
9818
9819 return FoundError;
9820}
9821
Samuel Antao661c0902016-05-26 17:39:58 +00009822namespace {
9823// Utility struct that gathers all the related lists associated with a mappable
9824// expression.
9825struct MappableVarListInfo final {
9826 // The list of expressions.
9827 ArrayRef<Expr *> VarList;
9828 // The list of processed expressions.
9829 SmallVector<Expr *, 16> ProcessedVarList;
9830 // The mappble components for each expression.
9831 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
9832 // The base declaration of the variable.
9833 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
9834
9835 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
9836 // We have a list of components and base declarations for each entry in the
9837 // variable list.
9838 VarComponents.reserve(VarList.size());
9839 VarBaseDeclarations.reserve(VarList.size());
9840 }
9841};
9842}
9843
9844// Check the validity of the provided variable list for the provided clause kind
9845// \a CKind. In the check process the valid expressions, and mappable expression
9846// components and variables are extracted and used to fill \a Vars,
9847// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
9848// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
9849static void
9850checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
9851 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
9852 SourceLocation StartLoc,
9853 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
9854 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +00009855 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
9856 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +00009857 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +00009858
Samuel Antao90927002016-04-26 14:54:23 +00009859 // Keep track of the mappable components and base declarations in this clause.
9860 // Each entry in the list is going to have a list of components associated. We
9861 // record each set of the components so that we can build the clause later on.
9862 // In the end we should have the same amount of declarations and component
9863 // lists.
Samuel Antao90927002016-04-26 14:54:23 +00009864
Samuel Antao661c0902016-05-26 17:39:58 +00009865 for (auto &RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +00009866 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +00009867 SourceLocation ELoc = RE->getExprLoc();
9868
Kelvin Li0bff7af2015-11-23 05:32:03 +00009869 auto *VE = RE->IgnoreParenLValueCasts();
9870
9871 if (VE->isValueDependent() || VE->isTypeDependent() ||
9872 VE->isInstantiationDependent() ||
9873 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009874 // We can only analyze this information once the missing information is
9875 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +00009876 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +00009877 continue;
9878 }
9879
9880 auto *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +00009881
Samuel Antao5de996e2016-01-22 20:21:36 +00009882 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +00009883 SemaRef.Diag(ELoc,
9884 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +00009885 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +00009886 continue;
9887 }
9888
Samuel Antao90927002016-04-26 14:54:23 +00009889 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
9890 ValueDecl *CurDeclaration = nullptr;
9891
9892 // Obtain the array or member expression bases if required. Also, fill the
9893 // components array with all the components identified in the process.
Samuel Antao661c0902016-05-26 17:39:58 +00009894 auto *BE =
9895 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +00009896 if (!BE)
9897 continue;
9898
Samuel Antao90927002016-04-26 14:54:23 +00009899 assert(!CurComponents.empty() &&
9900 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +00009901
Samuel Antao90927002016-04-26 14:54:23 +00009902 // For the following checks, we rely on the base declaration which is
9903 // expected to be associated with the last component. The declaration is
9904 // expected to be a variable or a field (if 'this' is being mapped).
9905 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
9906 assert(CurDeclaration && "Null decl on map clause.");
9907 assert(
9908 CurDeclaration->isCanonicalDecl() &&
9909 "Expecting components to have associated only canonical declarations.");
9910
9911 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
9912 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +00009913
9914 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +00009915 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +00009916
9917 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +00009918 // threadprivate variables cannot appear in a map clause.
9919 // OpenMP 4.5 [2.10.5, target update Construct]
9920 // threadprivate variables cannot appear in a from clause.
9921 if (VD && DSAS->isThreadPrivate(VD)) {
9922 auto DVar = DSAS->getTopDSA(VD, false);
9923 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
9924 << getOpenMPClauseName(CKind);
9925 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +00009926 continue;
9927 }
9928
Samuel Antao5de996e2016-01-22 20:21:36 +00009929 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
9930 // A list item cannot appear in both a map clause and a data-sharing
9931 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +00009932
Samuel Antao5de996e2016-01-22 20:21:36 +00009933 // Check conflicts with other map clause expressions. We check the conflicts
9934 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +00009935 // environment, because the restrictions are different. We only have to
9936 // check conflicts across regions for the map clauses.
9937 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
9938 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +00009939 break;
Samuel Antao661c0902016-05-26 17:39:58 +00009940 if (CKind == OMPC_map &&
9941 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
9942 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +00009943 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +00009944
Samuel Antao661c0902016-05-26 17:39:58 +00009945 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +00009946 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9947 // If the type of a list item is a reference to a type T then the type will
9948 // be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +00009949 QualType Type = CurDeclaration->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +00009950
Samuel Antao661c0902016-05-26 17:39:58 +00009951 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
9952 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +00009953 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +00009954 // A list item must have a mappable type.
Samuel Antao661c0902016-05-26 17:39:58 +00009955 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
9956 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +00009957 continue;
9958
Samuel Antao661c0902016-05-26 17:39:58 +00009959 if (CKind == OMPC_map) {
9960 // target enter data
9961 // OpenMP [2.10.2, Restrictions, p. 99]
9962 // A map-type must be specified in all map clauses and must be either
9963 // to or alloc.
9964 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
9965 if (DKind == OMPD_target_enter_data &&
9966 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
9967 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
9968 << (IsMapTypeImplicit ? 1 : 0)
9969 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
9970 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009971 continue;
9972 }
Samuel Antao661c0902016-05-26 17:39:58 +00009973
9974 // target exit_data
9975 // OpenMP [2.10.3, Restrictions, p. 102]
9976 // A map-type must be specified in all map clauses and must be either
9977 // from, release, or delete.
9978 if (DKind == OMPD_target_exit_data &&
9979 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
9980 MapType == OMPC_MAP_delete)) {
9981 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
9982 << (IsMapTypeImplicit ? 1 : 0)
9983 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
9984 << getOpenMPDirectiveName(DKind);
9985 continue;
9986 }
9987
9988 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
9989 // A list item cannot appear in both a map clause and a data-sharing
9990 // attribute clause on the same construct
9991 if (DKind == OMPD_target && VD) {
9992 auto DVar = DSAS->getTopDSA(VD, false);
9993 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +00009994 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +00009995 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +00009996 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +00009997 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
9998 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
9999 continue;
10000 }
10001 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010002 }
10003
Samuel Antao90927002016-04-26 14:54:23 +000010004 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000010005 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000010006
10007 // Store the components in the stack so that they can be used to check
10008 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000010009 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
10010 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000010011
10012 // Save the components and declaration to create the clause. For purposes of
10013 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000010014 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000010015 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
10016 MVLI.VarComponents.back().append(CurComponents.begin(),
10017 CurComponents.end());
10018 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
10019 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010020 }
Samuel Antao661c0902016-05-26 17:39:58 +000010021}
10022
10023OMPClause *
10024Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
10025 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
10026 SourceLocation MapLoc, SourceLocation ColonLoc,
10027 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10028 SourceLocation LParenLoc, SourceLocation EndLoc) {
10029 MappableVarListInfo MVLI(VarList);
10030 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
10031 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010032
Samuel Antao5de996e2016-01-22 20:21:36 +000010033 // We need to produce a map clause even if we don't have variables so that
10034 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +000010035 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10036 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10037 MVLI.VarComponents, MapTypeModifier, MapType,
10038 IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010039}
Kelvin Li099bb8c2015-11-24 20:50:12 +000010040
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010041QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
10042 TypeResult ParsedType) {
10043 assert(ParsedType.isUsable());
10044
10045 QualType ReductionType = GetTypeFromParser(ParsedType.get());
10046 if (ReductionType.isNull())
10047 return QualType();
10048
10049 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
10050 // A type name in a declare reduction directive cannot be a function type, an
10051 // array type, a reference type, or a type qualified with const, volatile or
10052 // restrict.
10053 if (ReductionType.hasQualifiers()) {
10054 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
10055 return QualType();
10056 }
10057
10058 if (ReductionType->isFunctionType()) {
10059 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
10060 return QualType();
10061 }
10062 if (ReductionType->isReferenceType()) {
10063 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
10064 return QualType();
10065 }
10066 if (ReductionType->isArrayType()) {
10067 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
10068 return QualType();
10069 }
10070 return ReductionType;
10071}
10072
10073Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
10074 Scope *S, DeclContext *DC, DeclarationName Name,
10075 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
10076 AccessSpecifier AS, Decl *PrevDeclInScope) {
10077 SmallVector<Decl *, 8> Decls;
10078 Decls.reserve(ReductionTypes.size());
10079
10080 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
10081 ForRedeclaration);
10082 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
10083 // A reduction-identifier may not be re-declared in the current scope for the
10084 // same type or for a type that is compatible according to the base language
10085 // rules.
10086 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
10087 OMPDeclareReductionDecl *PrevDRD = nullptr;
10088 bool InCompoundScope = true;
10089 if (S != nullptr) {
10090 // Find previous declaration with the same name not referenced in other
10091 // declarations.
10092 FunctionScopeInfo *ParentFn = getEnclosingFunction();
10093 InCompoundScope =
10094 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
10095 LookupName(Lookup, S);
10096 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
10097 /*AllowInlineNamespace=*/false);
10098 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
10099 auto Filter = Lookup.makeFilter();
10100 while (Filter.hasNext()) {
10101 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
10102 if (InCompoundScope) {
10103 auto I = UsedAsPrevious.find(PrevDecl);
10104 if (I == UsedAsPrevious.end())
10105 UsedAsPrevious[PrevDecl] = false;
10106 if (auto *D = PrevDecl->getPrevDeclInScope())
10107 UsedAsPrevious[D] = true;
10108 }
10109 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
10110 PrevDecl->getLocation();
10111 }
10112 Filter.done();
10113 if (InCompoundScope) {
10114 for (auto &PrevData : UsedAsPrevious) {
10115 if (!PrevData.second) {
10116 PrevDRD = PrevData.first;
10117 break;
10118 }
10119 }
10120 }
10121 } else if (PrevDeclInScope != nullptr) {
10122 auto *PrevDRDInScope = PrevDRD =
10123 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
10124 do {
10125 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
10126 PrevDRDInScope->getLocation();
10127 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
10128 } while (PrevDRDInScope != nullptr);
10129 }
10130 for (auto &TyData : ReductionTypes) {
10131 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
10132 bool Invalid = false;
10133 if (I != PreviousRedeclTypes.end()) {
10134 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
10135 << TyData.first;
10136 Diag(I->second, diag::note_previous_definition);
10137 Invalid = true;
10138 }
10139 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
10140 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
10141 Name, TyData.first, PrevDRD);
10142 DC->addDecl(DRD);
10143 DRD->setAccess(AS);
10144 Decls.push_back(DRD);
10145 if (Invalid)
10146 DRD->setInvalidDecl();
10147 else
10148 PrevDRD = DRD;
10149 }
10150
10151 return DeclGroupPtrTy::make(
10152 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
10153}
10154
10155void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
10156 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10157
10158 // Enter new function scope.
10159 PushFunctionScope();
10160 getCurFunction()->setHasBranchProtectedScope();
10161 getCurFunction()->setHasOMPDeclareReductionCombiner();
10162
10163 if (S != nullptr)
10164 PushDeclContext(S, DRD);
10165 else
10166 CurContext = DRD;
10167
10168 PushExpressionEvaluationContext(PotentiallyEvaluated);
10169
10170 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010171 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
10172 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
10173 // uses semantics of argument handles by value, but it should be passed by
10174 // reference. C lang does not support references, so pass all parameters as
10175 // pointers.
10176 // Create 'T omp_in;' variable.
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010177 auto *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010178 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010179 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
10180 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
10181 // uses semantics of argument handles by value, but it should be passed by
10182 // reference. C lang does not support references, so pass all parameters as
10183 // pointers.
10184 // Create 'T omp_out;' variable.
10185 auto *OmpOutParm =
10186 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
10187 if (S != nullptr) {
10188 PushOnScopeChains(OmpInParm, S);
10189 PushOnScopeChains(OmpOutParm, S);
10190 } else {
10191 DRD->addDecl(OmpInParm);
10192 DRD->addDecl(OmpOutParm);
10193 }
10194}
10195
10196void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
10197 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10198 DiscardCleanupsInEvaluationContext();
10199 PopExpressionEvaluationContext();
10200
10201 PopDeclContext();
10202 PopFunctionScopeInfo();
10203
10204 if (Combiner != nullptr)
10205 DRD->setCombiner(Combiner);
10206 else
10207 DRD->setInvalidDecl();
10208}
10209
10210void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
10211 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10212
10213 // Enter new function scope.
10214 PushFunctionScope();
10215 getCurFunction()->setHasBranchProtectedScope();
10216
10217 if (S != nullptr)
10218 PushDeclContext(S, DRD);
10219 else
10220 CurContext = DRD;
10221
10222 PushExpressionEvaluationContext(PotentiallyEvaluated);
10223
10224 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010225 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
10226 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
10227 // uses semantics of argument handles by value, but it should be passed by
10228 // reference. C lang does not support references, so pass all parameters as
10229 // pointers.
10230 // Create 'T omp_priv;' variable.
10231 auto *OmpPrivParm =
10232 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010233 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
10234 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
10235 // uses semantics of argument handles by value, but it should be passed by
10236 // reference. C lang does not support references, so pass all parameters as
10237 // pointers.
10238 // Create 'T omp_orig;' variable.
10239 auto *OmpOrigParm =
10240 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010241 if (S != nullptr) {
10242 PushOnScopeChains(OmpPrivParm, S);
10243 PushOnScopeChains(OmpOrigParm, S);
10244 } else {
10245 DRD->addDecl(OmpPrivParm);
10246 DRD->addDecl(OmpOrigParm);
10247 }
10248}
10249
10250void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D,
10251 Expr *Initializer) {
10252 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10253 DiscardCleanupsInEvaluationContext();
10254 PopExpressionEvaluationContext();
10255
10256 PopDeclContext();
10257 PopFunctionScopeInfo();
10258
10259 if (Initializer != nullptr)
10260 DRD->setInitializer(Initializer);
10261 else
10262 DRD->setInvalidDecl();
10263}
10264
10265Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
10266 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
10267 for (auto *D : DeclReductions.get()) {
10268 if (IsValid) {
10269 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10270 if (S != nullptr)
10271 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
10272 } else
10273 D->setInvalidDecl();
10274 }
10275 return DeclReductions;
10276}
10277
David Majnemer9d168222016-08-05 17:44:54 +000010278OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000010279 SourceLocation StartLoc,
10280 SourceLocation LParenLoc,
10281 SourceLocation EndLoc) {
10282 Expr *ValExpr = NumTeams;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010283
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010284 // OpenMP [teams Constrcut, Restrictions]
10285 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000010286 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
10287 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010288 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010289
10290 return new (Context) OMPNumTeamsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10291}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010292
10293OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
10294 SourceLocation StartLoc,
10295 SourceLocation LParenLoc,
10296 SourceLocation EndLoc) {
10297 Expr *ValExpr = ThreadLimit;
10298
10299 // OpenMP [teams Constrcut, Restrictions]
10300 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000010301 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
10302 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010303 return nullptr;
10304
David Majnemer9d168222016-08-05 17:44:54 +000010305 return new (Context)
10306 OMPThreadLimitClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010307}
Alexey Bataeva0569352015-12-01 10:17:31 +000010308
10309OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
10310 SourceLocation StartLoc,
10311 SourceLocation LParenLoc,
10312 SourceLocation EndLoc) {
10313 Expr *ValExpr = Priority;
10314
10315 // OpenMP [2.9.1, task Constrcut]
10316 // The priority-value is a non-negative numerical scalar expression.
10317 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
10318 /*StrictlyPositive=*/false))
10319 return nullptr;
10320
10321 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10322}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010323
10324OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
10325 SourceLocation StartLoc,
10326 SourceLocation LParenLoc,
10327 SourceLocation EndLoc) {
10328 Expr *ValExpr = Grainsize;
10329
10330 // OpenMP [2.9.2, taskloop Constrcut]
10331 // The parameter of the grainsize clause must be a positive integer
10332 // expression.
10333 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
10334 /*StrictlyPositive=*/true))
10335 return nullptr;
10336
10337 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10338}
Alexey Bataev382967a2015-12-08 12:06:20 +000010339
10340OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
10341 SourceLocation StartLoc,
10342 SourceLocation LParenLoc,
10343 SourceLocation EndLoc) {
10344 Expr *ValExpr = NumTasks;
10345
10346 // OpenMP [2.9.2, taskloop Constrcut]
10347 // The parameter of the num_tasks clause must be a positive integer
10348 // expression.
10349 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
10350 /*StrictlyPositive=*/true))
10351 return nullptr;
10352
10353 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10354}
10355
Alexey Bataev28c75412015-12-15 08:19:24 +000010356OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
10357 SourceLocation LParenLoc,
10358 SourceLocation EndLoc) {
10359 // OpenMP [2.13.2, critical construct, Description]
10360 // ... where hint-expression is an integer constant expression that evaluates
10361 // to a valid lock hint.
10362 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
10363 if (HintExpr.isInvalid())
10364 return nullptr;
10365 return new (Context)
10366 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
10367}
10368
Carlo Bertollib4adf552016-01-15 18:50:31 +000010369OMPClause *Sema::ActOnOpenMPDistScheduleClause(
10370 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
10371 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
10372 SourceLocation EndLoc) {
10373 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
10374 std::string Values;
10375 Values += "'";
10376 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
10377 Values += "'";
10378 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
10379 << Values << getOpenMPClauseName(OMPC_dist_schedule);
10380 return nullptr;
10381 }
10382 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000010383 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000010384 if (ChunkSize) {
10385 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
10386 !ChunkSize->isInstantiationDependent() &&
10387 !ChunkSize->containsUnexpandedParameterPack()) {
10388 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
10389 ExprResult Val =
10390 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
10391 if (Val.isInvalid())
10392 return nullptr;
10393
10394 ValExpr = Val.get();
10395
10396 // OpenMP [2.7.1, Restrictions]
10397 // chunk_size must be a loop invariant integer expression with a positive
10398 // value.
10399 llvm::APSInt Result;
10400 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
10401 if (Result.isSigned() && !Result.isStrictlyPositive()) {
10402 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
10403 << "dist_schedule" << ChunkSize->getSourceRange();
10404 return nullptr;
10405 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +000010406 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
10407 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +000010408 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
10409 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
10410 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000010411 }
10412 }
10413 }
10414
10415 return new (Context)
10416 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000010417 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000010418}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010419
10420OMPClause *Sema::ActOnOpenMPDefaultmapClause(
10421 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
10422 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
10423 SourceLocation KindLoc, SourceLocation EndLoc) {
10424 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000010425 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010426 std::string Value;
10427 SourceLocation Loc;
10428 Value += "'";
10429 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
10430 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000010431 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010432 Loc = MLoc;
10433 } else {
10434 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000010435 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010436 Loc = KindLoc;
10437 }
10438 Value += "'";
10439 Diag(Loc, diag::err_omp_unexpected_clause_value)
10440 << Value << getOpenMPClauseName(OMPC_defaultmap);
10441 return nullptr;
10442 }
10443
10444 return new (Context)
10445 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
10446}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010447
10448bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
10449 DeclContext *CurLexicalContext = getCurLexicalContext();
10450 if (!CurLexicalContext->isFileContext() &&
10451 !CurLexicalContext->isExternCContext() &&
10452 !CurLexicalContext->isExternCXXContext()) {
10453 Diag(Loc, diag::err_omp_region_not_file_context);
10454 return false;
10455 }
10456 if (IsInOpenMPDeclareTargetContext) {
10457 Diag(Loc, diag::err_omp_enclosed_declare_target);
10458 return false;
10459 }
10460
10461 IsInOpenMPDeclareTargetContext = true;
10462 return true;
10463}
10464
10465void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
10466 assert(IsInOpenMPDeclareTargetContext &&
10467 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
10468
10469 IsInOpenMPDeclareTargetContext = false;
10470}
10471
David Majnemer9d168222016-08-05 17:44:54 +000010472void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
10473 CXXScopeSpec &ScopeSpec,
10474 const DeclarationNameInfo &Id,
10475 OMPDeclareTargetDeclAttr::MapTypeTy MT,
10476 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010477 LookupResult Lookup(*this, Id, LookupOrdinaryName);
10478 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
10479
10480 if (Lookup.isAmbiguous())
10481 return;
10482 Lookup.suppressDiagnostics();
10483
10484 if (!Lookup.isSingleResult()) {
10485 if (TypoCorrection Corrected =
10486 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
10487 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
10488 CTK_ErrorRecovery)) {
10489 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
10490 << Id.getName());
10491 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
10492 return;
10493 }
10494
10495 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
10496 return;
10497 }
10498
10499 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
10500 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
10501 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
10502 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
10503
10504 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
10505 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
10506 ND->addAttr(A);
10507 if (ASTMutationListener *ML = Context.getASTMutationListener())
10508 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
10509 checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
10510 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
10511 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
10512 << Id.getName();
10513 }
10514 } else
10515 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
10516}
10517
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010518static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
10519 Sema &SemaRef, Decl *D) {
10520 if (!D)
10521 return;
10522 Decl *LD = nullptr;
10523 if (isa<TagDecl>(D)) {
10524 LD = cast<TagDecl>(D)->getDefinition();
10525 } else if (isa<VarDecl>(D)) {
10526 LD = cast<VarDecl>(D)->getDefinition();
10527
10528 // If this is an implicit variable that is legal and we do not need to do
10529 // anything.
10530 if (cast<VarDecl>(D)->isImplicit()) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010531 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10532 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10533 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010534 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010535 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010536 return;
10537 }
10538
10539 } else if (isa<FunctionDecl>(D)) {
10540 const FunctionDecl *FD = nullptr;
10541 if (cast<FunctionDecl>(D)->hasBody(FD))
10542 LD = const_cast<FunctionDecl *>(FD);
10543
10544 // If the definition is associated with the current declaration in the
10545 // target region (it can be e.g. a lambda) that is legal and we do not need
10546 // to do anything else.
10547 if (LD == D) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010548 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10549 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10550 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010551 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010552 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010553 return;
10554 }
10555 }
10556 if (!LD)
10557 LD = D;
10558 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
10559 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
10560 // Outlined declaration is not declared target.
10561 if (LD->isOutOfLine()) {
10562 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
10563 SemaRef.Diag(SL, diag::note_used_here) << SR;
10564 } else {
10565 DeclContext *DC = LD->getDeclContext();
10566 while (DC) {
10567 if (isa<FunctionDecl>(DC) &&
10568 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
10569 break;
10570 DC = DC->getParent();
10571 }
10572 if (DC)
10573 return;
10574
10575 // Is not declared in target context.
10576 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
10577 SemaRef.Diag(SL, diag::note_used_here) << SR;
10578 }
10579 // Mark decl as declared target to prevent further diagnostic.
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010580 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10581 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10582 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010583 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010584 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010585 }
10586}
10587
10588static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
10589 Sema &SemaRef, DSAStackTy *Stack,
10590 ValueDecl *VD) {
10591 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
10592 return true;
10593 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
10594 return false;
10595 return true;
10596}
10597
10598void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
10599 if (!D || D->isInvalidDecl())
10600 return;
10601 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
10602 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
10603 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
10604 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10605 if (DSAStack->isThreadPrivate(VD)) {
10606 Diag(SL, diag::err_omp_threadprivate_in_target);
10607 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
10608 return;
10609 }
10610 }
10611 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
10612 // Problem if any with var declared with incomplete type will be reported
10613 // as normal, so no need to check it here.
10614 if ((E || !VD->getType()->isIncompleteType()) &&
10615 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
10616 // Mark decl as declared target to prevent further diagnostic.
10617 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010618 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10619 Context, OMPDeclareTargetDeclAttr::MT_To);
10620 VD->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010621 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010622 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010623 }
10624 return;
10625 }
10626 }
10627 if (!E) {
10628 // Checking declaration inside declare target region.
10629 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
10630 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010631 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10632 Context, OMPDeclareTargetDeclAttr::MT_To);
10633 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010634 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010635 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010636 }
10637 return;
10638 }
10639 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
10640}
Samuel Antao661c0902016-05-26 17:39:58 +000010641
10642OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
10643 SourceLocation StartLoc,
10644 SourceLocation LParenLoc,
10645 SourceLocation EndLoc) {
10646 MappableVarListInfo MVLI(VarList);
10647 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
10648 if (MVLI.ProcessedVarList.empty())
10649 return nullptr;
10650
10651 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10652 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10653 MVLI.VarComponents);
10654}
Samuel Antaoec172c62016-05-26 17:49:04 +000010655
10656OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
10657 SourceLocation StartLoc,
10658 SourceLocation LParenLoc,
10659 SourceLocation EndLoc) {
10660 MappableVarListInfo MVLI(VarList);
10661 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
10662 if (MVLI.ProcessedVarList.empty())
10663 return nullptr;
10664
10665 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10666 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10667 MVLI.VarComponents);
10668}
Carlo Bertolli2404b172016-07-13 15:37:16 +000010669
10670OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
10671 SourceLocation StartLoc,
10672 SourceLocation LParenLoc,
10673 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000010674 MappableVarListInfo MVLI(VarList);
10675 SmallVector<Expr *, 8> PrivateCopies;
10676 SmallVector<Expr *, 8> Inits;
10677
Carlo Bertolli2404b172016-07-13 15:37:16 +000010678 for (auto &RefExpr : VarList) {
10679 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
10680 SourceLocation ELoc;
10681 SourceRange ERange;
10682 Expr *SimpleRefExpr = RefExpr;
10683 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10684 if (Res.second) {
10685 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000010686 MVLI.ProcessedVarList.push_back(RefExpr);
10687 PrivateCopies.push_back(nullptr);
10688 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000010689 }
10690 ValueDecl *D = Res.first;
10691 if (!D)
10692 continue;
10693
10694 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000010695 Type = Type.getNonReferenceType().getUnqualifiedType();
10696
10697 auto *VD = dyn_cast<VarDecl>(D);
10698
10699 // Item should be a pointer or reference to pointer.
10700 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000010701 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
10702 << 0 << RefExpr->getSourceRange();
10703 continue;
10704 }
Samuel Antaocc10b852016-07-28 14:23:26 +000010705
10706 // Build the private variable and the expression that refers to it.
10707 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
10708 D->hasAttrs() ? &D->getAttrs() : nullptr);
10709 if (VDPrivate->isInvalidDecl())
10710 continue;
10711
10712 CurContext->addDecl(VDPrivate);
10713 auto VDPrivateRefExpr = buildDeclRefExpr(
10714 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
10715
10716 // Add temporary variable to initialize the private copy of the pointer.
10717 auto *VDInit =
10718 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
10719 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
10720 RefExpr->getExprLoc());
10721 AddInitializerToDecl(VDPrivate,
10722 DefaultLvalueConversion(VDInitRefExpr).get(),
10723 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
10724
10725 // If required, build a capture to implement the privatization initialized
10726 // with the current list item value.
10727 DeclRefExpr *Ref = nullptr;
10728 if (!VD)
10729 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
10730 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
10731 PrivateCopies.push_back(VDPrivateRefExpr);
10732 Inits.push_back(VDInitRefExpr);
10733
10734 // We need to add a data sharing attribute for this variable to make sure it
10735 // is correctly captured. A variable that shows up in a use_device_ptr has
10736 // similar properties of a first private variable.
10737 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
10738
10739 // Create a mappable component for the list item. List items in this clause
10740 // only need a component.
10741 MVLI.VarBaseDeclarations.push_back(D);
10742 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
10743 MVLI.VarComponents.back().push_back(
10744 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000010745 }
10746
Samuel Antaocc10b852016-07-28 14:23:26 +000010747 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000010748 return nullptr;
10749
Samuel Antaocc10b852016-07-28 14:23:26 +000010750 return OMPUseDevicePtrClause::Create(
10751 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
10752 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000010753}
Carlo Bertolli70594e92016-07-13 17:16:49 +000010754
10755OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
10756 SourceLocation StartLoc,
10757 SourceLocation LParenLoc,
10758 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000010759 MappableVarListInfo MVLI(VarList);
Carlo Bertolli70594e92016-07-13 17:16:49 +000010760 for (auto &RefExpr : VarList) {
10761 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
10762 SourceLocation ELoc;
10763 SourceRange ERange;
10764 Expr *SimpleRefExpr = RefExpr;
10765 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10766 if (Res.second) {
10767 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000010768 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000010769 }
10770 ValueDecl *D = Res.first;
10771 if (!D)
10772 continue;
10773
10774 QualType Type = D->getType();
10775 // item should be a pointer or array or reference to pointer or array
10776 if (!Type.getNonReferenceType()->isPointerType() &&
10777 !Type.getNonReferenceType()->isArrayType()) {
10778 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
10779 << 0 << RefExpr->getSourceRange();
10780 continue;
10781 }
Samuel Antao6890b092016-07-28 14:25:09 +000010782
10783 // Check if the declaration in the clause does not show up in any data
10784 // sharing attribute.
10785 auto DVar = DSAStack->getTopDSA(D, false);
10786 if (isOpenMPPrivate(DVar.CKind)) {
10787 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
10788 << getOpenMPClauseName(DVar.CKind)
10789 << getOpenMPClauseName(OMPC_is_device_ptr)
10790 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
10791 ReportOriginalDSA(*this, DSAStack, D, DVar);
10792 continue;
10793 }
10794
10795 Expr *ConflictExpr;
10796 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000010797 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000010798 [&ConflictExpr](
10799 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
10800 OpenMPClauseKind) -> bool {
10801 ConflictExpr = R.front().getAssociatedExpression();
10802 return true;
10803 })) {
10804 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
10805 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
10806 << ConflictExpr->getSourceRange();
10807 continue;
10808 }
10809
10810 // Store the components in the stack so that they can be used to check
10811 // against other clauses later on.
10812 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
10813 DSAStack->addMappableExpressionComponents(
10814 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
10815
10816 // Record the expression we've just processed.
10817 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
10818
10819 // Create a mappable component for the list item. List items in this clause
10820 // only need a component. We use a null declaration to signal fields in
10821 // 'this'.
10822 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
10823 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
10824 "Unexpected device pointer expression!");
10825 MVLI.VarBaseDeclarations.push_back(
10826 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
10827 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
10828 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000010829 }
10830
Samuel Antao6890b092016-07-28 14:25:09 +000010831 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000010832 return nullptr;
10833
Samuel Antao6890b092016-07-28 14:25:09 +000010834 return OMPIsDevicePtrClause::Create(
10835 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
10836 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000010837}