blob: d2c08ca97288bd72b2b2a41a8bdf04f2db258320 [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 Bataevf29276e2014-06-18 04:14:57 +000048template <class T> struct MatchesAny {
Alexey Bataev23b69422014-06-18 07:08:49 +000049 explicit MatchesAny(ArrayRef<T> Arr) : Arr(std::move(Arr)) {}
Alexey Bataevf29276e2014-06-18 04:14:57 +000050 bool operator()(T Kind) {
51 for (auto KindEl : Arr)
52 if (KindEl == Kind)
53 return true;
54 return false;
55 }
56
57private:
58 ArrayRef<T> Arr;
59};
Alexey Bataev23b69422014-06-18 07:08:49 +000060struct MatchesAlways {
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000061 MatchesAlways() {}
Alexey Bataev7ff55242014-06-19 09:13:45 +000062 template <class T> bool operator()(T) { return true; }
Alexey Bataevf29276e2014-06-18 04:14:57 +000063};
64
65typedef MatchesAny<OpenMPClauseKind> MatchesAnyClause;
66typedef MatchesAny<OpenMPDirectiveKind> MatchesAnyDirective;
Alexey Bataev758e55e2013-09-06 18:03:48 +000067
68/// \brief Stack for tracking declarations used in OpenMP directives and
69/// clauses and their data-sharing attributes.
70class DSAStackTy {
71public:
72 struct DSAVarData {
73 OpenMPDirectiveKind DKind;
74 OpenMPClauseKind CKind;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000075 Expr *RefExpr;
Alexey Bataev90c228f2016-02-08 09:29:13 +000076 DeclRefExpr *PrivateCopy;
Alexey Bataevbae9a792014-06-27 10:37:06 +000077 SourceLocation ImplicitDSALoc;
78 DSAVarData()
79 : DKind(OMPD_unknown), CKind(OMPC_unknown), RefExpr(nullptr),
Alexey Bataev90c228f2016-02-08 09:29:13 +000080 PrivateCopy(nullptr), ImplicitDSALoc() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +000081 };
Alexey Bataeved09d242014-05-28 05:53:51 +000082
Alexey Bataev758e55e2013-09-06 18:03:48 +000083private:
Samuel Antao5de996e2016-01-22 20:21:36 +000084 typedef SmallVector<Expr *, 4> MapInfo;
85
Alexey Bataev758e55e2013-09-06 18:03:48 +000086 struct DSAInfo {
87 OpenMPClauseKind Attributes;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000088 Expr *RefExpr;
Alexey Bataev90c228f2016-02-08 09:29:13 +000089 DeclRefExpr *PrivateCopy;
Alexey Bataev758e55e2013-09-06 18:03:48 +000090 };
Alexey Bataev90c228f2016-02-08 09:29:13 +000091 typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy;
92 typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +000093 typedef std::pair<unsigned, VarDecl *> LCDeclInfo;
94 typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy;
Alexey Bataev90c228f2016-02-08 09:29:13 +000095 typedef llvm::DenseMap<ValueDecl *, MapInfo> MappedDeclsTy;
Alexey Bataev28c75412015-12-15 08:19:24 +000096 typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
97 CriticalsWithHintsTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +000098
99 struct SharingMapTy {
100 DeclSAMapTy SharingMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000101 AlignedMapTy AlignedMap;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000102 MappedDeclsTy MappedDecls;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000103 LoopControlVariablesMapTy LCVMap;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000104 DefaultDataSharingAttributes DefaultAttr;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000105 SourceLocation DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000106 OpenMPDirectiveKind Directive;
107 DeclarationNameInfo DirectiveName;
108 Scope *CurScope;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000109 SourceLocation ConstructLoc;
Alexey Bataev346265e2015-09-25 10:37:12 +0000110 /// \brief first argument (Expr *) contains optional argument of the
111 /// 'ordered' clause, the second one is true if the regions has 'ordered'
112 /// clause, false otherwise.
113 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000114 bool NowaitRegion;
Alexey Bataev25e5b442015-09-15 12:52:43 +0000115 bool CancelRegion;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000116 unsigned AssociatedLoops;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000117 SourceLocation InnerTeamsRegionLoc;
Alexey Bataeved09d242014-05-28 05:53:51 +0000118 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000119 Scope *CurScope, SourceLocation Loc)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000120 : SharingMap(), AlignedMap(), LCVMap(), DefaultAttr(DSA_unspecified),
Alexey Bataevbae9a792014-06-27 10:37:06 +0000121 Directive(DKind), DirectiveName(std::move(Name)), CurScope(CurScope),
Alexey Bataev346265e2015-09-25 10:37:12 +0000122 ConstructLoc(Loc), OrderedRegion(), NowaitRegion(false),
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000123 CancelRegion(false), AssociatedLoops(1), InnerTeamsRegionLoc() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +0000124 SharingMapTy()
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000125 : SharingMap(), AlignedMap(), LCVMap(), DefaultAttr(DSA_unspecified),
Alexey Bataevbae9a792014-06-27 10:37:06 +0000126 Directive(OMPD_unknown), DirectiveName(), CurScope(nullptr),
Alexey Bataev346265e2015-09-25 10:37:12 +0000127 ConstructLoc(), OrderedRegion(), NowaitRegion(false),
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000128 CancelRegion(false), AssociatedLoops(1), InnerTeamsRegionLoc() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +0000129 };
130
Axel Naumann323862e2016-02-03 10:45:22 +0000131 typedef SmallVector<SharingMapTy, 4> StackTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000132
133 /// \brief Stack of used declaration and their data-sharing attributes.
134 StackTy Stack;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000135 /// \brief true, if check for DSA must be from parent directive, false, if
136 /// from current directive.
Alexey Bataevaac108a2015-06-23 04:51:00 +0000137 OpenMPClauseKind ClauseKindMode;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000138 Sema &SemaRef;
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000139 bool ForceCapturing;
Alexey Bataev28c75412015-12-15 08:19:24 +0000140 CriticalsWithHintsTy Criticals;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000141
142 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
143
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000144 DSAVarData getDSA(StackTy::reverse_iterator& Iter, ValueDecl *D);
Alexey Bataevec3da872014-01-31 05:15:34 +0000145
146 /// \brief Checks if the variable is a local for OpenMP region.
147 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
Alexey Bataeved09d242014-05-28 05:53:51 +0000148
Alexey Bataev758e55e2013-09-06 18:03:48 +0000149public:
Alexey Bataevaac108a2015-06-23 04:51:00 +0000150 explicit DSAStackTy(Sema &S)
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000151 : Stack(1), ClauseKindMode(OMPC_unknown), SemaRef(S),
152 ForceCapturing(false) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000153
Alexey Bataevaac108a2015-06-23 04:51:00 +0000154 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
155 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000156
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000157 bool isForceVarCapturing() const { return ForceCapturing; }
158 void setForceVarCapturing(bool V) { ForceCapturing = V; }
159
Alexey Bataev758e55e2013-09-06 18:03:48 +0000160 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000161 Scope *CurScope, SourceLocation Loc) {
162 Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
163 Stack.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000164 }
165
166 void pop() {
167 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
168 Stack.pop_back();
169 }
170
Alexey Bataev28c75412015-12-15 08:19:24 +0000171 void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
172 Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
173 }
174 const std::pair<OMPCriticalDirective *, llvm::APSInt>
175 getCriticalWithHint(const DeclarationNameInfo &Name) const {
176 auto I = Criticals.find(Name.getAsString());
177 if (I != Criticals.end())
178 return I->second;
179 return std::make_pair(nullptr, llvm::APSInt());
180 }
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000181 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000182 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000183 /// for diagnostics.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000184 Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000185
Alexey Bataev9c821032015-04-30 04:23:23 +0000186 /// \brief Register specified variable as loop control variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000187 void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
Alexey Bataev9c821032015-04-30 04:23:23 +0000188 /// \brief Check if the specified variable is a loop control variable for
189 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000190 /// \return The index of the loop control variable in the list of associated
191 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000192 LCDeclInfo isLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000193 /// \brief Check if the specified variable is a loop control variable for
194 /// parent region.
195 /// \return The index of the loop control variable in the list of associated
196 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000197 LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000198 /// \brief Get the loop control variable for the I-th loop (or nullptr) in
199 /// parent directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000200 ValueDecl *getParentLoopControlVariable(unsigned I);
Alexey Bataev9c821032015-04-30 04:23:23 +0000201
Alexey Bataev758e55e2013-09-06 18:03:48 +0000202 /// \brief Adds explicit data sharing attribute to the specified declaration.
Alexey Bataev90c228f2016-02-08 09:29:13 +0000203 void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
204 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000205
Alexey Bataev758e55e2013-09-06 18:03:48 +0000206 /// \brief Returns data sharing attributes from top of the stack for the
207 /// specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000208 DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000209 /// \brief Returns data-sharing attributes for the specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000210 DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000211 /// \brief Checks if the specified variables has data-sharing attributes which
212 /// match specified \a CPred predicate in any directive which matches \a DPred
213 /// predicate.
214 template <class ClausesPredicate, class DirectivesPredicate>
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000215 DSAVarData hasDSA(ValueDecl *D, ClausesPredicate CPred,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000216 DirectivesPredicate DPred, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000217 /// \brief Checks if the specified variables has data-sharing attributes which
218 /// match specified \a CPred predicate in any innermost directive which
219 /// matches \a DPred predicate.
220 template <class ClausesPredicate, class DirectivesPredicate>
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000221 DSAVarData hasInnermostDSA(ValueDecl *D, ClausesPredicate CPred,
222 DirectivesPredicate DPred, bool FromParent);
Alexey Bataevaac108a2015-06-23 04:51:00 +0000223 /// \brief Checks if the specified variables has explicit data-sharing
224 /// attributes which match specified \a CPred predicate at the specified
225 /// OpenMP region.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000226 bool hasExplicitDSA(ValueDecl *D,
Alexey Bataevaac108a2015-06-23 04:51:00 +0000227 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
228 unsigned Level);
Samuel Antao4be30e92015-10-02 17:14:03 +0000229
230 /// \brief Returns true if the directive at level \Level matches in the
231 /// specified \a DPred predicate.
232 bool hasExplicitDirective(
233 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
234 unsigned Level);
235
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000236 /// \brief Finds a directive which matches specified \a DPred predicate.
237 template <class NamedDirectivesPredicate>
238 bool hasDirective(NamedDirectivesPredicate DPred, bool FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000239
Alexey Bataev758e55e2013-09-06 18:03:48 +0000240 /// \brief Returns currently analyzed directive.
241 OpenMPDirectiveKind getCurrentDirective() const {
242 return Stack.back().Directive;
243 }
Alexey Bataev549210e2014-06-24 04:39:47 +0000244 /// \brief Returns parent directive.
245 OpenMPDirectiveKind getParentDirective() const {
246 if (Stack.size() > 2)
247 return Stack[Stack.size() - 2].Directive;
248 return OMPD_unknown;
249 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000250 /// \brief Return the directive associated with the provided scope.
251 OpenMPDirectiveKind getDirectiveForScope(const Scope *S) const;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000252
253 /// \brief Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000254 void setDefaultDSANone(SourceLocation Loc) {
255 Stack.back().DefaultAttr = DSA_none;
256 Stack.back().DefaultAttrLoc = Loc;
257 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000258 /// \brief Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000259 void setDefaultDSAShared(SourceLocation Loc) {
260 Stack.back().DefaultAttr = DSA_shared;
261 Stack.back().DefaultAttrLoc = Loc;
262 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000263
264 DefaultDataSharingAttributes getDefaultDSA() const {
265 return Stack.back().DefaultAttr;
266 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000267 SourceLocation getDefaultDSALocation() const {
268 return Stack.back().DefaultAttrLoc;
269 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000270
Alexey Bataevf29276e2014-06-18 04:14:57 +0000271 /// \brief Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000272 bool isThreadPrivate(VarDecl *D) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000273 DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000274 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000275 }
276
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000277 /// \brief Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataev346265e2015-09-25 10:37:12 +0000278 void setOrderedRegion(bool IsOrdered, Expr *Param) {
279 Stack.back().OrderedRegion.setInt(IsOrdered);
280 Stack.back().OrderedRegion.setPointer(Param);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000281 }
282 /// \brief Returns true, if parent region is ordered (has associated
283 /// 'ordered' clause), false - otherwise.
284 bool isParentOrderedRegion() const {
285 if (Stack.size() > 2)
Alexey Bataev346265e2015-09-25 10:37:12 +0000286 return Stack[Stack.size() - 2].OrderedRegion.getInt();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000287 return false;
288 }
Alexey Bataev346265e2015-09-25 10:37:12 +0000289 /// \brief Returns optional parameter for the ordered region.
290 Expr *getParentOrderedRegionParam() const {
291 if (Stack.size() > 2)
292 return Stack[Stack.size() - 2].OrderedRegion.getPointer();
293 return nullptr;
294 }
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000295 /// \brief Marks current region as nowait (it has a 'nowait' clause).
296 void setNowaitRegion(bool IsNowait = true) {
297 Stack.back().NowaitRegion = IsNowait;
298 }
299 /// \brief Returns true, if parent region is nowait (has associated
300 /// 'nowait' clause), false - otherwise.
301 bool isParentNowaitRegion() const {
302 if (Stack.size() > 2)
303 return Stack[Stack.size() - 2].NowaitRegion;
304 return false;
305 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000306 /// \brief Marks parent region as cancel region.
307 void setParentCancelRegion(bool Cancel = true) {
308 if (Stack.size() > 2)
309 Stack[Stack.size() - 2].CancelRegion =
310 Stack[Stack.size() - 2].CancelRegion || Cancel;
311 }
312 /// \brief Return true if current region has inner cancel construct.
313 bool isCancelRegion() const {
314 return Stack.back().CancelRegion;
315 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000316
Alexey Bataev9c821032015-04-30 04:23:23 +0000317 /// \brief Set collapse value for the region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000318 void setAssociatedLoops(unsigned Val) { Stack.back().AssociatedLoops = Val; }
Alexey Bataev9c821032015-04-30 04:23:23 +0000319 /// \brief Return collapse value for region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000320 unsigned getAssociatedLoops() const { return Stack.back().AssociatedLoops; }
Alexey Bataev9c821032015-04-30 04:23:23 +0000321
Alexey Bataev13314bf2014-10-09 04:18:56 +0000322 /// \brief Marks current target region as one with closely nested teams
323 /// region.
324 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
325 if (Stack.size() > 2)
326 Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
327 }
328 /// \brief Returns true, if current region has closely nested teams region.
329 bool hasInnerTeamsRegion() const {
330 return getInnerTeamsRegionLoc().isValid();
331 }
332 /// \brief Returns location of the nested teams region (if any).
333 SourceLocation getInnerTeamsRegionLoc() const {
334 if (Stack.size() > 1)
335 return Stack.back().InnerTeamsRegionLoc;
336 return SourceLocation();
337 }
338
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000339 Scope *getCurScope() const { return Stack.back().CurScope; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000340 Scope *getCurScope() { return Stack.back().CurScope; }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000341 SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000342
Samuel Antao5de996e2016-01-22 20:21:36 +0000343 // Do the check specified in MapInfoCheck and return true if any issue is
344 // found.
345 template <class MapInfoCheck>
346 bool checkMapInfoForVar(ValueDecl *VD, bool CurrentRegionOnly,
347 MapInfoCheck Check) {
348 auto SI = Stack.rbegin();
349 auto SE = Stack.rend();
350
351 if (SI == SE)
352 return false;
353
354 if (CurrentRegionOnly) {
355 SE = std::next(SI);
356 } else {
357 ++SI;
358 }
359
360 for (; SI != SE; ++SI) {
361 auto MI = SI->MappedDecls.find(VD);
362 if (MI != SI->MappedDecls.end()) {
363 for (Expr *E : MI->second) {
364 if (Check(E))
365 return true;
366 }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000367 }
368 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000369 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000370 }
371
Samuel Antao5de996e2016-01-22 20:21:36 +0000372 void addExprToVarMapInfo(ValueDecl *VD, Expr *E) {
Kelvin Li0bff7af2015-11-23 05:32:03 +0000373 if (Stack.size() > 1) {
Samuel Antao5de996e2016-01-22 20:21:36 +0000374 Stack.back().MappedDecls[VD].push_back(E);
Kelvin Li0bff7af2015-11-23 05:32:03 +0000375 }
376 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000377};
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000378bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
Alexey Bataev35aaee62016-04-13 13:36:48 +0000379 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
380 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000381}
Alexey Bataeved09d242014-05-28 05:53:51 +0000382} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000383
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000384static ValueDecl *getCanonicalDecl(ValueDecl *D) {
385 auto *VD = dyn_cast<VarDecl>(D);
386 auto *FD = dyn_cast<FieldDecl>(D);
387 if (VD != nullptr) {
388 VD = VD->getCanonicalDecl();
389 D = VD;
390 } else {
391 assert(FD);
392 FD = FD->getCanonicalDecl();
393 D = FD;
394 }
395 return D;
396}
397
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000398DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator& Iter,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000399 ValueDecl *D) {
400 D = getCanonicalDecl(D);
401 auto *VD = dyn_cast<VarDecl>(D);
402 auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000403 DSAVarData DVar;
Alexey Bataevdf9b1592014-06-25 04:09:13 +0000404 if (Iter == std::prev(Stack.rend())) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000405 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
406 // in a region but not in construct]
407 // File-scope or namespace-scope variables referenced in called routines
408 // in the region are shared unless they appear in a threadprivate
409 // directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000410 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000411 DVar.CKind = OMPC_shared;
412
413 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
414 // in a region but not in construct]
415 // Variables with static storage duration that are declared in called
416 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000417 if (VD && VD->hasGlobalStorage())
418 DVar.CKind = OMPC_shared;
419
420 // Non-static data members are shared by default.
421 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000422 DVar.CKind = OMPC_shared;
423
Alexey Bataev758e55e2013-09-06 18:03:48 +0000424 return DVar;
425 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000426
Alexey Bataev758e55e2013-09-06 18:03:48 +0000427 DVar.DKind = Iter->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +0000428 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
429 // in a Construct, C/C++, predetermined, p.1]
430 // Variables with automatic storage duration that are declared in a scope
431 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000432 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
433 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000434 DVar.CKind = OMPC_private;
435 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000436 }
437
Alexey Bataev758e55e2013-09-06 18:03:48 +0000438 // Explicitly specified attributes and local variables with predetermined
439 // attributes.
440 if (Iter->SharingMap.count(D)) {
441 DVar.RefExpr = Iter->SharingMap[D].RefExpr;
Alexey Bataev90c228f2016-02-08 09:29:13 +0000442 DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000443 DVar.CKind = Iter->SharingMap[D].Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000444 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000445 return DVar;
446 }
447
448 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
449 // in a Construct, C/C++, implicitly determined, p.1]
450 // In a parallel or task construct, the data-sharing attributes of these
451 // variables are determined by the default clause, if present.
452 switch (Iter->DefaultAttr) {
453 case DSA_shared:
454 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000455 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000456 return DVar;
457 case DSA_none:
458 return DVar;
459 case DSA_unspecified:
460 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
461 // in a Construct, implicitly determined, p.2]
462 // In a parallel construct, if no default clause is present, these
463 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000464 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000465 if (isOpenMPParallelDirective(DVar.DKind) ||
466 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000467 DVar.CKind = OMPC_shared;
468 return DVar;
469 }
470
471 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
472 // in a Construct, implicitly determined, p.4]
473 // In a task construct, if no default clause is present, a variable that in
474 // the enclosing context is determined to be shared by all implicit tasks
475 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000476 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000477 DSAVarData DVarTemp;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000478 for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000479 I != EE; ++I) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000480 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000481 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000482 // In a task construct, if no default clause is present, a variable
483 // whose data-sharing attribute is not determined by the rules above is
484 // firstprivate.
485 DVarTemp = getDSA(I, D);
486 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000487 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000488 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000489 return DVar;
490 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000491 if (isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000492 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000493 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000494 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000495 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000496 return DVar;
497 }
498 }
499 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
500 // in a Construct, implicitly determined, p.3]
501 // For constructs other than task, if no default clause is present, these
502 // variables inherit their data-sharing attributes from the enclosing
503 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000504 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000505}
506
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000507Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000508 assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000509 D = getCanonicalDecl(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000510 auto It = Stack.back().AlignedMap.find(D);
511 if (It == Stack.back().AlignedMap.end()) {
512 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
513 Stack.back().AlignedMap[D] = NewDE;
514 return nullptr;
515 } else {
516 assert(It->second && "Unexpected nullptr expr in the aligned map");
517 return It->second;
518 }
519 return nullptr;
520}
521
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000522void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
Alexey Bataev9c821032015-04-30 04:23:23 +0000523 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000524 D = getCanonicalDecl(D);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000525 Stack.back().LCVMap.insert(
526 std::make_pair(D, LCDeclInfo(Stack.back().LCVMap.size() + 1, Capture)));
Alexey Bataev9c821032015-04-30 04:23:23 +0000527}
528
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000529DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
Alexey Bataev9c821032015-04-30 04:23:23 +0000530 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000531 D = getCanonicalDecl(D);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000532 return Stack.back().LCVMap.count(D) > 0 ? Stack.back().LCVMap[D]
533 : LCDeclInfo(0, nullptr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000534}
535
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000536DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000537 assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000538 D = getCanonicalDecl(D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000539 return Stack[Stack.size() - 2].LCVMap.count(D) > 0
540 ? Stack[Stack.size() - 2].LCVMap[D]
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000541 : LCDeclInfo(0, nullptr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000542}
543
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000544ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000545 assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
546 if (Stack[Stack.size() - 2].LCVMap.size() < I)
547 return nullptr;
548 for (auto &Pair : Stack[Stack.size() - 2].LCVMap) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000549 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000550 return Pair.first;
551 }
552 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +0000553}
554
Alexey Bataev90c228f2016-02-08 09:29:13 +0000555void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
556 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000557 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000558 if (A == OMPC_threadprivate) {
559 Stack[0].SharingMap[D].Attributes = A;
560 Stack[0].SharingMap[D].RefExpr = E;
Alexey Bataev90c228f2016-02-08 09:29:13 +0000561 Stack[0].SharingMap[D].PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000562 } else {
563 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
564 Stack.back().SharingMap[D].Attributes = A;
565 Stack.back().SharingMap[D].RefExpr = E;
Alexey Bataev90c228f2016-02-08 09:29:13 +0000566 Stack.back().SharingMap[D].PrivateCopy = PrivateCopy;
567 if (PrivateCopy)
568 addDSA(PrivateCopy->getDecl(), PrivateCopy, A);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000569 }
570}
571
Alexey Bataeved09d242014-05-28 05:53:51 +0000572bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000573 D = D->getCanonicalDecl();
Alexey Bataevec3da872014-01-31 05:15:34 +0000574 if (Stack.size() > 2) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000575 reverse_iterator I = Iter, E = std::prev(Stack.rend());
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000576 Scope *TopScope = nullptr;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000577 while (I != E && !isParallelOrTaskRegion(I->Directive)) {
Alexey Bataevec3da872014-01-31 05:15:34 +0000578 ++I;
579 }
Alexey Bataeved09d242014-05-28 05:53:51 +0000580 if (I == E)
581 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000582 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000583 Scope *CurScope = getCurScope();
584 while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000585 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000586 }
587 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000588 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000589 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000590}
591
Alexey Bataev39f915b82015-05-08 10:41:21 +0000592/// \brief Build a variable declaration for OpenMP loop iteration variable.
593static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000594 StringRef Name, const AttrVec *Attrs = nullptr) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000595 DeclContext *DC = SemaRef.CurContext;
596 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
597 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
598 VarDecl *Decl =
599 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000600 if (Attrs) {
601 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
602 I != E; ++I)
603 Decl->addAttr(*I);
604 }
Alexey Bataev39f915b82015-05-08 10:41:21 +0000605 Decl->setImplicit();
606 return Decl;
607}
608
609static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
610 SourceLocation Loc,
611 bool RefersToCapture = false) {
612 D->setReferenced();
613 D->markUsed(S.Context);
614 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
615 SourceLocation(), D, RefersToCapture, Loc, Ty,
616 VK_LValue);
617}
618
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000619DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
620 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000621 DSAVarData DVar;
622
623 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
624 // in a Construct, C/C++, predetermined, p.1]
625 // Variables appearing in threadprivate directives are threadprivate.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000626 auto *VD = dyn_cast<VarDecl>(D);
627 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
628 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
Samuel Antaof8b50122015-07-13 22:54:53 +0000629 SemaRef.getLangOpts().OpenMPUseTLS &&
630 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000631 (VD && VD->getStorageClass() == SC_Register &&
632 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
633 addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
Alexey Bataev39f915b82015-05-08 10:41:21 +0000634 D->getLocation()),
Alexey Bataevf2453a02015-05-06 07:25:08 +0000635 OMPC_threadprivate);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000636 }
637 if (Stack[0].SharingMap.count(D)) {
638 DVar.RefExpr = Stack[0].SharingMap[D].RefExpr;
639 DVar.CKind = OMPC_threadprivate;
640 return DVar;
641 }
642
Dmitry Polukhin0b0da292016-04-06 11:38:59 +0000643 if (Stack.size() == 1) {
644 // Not in OpenMP execution region and top scope was already checked.
645 return DVar;
646 }
647
Alexey Bataev758e55e2013-09-06 18:03:48 +0000648 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000649 // in a Construct, C/C++, predetermined, p.4]
650 // Static data members are shared.
651 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
652 // in a Construct, C/C++, predetermined, p.7]
653 // Variables with static storage duration that are declared in a scope
654 // inside the construct are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000655 if (VD && VD->isStaticDataMember()) {
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000656 DSAVarData DVarTemp =
657 hasDSA(D, isOpenMPPrivate, MatchesAlways(), FromParent);
658 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
Alexey Bataevec3da872014-01-31 05:15:34 +0000659 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000660
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000661 DVar.CKind = OMPC_shared;
662 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000663 }
664
665 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000666 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
667 Type = SemaRef.getASTContext().getBaseElementType(Type);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000668 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
669 // in a Construct, C/C++, predetermined, p.6]
670 // Variables with const qualified type having no mutable member are
671 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000672 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +0000673 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataevc9bd03d2015-12-17 06:55:08 +0000674 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
675 if (auto *CTD = CTSD->getSpecializedTemplate())
676 RD = CTD->getTemplatedDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000677 if (IsConstant &&
Alexey Bataev4bcad7f2016-02-10 10:50:12 +0000678 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
679 RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000680 // Variables with const-qualified type having no mutable member may be
681 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000682 DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
683 MatchesAlways(), FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000684 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
685 return DVar;
686
Alexey Bataev758e55e2013-09-06 18:03:48 +0000687 DVar.CKind = OMPC_shared;
688 return DVar;
689 }
690
Alexey Bataev758e55e2013-09-06 18:03:48 +0000691 // Explicitly specified attributes and local variables with predetermined
692 // attributes.
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000693 auto StartI = std::next(Stack.rbegin());
694 auto EndI = std::prev(Stack.rend());
695 if (FromParent && StartI != EndI) {
696 StartI = std::next(StartI);
697 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000698 auto I = std::prev(StartI);
699 if (I->SharingMap.count(D)) {
700 DVar.RefExpr = I->SharingMap[D].RefExpr;
Alexey Bataev90c228f2016-02-08 09:29:13 +0000701 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000702 DVar.CKind = I->SharingMap[D].Attributes;
703 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000704 }
705
706 return DVar;
707}
708
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000709DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
710 bool FromParent) {
711 D = getCanonicalDecl(D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000712 auto StartI = Stack.rbegin();
713 auto EndI = std::prev(Stack.rend());
714 if (FromParent && StartI != EndI) {
715 StartI = std::next(StartI);
716 }
717 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000718}
719
Alexey Bataevf29276e2014-06-18 04:14:57 +0000720template <class ClausesPredicate, class DirectivesPredicate>
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000721DSAStackTy::DSAVarData DSAStackTy::hasDSA(ValueDecl *D, ClausesPredicate CPred,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000722 DirectivesPredicate DPred,
723 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000724 D = getCanonicalDecl(D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000725 auto StartI = std::next(Stack.rbegin());
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000726 auto EndI = Stack.rend();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000727 if (FromParent && StartI != EndI) {
728 StartI = std::next(StartI);
729 }
730 for (auto I = StartI, EE = EndI; I != EE; ++I) {
731 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000732 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000733 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000734 if (CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000735 return DVar;
736 }
737 return DSAVarData();
738}
739
Alexey Bataevf29276e2014-06-18 04:14:57 +0000740template <class ClausesPredicate, class DirectivesPredicate>
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000741DSAStackTy::DSAVarData
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000742DSAStackTy::hasInnermostDSA(ValueDecl *D, ClausesPredicate CPred,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000743 DirectivesPredicate DPred, bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000744 D = getCanonicalDecl(D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000745 auto StartI = std::next(Stack.rbegin());
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000746 auto EndI = Stack.rend();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000747 if (FromParent && StartI != EndI) {
748 StartI = std::next(StartI);
749 }
750 for (auto I = StartI, EE = EndI; I != EE; ++I) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000751 if (!DPred(I->Directive))
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000752 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +0000753 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000754 if (CPred(DVar.CKind))
Alexey Bataevc5e02582014-06-16 07:08:35 +0000755 return DVar;
756 return DSAVarData();
757 }
758 return DSAVarData();
759}
760
Alexey Bataevaac108a2015-06-23 04:51:00 +0000761bool DSAStackTy::hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000762 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataevaac108a2015-06-23 04:51:00 +0000763 unsigned Level) {
764 if (CPred(ClauseKindMode))
765 return true;
766 if (isClauseParsingMode())
767 ++Level;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000768 D = getCanonicalDecl(D);
Alexey Bataevaac108a2015-06-23 04:51:00 +0000769 auto StartI = Stack.rbegin();
770 auto EndI = std::prev(Stack.rend());
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +0000771 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +0000772 return false;
773 std::advance(StartI, Level);
774 return (StartI->SharingMap.count(D) > 0) && StartI->SharingMap[D].RefExpr &&
775 CPred(StartI->SharingMap[D].Attributes);
776}
777
Samuel Antao4be30e92015-10-02 17:14:03 +0000778bool DSAStackTy::hasExplicitDirective(
779 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
780 unsigned Level) {
781 if (isClauseParsingMode())
782 ++Level;
783 auto StartI = Stack.rbegin();
784 auto EndI = std::prev(Stack.rend());
785 if (std::distance(StartI, EndI) <= (int)Level)
786 return false;
787 std::advance(StartI, Level);
788 return DPred(StartI->Directive);
789}
790
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000791template <class NamedDirectivesPredicate>
792bool DSAStackTy::hasDirective(NamedDirectivesPredicate DPred, bool FromParent) {
793 auto StartI = std::next(Stack.rbegin());
794 auto EndI = std::prev(Stack.rend());
795 if (FromParent && StartI != EndI) {
796 StartI = std::next(StartI);
797 }
798 for (auto I = StartI, EE = EndI; I != EE; ++I) {
799 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
800 return true;
801 }
802 return false;
803}
804
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000805OpenMPDirectiveKind DSAStackTy::getDirectiveForScope(const Scope *S) const {
806 for (auto I = Stack.rbegin(), EE = Stack.rend(); I != EE; ++I)
807 if (I->CurScope == S)
808 return I->Directive;
809 return OMPD_unknown;
810}
811
Alexey Bataev758e55e2013-09-06 18:03:48 +0000812void Sema::InitDataSharingAttributesStack() {
813 VarDataSharingAttributesStack = new DSAStackTy(*this);
814}
815
816#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
817
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000818bool Sema::IsOpenMPCapturedByRef(ValueDecl *D,
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000819 const CapturedRegionScopeInfo *RSI) {
820 assert(LangOpts.OpenMP && "OpenMP is not allowed");
821
822 auto &Ctx = getASTContext();
823 bool IsByRef = true;
824
825 // Find the directive that is associated with the provided scope.
826 auto DKind = DSAStack->getDirectiveForScope(RSI->TheScope);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000827 auto Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000828
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +0000829 if (isOpenMPTargetExecutionDirective(DKind)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000830 // This table summarizes how a given variable should be passed to the device
831 // given its type and the clauses where it appears. This table is based on
832 // the description in OpenMP 4.5 [2.10.4, target Construct] and
833 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
834 //
835 // =========================================================================
836 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
837 // | |(tofrom:scalar)| | pvt | | | |
838 // =========================================================================
839 // | scl | | | | - | | bycopy|
840 // | scl | | - | x | - | - | bycopy|
841 // | scl | | x | - | - | - | null |
842 // | scl | x | | | - | | byref |
843 // | scl | x | - | x | - | - | bycopy|
844 // | scl | x | x | - | - | - | null |
845 // | scl | | - | - | - | x | byref |
846 // | scl | x | - | - | - | x | byref |
847 //
848 // | agg | n.a. | | | - | | byref |
849 // | agg | n.a. | - | x | - | - | byref |
850 // | agg | n.a. | x | - | - | - | null |
851 // | agg | n.a. | - | - | - | x | byref |
852 // | agg | n.a. | - | - | - | x[] | byref |
853 //
854 // | ptr | n.a. | | | - | | bycopy|
855 // | ptr | n.a. | - | x | - | - | bycopy|
856 // | ptr | n.a. | x | - | - | - | null |
857 // | ptr | n.a. | - | - | - | x | byref |
858 // | ptr | n.a. | - | - | - | x[] | bycopy|
859 // | ptr | n.a. | - | - | x | | bycopy|
860 // | ptr | n.a. | - | - | x | x | bycopy|
861 // | ptr | n.a. | - | - | x | x[] | bycopy|
862 // =========================================================================
863 // Legend:
864 // scl - scalar
865 // ptr - pointer
866 // agg - aggregate
867 // x - applies
868 // - - invalid in this combination
869 // [] - mapped with an array section
870 // byref - should be mapped by reference
871 // byval - should be mapped by value
872 // null - initialize a local variable to null on the device
873 //
874 // Observations:
875 // - All scalar declarations that show up in a map clause have to be passed
876 // by reference, because they may have been mapped in the enclosing data
877 // environment.
878 // - If the scalar value does not fit the size of uintptr, it has to be
879 // passed by reference, regardless the result in the table above.
880 // - For pointers mapped by value that have either an implicit map or an
881 // array section, the runtime library may pass the NULL value to the
882 // device instead of the value passed to it by the compiler.
883
884 // FIXME: Right now, only implicit maps are implemented. Properly mapping
885 // values requires having the map, private, and firstprivate clauses SEMA
886 // and parsing in place, which we don't yet.
887
888 if (Ty->isReferenceType())
889 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
890 IsByRef = !Ty->isScalarType();
891 }
892
893 // When passing data by value, we need to make sure it fits the uintptr size
894 // and alignment, because the runtime library only deals with uintptr types.
895 // If it does not fit the uintptr size, we need to pass the data by reference
896 // instead.
897 if (!IsByRef &&
898 (Ctx.getTypeSizeInChars(Ty) >
899 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000900 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType())))
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000901 IsByRef = true;
902
903 return IsByRef;
904}
905
Alexey Bataev90c228f2016-02-08 09:29:13 +0000906VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
Alexey Bataevf841bd92014-12-16 07:00:22 +0000907 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000908 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +0000909
910 // If we are attempting to capture a global variable in a directive with
911 // 'target' we return true so that this global is also mapped to the device.
912 //
913 // FIXME: If the declaration is enclosed in a 'declare target' directive,
914 // then it should not be captured. Therefore, an extra check has to be
915 // inserted here once support for 'declare target' is added.
916 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000917 auto *VD = dyn_cast<VarDecl>(D);
918 if (VD && !VD->hasLocalStorage()) {
Samuel Antao4be30e92015-10-02 17:14:03 +0000919 if (DSAStack->getCurrentDirective() == OMPD_target &&
Alexey Bataev90c228f2016-02-08 09:29:13 +0000920 !DSAStack->isClauseParsingMode())
921 return VD;
Samuel Antao4be30e92015-10-02 17:14:03 +0000922 if (DSAStack->getCurScope() &&
923 DSAStack->hasDirective(
924 [](OpenMPDirectiveKind K, const DeclarationNameInfo &DNI,
925 SourceLocation Loc) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +0000926 return isOpenMPTargetExecutionDirective(K);
Samuel Antao4be30e92015-10-02 17:14:03 +0000927 },
Alexey Bataev90c228f2016-02-08 09:29:13 +0000928 false))
929 return VD;
Samuel Antao4be30e92015-10-02 17:14:03 +0000930 }
931
Alexey Bataev48977c32015-08-04 08:10:48 +0000932 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
933 (!DSAStack->isClauseParsingMode() ||
934 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000935 auto &&Info = DSAStack->isLoopControlVariable(D);
936 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000937 (VD && VD->hasLocalStorage() &&
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000938 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000939 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000940 return VD ? VD : Info.second;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000941 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +0000942 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +0000943 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000944 DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate, MatchesAlways(),
Alexey Bataevaac108a2015-06-23 04:51:00 +0000945 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +0000946 if (DVarPrivate.CKind != OMPC_unknown)
947 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +0000948 }
Alexey Bataev90c228f2016-02-08 09:29:13 +0000949 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +0000950}
951
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000952bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
Alexey Bataevaac108a2015-06-23 04:51:00 +0000953 assert(LangOpts.OpenMP && "OpenMP is not allowed");
954 return DSAStack->hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000955 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
Alexey Bataevaac108a2015-06-23 04:51:00 +0000956}
957
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000958bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
Samuel Antao4be30e92015-10-02 17:14:03 +0000959 assert(LangOpts.OpenMP && "OpenMP is not allowed");
960 // Return true if the current level is no longer enclosed in a target region.
961
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000962 auto *VD = dyn_cast<VarDecl>(D);
963 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +0000964 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
965 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +0000966}
967
Alexey Bataeved09d242014-05-28 05:53:51 +0000968void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000969
970void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
971 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000972 Scope *CurScope, SourceLocation Loc) {
973 DSAStack->push(DKind, DirName, CurScope, Loc);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000974 PushExpressionEvaluationContext(PotentiallyEvaluated);
975}
976
Alexey Bataevaac108a2015-06-23 04:51:00 +0000977void Sema::StartOpenMPClause(OpenMPClauseKind K) {
978 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +0000979}
980
Alexey Bataevaac108a2015-06-23 04:51:00 +0000981void Sema::EndOpenMPClause() {
982 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +0000983}
984
Alexey Bataev758e55e2013-09-06 18:03:48 +0000985void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000986 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
987 // A variable of class type (or array thereof) that appears in a lastprivate
988 // clause requires an accessible, unambiguous default constructor for the
989 // class type, unless the list item is also specified in a firstprivate
990 // clause.
991 if (auto D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000992 for (auto *C : D->clauses()) {
993 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
994 SmallVector<Expr *, 8> PrivateCopies;
995 for (auto *DE : Clause->varlists()) {
996 if (DE->isValueDependent() || DE->isTypeDependent()) {
997 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000998 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +0000999 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001000 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataev005248a2016-02-25 05:25:57 +00001001 VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1002 QualType Type = VD->getType().getNonReferenceType();
1003 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001004 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001005 // Generate helper private variable and initialize it with the
1006 // default value. The address of the original variable is replaced
1007 // by the address of the new private variable in CodeGen. This new
1008 // variable is not added to IdResolver, so the code in the OpenMP
1009 // region uses original variable for proper diagnostics.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001010 auto *VDPrivate = buildVarDecl(
1011 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev005248a2016-02-25 05:25:57 +00001012 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev38e89532015-04-16 04:54:05 +00001013 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
1014 if (VDPrivate->isInvalidDecl())
1015 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001016 PrivateCopies.push_back(buildDeclRefExpr(
1017 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001018 } else {
1019 // The variable is also a firstprivate, so initialization sequence
1020 // for private copy is generated already.
1021 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001022 }
1023 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001024 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001025 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001026 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001027 }
1028 }
1029 }
1030
Alexey Bataev758e55e2013-09-06 18:03:48 +00001031 DSAStack->pop();
1032 DiscardCleanupsInEvaluationContext();
1033 PopExpressionEvaluationContext();
1034}
1035
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001036static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1037 Expr *NumIterations, Sema &SemaRef,
1038 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001039
Alexey Bataeva769e072013-03-22 06:34:35 +00001040namespace {
1041
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001042class VarDeclFilterCCC : public CorrectionCandidateCallback {
1043private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001044 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001045
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001046public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001047 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001048 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001049 NamedDecl *ND = Candidate.getCorrectionDecl();
1050 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) {
1051 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001052 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1053 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001054 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001055 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001056 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001057};
Alexey Bataeved09d242014-05-28 05:53:51 +00001058} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001059
1060ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1061 CXXScopeSpec &ScopeSpec,
1062 const DeclarationNameInfo &Id) {
1063 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1064 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1065
1066 if (Lookup.isAmbiguous())
1067 return ExprError();
1068
1069 VarDecl *VD;
1070 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001071 if (TypoCorrection Corrected = CorrectTypo(
1072 Id, LookupOrdinaryName, CurScope, nullptr,
1073 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001074 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001075 PDiag(Lookup.empty()
1076 ? diag::err_undeclared_var_use_suggest
1077 : diag::err_omp_expected_var_arg_suggest)
1078 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001079 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001080 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001081 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1082 : diag::err_omp_expected_var_arg)
1083 << Id.getName();
1084 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001085 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001086 } else {
1087 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00001088 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001089 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1090 return ExprError();
1091 }
1092 }
1093 Lookup.suppressDiagnostics();
1094
1095 // OpenMP [2.9.2, Syntax, C/C++]
1096 // Variables must be file-scope, namespace-scope, or static block-scope.
1097 if (!VD->hasGlobalStorage()) {
1098 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001099 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1100 bool IsDecl =
1101 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001102 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00001103 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1104 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001105 return ExprError();
1106 }
1107
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001108 VarDecl *CanonicalVD = VD->getCanonicalDecl();
1109 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001110 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1111 // A threadprivate directive for file-scope variables must appear outside
1112 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001113 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1114 !getCurLexicalContext()->isTranslationUnit()) {
1115 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001116 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1117 bool IsDecl =
1118 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1119 Diag(VD->getLocation(),
1120 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1121 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001122 return ExprError();
1123 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001124 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1125 // A threadprivate directive for static class member variables must appear
1126 // in the class definition, in the same scope in which the member
1127 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001128 if (CanonicalVD->isStaticDataMember() &&
1129 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1130 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001131 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1132 bool IsDecl =
1133 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1134 Diag(VD->getLocation(),
1135 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1136 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001137 return ExprError();
1138 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001139 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1140 // A threadprivate directive for namespace-scope variables must appear
1141 // outside any definition or declaration other than the namespace
1142 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001143 if (CanonicalVD->getDeclContext()->isNamespace() &&
1144 (!getCurLexicalContext()->isFileContext() ||
1145 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1146 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001147 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1148 bool IsDecl =
1149 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1150 Diag(VD->getLocation(),
1151 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1152 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001153 return ExprError();
1154 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001155 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1156 // A threadprivate directive for static block-scope variables must appear
1157 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001158 if (CanonicalVD->isStaticLocal() && CurScope &&
1159 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001160 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001161 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1162 bool IsDecl =
1163 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1164 Diag(VD->getLocation(),
1165 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1166 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001167 return ExprError();
1168 }
1169
1170 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1171 // A threadprivate directive must lexically precede all references to any
1172 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001173 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001174 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +00001175 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001176 return ExprError();
1177 }
1178
1179 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00001180 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1181 SourceLocation(), VD,
1182 /*RefersToEnclosingVariableOrCapture=*/false,
1183 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001184}
1185
Alexey Bataeved09d242014-05-28 05:53:51 +00001186Sema::DeclGroupPtrTy
1187Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1188 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001189 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001190 CurContext->addDecl(D);
1191 return DeclGroupPtrTy::make(DeclGroupRef(D));
1192 }
David Blaikie0403cb12016-01-15 23:43:25 +00001193 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00001194}
1195
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001196namespace {
1197class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1198 Sema &SemaRef;
1199
1200public:
1201 bool VisitDeclRefExpr(const DeclRefExpr *E) {
1202 if (auto VD = dyn_cast<VarDecl>(E->getDecl())) {
1203 if (VD->hasLocalStorage()) {
1204 SemaRef.Diag(E->getLocStart(),
1205 diag::err_omp_local_var_in_threadprivate_init)
1206 << E->getSourceRange();
1207 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1208 << VD << VD->getSourceRange();
1209 return true;
1210 }
1211 }
1212 return false;
1213 }
1214 bool VisitStmt(const Stmt *S) {
1215 for (auto Child : S->children()) {
1216 if (Child && Visit(Child))
1217 return true;
1218 }
1219 return false;
1220 }
Alexey Bataev23b69422014-06-18 07:08:49 +00001221 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001222};
1223} // namespace
1224
Alexey Bataeved09d242014-05-28 05:53:51 +00001225OMPThreadPrivateDecl *
1226Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001227 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00001228 for (auto &RefExpr : VarList) {
1229 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001230 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1231 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00001232
Alexey Bataev376b4a42016-02-09 09:41:09 +00001233 // Mark variable as used.
1234 VD->setReferenced();
1235 VD->markUsed(Context);
1236
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001237 QualType QType = VD->getType();
1238 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1239 // It will be analyzed later.
1240 Vars.push_back(DE);
1241 continue;
1242 }
1243
Alexey Bataeva769e072013-03-22 06:34:35 +00001244 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1245 // A threadprivate variable must not have an incomplete type.
1246 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001247 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001248 continue;
1249 }
1250
1251 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1252 // A threadprivate variable must not have a reference type.
1253 if (VD->getType()->isReferenceType()) {
1254 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001255 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1256 bool IsDecl =
1257 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1258 Diag(VD->getLocation(),
1259 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1260 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001261 continue;
1262 }
1263
Samuel Antaof8b50122015-07-13 22:54:53 +00001264 // Check if this is a TLS variable. If TLS is not being supported, produce
1265 // the corresponding diagnostic.
1266 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1267 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1268 getLangOpts().OpenMPUseTLS &&
1269 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00001270 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1271 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00001272 Diag(ILoc, diag::err_omp_var_thread_local)
1273 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00001274 bool IsDecl =
1275 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1276 Diag(VD->getLocation(),
1277 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1278 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001279 continue;
1280 }
1281
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001282 // Check if initial value of threadprivate variable reference variable with
1283 // local storage (it is not supported by runtime).
1284 if (auto Init = VD->getAnyInitializer()) {
1285 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001286 if (Checker.Visit(Init))
1287 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001288 }
1289
Alexey Bataeved09d242014-05-28 05:53:51 +00001290 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00001291 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00001292 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1293 Context, SourceRange(Loc, Loc)));
1294 if (auto *ML = Context.getASTMutationListener())
1295 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00001296 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001297 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001298 if (!Vars.empty()) {
1299 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1300 Vars);
1301 D->setAccess(AS_public);
1302 }
1303 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00001304}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001305
Alexey Bataev7ff55242014-06-19 09:13:45 +00001306static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001307 const ValueDecl *D, DSAStackTy::DSAVarData DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00001308 bool IsLoopIterVar = false) {
1309 if (DVar.RefExpr) {
1310 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1311 << getOpenMPClauseName(DVar.CKind);
1312 return;
1313 }
1314 enum {
1315 PDSA_StaticMemberShared,
1316 PDSA_StaticLocalVarShared,
1317 PDSA_LoopIterVarPrivate,
1318 PDSA_LoopIterVarLinear,
1319 PDSA_LoopIterVarLastprivate,
1320 PDSA_ConstVarShared,
1321 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001322 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001323 PDSA_LocalVarPrivate,
1324 PDSA_Implicit
1325 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001326 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001327 auto ReportLoc = D->getLocation();
1328 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00001329 if (IsLoopIterVar) {
1330 if (DVar.CKind == OMPC_private)
1331 Reason = PDSA_LoopIterVarPrivate;
1332 else if (DVar.CKind == OMPC_lastprivate)
1333 Reason = PDSA_LoopIterVarLastprivate;
1334 else
1335 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00001336 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1337 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001338 Reason = PDSA_TaskVarFirstprivate;
1339 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001340 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001341 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001342 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001343 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001344 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001345 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001346 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00001347 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001348 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001349 ReportHint = true;
1350 Reason = PDSA_LocalVarPrivate;
1351 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001352 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001353 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001354 << Reason << ReportHint
1355 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1356 } else if (DVar.ImplicitDSALoc.isValid()) {
1357 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1358 << getOpenMPClauseName(DVar.CKind);
1359 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001360}
1361
Alexey Bataev758e55e2013-09-06 18:03:48 +00001362namespace {
1363class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1364 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001365 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001366 bool ErrorFound;
1367 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001368 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001369 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataeved09d242014-05-28 05:53:51 +00001370
Alexey Bataev758e55e2013-09-06 18:03:48 +00001371public:
1372 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001373 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001374 // Skip internally declared variables.
Alexey Bataeved09d242014-05-28 05:53:51 +00001375 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1376 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001377
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001378 auto DVar = Stack->getTopDSA(VD, false);
1379 // Check if the variable has explicit DSA set and stop analysis if it so.
1380 if (DVar.RefExpr) return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001381
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001382 auto ELoc = E->getExprLoc();
1383 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001384 // The default(none) clause requires that each variable that is referenced
1385 // in the construct, and does not have a predetermined data-sharing
1386 // attribute, must have its data-sharing attribute explicitly determined
1387 // by being listed in a data-sharing attribute clause.
1388 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001389 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001390 VarsWithInheritedDSA.count(VD) == 0) {
1391 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001392 return;
1393 }
1394
1395 // OpenMP [2.9.3.6, Restrictions, p.2]
1396 // A list item that appears in a reduction clause of the innermost
1397 // enclosing worksharing or parallel construct may not be accessed in an
1398 // explicit task.
Alexey Bataevf29276e2014-06-18 04:14:57 +00001399 DVar = Stack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001400 [](OpenMPDirectiveKind K) -> bool {
1401 return isOpenMPParallelDirective(K) ||
Alexey Bataev13314bf2014-10-09 04:18:56 +00001402 isOpenMPWorksharingDirective(K) ||
1403 isOpenMPTeamsDirective(K);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001404 },
1405 false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001406 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00001407 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001408 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1409 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001410 return;
1411 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001412
1413 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001414 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001415 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1416 !Stack->isLoopControlVariable(VD).first)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001417 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001418 }
1419 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001420 void VisitMemberExpr(MemberExpr *E) {
1421 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
1422 if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
1423 auto DVar = Stack->getTopDSA(FD, false);
1424 // Check if the variable has explicit DSA set and stop analysis if it
1425 // so.
1426 if (DVar.RefExpr)
1427 return;
1428
1429 auto ELoc = E->getExprLoc();
1430 auto DKind = Stack->getCurrentDirective();
1431 // OpenMP [2.9.3.6, Restrictions, p.2]
1432 // A list item that appears in a reduction clause of the innermost
1433 // enclosing worksharing or parallel construct may not be accessed in
Alexey Bataevd985eda2016-02-10 11:29:16 +00001434 // an explicit task.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001435 DVar =
1436 Stack->hasInnermostDSA(FD, MatchesAnyClause(OMPC_reduction),
1437 [](OpenMPDirectiveKind K) -> bool {
1438 return isOpenMPParallelDirective(K) ||
1439 isOpenMPWorksharingDirective(K) ||
1440 isOpenMPTeamsDirective(K);
1441 },
1442 false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001443 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001444 ErrorFound = true;
1445 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1446 ReportOriginalDSA(SemaRef, Stack, FD, DVar);
1447 return;
1448 }
1449
1450 // Define implicit data-sharing attributes for task.
1451 DVar = Stack->getImplicitDSA(FD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001452 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1453 !Stack->isLoopControlVariable(FD).first)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001454 ImplicitFirstprivate.push_back(E);
1455 }
1456 }
1457 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001458 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001459 for (auto *C : S->clauses()) {
1460 // Skip analysis of arguments of implicitly defined firstprivate clause
1461 // for task directives.
1462 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1463 for (auto *CC : C->children()) {
1464 if (CC)
1465 Visit(CC);
1466 }
1467 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001468 }
1469 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001470 for (auto *C : S->children()) {
1471 if (C && !isa<OMPExecutableDirective>(C))
1472 Visit(C);
1473 }
Alexey Bataeved09d242014-05-28 05:53:51 +00001474 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001475
1476 bool isErrorFound() { return ErrorFound; }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001477 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001478 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
Alexey Bataev4acb8592014-07-07 13:01:15 +00001479 return VarsWithInheritedDSA;
1480 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001481
Alexey Bataev7ff55242014-06-19 09:13:45 +00001482 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1483 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00001484};
Alexey Bataeved09d242014-05-28 05:53:51 +00001485} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00001486
Alexey Bataevbae9a792014-06-27 10:37:06 +00001487void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001488 switch (DKind) {
1489 case OMPD_parallel: {
1490 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001491 QualType KmpInt32PtrTy =
1492 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001493 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001494 std::make_pair(".global_tid.", KmpInt32PtrTy),
1495 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1496 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001497 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001498 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1499 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001500 break;
1501 }
1502 case OMPD_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001503 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001504 std::make_pair(StringRef(), QualType()) // __context with shared vars
1505 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001506 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1507 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001508 break;
1509 }
1510 case OMPD_for: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001511 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001512 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001513 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001514 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1515 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001516 break;
1517 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00001518 case OMPD_for_simd: {
1519 Sema::CapturedParamNameType Params[] = {
1520 std::make_pair(StringRef(), QualType()) // __context with shared vars
1521 };
1522 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1523 Params);
1524 break;
1525 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001526 case OMPD_sections: {
1527 Sema::CapturedParamNameType Params[] = {
1528 std::make_pair(StringRef(), QualType()) // __context with shared vars
1529 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001530 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1531 Params);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001532 break;
1533 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001534 case OMPD_section: {
1535 Sema::CapturedParamNameType Params[] = {
1536 std::make_pair(StringRef(), QualType()) // __context with shared vars
1537 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001538 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1539 Params);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001540 break;
1541 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001542 case OMPD_single: {
1543 Sema::CapturedParamNameType Params[] = {
1544 std::make_pair(StringRef(), QualType()) // __context with shared vars
1545 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001546 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1547 Params);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001548 break;
1549 }
Alexander Musman80c22892014-07-17 08:54:58 +00001550 case OMPD_master: {
1551 Sema::CapturedParamNameType Params[] = {
1552 std::make_pair(StringRef(), QualType()) // __context with shared vars
1553 };
1554 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1555 Params);
1556 break;
1557 }
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001558 case OMPD_critical: {
1559 Sema::CapturedParamNameType Params[] = {
1560 std::make_pair(StringRef(), QualType()) // __context with shared vars
1561 };
1562 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1563 Params);
1564 break;
1565 }
Alexey Bataev4acb8592014-07-07 13:01:15 +00001566 case OMPD_parallel_for: {
1567 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001568 QualType KmpInt32PtrTy =
1569 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataev4acb8592014-07-07 13:01:15 +00001570 Sema::CapturedParamNameType Params[] = {
1571 std::make_pair(".global_tid.", KmpInt32PtrTy),
1572 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1573 std::make_pair(StringRef(), QualType()) // __context with shared vars
1574 };
1575 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1576 Params);
1577 break;
1578 }
Alexander Musmane4e893b2014-09-23 09:33:00 +00001579 case OMPD_parallel_for_simd: {
1580 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001581 QualType KmpInt32PtrTy =
1582 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexander Musmane4e893b2014-09-23 09:33:00 +00001583 Sema::CapturedParamNameType Params[] = {
1584 std::make_pair(".global_tid.", KmpInt32PtrTy),
1585 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1586 std::make_pair(StringRef(), QualType()) // __context with shared vars
1587 };
1588 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1589 Params);
1590 break;
1591 }
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001592 case OMPD_parallel_sections: {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001593 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001594 QualType KmpInt32PtrTy =
1595 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001596 Sema::CapturedParamNameType Params[] = {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001597 std::make_pair(".global_tid.", KmpInt32PtrTy),
1598 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001599 std::make_pair(StringRef(), QualType()) // __context with shared vars
1600 };
1601 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1602 Params);
1603 break;
1604 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001605 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001606 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001607 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1608 FunctionProtoType::ExtProtoInfo EPI;
1609 EPI.Variadic = true;
1610 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001611 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001612 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataev48591dd2016-04-20 04:01:36 +00001613 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1614 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
1615 std::make_pair(".copy_fn.",
1616 Context.getPointerType(CopyFnType).withConst()),
1617 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001618 std::make_pair(StringRef(), QualType()) // __context with shared vars
1619 };
1620 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1621 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001622 // Mark this captured region as inlined, because we don't use outlined
1623 // function directly.
1624 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1625 AlwaysInlineAttr::CreateImplicit(
1626 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001627 break;
1628 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001629 case OMPD_ordered: {
1630 Sema::CapturedParamNameType Params[] = {
1631 std::make_pair(StringRef(), QualType()) // __context with shared vars
1632 };
1633 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1634 Params);
1635 break;
1636 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001637 case OMPD_atomic: {
1638 Sema::CapturedParamNameType Params[] = {
1639 std::make_pair(StringRef(), QualType()) // __context with shared vars
1640 };
1641 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1642 Params);
1643 break;
1644 }
Michael Wong65f367f2015-07-21 13:44:28 +00001645 case OMPD_target_data:
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00001646 case OMPD_target:
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00001647 case OMPD_target_parallel:
1648 case OMPD_target_parallel_for: {
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001649 Sema::CapturedParamNameType Params[] = {
1650 std::make_pair(StringRef(), QualType()) // __context with shared vars
1651 };
1652 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1653 Params);
1654 break;
1655 }
Alexey Bataev13314bf2014-10-09 04:18:56 +00001656 case OMPD_teams: {
1657 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001658 QualType KmpInt32PtrTy =
1659 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataev13314bf2014-10-09 04:18:56 +00001660 Sema::CapturedParamNameType Params[] = {
1661 std::make_pair(".global_tid.", KmpInt32PtrTy),
1662 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1663 std::make_pair(StringRef(), QualType()) // __context with shared vars
1664 };
1665 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1666 Params);
1667 break;
1668 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001669 case OMPD_taskgroup: {
1670 Sema::CapturedParamNameType Params[] = {
1671 std::make_pair(StringRef(), QualType()) // __context with shared vars
1672 };
1673 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1674 Params);
1675 break;
1676 }
Alexey Bataev49f6e782015-12-01 04:18:41 +00001677 case OMPD_taskloop: {
Alexey Bataev7292c292016-04-25 12:22:29 +00001678 QualType KmpInt32Ty =
1679 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1680 QualType KmpUInt64Ty =
1681 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
1682 QualType KmpInt64Ty =
1683 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
1684 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1685 FunctionProtoType::ExtProtoInfo EPI;
1686 EPI.Variadic = true;
1687 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00001688 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00001689 std::make_pair(".global_tid.", KmpInt32Ty),
1690 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1691 std::make_pair(".privates.",
1692 Context.VoidPtrTy.withConst().withRestrict()),
1693 std::make_pair(
1694 ".copy_fn.",
1695 Context.getPointerType(CopyFnType).withConst().withRestrict()),
1696 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1697 std::make_pair(".lb.", KmpUInt64Ty),
1698 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
1699 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataev49f6e782015-12-01 04:18:41 +00001700 std::make_pair(StringRef(), QualType()) // __context with shared vars
1701 };
1702 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1703 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00001704 // Mark this captured region as inlined, because we don't use outlined
1705 // function directly.
1706 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1707 AlwaysInlineAttr::CreateImplicit(
1708 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev49f6e782015-12-01 04:18:41 +00001709 break;
1710 }
Alexey Bataev0a6ed842015-12-03 09:40:15 +00001711 case OMPD_taskloop_simd: {
1712 Sema::CapturedParamNameType Params[] = {
1713 std::make_pair(StringRef(), QualType()) // __context with shared vars
1714 };
1715 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1716 Params);
1717 break;
1718 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00001719 case OMPD_distribute: {
1720 Sema::CapturedParamNameType Params[] = {
1721 std::make_pair(StringRef(), QualType()) // __context with shared vars
1722 };
1723 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1724 Params);
1725 break;
1726 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001727 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001728 case OMPD_taskyield:
1729 case OMPD_barrier:
1730 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001731 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00001732 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00001733 case OMPD_flush:
Samuel Antaodf67fc42016-01-19 19:15:56 +00001734 case OMPD_target_enter_data:
Samuel Antao72590762016-01-19 20:04:50 +00001735 case OMPD_target_exit_data:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00001736 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00001737 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001738 case OMPD_declare_target:
1739 case OMPD_end_declare_target:
Alexey Bataev9959db52014-05-06 10:08:46 +00001740 llvm_unreachable("OpenMP Directive is not allowed");
1741 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001742 llvm_unreachable("Unknown OpenMP directive");
1743 }
1744}
1745
Alexey Bataev3392d762016-02-16 11:18:12 +00001746static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00001747 Expr *CaptureExpr, bool WithInit,
1748 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001749 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00001750 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00001751 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00001752 QualType Ty = Init->getType();
1753 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
1754 if (S.getLangOpts().CPlusPlus)
1755 Ty = C.getLValueReferenceType(Ty);
1756 else {
1757 Ty = C.getPointerType(Ty);
1758 ExprResult Res =
1759 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
1760 if (!Res.isUsable())
1761 return nullptr;
1762 Init = Res.get();
1763 }
Alexey Bataev61205072016-03-02 04:57:40 +00001764 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00001765 }
1766 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001767 if (!WithInit)
1768 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
Alexey Bataev4244be22016-02-11 05:35:55 +00001769 S.CurContext->addHiddenDecl(CED);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001770 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false,
1771 /*TypeMayContainAuto=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00001772 return CED;
1773}
1774
Alexey Bataev61205072016-03-02 04:57:40 +00001775static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
1776 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00001777 OMPCapturedExprDecl *CD;
1778 if (auto *VD = S.IsOpenMPCapturedDecl(D))
1779 CD = cast<OMPCapturedExprDecl>(VD);
1780 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00001781 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
1782 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001783 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00001784 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00001785}
1786
Alexey Bataev5a3af132016-03-29 08:58:54 +00001787static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
1788 if (!Ref) {
1789 auto *CD =
1790 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
1791 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
1792 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
1793 CaptureExpr->getExprLoc());
1794 }
1795 ExprResult Res = Ref;
1796 if (!S.getLangOpts().CPlusPlus &&
1797 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
1798 Ref->getType()->isPointerType())
1799 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
1800 if (!Res.isUsable())
1801 return ExprError();
1802 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00001803}
1804
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001805StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1806 ArrayRef<OMPClause *> Clauses) {
1807 if (!S.isUsable()) {
1808 ActOnCapturedRegionError();
1809 return StmtError();
1810 }
Alexey Bataev993d2802015-12-28 06:23:08 +00001811
1812 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00001813 OMPScheduleClause *SC = nullptr;
Alexey Bataev993d2802015-12-28 06:23:08 +00001814 SmallVector<OMPLinearClause *, 4> LCs;
Alexey Bataev040d5402015-05-12 08:35:28 +00001815 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001816 for (auto *Clause : Clauses) {
Alexey Bataev16dc7b62015-05-20 03:46:04 +00001817 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001818 Clause->getClauseKind() == OMPC_copyprivate ||
1819 (getLangOpts().OpenMPUseTLS &&
1820 getASTContext().getTargetInfo().isTLSSupported() &&
1821 Clause->getClauseKind() == OMPC_copyin)) {
1822 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00001823 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001824 for (auto *VarRef : Clause->children()) {
1825 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00001826 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001827 }
1828 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001829 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001830 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
Alexey Bataev040d5402015-05-12 08:35:28 +00001831 // Mark all variables in private list clauses as used in inner region.
1832 // Required for proper codegen of combined directives.
1833 // TODO: add processing for other clauses.
Alexey Bataev3392d762016-02-16 11:18:12 +00001834 if (auto *C = OMPClauseWithPreInit::get(Clause)) {
Alexey Bataev005248a2016-02-25 05:25:57 +00001835 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
1836 for (auto *D : DS->decls())
Alexey Bataev3392d762016-02-16 11:18:12 +00001837 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
1838 }
Alexey Bataev4244be22016-02-11 05:35:55 +00001839 }
Alexey Bataev005248a2016-02-25 05:25:57 +00001840 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
1841 if (auto *E = C->getPostUpdateExpr())
1842 MarkDeclarationsReferencedInExpr(E);
1843 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001844 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001845 if (Clause->getClauseKind() == OMPC_schedule)
1846 SC = cast<OMPScheduleClause>(Clause);
1847 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00001848 OC = cast<OMPOrderedClause>(Clause);
1849 else if (Clause->getClauseKind() == OMPC_linear)
1850 LCs.push_back(cast<OMPLinearClause>(Clause));
1851 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001852 bool ErrorFound = false;
1853 // OpenMP, 2.7.1 Loop Construct, Restrictions
1854 // The nonmonotonic modifier cannot be specified if an ordered clause is
1855 // specified.
1856 if (SC &&
1857 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
1858 SC->getSecondScheduleModifier() ==
1859 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
1860 OC) {
1861 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
1862 ? SC->getFirstScheduleModifierLoc()
1863 : SC->getSecondScheduleModifierLoc(),
1864 diag::err_omp_schedule_nonmonotonic_ordered)
1865 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1866 ErrorFound = true;
1867 }
Alexey Bataev993d2802015-12-28 06:23:08 +00001868 if (!LCs.empty() && OC && OC->getNumForLoops()) {
1869 for (auto *C : LCs) {
1870 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
1871 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1872 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001873 ErrorFound = true;
1874 }
Alexey Bataev113438c2015-12-30 12:06:23 +00001875 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
1876 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
1877 OC->getNumForLoops()) {
1878 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
1879 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
1880 ErrorFound = true;
1881 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001882 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00001883 ActOnCapturedRegionError();
1884 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001885 }
1886 return ActOnCapturedRegionEnd(S.get());
1887}
1888
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001889static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1890 OpenMPDirectiveKind CurrentRegion,
1891 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001892 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001893 SourceLocation StartLoc) {
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001894 // Allowed nesting of constructs
1895 // +------------------+-----------------+------------------------------------+
1896 // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)|
1897 // +------------------+-----------------+------------------------------------+
1898 // | parallel | parallel | * |
1899 // | parallel | for | * |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001900 // | parallel | for simd | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001901 // | parallel | master | * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001902 // | parallel | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001903 // | parallel | simd | * |
1904 // | parallel | sections | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001905 // | parallel | section | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001906 // | parallel | single | * |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001907 // | parallel | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001908 // | parallel |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001909 // | parallel |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001910 // | parallel | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001911 // | parallel | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001912 // | parallel | barrier | * |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001913 // | parallel | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001914 // | parallel | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001915 // | parallel | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001916 // | parallel | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001917 // | parallel | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001918 // | parallel | target | * |
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00001919 // | parallel | target parallel | * |
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00001920 // | parallel | target parallel | * |
1921 // | | for | |
Samuel Antaodf67fc42016-01-19 19:15:56 +00001922 // | parallel | target enter | * |
1923 // | | data | |
Samuel Antao72590762016-01-19 20:04:50 +00001924 // | parallel | target exit | * |
1925 // | | data | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001926 // | parallel | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001927 // | parallel | cancellation | |
1928 // | | point | ! |
Alexey Bataev80909872015-07-02 11:25:17 +00001929 // | parallel | cancel | ! |
Alexey Bataev49f6e782015-12-01 04:18:41 +00001930 // | parallel | taskloop | * |
Alexey Bataev0a6ed842015-12-03 09:40:15 +00001931 // | parallel | taskloop simd | * |
Samuel Antaodf67fc42016-01-19 19:15:56 +00001932 // | parallel | distribute | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001933 // +------------------+-----------------+------------------------------------+
1934 // | for | parallel | * |
1935 // | for | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001936 // | for | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001937 // | for | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001938 // | for | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001939 // | for | simd | * |
1940 // | for | sections | + |
1941 // | for | section | + |
1942 // | for | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001943 // | for | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001944 // | for |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001945 // | for |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001946 // | for | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001947 // | for | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001948 // | for | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001949 // | for | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001950 // | for | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001951 // | for | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001952 // | for | ordered | * (if construct is ordered) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001953 // | for | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001954 // | for | target | * |
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00001955 // | for | target parallel | * |
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00001956 // | for | target parallel | * |
1957 // | | for | |
Samuel Antaodf67fc42016-01-19 19:15:56 +00001958 // | for | target enter | * |
1959 // | | data | |
Samuel Antao72590762016-01-19 20:04:50 +00001960 // | for | target exit | * |
1961 // | | data | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001962 // | for | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001963 // | for | cancellation | |
1964 // | | point | ! |
Alexey Bataev80909872015-07-02 11:25:17 +00001965 // | for | cancel | ! |
Alexey Bataev49f6e782015-12-01 04:18:41 +00001966 // | for | taskloop | * |
Alexey Bataev0a6ed842015-12-03 09:40:15 +00001967 // | for | taskloop simd | * |
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00001968 // | for | distribute | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001969 // +------------------+-----------------+------------------------------------+
Alexander Musman80c22892014-07-17 08:54:58 +00001970 // | master | parallel | * |
1971 // | master | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001972 // | master | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001973 // | master | master | * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001974 // | master | critical | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001975 // | master | simd | * |
1976 // | master | sections | + |
1977 // | master | section | + |
1978 // | master | single | + |
1979 // | master | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001980 // | master |parallel for simd| * |
Alexander Musman80c22892014-07-17 08:54:58 +00001981 // | master |parallel sections| * |
1982 // | master | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001983 // | master | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001984 // | master | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001985 // | master | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001986 // | master | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001987 // | master | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001988 // | master | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001989 // | master | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001990 // | master | target | * |
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00001991 // | master | target parallel | * |
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00001992 // | master | target parallel | * |
1993 // | | for | |
Samuel Antaodf67fc42016-01-19 19:15:56 +00001994 // | master | target enter | * |
1995 // | | data | |
Samuel Antao72590762016-01-19 20:04:50 +00001996 // | master | target exit | * |
1997 // | | data | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001998 // | master | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001999 // | master | cancellation | |
2000 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00002001 // | master | cancel | |
Alexey Bataev49f6e782015-12-01 04:18:41 +00002002 // | master | taskloop | * |
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002003 // | master | taskloop simd | * |
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002004 // | master | distribute | |
Alexander Musman80c22892014-07-17 08:54:58 +00002005 // +------------------+-----------------+------------------------------------+
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002006 // | critical | parallel | * |
2007 // | critical | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00002008 // | critical | for simd | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002009 // | critical | master | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002010 // | critical | critical | * (should have different names) |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002011 // | critical | simd | * |
2012 // | critical | sections | + |
2013 // | critical | section | + |
2014 // | critical | single | + |
2015 // | critical | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00002016 // | critical |parallel for simd| * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002017 // | critical |parallel sections| * |
2018 // | critical | task | * |
2019 // | critical | taskyield | * |
2020 // | critical | barrier | + |
2021 // | critical | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002022 // | critical | taskgroup | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002023 // | critical | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00002024 // | critical | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002025 // | critical | target | * |
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002026 // | critical | target parallel | * |
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002027 // | critical | target parallel | * |
2028 // | | for | |
Samuel Antaodf67fc42016-01-19 19:15:56 +00002029 // | critical | target enter | * |
2030 // | | data | |
Samuel Antao72590762016-01-19 20:04:50 +00002031 // | critical | target exit | * |
2032 // | | data | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00002033 // | critical | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002034 // | critical | cancellation | |
2035 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00002036 // | critical | cancel | |
Alexey Bataev49f6e782015-12-01 04:18:41 +00002037 // | critical | taskloop | * |
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002038 // | critical | taskloop simd | * |
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002039 // | critical | distribute | |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002040 // +------------------+-----------------+------------------------------------+
Alexey Bataev18eb25e2014-06-30 10:22:46 +00002041 // | simd | parallel | |
2042 // | simd | for | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00002043 // | simd | for simd | |
Alexander Musman80c22892014-07-17 08:54:58 +00002044 // | simd | master | |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002045 // | simd | critical | |
Alexey Bataev1f092212016-02-02 04:59:52 +00002046 // | simd | simd | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00002047 // | simd | sections | |
2048 // | simd | section | |
2049 // | simd | single | |
Alexey Bataev4acb8592014-07-07 13:01:15 +00002050 // | simd | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00002051 // | simd |parallel for simd| |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002052 // | simd |parallel sections| |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002053 // | simd | task | |
Alexey Bataev68446b72014-07-18 07:47:19 +00002054 // | simd | taskyield | |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002055 // | simd | barrier | |
Alexey Bataev2df347a2014-07-18 10:17:07 +00002056 // | simd | taskwait | |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002057 // | simd | taskgroup | |
Alexey Bataev6125da92014-07-21 11:26:11 +00002058 // | simd | flush | |
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002059 // | simd | ordered | + (with simd clause) |
Alexey Bataev0162e452014-07-22 10:10:35 +00002060 // | simd | atomic | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002061 // | simd | target | |
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002062 // | simd | target parallel | |
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002063 // | simd | target parallel | |
2064 // | | for | |
Samuel Antaodf67fc42016-01-19 19:15:56 +00002065 // | simd | target enter | |
2066 // | | data | |
Samuel Antao72590762016-01-19 20:04:50 +00002067 // | simd | target exit | |
2068 // | | data | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00002069 // | simd | teams | |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002070 // | simd | cancellation | |
2071 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00002072 // | simd | cancel | |
Alexey Bataev49f6e782015-12-01 04:18:41 +00002073 // | simd | taskloop | |
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002074 // | simd | taskloop simd | |
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002075 // | simd | distribute | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00002076 // +------------------+-----------------+------------------------------------+
Alexander Musmanf82886e2014-09-18 05:12:34 +00002077 // | for simd | parallel | |
2078 // | for simd | for | |
2079 // | for simd | for simd | |
2080 // | for simd | master | |
2081 // | for simd | critical | |
Alexey Bataev1f092212016-02-02 04:59:52 +00002082 // | for simd | simd | * |
Alexander Musmanf82886e2014-09-18 05:12:34 +00002083 // | for simd | sections | |
2084 // | for simd | section | |
2085 // | for simd | single | |
2086 // | for simd | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00002087 // | for simd |parallel for simd| |
Alexander Musmanf82886e2014-09-18 05:12:34 +00002088 // | for simd |parallel sections| |
2089 // | for simd | task | |
2090 // | for simd | taskyield | |
2091 // | for simd | barrier | |
2092 // | for simd | taskwait | |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002093 // | for simd | taskgroup | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00002094 // | for simd | flush | |
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002095 // | for simd | ordered | + (with simd clause) |
Alexander Musmanf82886e2014-09-18 05:12:34 +00002096 // | for simd | atomic | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002097 // | for simd | target | |
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002098 // | for simd | target parallel | |
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002099 // | for simd | target parallel | |
2100 // | | for | |
Samuel Antaodf67fc42016-01-19 19:15:56 +00002101 // | for simd | target enter | |
2102 // | | data | |
Samuel Antao72590762016-01-19 20:04:50 +00002103 // | for simd | target exit | |
2104 // | | data | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00002105 // | for simd | teams | |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002106 // | for simd | cancellation | |
2107 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00002108 // | for simd | cancel | |
Alexey Bataev49f6e782015-12-01 04:18:41 +00002109 // | for simd | taskloop | |
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002110 // | for simd | taskloop simd | |
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002111 // | for simd | distribute | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00002112 // +------------------+-----------------+------------------------------------+
Alexander Musmane4e893b2014-09-23 09:33:00 +00002113 // | parallel for simd| parallel | |
2114 // | parallel for simd| for | |
2115 // | parallel for simd| for simd | |
2116 // | parallel for simd| master | |
2117 // | parallel for simd| critical | |
Alexey Bataev1f092212016-02-02 04:59:52 +00002118 // | parallel for simd| simd | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00002119 // | parallel for simd| sections | |
2120 // | parallel for simd| section | |
2121 // | parallel for simd| single | |
2122 // | parallel for simd| parallel for | |
2123 // | parallel for simd|parallel for simd| |
2124 // | parallel for simd|parallel sections| |
2125 // | parallel for simd| task | |
2126 // | parallel for simd| taskyield | |
2127 // | parallel for simd| barrier | |
2128 // | parallel for simd| taskwait | |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002129 // | parallel for simd| taskgroup | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00002130 // | parallel for simd| flush | |
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002131 // | parallel for simd| ordered | + (with simd clause) |
Alexander Musmane4e893b2014-09-23 09:33:00 +00002132 // | parallel for simd| atomic | |
2133 // | parallel for simd| target | |
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002134 // | parallel for simd| target parallel | |
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002135 // | parallel for simd| target parallel | |
2136 // | | for | |
Samuel Antaodf67fc42016-01-19 19:15:56 +00002137 // | parallel for simd| target enter | |
2138 // | | data | |
Samuel Antao72590762016-01-19 20:04:50 +00002139 // | parallel for simd| target exit | |
2140 // | | data | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00002141 // | parallel for simd| teams | |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002142 // | parallel for simd| cancellation | |
2143 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00002144 // | parallel for simd| cancel | |
Alexey Bataev49f6e782015-12-01 04:18:41 +00002145 // | parallel for simd| taskloop | |
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002146 // | parallel for simd| taskloop simd | |
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002147 // | parallel for simd| distribute | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00002148 // +------------------+-----------------+------------------------------------+
Alexey Bataev18eb25e2014-06-30 10:22:46 +00002149 // | sections | parallel | * |
2150 // | sections | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00002151 // | sections | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00002152 // | sections | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002153 // | sections | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00002154 // | sections | simd | * |
2155 // | sections | sections | + |
2156 // | sections | section | * |
2157 // | sections | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00002158 // | sections | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00002159 // | sections |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002160 // | sections |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002161 // | sections | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00002162 // | sections | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002163 // | sections | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00002164 // | sections | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002165 // | sections | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00002166 // | sections | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002167 // | sections | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00002168 // | sections | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002169 // | sections | target | * |
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002170 // | sections | target parallel | * |
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002171 // | sections | target parallel | * |
2172 // | | for | |
Samuel Antaodf67fc42016-01-19 19:15:56 +00002173 // | sections | target enter | * |
2174 // | | data | |
Samuel Antao72590762016-01-19 20:04:50 +00002175 // | sections | target exit | * |
2176 // | | data | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00002177 // | sections | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002178 // | sections | cancellation | |
2179 // | | point | ! |
Alexey Bataev80909872015-07-02 11:25:17 +00002180 // | sections | cancel | ! |
Alexey Bataev49f6e782015-12-01 04:18:41 +00002181 // | sections | taskloop | * |
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002182 // | sections | taskloop simd | * |
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002183 // | sections | distribute | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00002184 // +------------------+-----------------+------------------------------------+
2185 // | section | parallel | * |
2186 // | section | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00002187 // | section | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00002188 // | section | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002189 // | section | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00002190 // | section | simd | * |
2191 // | section | sections | + |
2192 // | section | section | + |
2193 // | section | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00002194 // | section | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00002195 // | section |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002196 // | section |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002197 // | section | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00002198 // | section | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002199 // | section | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00002200 // | section | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002201 // | section | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00002202 // | section | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002203 // | section | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00002204 // | section | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002205 // | section | target | * |
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002206 // | section | target parallel | * |
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002207 // | section | target parallel | * |
2208 // | | for | |
Samuel Antaodf67fc42016-01-19 19:15:56 +00002209 // | section | target enter | * |
2210 // | | data | |
Samuel Antao72590762016-01-19 20:04:50 +00002211 // | section | target exit | * |
2212 // | | data | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00002213 // | section | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002214 // | section | cancellation | |
2215 // | | point | ! |
Alexey Bataev80909872015-07-02 11:25:17 +00002216 // | section | cancel | ! |
Alexey Bataev49f6e782015-12-01 04:18:41 +00002217 // | section | taskloop | * |
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002218 // | section | taskloop simd | * |
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002219 // | section | distribute | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00002220 // +------------------+-----------------+------------------------------------+
2221 // | single | parallel | * |
2222 // | single | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00002223 // | single | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00002224 // | single | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002225 // | single | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00002226 // | single | simd | * |
2227 // | single | sections | + |
2228 // | single | section | + |
2229 // | single | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00002230 // | single | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00002231 // | single |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002232 // | single |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002233 // | single | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00002234 // | single | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002235 // | single | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00002236 // | single | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002237 // | single | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00002238 // | single | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002239 // | single | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00002240 // | single | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002241 // | single | target | * |
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002242 // | single | target parallel | * |
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002243 // | single | target parallel | * |
2244 // | | for | |
Samuel Antaodf67fc42016-01-19 19:15:56 +00002245 // | single | target enter | * |
2246 // | | data | |
Samuel Antao72590762016-01-19 20:04:50 +00002247 // | single | target exit | * |
2248 // | | data | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00002249 // | single | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002250 // | single | cancellation | |
2251 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00002252 // | single | cancel | |
Alexey Bataev49f6e782015-12-01 04:18:41 +00002253 // | single | taskloop | * |
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002254 // | single | taskloop simd | * |
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002255 // | single | distribute | |
Alexey Bataev4acb8592014-07-07 13:01:15 +00002256 // +------------------+-----------------+------------------------------------+
2257 // | parallel for | parallel | * |
2258 // | parallel for | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00002259 // | parallel for | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00002260 // | parallel for | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002261 // | parallel for | critical | * |
Alexey Bataev4acb8592014-07-07 13:01:15 +00002262 // | parallel for | simd | * |
2263 // | parallel for | sections | + |
2264 // | parallel for | section | + |
2265 // | parallel for | single | + |
2266 // | parallel for | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00002267 // | parallel for |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002268 // | parallel for |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002269 // | parallel for | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00002270 // | parallel for | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002271 // | parallel for | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00002272 // | parallel for | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002273 // | parallel for | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00002274 // | parallel for | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002275 // | parallel for | ordered | * (if construct is ordered) |
Alexey Bataev0162e452014-07-22 10:10:35 +00002276 // | parallel for | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002277 // | parallel for | target | * |
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002278 // | parallel for | target parallel | * |
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002279 // | parallel for | target parallel | * |
2280 // | | for | |
Samuel Antaodf67fc42016-01-19 19:15:56 +00002281 // | parallel for | target enter | * |
2282 // | | data | |
Samuel Antao72590762016-01-19 20:04:50 +00002283 // | parallel for | target exit | * |
2284 // | | data | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00002285 // | parallel for | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002286 // | parallel for | cancellation | |
2287 // | | point | ! |
Alexey Bataev80909872015-07-02 11:25:17 +00002288 // | parallel for | cancel | ! |
Alexey Bataev49f6e782015-12-01 04:18:41 +00002289 // | parallel for | taskloop | * |
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002290 // | parallel for | taskloop simd | * |
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002291 // | parallel for | distribute | |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002292 // +------------------+-----------------+------------------------------------+
2293 // | parallel sections| parallel | * |
2294 // | parallel sections| for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00002295 // | parallel sections| for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00002296 // | parallel sections| master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002297 // | parallel sections| critical | + |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002298 // | parallel sections| simd | * |
2299 // | parallel sections| sections | + |
2300 // | parallel sections| section | * |
2301 // | parallel sections| single | + |
2302 // | parallel sections| parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00002303 // | parallel sections|parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002304 // | parallel sections|parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002305 // | parallel sections| task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00002306 // | parallel sections| taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002307 // | parallel sections| barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00002308 // | parallel sections| taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002309 // | parallel sections| taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00002310 // | parallel sections| flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002311 // | parallel sections| ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00002312 // | parallel sections| atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002313 // | parallel sections| target | * |
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002314 // | parallel sections| target parallel | * |
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002315 // | parallel sections| target parallel | * |
2316 // | | for | |
Samuel Antaodf67fc42016-01-19 19:15:56 +00002317 // | parallel sections| target enter | * |
2318 // | | data | |
Samuel Antao72590762016-01-19 20:04:50 +00002319 // | parallel sections| target exit | * |
2320 // | | data | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00002321 // | parallel sections| teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002322 // | parallel sections| cancellation | |
2323 // | | point | ! |
Alexey Bataev80909872015-07-02 11:25:17 +00002324 // | parallel sections| cancel | ! |
Alexey Bataev49f6e782015-12-01 04:18:41 +00002325 // | parallel sections| taskloop | * |
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002326 // | parallel sections| taskloop simd | * |
Samuel Antaodf67fc42016-01-19 19:15:56 +00002327 // | parallel sections| distribute | |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002328 // +------------------+-----------------+------------------------------------+
2329 // | task | parallel | * |
2330 // | task | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00002331 // | task | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00002332 // | task | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002333 // | task | critical | * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002334 // | task | simd | * |
2335 // | task | sections | + |
Alexander Musman80c22892014-07-17 08:54:58 +00002336 // | task | section | + |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002337 // | task | single | + |
2338 // | task | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00002339 // | task |parallel for simd| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002340 // | task |parallel sections| * |
2341 // | task | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00002342 // | task | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002343 // | task | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00002344 // | task | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002345 // | task | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00002346 // | task | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002347 // | task | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00002348 // | task | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002349 // | task | target | * |
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002350 // | task | target parallel | * |
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002351 // | task | target parallel | * |
2352 // | | for | |
Samuel Antaodf67fc42016-01-19 19:15:56 +00002353 // | task | target enter | * |
2354 // | | data | |
Samuel Antao72590762016-01-19 20:04:50 +00002355 // | task | target exit | * |
2356 // | | data | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00002357 // | task | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002358 // | task | cancellation | |
Alexey Bataev80909872015-07-02 11:25:17 +00002359 // | | point | ! |
2360 // | task | cancel | ! |
Alexey Bataev49f6e782015-12-01 04:18:41 +00002361 // | task | taskloop | * |
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002362 // | task | taskloop simd | * |
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002363 // | task | distribute | |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002364 // +------------------+-----------------+------------------------------------+
2365 // | ordered | parallel | * |
2366 // | ordered | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00002367 // | ordered | for simd | + |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002368 // | ordered | master | * |
2369 // | ordered | critical | * |
2370 // | ordered | simd | * |
2371 // | ordered | sections | + |
2372 // | ordered | section | + |
2373 // | ordered | single | + |
2374 // | ordered | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00002375 // | ordered |parallel for simd| * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002376 // | ordered |parallel sections| * |
2377 // | ordered | task | * |
2378 // | ordered | taskyield | * |
2379 // | ordered | barrier | + |
2380 // | ordered | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002381 // | ordered | taskgroup | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002382 // | ordered | flush | * |
2383 // | ordered | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00002384 // | ordered | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002385 // | ordered | target | * |
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002386 // | ordered | target parallel | * |
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002387 // | ordered | target parallel | * |
2388 // | | for | |
Samuel Antaodf67fc42016-01-19 19:15:56 +00002389 // | ordered | target enter | * |
2390 // | | data | |
Samuel Antao72590762016-01-19 20:04:50 +00002391 // | ordered | target exit | * |
2392 // | | data | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00002393 // | ordered | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002394 // | ordered | cancellation | |
2395 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00002396 // | ordered | cancel | |
Alexey Bataev49f6e782015-12-01 04:18:41 +00002397 // | ordered | taskloop | * |
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002398 // | ordered | taskloop simd | * |
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002399 // | ordered | distribute | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002400 // +------------------+-----------------+------------------------------------+
2401 // | atomic | parallel | |
2402 // | atomic | for | |
2403 // | atomic | for simd | |
2404 // | atomic | master | |
2405 // | atomic | critical | |
2406 // | atomic | simd | |
2407 // | atomic | sections | |
2408 // | atomic | section | |
2409 // | atomic | single | |
2410 // | atomic | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00002411 // | atomic |parallel for simd| |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002412 // | atomic |parallel sections| |
2413 // | atomic | task | |
2414 // | atomic | taskyield | |
2415 // | atomic | barrier | |
2416 // | atomic | taskwait | |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002417 // | atomic | taskgroup | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002418 // | atomic | flush | |
2419 // | atomic | ordered | |
2420 // | atomic | atomic | |
2421 // | atomic | target | |
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002422 // | atomic | target parallel | |
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002423 // | atomic | target parallel | |
2424 // | | for | |
Samuel Antaodf67fc42016-01-19 19:15:56 +00002425 // | atomic | target enter | |
2426 // | | data | |
Samuel Antao72590762016-01-19 20:04:50 +00002427 // | atomic | target exit | |
2428 // | | data | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00002429 // | atomic | teams | |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002430 // | atomic | cancellation | |
2431 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00002432 // | atomic | cancel | |
Alexey Bataev49f6e782015-12-01 04:18:41 +00002433 // | atomic | taskloop | |
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002434 // | atomic | taskloop simd | |
Samuel Antaodf67fc42016-01-19 19:15:56 +00002435 // | atomic | distribute | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002436 // +------------------+-----------------+------------------------------------+
2437 // | target | parallel | * |
2438 // | target | for | * |
2439 // | target | for simd | * |
2440 // | target | master | * |
2441 // | target | critical | * |
2442 // | target | simd | * |
2443 // | target | sections | * |
2444 // | target | section | * |
2445 // | target | single | * |
2446 // | target | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00002447 // | target |parallel for simd| * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002448 // | target |parallel sections| * |
2449 // | target | task | * |
2450 // | target | taskyield | * |
2451 // | target | barrier | * |
2452 // | target | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002453 // | target | taskgroup | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002454 // | target | flush | * |
2455 // | target | ordered | * |
2456 // | target | atomic | * |
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002457 // | target | target | |
2458 // | target | target parallel | |
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002459 // | target | target parallel | |
2460 // | | for | |
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002461 // | target | target enter | |
Samuel Antaodf67fc42016-01-19 19:15:56 +00002462 // | | data | |
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002463 // | target | target exit | |
Samuel Antao72590762016-01-19 20:04:50 +00002464 // | | data | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00002465 // | target | teams | * |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002466 // | target | cancellation | |
2467 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00002468 // | target | cancel | |
Alexey Bataev49f6e782015-12-01 04:18:41 +00002469 // | target | taskloop | * |
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002470 // | target | taskloop simd | * |
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002471 // | target | distribute | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00002472 // +------------------+-----------------+------------------------------------+
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002473 // | target parallel | parallel | * |
2474 // | target parallel | for | * |
2475 // | target parallel | for simd | * |
2476 // | target parallel | master | * |
2477 // | target parallel | critical | * |
2478 // | target parallel | simd | * |
2479 // | target parallel | sections | * |
2480 // | target parallel | section | * |
2481 // | target parallel | single | * |
2482 // | target parallel | parallel for | * |
2483 // | target parallel |parallel for simd| * |
2484 // | target parallel |parallel sections| * |
2485 // | target parallel | task | * |
2486 // | target parallel | taskyield | * |
2487 // | target parallel | barrier | * |
2488 // | target parallel | taskwait | * |
2489 // | target parallel | taskgroup | * |
2490 // | target parallel | flush | * |
2491 // | target parallel | ordered | * |
2492 // | target parallel | atomic | * |
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002493 // | target parallel | target | |
2494 // | target parallel | target parallel | |
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002495 // | target parallel | target parallel | |
2496 // | | for | |
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002497 // | target parallel | target enter | |
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002498 // | | data | |
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002499 // | target parallel | target exit | |
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002500 // | | data | |
2501 // | target parallel | teams | |
2502 // | target parallel | cancellation | |
2503 // | | point | ! |
2504 // | target parallel | cancel | ! |
2505 // | target parallel | taskloop | * |
2506 // | target parallel | taskloop simd | * |
2507 // | target parallel | distribute | |
2508 // +------------------+-----------------+------------------------------------+
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002509 // | target parallel | parallel | * |
2510 // | for | | |
2511 // | target parallel | for | * |
2512 // | for | | |
2513 // | target parallel | for simd | * |
2514 // | for | | |
2515 // | target parallel | master | * |
2516 // | for | | |
2517 // | target parallel | critical | * |
2518 // | for | | |
2519 // | target parallel | simd | * |
2520 // | for | | |
2521 // | target parallel | sections | * |
2522 // | for | | |
2523 // | target parallel | section | * |
2524 // | for | | |
2525 // | target parallel | single | * |
2526 // | for | | |
2527 // | target parallel | parallel for | * |
2528 // | for | | |
2529 // | target parallel |parallel for simd| * |
2530 // | for | | |
2531 // | target parallel |parallel sections| * |
2532 // | for | | |
2533 // | target parallel | task | * |
2534 // | for | | |
2535 // | target parallel | taskyield | * |
2536 // | for | | |
2537 // | target parallel | barrier | * |
2538 // | for | | |
2539 // | target parallel | taskwait | * |
2540 // | for | | |
2541 // | target parallel | taskgroup | * |
2542 // | for | | |
2543 // | target parallel | flush | * |
2544 // | for | | |
2545 // | target parallel | ordered | * |
2546 // | for | | |
2547 // | target parallel | atomic | * |
2548 // | for | | |
2549 // | target parallel | target | |
2550 // | for | | |
2551 // | target parallel | target parallel | |
2552 // | for | | |
2553 // | target parallel | target parallel | |
2554 // | for | for | |
2555 // | target parallel | target enter | |
2556 // | for | data | |
2557 // | target parallel | target exit | |
2558 // | for | data | |
2559 // | target parallel | teams | |
2560 // | for | | |
2561 // | target parallel | cancellation | |
2562 // | for | point | ! |
2563 // | target parallel | cancel | ! |
2564 // | for | | |
2565 // | target parallel | taskloop | * |
2566 // | for | | |
2567 // | target parallel | taskloop simd | * |
2568 // | for | | |
2569 // | target parallel | distribute | |
2570 // | for | | |
2571 // +------------------+-----------------+------------------------------------+
Alexey Bataev13314bf2014-10-09 04:18:56 +00002572 // | teams | parallel | * |
2573 // | teams | for | + |
2574 // | teams | for simd | + |
2575 // | teams | master | + |
2576 // | teams | critical | + |
2577 // | teams | simd | + |
2578 // | teams | sections | + |
2579 // | teams | section | + |
2580 // | teams | single | + |
2581 // | teams | parallel for | * |
2582 // | teams |parallel for simd| * |
2583 // | teams |parallel sections| * |
2584 // | teams | task | + |
2585 // | teams | taskyield | + |
2586 // | teams | barrier | + |
2587 // | teams | taskwait | + |
Alexey Bataev80909872015-07-02 11:25:17 +00002588 // | teams | taskgroup | + |
Alexey Bataev13314bf2014-10-09 04:18:56 +00002589 // | teams | flush | + |
2590 // | teams | ordered | + |
2591 // | teams | atomic | + |
2592 // | teams | target | + |
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002593 // | teams | target parallel | + |
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002594 // | teams | target parallel | + |
2595 // | | for | |
Samuel Antaodf67fc42016-01-19 19:15:56 +00002596 // | teams | target enter | + |
2597 // | | data | |
Samuel Antao72590762016-01-19 20:04:50 +00002598 // | teams | target exit | + |
2599 // | | data | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00002600 // | teams | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002601 // | teams | cancellation | |
2602 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00002603 // | teams | cancel | |
Alexey Bataev49f6e782015-12-01 04:18:41 +00002604 // | teams | taskloop | + |
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002605 // | teams | taskloop simd | + |
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002606 // | teams | distribute | ! |
Alexey Bataev49f6e782015-12-01 04:18:41 +00002607 // +------------------+-----------------+------------------------------------+
2608 // | taskloop | parallel | * |
2609 // | taskloop | for | + |
2610 // | taskloop | for simd | + |
2611 // | taskloop | master | + |
2612 // | taskloop | critical | * |
2613 // | taskloop | simd | * |
2614 // | taskloop | sections | + |
2615 // | taskloop | section | + |
2616 // | taskloop | single | + |
2617 // | taskloop | parallel for | * |
2618 // | taskloop |parallel for simd| * |
2619 // | taskloop |parallel sections| * |
2620 // | taskloop | task | * |
2621 // | taskloop | taskyield | * |
2622 // | taskloop | barrier | + |
2623 // | taskloop | taskwait | * |
2624 // | taskloop | taskgroup | * |
2625 // | taskloop | flush | * |
2626 // | taskloop | ordered | + |
2627 // | taskloop | atomic | * |
2628 // | taskloop | target | * |
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002629 // | taskloop | target parallel | * |
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002630 // | taskloop | target parallel | * |
2631 // | | for | |
Samuel Antaodf67fc42016-01-19 19:15:56 +00002632 // | taskloop | target enter | * |
2633 // | | data | |
Samuel Antao72590762016-01-19 20:04:50 +00002634 // | taskloop | target exit | * |
2635 // | | data | |
Alexey Bataev49f6e782015-12-01 04:18:41 +00002636 // | taskloop | teams | + |
2637 // | taskloop | cancellation | |
2638 // | | point | |
2639 // | taskloop | cancel | |
2640 // | taskloop | taskloop | * |
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002641 // | taskloop | distribute | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00002642 // +------------------+-----------------+------------------------------------+
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002643 // | taskloop simd | parallel | |
2644 // | taskloop simd | for | |
2645 // | taskloop simd | for simd | |
2646 // | taskloop simd | master | |
2647 // | taskloop simd | critical | |
Alexey Bataev1f092212016-02-02 04:59:52 +00002648 // | taskloop simd | simd | * |
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002649 // | taskloop simd | sections | |
2650 // | taskloop simd | section | |
2651 // | taskloop simd | single | |
2652 // | taskloop simd | parallel for | |
2653 // | taskloop simd |parallel for simd| |
2654 // | taskloop simd |parallel sections| |
2655 // | taskloop simd | task | |
2656 // | taskloop simd | taskyield | |
2657 // | taskloop simd | barrier | |
2658 // | taskloop simd | taskwait | |
2659 // | taskloop simd | taskgroup | |
2660 // | taskloop simd | flush | |
2661 // | taskloop simd | ordered | + (with simd clause) |
2662 // | taskloop simd | atomic | |
2663 // | taskloop simd | target | |
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002664 // | taskloop simd | target parallel | |
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002665 // | taskloop simd | target parallel | |
2666 // | | for | |
Samuel Antaodf67fc42016-01-19 19:15:56 +00002667 // | taskloop simd | target enter | |
2668 // | | data | |
Samuel Antao72590762016-01-19 20:04:50 +00002669 // | taskloop simd | target exit | |
2670 // | | data | |
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002671 // | taskloop simd | teams | |
2672 // | taskloop simd | cancellation | |
2673 // | | point | |
2674 // | taskloop simd | cancel | |
2675 // | taskloop simd | taskloop | |
2676 // | taskloop simd | taskloop simd | |
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002677 // | taskloop simd | distribute | |
2678 // +------------------+-----------------+------------------------------------+
2679 // | distribute | parallel | * |
2680 // | distribute | for | * |
2681 // | distribute | for simd | * |
2682 // | distribute | master | * |
2683 // | distribute | critical | * |
2684 // | distribute | simd | * |
2685 // | distribute | sections | * |
2686 // | distribute | section | * |
2687 // | distribute | single | * |
2688 // | distribute | parallel for | * |
2689 // | distribute |parallel for simd| * |
2690 // | distribute |parallel sections| * |
2691 // | distribute | task | * |
2692 // | distribute | taskyield | * |
2693 // | distribute | barrier | * |
2694 // | distribute | taskwait | * |
2695 // | distribute | taskgroup | * |
2696 // | distribute | flush | * |
2697 // | distribute | ordered | + |
2698 // | distribute | atomic | * |
2699 // | distribute | target | |
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002700 // | distribute | target parallel | |
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002701 // | distribute | target parallel | |
2702 // | | for | |
Samuel Antaodf67fc42016-01-19 19:15:56 +00002703 // | distribute | target enter | |
2704 // | | data | |
Samuel Antao72590762016-01-19 20:04:50 +00002705 // | distribute | target exit | |
2706 // | | data | |
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002707 // | distribute | teams | |
2708 // | distribute | cancellation | + |
2709 // | | point | |
2710 // | distribute | cancel | + |
2711 // | distribute | taskloop | * |
2712 // | distribute | taskloop simd | * |
2713 // | distribute | distribute | |
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002714 // +------------------+-----------------+------------------------------------+
Alexey Bataev549210e2014-06-24 04:39:47 +00002715 if (Stack->getCurScope()) {
2716 auto ParentRegion = Stack->getParentDirective();
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002717 auto OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002718 bool NestingProhibited = false;
2719 bool CloseNesting = true;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002720 enum {
2721 NoRecommend,
2722 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00002723 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002724 ShouldBeInTargetRegion,
2725 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002726 } Recommend = NoRecommend;
Alexey Bataev1f092212016-02-02 04:59:52 +00002727 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered &&
2728 CurrentRegion != OMPD_simd) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002729 // OpenMP [2.16, Nesting of Regions]
2730 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002731 // OpenMP [2.8.1,simd Construct, Restrictions]
2732 // An ordered construct with the simd clause is the only OpenMP construct
2733 // that can appear in the simd region.
Alexey Bataev549210e2014-06-24 04:39:47 +00002734 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd);
2735 return true;
2736 }
Alexey Bataev0162e452014-07-22 10:10:35 +00002737 if (ParentRegion == OMPD_atomic) {
2738 // OpenMP [2.16, Nesting of Regions]
2739 // OpenMP constructs may not be nested inside an atomic region.
2740 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2741 return true;
2742 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002743 if (CurrentRegion == OMPD_section) {
2744 // OpenMP [2.7.2, sections Construct, Restrictions]
2745 // Orphaned section directives are prohibited. That is, the section
2746 // directives must appear within the sections construct and must not be
2747 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002748 if (ParentRegion != OMPD_sections &&
2749 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002750 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2751 << (ParentRegion != OMPD_unknown)
2752 << getOpenMPDirectiveName(ParentRegion);
2753 return true;
2754 }
2755 return false;
2756 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002757 // Allow some constructs to be orphaned (they could be used in functions,
2758 // called from OpenMP regions with the required preconditions).
2759 if (ParentRegion == OMPD_unknown)
2760 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00002761 if (CurrentRegion == OMPD_cancellation_point ||
2762 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002763 // OpenMP [2.16, Nesting of Regions]
2764 // A cancellation point construct for which construct-type-clause is
2765 // taskgroup must be nested inside a task construct. A cancellation
2766 // point construct for which construct-type-clause is not taskgroup must
2767 // be closely nested inside an OpenMP construct that matches the type
2768 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00002769 // A cancel construct for which construct-type-clause is taskgroup must be
2770 // nested inside a task construct. A cancel construct for which
2771 // construct-type-clause is not taskgroup must be closely nested inside an
2772 // OpenMP construct that matches the type specified in
2773 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002774 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002775 !((CancelRegion == OMPD_parallel &&
2776 (ParentRegion == OMPD_parallel ||
2777 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00002778 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002779 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
2780 ParentRegion == OMPD_target_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002781 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2782 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00002783 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2784 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002785 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00002786 // OpenMP [2.16, Nesting of Regions]
2787 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002788 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00002789 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002790 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002791 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2792 // OpenMP [2.16, Nesting of Regions]
2793 // A critical region may not be nested (closely or otherwise) inside a
2794 // critical region with the same name. Note that this restriction is not
2795 // sufficient to prevent deadlock.
2796 SourceLocation PreviousCriticalLoc;
2797 bool DeadLock =
2798 Stack->hasDirective([CurrentName, &PreviousCriticalLoc](
2799 OpenMPDirectiveKind K,
2800 const DeclarationNameInfo &DNI,
2801 SourceLocation Loc)
2802 ->bool {
2803 if (K == OMPD_critical &&
2804 DNI.getName() == CurrentName.getName()) {
2805 PreviousCriticalLoc = Loc;
2806 return true;
2807 } else
2808 return false;
2809 },
2810 false /* skip top directive */);
2811 if (DeadLock) {
2812 SemaRef.Diag(StartLoc,
2813 diag::err_omp_prohibited_region_critical_same_name)
2814 << CurrentName.getName();
2815 if (PreviousCriticalLoc.isValid())
2816 SemaRef.Diag(PreviousCriticalLoc,
2817 diag::note_omp_previous_critical_region);
2818 return true;
2819 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002820 } else if (CurrentRegion == OMPD_barrier) {
2821 // OpenMP [2.16, Nesting of Regions]
2822 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002823 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002824 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2825 isOpenMPTaskingDirective(ParentRegion) ||
2826 ParentRegion == OMPD_master ||
2827 ParentRegion == OMPD_critical ||
2828 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00002829 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Alexander Musmanf82886e2014-09-18 05:12:34 +00002830 !isOpenMPParallelDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002831 // OpenMP [2.16, Nesting of Regions]
2832 // A worksharing region may not be closely nested inside a worksharing,
2833 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002834 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2835 isOpenMPTaskingDirective(ParentRegion) ||
2836 ParentRegion == OMPD_master ||
2837 ParentRegion == OMPD_critical ||
2838 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002839 Recommend = ShouldBeInParallelRegion;
2840 } else if (CurrentRegion == OMPD_ordered) {
2841 // OpenMP [2.16, Nesting of Regions]
2842 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002843 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002844 // An ordered region must be closely nested inside a loop region (or
2845 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002846 // OpenMP [2.8.1,simd Construct, Restrictions]
2847 // An ordered construct with the simd clause is the only OpenMP construct
2848 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002849 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002850 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002851 !(isOpenMPSimdDirective(ParentRegion) ||
2852 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002853 Recommend = ShouldBeInOrderedRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002854 } else if (isOpenMPTeamsDirective(CurrentRegion)) {
2855 // OpenMP [2.16, Nesting of Regions]
2856 // If specified, a teams construct must be contained within a target
2857 // construct.
2858 NestingProhibited = ParentRegion != OMPD_target;
2859 Recommend = ShouldBeInTargetRegion;
2860 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2861 }
2862 if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) {
2863 // OpenMP [2.16, Nesting of Regions]
2864 // distribute, parallel, parallel sections, parallel workshare, and the
2865 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2866 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002867 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2868 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002869 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002870 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002871 if (!NestingProhibited && isOpenMPDistributeDirective(CurrentRegion)) {
2872 // OpenMP 4.5 [2.17 Nesting of Regions]
2873 // The region associated with the distribute construct must be strictly
2874 // nested inside a teams region
2875 NestingProhibited = !isOpenMPTeamsDirective(ParentRegion);
2876 Recommend = ShouldBeInTeamsRegion;
2877 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002878 if (!NestingProhibited &&
2879 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2880 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2881 // OpenMP 4.5 [2.17 Nesting of Regions]
2882 // If a target, target update, target data, target enter data, or
2883 // target exit data construct is encountered during execution of a
2884 // target region, the behavior is unspecified.
2885 NestingProhibited = Stack->hasDirective(
2886 [&OffendingRegion](OpenMPDirectiveKind K,
2887 const DeclarationNameInfo &DNI,
2888 SourceLocation Loc) -> bool {
2889 if (isOpenMPTargetExecutionDirective(K)) {
2890 OffendingRegion = K;
2891 return true;
2892 } else
2893 return false;
2894 },
2895 false /* don't skip top directive */);
2896 CloseNesting = false;
2897 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002898 if (NestingProhibited) {
2899 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002900 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2901 << Recommend << getOpenMPDirectiveName(CurrentRegion);
Alexey Bataev549210e2014-06-24 04:39:47 +00002902 return true;
2903 }
2904 }
2905 return false;
2906}
2907
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002908static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2909 ArrayRef<OMPClause *> Clauses,
2910 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2911 bool ErrorFound = false;
2912 unsigned NamedModifiersNumber = 0;
2913 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2914 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002915 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002916 for (const auto *C : Clauses) {
2917 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2918 // At most one if clause without a directive-name-modifier can appear on
2919 // the directive.
2920 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2921 if (FoundNameModifiers[CurNM]) {
2922 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2923 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2924 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2925 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002926 } else if (CurNM != OMPD_unknown) {
2927 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002928 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002929 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002930 FoundNameModifiers[CurNM] = IC;
2931 if (CurNM == OMPD_unknown)
2932 continue;
2933 // Check if the specified name modifier is allowed for the current
2934 // directive.
2935 // At most one if clause with the particular directive-name-modifier can
2936 // appear on the directive.
2937 bool MatchFound = false;
2938 for (auto NM : AllowedNameModifiers) {
2939 if (CurNM == NM) {
2940 MatchFound = true;
2941 break;
2942 }
2943 }
2944 if (!MatchFound) {
2945 S.Diag(IC->getNameModifierLoc(),
2946 diag::err_omp_wrong_if_directive_name_modifier)
2947 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2948 ErrorFound = true;
2949 }
2950 }
2951 }
2952 // If any if clause on the directive includes a directive-name-modifier then
2953 // all if clauses on the directive must include a directive-name-modifier.
2954 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2955 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2956 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2957 diag::err_omp_no_more_if_clause);
2958 } else {
2959 std::string Values;
2960 std::string Sep(", ");
2961 unsigned AllowedCnt = 0;
2962 unsigned TotalAllowedNum =
2963 AllowedNameModifiers.size() - NamedModifiersNumber;
2964 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2965 ++Cnt) {
2966 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2967 if (!FoundNameModifiers[NM]) {
2968 Values += "'";
2969 Values += getOpenMPDirectiveName(NM);
2970 Values += "'";
2971 if (AllowedCnt + 2 == TotalAllowedNum)
2972 Values += " or ";
2973 else if (AllowedCnt + 1 != TotalAllowedNum)
2974 Values += Sep;
2975 ++AllowedCnt;
2976 }
2977 }
2978 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2979 diag::err_omp_unnamed_if_clause)
2980 << (TotalAllowedNum > 1) << Values;
2981 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002982 for (auto Loc : NameModifierLoc) {
2983 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2984 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002985 ErrorFound = true;
2986 }
2987 return ErrorFound;
2988}
2989
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002990StmtResult Sema::ActOnOpenMPExecutableDirective(
2991 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2992 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2993 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002994 StmtResult Res = StmtError();
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002995 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
2996 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002997 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002998
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002999 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003000 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003001 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00003002 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00003003 if (AStmt) {
3004 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
3005
3006 // Check default data sharing attributes for referenced variables.
3007 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
3008 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
3009 if (DSAChecker.isErrorFound())
3010 return StmtError();
3011 // Generate list of implicitly defined firstprivate variables.
3012 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00003013
3014 if (!DSAChecker.getImplicitFirstprivate().empty()) {
3015 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
3016 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
3017 SourceLocation(), SourceLocation())) {
3018 ClausesWithImplicit.push_back(Implicit);
3019 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
3020 DSAChecker.getImplicitFirstprivate().size();
3021 } else
3022 ErrorFound = true;
3023 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003024 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003025
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003026 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003027 switch (Kind) {
3028 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00003029 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
3030 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003031 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003032 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003033 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00003034 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3035 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003036 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00003037 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00003038 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3039 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003040 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00003041 case OMPD_for_simd:
3042 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3043 EndLoc, VarsWithInheritedDSA);
3044 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003045 case OMPD_sections:
3046 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
3047 EndLoc);
3048 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003049 case OMPD_section:
3050 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00003051 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003052 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
3053 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003054 case OMPD_single:
3055 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
3056 EndLoc);
3057 break;
Alexander Musman80c22892014-07-17 08:54:58 +00003058 case OMPD_master:
3059 assert(ClausesWithImplicit.empty() &&
3060 "No clauses are allowed for 'omp master' directive");
3061 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
3062 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003063 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00003064 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
3065 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003066 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003067 case OMPD_parallel_for:
3068 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
3069 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003070 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003071 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00003072 case OMPD_parallel_for_simd:
3073 Res = ActOnOpenMPParallelForSimdDirective(
3074 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003075 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003076 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003077 case OMPD_parallel_sections:
3078 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
3079 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003080 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003081 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003082 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003083 Res =
3084 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003085 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003086 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00003087 case OMPD_taskyield:
3088 assert(ClausesWithImplicit.empty() &&
3089 "No clauses are allowed for 'omp taskyield' directive");
3090 assert(AStmt == nullptr &&
3091 "No associated statement allowed for 'omp taskyield' directive");
3092 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
3093 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003094 case OMPD_barrier:
3095 assert(ClausesWithImplicit.empty() &&
3096 "No clauses are allowed for 'omp barrier' directive");
3097 assert(AStmt == nullptr &&
3098 "No associated statement allowed for 'omp barrier' directive");
3099 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
3100 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00003101 case OMPD_taskwait:
3102 assert(ClausesWithImplicit.empty() &&
3103 "No clauses are allowed for 'omp taskwait' directive");
3104 assert(AStmt == nullptr &&
3105 "No associated statement allowed for 'omp taskwait' directive");
3106 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
3107 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003108 case OMPD_taskgroup:
3109 assert(ClausesWithImplicit.empty() &&
3110 "No clauses are allowed for 'omp taskgroup' directive");
3111 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
3112 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00003113 case OMPD_flush:
3114 assert(AStmt == nullptr &&
3115 "No associated statement allowed for 'omp flush' directive");
3116 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
3117 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003118 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00003119 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
3120 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003121 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00003122 case OMPD_atomic:
3123 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
3124 EndLoc);
3125 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003126 case OMPD_teams:
3127 Res =
3128 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3129 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003130 case OMPD_target:
3131 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
3132 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003133 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003134 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003135 case OMPD_target_parallel:
3136 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
3137 StartLoc, EndLoc);
3138 AllowedNameModifiers.push_back(OMPD_target);
3139 AllowedNameModifiers.push_back(OMPD_parallel);
3140 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003141 case OMPD_target_parallel_for:
3142 Res = ActOnOpenMPTargetParallelForDirective(
3143 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3144 AllowedNameModifiers.push_back(OMPD_target);
3145 AllowedNameModifiers.push_back(OMPD_parallel);
3146 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003147 case OMPD_cancellation_point:
3148 assert(ClausesWithImplicit.empty() &&
3149 "No clauses are allowed for 'omp cancellation point' directive");
3150 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
3151 "cancellation point' directive");
3152 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
3153 break;
Alexey Bataev80909872015-07-02 11:25:17 +00003154 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00003155 assert(AStmt == nullptr &&
3156 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00003157 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
3158 CancelRegion);
3159 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00003160 break;
Michael Wong65f367f2015-07-21 13:44:28 +00003161 case OMPD_target_data:
3162 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
3163 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003164 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00003165 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00003166 case OMPD_target_enter_data:
3167 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
3168 EndLoc);
3169 AllowedNameModifiers.push_back(OMPD_target_enter_data);
3170 break;
Samuel Antao72590762016-01-19 20:04:50 +00003171 case OMPD_target_exit_data:
3172 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
3173 EndLoc);
3174 AllowedNameModifiers.push_back(OMPD_target_exit_data);
3175 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00003176 case OMPD_taskloop:
3177 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
3178 EndLoc, VarsWithInheritedDSA);
3179 AllowedNameModifiers.push_back(OMPD_taskloop);
3180 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003181 case OMPD_taskloop_simd:
3182 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3183 EndLoc, VarsWithInheritedDSA);
3184 AllowedNameModifiers.push_back(OMPD_taskloop);
3185 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003186 case OMPD_distribute:
3187 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
3188 EndLoc, VarsWithInheritedDSA);
3189 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003190 case OMPD_declare_target:
3191 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003192 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003193 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003194 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003195 llvm_unreachable("OpenMP Directive is not allowed");
3196 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003197 llvm_unreachable("Unknown OpenMP directive");
3198 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003199
Alexey Bataev4acb8592014-07-07 13:01:15 +00003200 for (auto P : VarsWithInheritedDSA) {
3201 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
3202 << P.first << P.second->getSourceRange();
3203 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003204 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
3205
3206 if (!AllowedNameModifiers.empty())
3207 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
3208 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003209
Alexey Bataeved09d242014-05-28 05:53:51 +00003210 if (ErrorFound)
3211 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003212 return Res;
3213}
3214
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003215Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
3216 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00003217 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00003218 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
3219 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00003220 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00003221 assert(Linears.size() == LinModifiers.size());
3222 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00003223 if (!DG || DG.get().isNull())
3224 return DeclGroupPtrTy();
3225
3226 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00003227 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003228 return DG;
3229 }
3230 auto *ADecl = DG.get().getSingleDecl();
3231 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
3232 ADecl = FTD->getTemplatedDecl();
3233
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003234 auto *FD = dyn_cast<FunctionDecl>(ADecl);
3235 if (!FD) {
3236 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003237 return DeclGroupPtrTy();
3238 }
3239
Alexey Bataev2af33e32016-04-07 12:45:37 +00003240 // OpenMP [2.8.2, declare simd construct, Description]
3241 // The parameter of the simdlen clause must be a constant positive integer
3242 // expression.
3243 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003244 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00003245 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003246 // OpenMP [2.8.2, declare simd construct, Description]
3247 // The special this pointer can be used as if was one of the arguments to the
3248 // function in any of the linear, aligned, or uniform clauses.
3249 // The uniform clause declares one or more arguments to have an invariant
3250 // value for all concurrent invocations of the function in the execution of a
3251 // single SIMD loop.
Alexey Bataevecba70f2016-04-12 11:02:11 +00003252 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
3253 Expr *UniformedLinearThis = nullptr;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003254 for (auto *E : Uniforms) {
3255 E = E->IgnoreParenImpCasts();
3256 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3257 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
3258 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3259 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00003260 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
3261 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003262 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003263 }
3264 if (isa<CXXThisExpr>(E)) {
3265 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003266 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003267 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003268 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3269 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00003270 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00003271 // OpenMP [2.8.2, declare simd construct, Description]
3272 // The aligned clause declares that the object to which each list item points
3273 // is aligned to the number of bytes expressed in the optional parameter of
3274 // the aligned clause.
3275 // The special this pointer can be used as if was one of the arguments to the
3276 // function in any of the linear, aligned, or uniform clauses.
3277 // The type of list items appearing in the aligned clause must be array,
3278 // pointer, reference to array, or reference to pointer.
3279 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
3280 Expr *AlignedThis = nullptr;
3281 for (auto *E : Aligneds) {
3282 E = E->IgnoreParenImpCasts();
3283 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3284 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3285 auto *CanonPVD = PVD->getCanonicalDecl();
3286 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3287 FD->getParamDecl(PVD->getFunctionScopeIndex())
3288 ->getCanonicalDecl() == CanonPVD) {
3289 // OpenMP [2.8.1, simd construct, Restrictions]
3290 // A list-item cannot appear in more than one aligned clause.
3291 if (AlignedArgs.count(CanonPVD) > 0) {
3292 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3293 << 1 << E->getSourceRange();
3294 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
3295 diag::note_omp_explicit_dsa)
3296 << getOpenMPClauseName(OMPC_aligned);
3297 continue;
3298 }
3299 AlignedArgs[CanonPVD] = E;
3300 QualType QTy = PVD->getType()
3301 .getNonReferenceType()
3302 .getUnqualifiedType()
3303 .getCanonicalType();
3304 const Type *Ty = QTy.getTypePtrOrNull();
3305 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
3306 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
3307 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
3308 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
3309 }
3310 continue;
3311 }
3312 }
3313 if (isa<CXXThisExpr>(E)) {
3314 if (AlignedThis) {
3315 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3316 << 2 << E->getSourceRange();
3317 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
3318 << getOpenMPClauseName(OMPC_aligned);
3319 }
3320 AlignedThis = E;
3321 continue;
3322 }
3323 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3324 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3325 }
3326 // The optional parameter of the aligned clause, alignment, must be a constant
3327 // positive integer expression. If no optional parameter is specified,
3328 // implementation-defined default alignments for SIMD instructions on the
3329 // target platforms are assumed.
3330 SmallVector<Expr *, 4> NewAligns;
3331 for (auto *E : Alignments) {
3332 ExprResult Align;
3333 if (E)
3334 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
3335 NewAligns.push_back(Align.get());
3336 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00003337 // OpenMP [2.8.2, declare simd construct, Description]
3338 // The linear clause declares one or more list items to be private to a SIMD
3339 // lane and to have a linear relationship with respect to the iteration space
3340 // of a loop.
3341 // The special this pointer can be used as if was one of the arguments to the
3342 // function in any of the linear, aligned, or uniform clauses.
3343 // When a linear-step expression is specified in a linear clause it must be
3344 // either a constant integer expression or an integer-typed parameter that is
3345 // specified in a uniform clause on the directive.
3346 llvm::DenseMap<Decl *, Expr *> LinearArgs;
3347 const bool IsUniformedThis = UniformedLinearThis != nullptr;
3348 auto MI = LinModifiers.begin();
3349 for (auto *E : Linears) {
3350 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
3351 ++MI;
3352 E = E->IgnoreParenImpCasts();
3353 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3354 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3355 auto *CanonPVD = PVD->getCanonicalDecl();
3356 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3357 FD->getParamDecl(PVD->getFunctionScopeIndex())
3358 ->getCanonicalDecl() == CanonPVD) {
3359 // OpenMP [2.15.3.7, linear Clause, Restrictions]
3360 // A list-item cannot appear in more than one linear clause.
3361 if (LinearArgs.count(CanonPVD) > 0) {
3362 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3363 << getOpenMPClauseName(OMPC_linear)
3364 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
3365 Diag(LinearArgs[CanonPVD]->getExprLoc(),
3366 diag::note_omp_explicit_dsa)
3367 << getOpenMPClauseName(OMPC_linear);
3368 continue;
3369 }
3370 // Each argument can appear in at most one uniform or linear clause.
3371 if (UniformedArgs.count(CanonPVD) > 0) {
3372 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3373 << getOpenMPClauseName(OMPC_linear)
3374 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
3375 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
3376 diag::note_omp_explicit_dsa)
3377 << getOpenMPClauseName(OMPC_uniform);
3378 continue;
3379 }
3380 LinearArgs[CanonPVD] = E;
3381 if (E->isValueDependent() || E->isTypeDependent() ||
3382 E->isInstantiationDependent() ||
3383 E->containsUnexpandedParameterPack())
3384 continue;
3385 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
3386 PVD->getOriginalType());
3387 continue;
3388 }
3389 }
3390 if (isa<CXXThisExpr>(E)) {
3391 if (UniformedLinearThis) {
3392 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3393 << getOpenMPClauseName(OMPC_linear)
3394 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
3395 << E->getSourceRange();
3396 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
3397 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
3398 : OMPC_linear);
3399 continue;
3400 }
3401 UniformedLinearThis = E;
3402 if (E->isValueDependent() || E->isTypeDependent() ||
3403 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
3404 continue;
3405 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
3406 E->getType());
3407 continue;
3408 }
3409 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3410 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3411 }
3412 Expr *Step = nullptr;
3413 Expr *NewStep = nullptr;
3414 SmallVector<Expr *, 4> NewSteps;
3415 for (auto *E : Steps) {
3416 // Skip the same step expression, it was checked already.
3417 if (Step == E || !E) {
3418 NewSteps.push_back(E ? NewStep : nullptr);
3419 continue;
3420 }
3421 Step = E;
3422 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
3423 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3424 auto *CanonPVD = PVD->getCanonicalDecl();
3425 if (UniformedArgs.count(CanonPVD) == 0) {
3426 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
3427 << Step->getSourceRange();
3428 } else if (E->isValueDependent() || E->isTypeDependent() ||
3429 E->isInstantiationDependent() ||
3430 E->containsUnexpandedParameterPack() ||
3431 CanonPVD->getType()->hasIntegerRepresentation())
3432 NewSteps.push_back(Step);
3433 else {
3434 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
3435 << Step->getSourceRange();
3436 }
3437 continue;
3438 }
3439 NewStep = Step;
3440 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
3441 !Step->isInstantiationDependent() &&
3442 !Step->containsUnexpandedParameterPack()) {
3443 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
3444 .get();
3445 if (NewStep)
3446 NewStep = VerifyIntegerConstantExpression(NewStep).get();
3447 }
3448 NewSteps.push_back(NewStep);
3449 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003450 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
3451 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00003452 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00003453 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
3454 const_cast<Expr **>(Linears.data()), Linears.size(),
3455 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
3456 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003457 ADecl->addAttr(NewAttr);
3458 return ConvertDeclToDeclGroup(ADecl);
3459}
3460
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003461StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
3462 Stmt *AStmt,
3463 SourceLocation StartLoc,
3464 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003465 if (!AStmt)
3466 return StmtError();
3467
Alexey Bataev9959db52014-05-06 10:08:46 +00003468 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3469 // 1.2.2 OpenMP Language Terminology
3470 // Structured block - An executable statement with a single entry at the
3471 // top and a single exit at the bottom.
3472 // The point of exit cannot be a branch out of the structured block.
3473 // longjmp() and throw() must not violate the entry/exit criteria.
3474 CS->getCapturedDecl()->setNothrow();
3475
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003476 getCurFunction()->setHasBranchProtectedScope();
3477
Alexey Bataev25e5b442015-09-15 12:52:43 +00003478 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3479 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003480}
3481
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003482namespace {
3483/// \brief Helper class for checking canonical form of the OpenMP loops and
3484/// extracting iteration space of each loop in the loop nest, that will be used
3485/// for IR generation.
3486class OpenMPIterationSpaceChecker {
3487 /// \brief Reference to Sema.
3488 Sema &SemaRef;
3489 /// \brief A location for diagnostics (when there is no some better location).
3490 SourceLocation DefaultLoc;
3491 /// \brief A location for diagnostics (when increment is not compatible).
3492 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003493 /// \brief A source location for referring to loop init later.
3494 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003495 /// \brief A source location for referring to condition later.
3496 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003497 /// \brief A source location for referring to increment later.
3498 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003499 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003500 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003501 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003502 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003503 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003504 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003505 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003506 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003507 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003508 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003509 /// \brief This flag is true when condition is one of:
3510 /// Var < UB
3511 /// Var <= UB
3512 /// UB > Var
3513 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003514 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003515 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003516 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003517 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003518 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003519
3520public:
3521 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003522 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003523 /// \brief Check init-expr for canonical loop form and save loop counter
3524 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00003525 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003526 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
3527 /// for less/greater and for strict/non-strict comparison.
3528 bool CheckCond(Expr *S);
3529 /// \brief Check incr-expr for canonical loop form and return true if it
3530 /// does not conform, otherwise save loop step (#Step).
3531 bool CheckInc(Expr *S);
3532 /// \brief Return the loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003533 ValueDecl *GetLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003534 /// \brief Return the reference expression to loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003535 Expr *GetLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003536 /// \brief Source range of the loop init.
3537 SourceRange GetInitSrcRange() const { return InitSrcRange; }
3538 /// \brief Source range of the loop condition.
3539 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
3540 /// \brief Source range of the loop increment.
3541 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
3542 /// \brief True if the step should be subtracted.
3543 bool ShouldSubtractStep() const { return SubtractStep; }
3544 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003545 Expr *
3546 BuildNumIterations(Scope *S, const bool LimitedType,
3547 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00003548 /// \brief Build the precondition expression for the loops.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003549 Expr *BuildPreCond(Scope *S, Expr *Cond,
3550 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003551 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003552 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
3553 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00003554 /// \brief Build reference expression to the private counter be used for
3555 /// codegen.
3556 Expr *BuildPrivateCounterVar() const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003557 /// \brief Build initization of the counter be used for codegen.
3558 Expr *BuildCounterInit() const;
3559 /// \brief Build step of the counter be used for codegen.
3560 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003561 /// \brief Return true if any expression is dependent.
3562 bool Dependent() const;
3563
3564private:
3565 /// \brief Check the right-hand side of an assignment in the increment
3566 /// expression.
3567 bool CheckIncRHS(Expr *RHS);
3568 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003569 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003570 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00003571 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00003572 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003573 /// \brief Helper to set loop increment.
3574 bool SetStep(Expr *NewStep, bool Subtract);
3575};
3576
3577bool OpenMPIterationSpaceChecker::Dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003578 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003579 assert(!LB && !UB && !Step);
3580 return false;
3581 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003582 return LCDecl->getType()->isDependentType() ||
3583 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
3584 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003585}
3586
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003587static Expr *getExprAsWritten(Expr *E) {
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003588 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
3589 E = ExprTemp->getSubExpr();
3590
3591 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
3592 E = MTE->GetTemporaryExpr();
3593
3594 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
3595 E = Binder->getSubExpr();
3596
3597 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
3598 E = ICE->getSubExprAsWritten();
3599 return E->IgnoreParens();
3600}
3601
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003602bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
3603 Expr *NewLCRefExpr,
3604 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003605 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003606 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003607 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003608 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003609 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003610 LCDecl = getCanonicalDecl(NewLCDecl);
3611 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003612 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
3613 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003614 if ((Ctor->isCopyOrMoveConstructor() ||
3615 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3616 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003617 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003618 LB = NewLB;
3619 return false;
3620}
3621
3622bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00003623 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003624 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003625 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
3626 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003627 if (!NewUB)
3628 return true;
3629 UB = NewUB;
3630 TestIsLessOp = LessOp;
3631 TestIsStrictOp = StrictOp;
3632 ConditionSrcRange = SR;
3633 ConditionLoc = SL;
3634 return false;
3635}
3636
3637bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
3638 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003639 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003640 if (!NewStep)
3641 return true;
3642 if (!NewStep->isValueDependent()) {
3643 // Check that the step is integer expression.
3644 SourceLocation StepLoc = NewStep->getLocStart();
3645 ExprResult Val =
3646 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
3647 if (Val.isInvalid())
3648 return true;
3649 NewStep = Val.get();
3650
3651 // OpenMP [2.6, Canonical Loop Form, Restrictions]
3652 // If test-expr is of form var relational-op b and relational-op is < or
3653 // <= then incr-expr must cause var to increase on each iteration of the
3654 // loop. If test-expr is of form var relational-op b and relational-op is
3655 // > or >= then incr-expr must cause var to decrease on each iteration of
3656 // the loop.
3657 // If test-expr is of form b relational-op var and relational-op is < or
3658 // <= then incr-expr must cause var to decrease on each iteration of the
3659 // loop. If test-expr is of form b relational-op var and relational-op is
3660 // > or >= then incr-expr must cause var to increase on each iteration of
3661 // the loop.
3662 llvm::APSInt Result;
3663 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3664 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3665 bool IsConstNeg =
3666 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003667 bool IsConstPos =
3668 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003669 bool IsConstZero = IsConstant && !Result.getBoolValue();
3670 if (UB && (IsConstZero ||
3671 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00003672 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003673 SemaRef.Diag(NewStep->getExprLoc(),
3674 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003675 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003676 SemaRef.Diag(ConditionLoc,
3677 diag::note_omp_loop_cond_requres_compatible_incr)
3678 << TestIsLessOp << ConditionSrcRange;
3679 return true;
3680 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003681 if (TestIsLessOp == Subtract) {
3682 NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus,
3683 NewStep).get();
3684 Subtract = !Subtract;
3685 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003686 }
3687
3688 Step = NewStep;
3689 SubtractStep = Subtract;
3690 return false;
3691}
3692
Alexey Bataev9c821032015-04-30 04:23:23 +00003693bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003694 // Check init-expr for canonical loop form and save loop counter
3695 // variable - #Var and its initialization value - #LB.
3696 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3697 // var = lb
3698 // integer-type var = lb
3699 // random-access-iterator-type var = lb
3700 // pointer-type var = lb
3701 //
3702 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00003703 if (EmitDiags) {
3704 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3705 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003706 return true;
3707 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003708 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003709 if (Expr *E = dyn_cast<Expr>(S))
3710 S = E->IgnoreParens();
3711 if (auto BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003712 if (BO->getOpcode() == BO_Assign) {
3713 auto *LHS = BO->getLHS()->IgnoreParens();
3714 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3715 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3716 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3717 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3718 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3719 }
3720 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3721 if (ME->isArrow() &&
3722 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3723 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3724 }
3725 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003726 } else if (auto DS = dyn_cast<DeclStmt>(S)) {
3727 if (DS->isSingleDecl()) {
3728 if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00003729 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003730 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00003731 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003732 SemaRef.Diag(S->getLocStart(),
3733 diag::ext_omp_loop_not_canonical_init)
3734 << S->getSourceRange();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003735 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003736 }
3737 }
3738 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003739 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3740 if (CE->getOperator() == OO_Equal) {
3741 auto *LHS = CE->getArg(0);
3742 if (auto DRE = dyn_cast<DeclRefExpr>(LHS)) {
3743 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3744 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3745 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3746 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3747 }
3748 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3749 if (ME->isArrow() &&
3750 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3751 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3752 }
3753 }
3754 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003755
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003756 if (Dependent() || SemaRef.CurContext->isDependentContext())
3757 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00003758 if (EmitDiags) {
3759 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3760 << S->getSourceRange();
3761 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003762 return true;
3763}
3764
Alexey Bataev23b69422014-06-18 07:08:49 +00003765/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003766/// variable (which may be the loop variable) if possible.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003767static const ValueDecl *GetInitLCDecl(Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003768 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00003769 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003770 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003771 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3772 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003773 if ((Ctor->isCopyOrMoveConstructor() ||
3774 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3775 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003776 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003777 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
3778 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
3779 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
3780 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3781 return getCanonicalDecl(ME->getMemberDecl());
3782 return getCanonicalDecl(VD);
3783 }
3784 }
3785 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3786 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3787 return getCanonicalDecl(ME->getMemberDecl());
3788 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003789}
3790
3791bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3792 // Check test-expr for canonical form, save upper-bound UB, flags for
3793 // less/greater and for strict/non-strict comparison.
3794 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3795 // var relational-op b
3796 // b relational-op var
3797 //
3798 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003799 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003800 return true;
3801 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003802 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003803 SourceLocation CondLoc = S->getLocStart();
3804 if (auto BO = dyn_cast<BinaryOperator>(S)) {
3805 if (BO->isRelationalOp()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003806 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003807 return SetUB(BO->getRHS(),
3808 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3809 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3810 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003811 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003812 return SetUB(BO->getLHS(),
3813 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3814 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3815 BO->getSourceRange(), BO->getOperatorLoc());
3816 }
3817 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3818 if (CE->getNumArgs() == 2) {
3819 auto Op = CE->getOperator();
3820 switch (Op) {
3821 case OO_Greater:
3822 case OO_GreaterEqual:
3823 case OO_Less:
3824 case OO_LessEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003825 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003826 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3827 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3828 CE->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003829 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003830 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3831 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3832 CE->getOperatorLoc());
3833 break;
3834 default:
3835 break;
3836 }
3837 }
3838 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003839 if (Dependent() || SemaRef.CurContext->isDependentContext())
3840 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003841 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003842 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003843 return true;
3844}
3845
3846bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3847 // RHS of canonical loop form increment can be:
3848 // var + incr
3849 // incr + var
3850 // var - incr
3851 //
3852 RHS = RHS->IgnoreParenImpCasts();
3853 if (auto BO = dyn_cast<BinaryOperator>(RHS)) {
3854 if (BO->isAdditiveOp()) {
3855 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003856 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003857 return SetStep(BO->getRHS(), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003858 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003859 return SetStep(BO->getLHS(), false);
3860 }
3861 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
3862 bool IsAdd = CE->getOperator() == OO_Plus;
3863 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003864 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003865 return SetStep(CE->getArg(1), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003866 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003867 return SetStep(CE->getArg(0), false);
3868 }
3869 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003870 if (Dependent() || SemaRef.CurContext->isDependentContext())
3871 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003872 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003873 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003874 return true;
3875}
3876
3877bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3878 // Check incr-expr for canonical loop form and return true if it
3879 // does not conform.
3880 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3881 // ++var
3882 // var++
3883 // --var
3884 // var--
3885 // var += incr
3886 // var -= incr
3887 // var = var + incr
3888 // var = incr + var
3889 // var = var - incr
3890 //
3891 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003892 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003893 return true;
3894 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003895 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003896 S = S->IgnoreParens();
3897 if (auto UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003898 if (UO->isIncrementDecrementOp() &&
3899 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003900 return SetStep(
3901 SemaRef.ActOnIntegerConstant(UO->getLocStart(),
3902 (UO->isDecrementOp() ? -1 : 1)).get(),
3903 false);
3904 } else if (auto BO = dyn_cast<BinaryOperator>(S)) {
3905 switch (BO->getOpcode()) {
3906 case BO_AddAssign:
3907 case BO_SubAssign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003908 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003909 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3910 break;
3911 case BO_Assign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003912 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003913 return CheckIncRHS(BO->getRHS());
3914 break;
3915 default:
3916 break;
3917 }
3918 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3919 switch (CE->getOperator()) {
3920 case OO_PlusPlus:
3921 case OO_MinusMinus:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003922 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003923 return SetStep(
3924 SemaRef.ActOnIntegerConstant(
3925 CE->getLocStart(),
3926 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(),
3927 false);
3928 break;
3929 case OO_PlusEqual:
3930 case OO_MinusEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003931 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003932 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3933 break;
3934 case OO_Equal:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003935 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003936 return CheckIncRHS(CE->getArg(1));
3937 break;
3938 default:
3939 break;
3940 }
3941 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003942 if (Dependent() || SemaRef.CurContext->isDependentContext())
3943 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003944 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003945 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003946 return true;
3947}
Alexander Musmana5f070a2014-10-01 06:03:56 +00003948
Alexey Bataev5a3af132016-03-29 08:58:54 +00003949static ExprResult
3950tryBuildCapture(Sema &SemaRef, Expr *Capture,
3951 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3952 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3953 return SemaRef.PerformImplicitConversion(
3954 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3955 /*AllowExplicit=*/true);
3956 auto I = Captures.find(Capture);
3957 if (I != Captures.end())
3958 return buildCapture(SemaRef, Capture, I->second);
3959 DeclRefExpr *Ref = nullptr;
3960 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3961 Captures[Capture] = Ref;
3962 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003963}
3964
Alexander Musmana5f070a2014-10-01 06:03:56 +00003965/// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003966Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3967 Scope *S, const bool LimitedType,
3968 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003969 ExprResult Diff;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003970 auto VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003971 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003972 SemaRef.getLangOpts().CPlusPlus) {
3973 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003974 auto *UBExpr = TestIsLessOp ? UB : LB;
3975 auto *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00003976 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3977 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003978 if (!Upper || !Lower)
3979 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003980
3981 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3982
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003983 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003984 // BuildBinOp already emitted error, this one is to point user to upper
3985 // and lower bound, and to tell what is passed to 'operator-'.
3986 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3987 << Upper->getSourceRange() << Lower->getSourceRange();
3988 return nullptr;
3989 }
3990 }
3991
3992 if (!Diff.isUsable())
3993 return nullptr;
3994
3995 // Upper - Lower [- 1]
3996 if (TestIsStrictOp)
3997 Diff = SemaRef.BuildBinOp(
3998 S, DefaultLoc, BO_Sub, Diff.get(),
3999 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4000 if (!Diff.isUsable())
4001 return nullptr;
4002
4003 // Upper - Lower [- 1] + Step
Alexey Bataev5a3af132016-03-29 08:58:54 +00004004 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
4005 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004006 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004007 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004008 if (!Diff.isUsable())
4009 return nullptr;
4010
4011 // Parentheses (for dumping/debugging purposes only).
4012 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4013 if (!Diff.isUsable())
4014 return nullptr;
4015
4016 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004017 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004018 if (!Diff.isUsable())
4019 return nullptr;
4020
Alexander Musman174b3ca2014-10-06 11:16:29 +00004021 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004022 QualType Type = Diff.get()->getType();
4023 auto &C = SemaRef.Context;
4024 bool UseVarType = VarType->hasIntegerRepresentation() &&
4025 C.getTypeSize(Type) > C.getTypeSize(VarType);
4026 if (!Type->isIntegerType() || UseVarType) {
4027 unsigned NewSize =
4028 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
4029 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
4030 : Type->hasSignedIntegerRepresentation();
4031 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00004032 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
4033 Diff = SemaRef.PerformImplicitConversion(
4034 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
4035 if (!Diff.isUsable())
4036 return nullptr;
4037 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004038 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00004039 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00004040 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
4041 if (NewSize != C.getTypeSize(Type)) {
4042 if (NewSize < C.getTypeSize(Type)) {
4043 assert(NewSize == 64 && "incorrect loop var size");
4044 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
4045 << InitSrcRange << ConditionSrcRange;
4046 }
4047 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004048 NewSize, Type->hasSignedIntegerRepresentation() ||
4049 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00004050 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
4051 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
4052 Sema::AA_Converting, true);
4053 if (!Diff.isUsable())
4054 return nullptr;
4055 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00004056 }
4057 }
4058
Alexander Musmana5f070a2014-10-01 06:03:56 +00004059 return Diff.get();
4060}
4061
Alexey Bataev5a3af132016-03-29 08:58:54 +00004062Expr *OpenMPIterationSpaceChecker::BuildPreCond(
4063 Scope *S, Expr *Cond,
4064 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004065 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
4066 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4067 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004068
Alexey Bataev5a3af132016-03-29 08:58:54 +00004069 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
4070 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
4071 if (!NewLB.isUsable() || !NewUB.isUsable())
4072 return nullptr;
4073
Alexey Bataev62dbb972015-04-22 11:59:37 +00004074 auto CondExpr = SemaRef.BuildBinOp(
4075 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
4076 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004077 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004078 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004079 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
4080 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00004081 CondExpr = SemaRef.PerformImplicitConversion(
4082 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
4083 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004084 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00004085 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4086 // Otherwise use original loop conditon and evaluate it in runtime.
4087 return CondExpr.isUsable() ? CondExpr.get() : Cond;
4088}
4089
Alexander Musmana5f070a2014-10-01 06:03:56 +00004090/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004091DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004092 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004093 auto *VD = dyn_cast<VarDecl>(LCDecl);
4094 if (!VD) {
4095 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
4096 auto *Ref = buildDeclRefExpr(
4097 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004098 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
4099 // If the loop control decl is explicitly marked as private, do not mark it
4100 // as captured again.
4101 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
4102 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004103 return Ref;
4104 }
4105 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00004106 DefaultLoc);
4107}
4108
4109Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004110 if (LCDecl && !LCDecl->isInvalidDecl()) {
4111 auto Type = LCDecl->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00004112 auto *PrivateVar =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004113 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
4114 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00004115 if (PrivateVar->isInvalidDecl())
4116 return nullptr;
4117 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
4118 }
4119 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004120}
4121
4122/// \brief Build initization of the counter be used for codegen.
4123Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
4124
4125/// \brief Build step of the counter be used for codegen.
4126Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
4127
4128/// \brief Iteration space of a single for loop.
4129struct LoopIterationSpace {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004130 /// \brief Condition of the loop.
4131 Expr *PreCond;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004132 /// \brief This expression calculates the number of iterations in the loop.
4133 /// It is always possible to calculate it before starting the loop.
4134 Expr *NumIterations;
4135 /// \brief The loop counter variable.
4136 Expr *CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00004137 /// \brief Private loop counter variable.
4138 Expr *PrivateCounterVar;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004139 /// \brief This is initializer for the initial value of #CounterVar.
4140 Expr *CounterInit;
4141 /// \brief This is step for the #CounterVar used to generate its update:
4142 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
4143 Expr *CounterStep;
4144 /// \brief Should step be subtracted?
4145 bool Subtract;
4146 /// \brief Source range of the loop init.
4147 SourceRange InitSrcRange;
4148 /// \brief Source range of the loop condition.
4149 SourceRange CondSrcRange;
4150 /// \brief Source range of the loop increment.
4151 SourceRange IncSrcRange;
4152};
4153
Alexey Bataev23b69422014-06-18 07:08:49 +00004154} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004155
Alexey Bataev9c821032015-04-30 04:23:23 +00004156void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
4157 assert(getLangOpts().OpenMP && "OpenMP is not active.");
4158 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004159 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
4160 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00004161 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
4162 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004163 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
4164 if (auto *D = ISC.GetLoopDecl()) {
4165 auto *VD = dyn_cast<VarDecl>(D);
4166 if (!VD) {
4167 if (auto *Private = IsOpenMPCapturedDecl(D))
4168 VD = Private;
4169 else {
4170 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
4171 /*WithInit=*/false);
4172 VD = cast<VarDecl>(Ref->getDecl());
4173 }
4174 }
4175 DSAStack->addLoopControlVariable(D, VD);
4176 }
4177 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004178 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00004179 }
4180}
4181
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004182/// \brief Called on a for stmt to check and extract its iteration space
4183/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00004184static bool CheckOpenMPIterationSpace(
4185 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
4186 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004187 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004188 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004189 LoopIterationSpace &ResultIterSpace,
4190 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004191 // OpenMP [2.6, Canonical Loop Form]
4192 // for (init-expr; test-expr; incr-expr) structured-block
4193 auto For = dyn_cast_or_null<ForStmt>(S);
4194 if (!For) {
4195 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004196 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
4197 << getOpenMPDirectiveName(DKind) << NestedLoopCount
4198 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
4199 if (NestedLoopCount > 1) {
4200 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
4201 SemaRef.Diag(DSA.getConstructLoc(),
4202 diag::note_omp_collapse_ordered_expr)
4203 << 2 << CollapseLoopCountExpr->getSourceRange()
4204 << OrderedLoopCountExpr->getSourceRange();
4205 else if (CollapseLoopCountExpr)
4206 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4207 diag::note_omp_collapse_ordered_expr)
4208 << 0 << CollapseLoopCountExpr->getSourceRange();
4209 else
4210 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4211 diag::note_omp_collapse_ordered_expr)
4212 << 1 << OrderedLoopCountExpr->getSourceRange();
4213 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004214 return true;
4215 }
4216 assert(For->getBody());
4217
4218 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
4219
4220 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00004221 auto Init = For->getInit();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004222 if (ISC.CheckInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004223 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004224
4225 bool HasErrors = false;
4226
4227 // Check loop variable's type.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004228 if (auto *LCDecl = ISC.GetLoopDecl()) {
4229 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004230
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004231 // OpenMP [2.6, Canonical Loop Form]
4232 // Var is one of the following:
4233 // A variable of signed or unsigned integer type.
4234 // For C++, a variable of a random access iterator type.
4235 // For C, a variable of a pointer type.
4236 auto VarType = LCDecl->getType().getNonReferenceType();
4237 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
4238 !VarType->isPointerType() &&
4239 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
4240 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
4241 << SemaRef.getLangOpts().CPlusPlus;
4242 HasErrors = true;
4243 }
4244
4245 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
4246 // a Construct
4247 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4248 // parallel for construct is (are) private.
4249 // The loop iteration variable in the associated for-loop of a simd
4250 // construct with just one associated for-loop is linear with a
4251 // constant-linear-step that is the increment of the associated for-loop.
4252 // Exclude loop var from the list of variables with implicitly defined data
4253 // sharing attributes.
4254 VarsWithImplicitDSA.erase(LCDecl);
4255
4256 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
4257 // in a Construct, C/C++].
4258 // The loop iteration variable in the associated for-loop of a simd
4259 // construct with just one associated for-loop may be listed in a linear
4260 // clause with a constant-linear-step that is the increment of the
4261 // associated for-loop.
4262 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4263 // parallel for construct may be listed in a private or lastprivate clause.
4264 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
4265 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
4266 // declared in the loop and it is predetermined as a private.
4267 auto PredeterminedCKind =
4268 isOpenMPSimdDirective(DKind)
4269 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
4270 : OMPC_private;
4271 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4272 DVar.CKind != PredeterminedCKind) ||
4273 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
4274 isOpenMPDistributeDirective(DKind)) &&
4275 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4276 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
4277 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
4278 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
4279 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
4280 << getOpenMPClauseName(PredeterminedCKind);
4281 if (DVar.RefExpr == nullptr)
4282 DVar.CKind = PredeterminedCKind;
4283 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
4284 HasErrors = true;
4285 } else if (LoopDeclRefExpr != nullptr) {
4286 // Make the loop iteration variable private (for worksharing constructs),
4287 // linear (for simd directives with the only one associated loop) or
4288 // lastprivate (for simd directives with several collapsed or ordered
4289 // loops).
4290 if (DVar.CKind == OMPC_unknown)
4291 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate, MatchesAlways(),
4292 /*FromParent=*/false);
4293 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
4294 }
4295
4296 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
4297
4298 // Check test-expr.
4299 HasErrors |= ISC.CheckCond(For->getCond());
4300
4301 // Check incr-expr.
4302 HasErrors |= ISC.CheckInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004303 }
4304
Alexander Musmana5f070a2014-10-01 06:03:56 +00004305 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004306 return HasErrors;
4307
Alexander Musmana5f070a2014-10-01 06:03:56 +00004308 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004309 ResultIterSpace.PreCond =
4310 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexander Musman174b3ca2014-10-06 11:16:29 +00004311 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004312 DSA.getCurScope(),
4313 (isOpenMPWorksharingDirective(DKind) ||
4314 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
4315 Captures);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004316 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
Alexey Bataeva8899172015-08-06 12:30:57 +00004317 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004318 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
4319 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
4320 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
4321 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
4322 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
4323 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
4324
Alexey Bataev62dbb972015-04-22 11:59:37 +00004325 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
4326 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004327 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00004328 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004329 ResultIterSpace.CounterInit == nullptr ||
4330 ResultIterSpace.CounterStep == nullptr);
4331
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004332 return HasErrors;
4333}
4334
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004335/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004336static ExprResult
4337BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
4338 ExprResult Start,
4339 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004340 // Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004341 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
4342 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004343 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00004344 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00004345 VarRef.get()->getType())) {
4346 NewStart = SemaRef.PerformImplicitConversion(
4347 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
4348 /*AllowExplicit=*/true);
4349 if (!NewStart.isUsable())
4350 return ExprError();
4351 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004352
4353 auto Init =
4354 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4355 return Init;
4356}
4357
Alexander Musmana5f070a2014-10-01 06:03:56 +00004358/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004359static ExprResult
4360BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
4361 ExprResult VarRef, ExprResult Start, ExprResult Iter,
4362 ExprResult Step, bool Subtract,
4363 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004364 // Add parentheses (for debugging purposes only).
4365 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
4366 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
4367 !Step.isUsable())
4368 return ExprError();
4369
Alexey Bataev5a3af132016-03-29 08:58:54 +00004370 ExprResult NewStep = Step;
4371 if (Captures)
4372 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004373 if (NewStep.isInvalid())
4374 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004375 ExprResult Update =
4376 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004377 if (!Update.isUsable())
4378 return ExprError();
4379
Alexey Bataevc0214e02016-02-16 12:13:49 +00004380 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
4381 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004382 ExprResult NewStart = Start;
4383 if (Captures)
4384 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004385 if (NewStart.isInvalid())
4386 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004387
Alexey Bataevc0214e02016-02-16 12:13:49 +00004388 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
4389 ExprResult SavedUpdate = Update;
4390 ExprResult UpdateVal;
4391 if (VarRef.get()->getType()->isOverloadableType() ||
4392 NewStart.get()->getType()->isOverloadableType() ||
4393 Update.get()->getType()->isOverloadableType()) {
4394 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4395 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4396 Update =
4397 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4398 if (Update.isUsable()) {
4399 UpdateVal =
4400 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
4401 VarRef.get(), SavedUpdate.get());
4402 if (UpdateVal.isUsable()) {
4403 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
4404 UpdateVal.get());
4405 }
4406 }
4407 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4408 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004409
Alexey Bataevc0214e02016-02-16 12:13:49 +00004410 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
4411 if (!Update.isUsable() || !UpdateVal.isUsable()) {
4412 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
4413 NewStart.get(), SavedUpdate.get());
4414 if (!Update.isUsable())
4415 return ExprError();
4416
Alexey Bataev11481f52016-02-17 10:29:05 +00004417 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
4418 VarRef.get()->getType())) {
4419 Update = SemaRef.PerformImplicitConversion(
4420 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
4421 if (!Update.isUsable())
4422 return ExprError();
4423 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00004424
4425 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
4426 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004427 return Update;
4428}
4429
4430/// \brief Convert integer expression \a E to make it have at least \a Bits
4431/// bits.
4432static ExprResult WidenIterationCount(unsigned Bits, Expr *E,
4433 Sema &SemaRef) {
4434 if (E == nullptr)
4435 return ExprError();
4436 auto &C = SemaRef.Context;
4437 QualType OldType = E->getType();
4438 unsigned HasBits = C.getTypeSize(OldType);
4439 if (HasBits >= Bits)
4440 return ExprResult(E);
4441 // OK to convert to signed, because new type has more bits than old.
4442 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
4443 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
4444 true);
4445}
4446
4447/// \brief Check if the given expression \a E is a constant integer that fits
4448/// into \a Bits bits.
4449static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
4450 if (E == nullptr)
4451 return false;
4452 llvm::APSInt Result;
4453 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
4454 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
4455 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004456}
4457
Alexey Bataev5a3af132016-03-29 08:58:54 +00004458/// Build preinits statement for the given declarations.
4459static Stmt *buildPreInits(ASTContext &Context,
4460 SmallVectorImpl<Decl *> &PreInits) {
4461 if (!PreInits.empty()) {
4462 return new (Context) DeclStmt(
4463 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
4464 SourceLocation(), SourceLocation());
4465 }
4466 return nullptr;
4467}
4468
4469/// Build preinits statement for the given declarations.
4470static Stmt *buildPreInits(ASTContext &Context,
4471 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
4472 if (!Captures.empty()) {
4473 SmallVector<Decl *, 16> PreInits;
4474 for (auto &Pair : Captures)
4475 PreInits.push_back(Pair.second->getDecl());
4476 return buildPreInits(Context, PreInits);
4477 }
4478 return nullptr;
4479}
4480
4481/// Build postupdate expression for the given list of postupdates expressions.
4482static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
4483 Expr *PostUpdate = nullptr;
4484 if (!PostUpdates.empty()) {
4485 for (auto *E : PostUpdates) {
4486 Expr *ConvE = S.BuildCStyleCastExpr(
4487 E->getExprLoc(),
4488 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
4489 E->getExprLoc(), E)
4490 .get();
4491 PostUpdate = PostUpdate
4492 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
4493 PostUpdate, ConvE)
4494 .get()
4495 : ConvE;
4496 }
4497 }
4498 return PostUpdate;
4499}
4500
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004501/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00004502/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
4503/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004504static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00004505CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
4506 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
4507 DSAStackTy &DSA,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004508 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00004509 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004510 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004511 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004512 // Found 'collapse' clause - calculate collapse number.
4513 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004514 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004515 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004516 }
4517 if (OrderedLoopCountExpr) {
4518 // Found 'ordered' clause - calculate collapse number.
4519 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004520 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
4521 if (Result.getLimitedValue() < NestedLoopCount) {
4522 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4523 diag::err_omp_wrong_ordered_loop_count)
4524 << OrderedLoopCountExpr->getSourceRange();
4525 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4526 diag::note_collapse_loop_count)
4527 << CollapseLoopCountExpr->getSourceRange();
4528 }
4529 NestedLoopCount = Result.getLimitedValue();
4530 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004531 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004532 // This is helper routine for loop directives (e.g., 'for', 'simd',
4533 // 'for simd', etc.).
Alexey Bataev5a3af132016-03-29 08:58:54 +00004534 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004535 SmallVector<LoopIterationSpace, 4> IterSpaces;
4536 IterSpaces.resize(NestedLoopCount);
4537 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004538 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004539 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004540 NestedLoopCount, CollapseLoopCountExpr,
4541 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004542 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00004543 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004544 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004545 // OpenMP [2.8.1, simd construct, Restrictions]
4546 // All loops associated with the construct must be perfectly nested; that
4547 // is, there must be no intervening code nor any OpenMP directive between
4548 // any two loops.
4549 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004550 }
4551
Alexander Musmana5f070a2014-10-01 06:03:56 +00004552 Built.clear(/* size */ NestedLoopCount);
4553
4554 if (SemaRef.CurContext->isDependentContext())
4555 return NestedLoopCount;
4556
4557 // An example of what is generated for the following code:
4558 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00004559 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00004560 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004561 // for (k = 0; k < NK; ++k)
4562 // for (j = J0; j < NJ; j+=2) {
4563 // <loop body>
4564 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004565 //
4566 // We generate the code below.
4567 // Note: the loop body may be outlined in CodeGen.
4568 // Note: some counters may be C++ classes, operator- is used to find number of
4569 // iterations and operator+= to calculate counter value.
4570 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
4571 // or i64 is currently supported).
4572 //
4573 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
4574 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
4575 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
4576 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
4577 // // similar updates for vars in clauses (e.g. 'linear')
4578 // <loop body (using local i and j)>
4579 // }
4580 // i = NI; // assign final values of counters
4581 // j = NJ;
4582 //
4583
4584 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
4585 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00004586 // Precondition tests if there is at least one iteration (all conditions are
4587 // true).
4588 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004589 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004590 ExprResult LastIteration32 = WidenIterationCount(
4591 32 /* Bits */, SemaRef.PerformImplicitConversion(
4592 N0->IgnoreImpCasts(), N0->getType(),
4593 Sema::AA_Converting, /*AllowExplicit=*/true)
4594 .get(),
4595 SemaRef);
4596 ExprResult LastIteration64 = WidenIterationCount(
4597 64 /* Bits */, SemaRef.PerformImplicitConversion(
4598 N0->IgnoreImpCasts(), N0->getType(),
4599 Sema::AA_Converting, /*AllowExplicit=*/true)
4600 .get(),
4601 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004602
4603 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
4604 return NestedLoopCount;
4605
4606 auto &C = SemaRef.Context;
4607 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
4608
4609 Scope *CurScope = DSA.getCurScope();
4610 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004611 if (PreCond.isUsable()) {
4612 PreCond = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_LAnd,
4613 PreCond.get(), IterSpaces[Cnt].PreCond);
4614 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004615 auto N = IterSpaces[Cnt].NumIterations;
4616 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
4617 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004618 LastIteration32 = SemaRef.BuildBinOp(
4619 CurScope, SourceLocation(), BO_Mul, LastIteration32.get(),
4620 SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4621 Sema::AA_Converting,
4622 /*AllowExplicit=*/true)
4623 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004624 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004625 LastIteration64 = SemaRef.BuildBinOp(
4626 CurScope, SourceLocation(), BO_Mul, LastIteration64.get(),
4627 SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4628 Sema::AA_Converting,
4629 /*AllowExplicit=*/true)
4630 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004631 }
4632
4633 // Choose either the 32-bit or 64-bit version.
4634 ExprResult LastIteration = LastIteration64;
4635 if (LastIteration32.isUsable() &&
4636 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4637 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
4638 FitsInto(
4639 32 /* Bits */,
4640 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4641 LastIteration64.get(), SemaRef)))
4642 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00004643 QualType VType = LastIteration.get()->getType();
4644 QualType RealVType = VType;
4645 QualType StrideVType = VType;
4646 if (isOpenMPTaskLoopDirective(DKind)) {
4647 VType =
4648 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4649 StrideVType =
4650 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4651 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004652
4653 if (!LastIteration.isUsable())
4654 return 0;
4655
4656 // Save the number of iterations.
4657 ExprResult NumIterations = LastIteration;
4658 {
4659 LastIteration = SemaRef.BuildBinOp(
4660 CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
4661 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4662 if (!LastIteration.isUsable())
4663 return 0;
4664 }
4665
4666 // Calculate the last iteration number beforehand instead of doing this on
4667 // each iteration. Do not do this if the number of iterations may be kfold-ed.
4668 llvm::APSInt Result;
4669 bool IsConstant =
4670 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4671 ExprResult CalcLastIteration;
4672 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004673 ExprResult SaveRef =
4674 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004675 LastIteration = SaveRef;
4676
4677 // Prepare SaveRef + 1.
4678 NumIterations = SemaRef.BuildBinOp(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004679 CurScope, SourceLocation(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004680 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4681 if (!NumIterations.isUsable())
4682 return 0;
4683 }
4684
4685 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4686
Alexander Musmanc6388682014-12-15 07:07:06 +00004687 // Build variables passed into runtime, nesessary for worksharing directives.
4688 ExprResult LB, UB, IL, ST, EUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004689 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4690 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004691 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004692 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4693 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00004694 SemaRef.AddInitializerToDecl(
4695 LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4696 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
4697
4698 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004699 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4700 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00004701 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
4702 /*DirectInit*/ false,
4703 /*TypeMayContainAuto*/ false);
4704
4705 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4706 // This will be used to implement clause 'lastprivate'.
4707 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00004708 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4709 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00004710 SemaRef.AddInitializerToDecl(
4711 ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4712 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
4713
4714 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00004715 VarDecl *STDecl =
4716 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4717 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00004718 SemaRef.AddInitializerToDecl(
4719 STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4720 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
4721
4722 // Build expression: UB = min(UB, LastIteration)
4723 // It is nesessary for CodeGen of directives with static scheduling.
4724 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4725 UB.get(), LastIteration.get());
4726 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4727 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4728 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4729 CondOp.get());
4730 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
4731 }
4732
4733 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004734 ExprResult IV;
4735 ExprResult Init;
4736 {
Alexey Bataev7292c292016-04-25 12:22:29 +00004737 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4738 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004739 Expr *RHS = (isOpenMPWorksharingDirective(DKind) ||
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004740 isOpenMPTaskLoopDirective(DKind) ||
4741 isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004742 ? LB.get()
4743 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4744 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4745 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004746 }
4747
Alexander Musmanc6388682014-12-15 07:07:06 +00004748 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004749 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00004750 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004751 (isOpenMPWorksharingDirective(DKind) ||
4752 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004753 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4754 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4755 NumIterations.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004756
4757 // Loop increment (IV = IV + 1)
4758 SourceLocation IncLoc;
4759 ExprResult Inc =
4760 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4761 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4762 if (!Inc.isUsable())
4763 return 0;
4764 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00004765 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4766 if (!Inc.isUsable())
4767 return 0;
4768
4769 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4770 // Used for directives with static scheduling.
4771 ExprResult NextLB, NextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004772 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4773 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004774 // LB + ST
4775 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4776 if (!NextLB.isUsable())
4777 return 0;
4778 // LB = LB + ST
4779 NextLB =
4780 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4781 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4782 if (!NextLB.isUsable())
4783 return 0;
4784 // UB + ST
4785 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4786 if (!NextUB.isUsable())
4787 return 0;
4788 // UB = UB + ST
4789 NextUB =
4790 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4791 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4792 if (!NextUB.isUsable())
4793 return 0;
4794 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004795
4796 // Build updates and final values of the loop counters.
4797 bool HasErrors = false;
4798 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004799 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004800 Built.Updates.resize(NestedLoopCount);
4801 Built.Finals.resize(NestedLoopCount);
4802 {
4803 ExprResult Div;
4804 // Go from inner nested loop to outer.
4805 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4806 LoopIterationSpace &IS = IterSpaces[Cnt];
4807 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4808 // Build: Iter = (IV / Div) % IS.NumIters
4809 // where Div is product of previous iterations' IS.NumIters.
4810 ExprResult Iter;
4811 if (Div.isUsable()) {
4812 Iter =
4813 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4814 } else {
4815 Iter = IV;
4816 assert((Cnt == (int)NestedLoopCount - 1) &&
4817 "unusable div expected on first iteration only");
4818 }
4819
4820 if (Cnt != 0 && Iter.isUsable())
4821 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4822 IS.NumIterations);
4823 if (!Iter.isUsable()) {
4824 HasErrors = true;
4825 break;
4826 }
4827
Alexey Bataev39f915b82015-05-08 10:41:21 +00004828 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004829 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4830 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4831 IS.CounterVar->getExprLoc(),
4832 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004833 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004834 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004835 if (!Init.isUsable()) {
4836 HasErrors = true;
4837 break;
4838 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00004839 ExprResult Update = BuildCounterUpdate(
4840 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4841 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004842 if (!Update.isUsable()) {
4843 HasErrors = true;
4844 break;
4845 }
4846
4847 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4848 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00004849 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004850 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004851 if (!Final.isUsable()) {
4852 HasErrors = true;
4853 break;
4854 }
4855
4856 // Build Div for the next iteration: Div <- Div * IS.NumIters
4857 if (Cnt != 0) {
4858 if (Div.isUnset())
4859 Div = IS.NumIterations;
4860 else
4861 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4862 IS.NumIterations);
4863
4864 // Add parentheses (for debugging purposes only).
4865 if (Div.isUsable())
4866 Div = SemaRef.ActOnParenExpr(UpdLoc, UpdLoc, Div.get());
4867 if (!Div.isUsable()) {
4868 HasErrors = true;
4869 break;
4870 }
4871 }
4872 if (!Update.isUsable() || !Final.isUsable()) {
4873 HasErrors = true;
4874 break;
4875 }
4876 // Save results
4877 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00004878 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004879 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004880 Built.Updates[Cnt] = Update.get();
4881 Built.Finals[Cnt] = Final.get();
4882 }
4883 }
4884
4885 if (HasErrors)
4886 return 0;
4887
4888 // Save results
4889 Built.IterationVarRef = IV.get();
4890 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00004891 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004892 Built.CalcLastIteration =
4893 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004894 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00004895 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004896 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004897 Built.Init = Init.get();
4898 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004899 Built.LB = LB.get();
4900 Built.UB = UB.get();
4901 Built.IL = IL.get();
4902 Built.ST = ST.get();
4903 Built.EUB = EUB.get();
4904 Built.NLB = NextLB.get();
4905 Built.NUB = NextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004906
Alexey Bataevabfc0692014-06-25 06:52:00 +00004907 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004908}
4909
Alexey Bataev10e775f2015-07-30 11:36:16 +00004910static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004911 auto CollapseClauses =
4912 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4913 if (CollapseClauses.begin() != CollapseClauses.end())
4914 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004915 return nullptr;
4916}
4917
Alexey Bataev10e775f2015-07-30 11:36:16 +00004918static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004919 auto OrderedClauses =
4920 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4921 if (OrderedClauses.begin() != OrderedClauses.end())
4922 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004923 return nullptr;
4924}
4925
Alexey Bataev66b15b52015-08-21 11:14:16 +00004926static bool checkSimdlenSafelenValues(Sema &S, const Expr *Simdlen,
4927 const Expr *Safelen) {
4928 llvm::APSInt SimdlenRes, SafelenRes;
4929 if (Simdlen->isValueDependent() || Simdlen->isTypeDependent() ||
4930 Simdlen->isInstantiationDependent() ||
4931 Simdlen->containsUnexpandedParameterPack())
4932 return false;
4933 if (Safelen->isValueDependent() || Safelen->isTypeDependent() ||
4934 Safelen->isInstantiationDependent() ||
4935 Safelen->containsUnexpandedParameterPack())
4936 return false;
4937 Simdlen->EvaluateAsInt(SimdlenRes, S.Context);
4938 Safelen->EvaluateAsInt(SafelenRes, S.Context);
4939 // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
4940 // If both simdlen and safelen clauses are specified, the value of the simdlen
4941 // parameter must be less than or equal to the value of the safelen parameter.
4942 if (SimdlenRes > SafelenRes) {
4943 S.Diag(Simdlen->getExprLoc(), diag::err_omp_wrong_simdlen_safelen_values)
4944 << Simdlen->getSourceRange() << Safelen->getSourceRange();
4945 return true;
4946 }
4947 return false;
4948}
4949
Alexey Bataev4acb8592014-07-07 13:01:15 +00004950StmtResult Sema::ActOnOpenMPSimdDirective(
4951 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4952 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004953 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004954 if (!AStmt)
4955 return StmtError();
4956
4957 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004958 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004959 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4960 // define the nested loops number.
4961 unsigned NestedLoopCount = CheckOpenMPLoop(
4962 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4963 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004964 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004965 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004966
Alexander Musmana5f070a2014-10-01 06:03:56 +00004967 assert((CurContext->isDependentContext() || B.builtAll()) &&
4968 "omp simd loop exprs were not built");
4969
Alexander Musman3276a272015-03-21 10:12:56 +00004970 if (!CurContext->isDependentContext()) {
4971 // Finalize the clauses that need pre-built expressions for CodeGen.
4972 for (auto C : Clauses) {
4973 if (auto LC = dyn_cast<OMPLinearClause>(C))
4974 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004975 B.NumIterations, *this, CurScope,
4976 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00004977 return StmtError();
4978 }
4979 }
4980
Alexey Bataev66b15b52015-08-21 11:14:16 +00004981 // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
4982 // If both simdlen and safelen clauses are specified, the value of the simdlen
4983 // parameter must be less than or equal to the value of the safelen parameter.
4984 OMPSafelenClause *Safelen = nullptr;
4985 OMPSimdlenClause *Simdlen = nullptr;
4986 for (auto *Clause : Clauses) {
4987 if (Clause->getClauseKind() == OMPC_safelen)
4988 Safelen = cast<OMPSafelenClause>(Clause);
4989 else if (Clause->getClauseKind() == OMPC_simdlen)
4990 Simdlen = cast<OMPSimdlenClause>(Clause);
4991 if (Safelen && Simdlen)
4992 break;
4993 }
4994 if (Simdlen && Safelen &&
4995 checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
4996 Safelen->getSafelen()))
4997 return StmtError();
4998
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004999 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005000 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5001 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005002}
5003
Alexey Bataev4acb8592014-07-07 13:01:15 +00005004StmtResult Sema::ActOnOpenMPForDirective(
5005 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5006 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005007 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005008 if (!AStmt)
5009 return StmtError();
5010
5011 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005012 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005013 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5014 // define the nested loops number.
5015 unsigned NestedLoopCount = CheckOpenMPLoop(
5016 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5017 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005018 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00005019 return StmtError();
5020
Alexander Musmana5f070a2014-10-01 06:03:56 +00005021 assert((CurContext->isDependentContext() || B.builtAll()) &&
5022 "omp for loop exprs were not built");
5023
Alexey Bataev54acd402015-08-04 11:18:19 +00005024 if (!CurContext->isDependentContext()) {
5025 // Finalize the clauses that need pre-built expressions for CodeGen.
5026 for (auto C : Clauses) {
5027 if (auto LC = dyn_cast<OMPLinearClause>(C))
5028 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005029 B.NumIterations, *this, CurScope,
5030 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005031 return StmtError();
5032 }
5033 }
5034
Alexey Bataevf29276e2014-06-18 04:14:57 +00005035 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005036 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005037 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00005038}
5039
Alexander Musmanf82886e2014-09-18 05:12:34 +00005040StmtResult Sema::ActOnOpenMPForSimdDirective(
5041 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5042 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005043 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005044 if (!AStmt)
5045 return StmtError();
5046
5047 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005048 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005049 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5050 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00005051 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005052 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
5053 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5054 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00005055 if (NestedLoopCount == 0)
5056 return StmtError();
5057
Alexander Musmanc6388682014-12-15 07:07:06 +00005058 assert((CurContext->isDependentContext() || B.builtAll()) &&
5059 "omp for simd loop exprs were not built");
5060
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005061 if (!CurContext->isDependentContext()) {
5062 // Finalize the clauses that need pre-built expressions for CodeGen.
5063 for (auto C : Clauses) {
5064 if (auto LC = dyn_cast<OMPLinearClause>(C))
5065 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005066 B.NumIterations, *this, CurScope,
5067 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005068 return StmtError();
5069 }
5070 }
5071
Alexey Bataev66b15b52015-08-21 11:14:16 +00005072 // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
5073 // If both simdlen and safelen clauses are specified, the value of the simdlen
5074 // parameter must be less than or equal to the value of the safelen parameter.
5075 OMPSafelenClause *Safelen = nullptr;
5076 OMPSimdlenClause *Simdlen = nullptr;
5077 for (auto *Clause : Clauses) {
5078 if (Clause->getClauseKind() == OMPC_safelen)
5079 Safelen = cast<OMPSafelenClause>(Clause);
5080 else if (Clause->getClauseKind() == OMPC_simdlen)
5081 Simdlen = cast<OMPSimdlenClause>(Clause);
5082 if (Safelen && Simdlen)
5083 break;
5084 }
5085 if (Simdlen && Safelen &&
5086 checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
5087 Safelen->getSafelen()))
5088 return StmtError();
5089
Alexander Musmanf82886e2014-09-18 05:12:34 +00005090 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005091 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5092 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00005093}
5094
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005095StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
5096 Stmt *AStmt,
5097 SourceLocation StartLoc,
5098 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005099 if (!AStmt)
5100 return StmtError();
5101
5102 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005103 auto BaseStmt = AStmt;
5104 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
5105 BaseStmt = CS->getCapturedStmt();
5106 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
5107 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00005108 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005109 return StmtError();
5110 // All associated statements must be '#pragma omp section' except for
5111 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00005112 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005113 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5114 if (SectionStmt)
5115 Diag(SectionStmt->getLocStart(),
5116 diag::err_omp_sections_substmt_not_section);
5117 return StmtError();
5118 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005119 cast<OMPSectionDirective>(SectionStmt)
5120 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005121 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005122 } else {
5123 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
5124 return StmtError();
5125 }
5126
5127 getCurFunction()->setHasBranchProtectedScope();
5128
Alexey Bataev25e5b442015-09-15 12:52:43 +00005129 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5130 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005131}
5132
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005133StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
5134 SourceLocation StartLoc,
5135 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005136 if (!AStmt)
5137 return StmtError();
5138
5139 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005140
5141 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00005142 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005143
Alexey Bataev25e5b442015-09-15 12:52:43 +00005144 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
5145 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005146}
5147
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005148StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
5149 Stmt *AStmt,
5150 SourceLocation StartLoc,
5151 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005152 if (!AStmt)
5153 return StmtError();
5154
5155 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00005156
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005157 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00005158
Alexey Bataev3255bf32015-01-19 05:20:46 +00005159 // OpenMP [2.7.3, single Construct, Restrictions]
5160 // The copyprivate clause must not be used with the nowait clause.
5161 OMPClause *Nowait = nullptr;
5162 OMPClause *Copyprivate = nullptr;
5163 for (auto *Clause : Clauses) {
5164 if (Clause->getClauseKind() == OMPC_nowait)
5165 Nowait = Clause;
5166 else if (Clause->getClauseKind() == OMPC_copyprivate)
5167 Copyprivate = Clause;
5168 if (Copyprivate && Nowait) {
5169 Diag(Copyprivate->getLocStart(),
5170 diag::err_omp_single_copyprivate_with_nowait);
5171 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
5172 return StmtError();
5173 }
5174 }
5175
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005176 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5177}
5178
Alexander Musman80c22892014-07-17 08:54:58 +00005179StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
5180 SourceLocation StartLoc,
5181 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005182 if (!AStmt)
5183 return StmtError();
5184
5185 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00005186
5187 getCurFunction()->setHasBranchProtectedScope();
5188
5189 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
5190}
5191
Alexey Bataev28c75412015-12-15 08:19:24 +00005192StmtResult Sema::ActOnOpenMPCriticalDirective(
5193 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
5194 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005195 if (!AStmt)
5196 return StmtError();
5197
5198 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005199
Alexey Bataev28c75412015-12-15 08:19:24 +00005200 bool ErrorFound = false;
5201 llvm::APSInt Hint;
5202 SourceLocation HintLoc;
5203 bool DependentHint = false;
5204 for (auto *C : Clauses) {
5205 if (C->getClauseKind() == OMPC_hint) {
5206 if (!DirName.getName()) {
5207 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
5208 ErrorFound = true;
5209 }
5210 Expr *E = cast<OMPHintClause>(C)->getHint();
5211 if (E->isTypeDependent() || E->isValueDependent() ||
5212 E->isInstantiationDependent())
5213 DependentHint = true;
5214 else {
5215 Hint = E->EvaluateKnownConstInt(Context);
5216 HintLoc = C->getLocStart();
5217 }
5218 }
5219 }
5220 if (ErrorFound)
5221 return StmtError();
5222 auto Pair = DSAStack->getCriticalWithHint(DirName);
5223 if (Pair.first && DirName.getName() && !DependentHint) {
5224 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
5225 Diag(StartLoc, diag::err_omp_critical_with_hint);
5226 if (HintLoc.isValid()) {
5227 Diag(HintLoc, diag::note_omp_critical_hint_here)
5228 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
5229 } else
5230 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
5231 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
5232 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
5233 << 1
5234 << C->getHint()->EvaluateKnownConstInt(Context).toString(
5235 /*Radix=*/10, /*Signed=*/false);
5236 } else
5237 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
5238 }
5239 }
5240
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005241 getCurFunction()->setHasBranchProtectedScope();
5242
Alexey Bataev28c75412015-12-15 08:19:24 +00005243 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
5244 Clauses, AStmt);
5245 if (!Pair.first && DirName.getName() && !DependentHint)
5246 DSAStack->addCriticalWithHint(Dir, Hint);
5247 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005248}
5249
Alexey Bataev4acb8592014-07-07 13:01:15 +00005250StmtResult Sema::ActOnOpenMPParallelForDirective(
5251 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5252 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005253 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005254 if (!AStmt)
5255 return StmtError();
5256
Alexey Bataev4acb8592014-07-07 13:01:15 +00005257 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5258 // 1.2.2 OpenMP Language Terminology
5259 // Structured block - An executable statement with a single entry at the
5260 // top and a single exit at the bottom.
5261 // The point of exit cannot be a branch out of the structured block.
5262 // longjmp() and throw() must not violate the entry/exit criteria.
5263 CS->getCapturedDecl()->setNothrow();
5264
Alexander Musmanc6388682014-12-15 07:07:06 +00005265 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005266 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5267 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00005268 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005269 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
5270 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5271 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00005272 if (NestedLoopCount == 0)
5273 return StmtError();
5274
Alexander Musmana5f070a2014-10-01 06:03:56 +00005275 assert((CurContext->isDependentContext() || B.builtAll()) &&
5276 "omp parallel for loop exprs were not built");
5277
Alexey Bataev54acd402015-08-04 11:18:19 +00005278 if (!CurContext->isDependentContext()) {
5279 // Finalize the clauses that need pre-built expressions for CodeGen.
5280 for (auto C : Clauses) {
5281 if (auto LC = dyn_cast<OMPLinearClause>(C))
5282 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005283 B.NumIterations, *this, CurScope,
5284 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005285 return StmtError();
5286 }
5287 }
5288
Alexey Bataev4acb8592014-07-07 13:01:15 +00005289 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005290 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005291 NestedLoopCount, Clauses, AStmt, B,
5292 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00005293}
5294
Alexander Musmane4e893b2014-09-23 09:33:00 +00005295StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
5296 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5297 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005298 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005299 if (!AStmt)
5300 return StmtError();
5301
Alexander Musmane4e893b2014-09-23 09:33:00 +00005302 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5303 // 1.2.2 OpenMP Language Terminology
5304 // Structured block - An executable statement with a single entry at the
5305 // top and a single exit at the bottom.
5306 // The point of exit cannot be a branch out of the structured block.
5307 // longjmp() and throw() must not violate the entry/exit criteria.
5308 CS->getCapturedDecl()->setNothrow();
5309
Alexander Musmanc6388682014-12-15 07:07:06 +00005310 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005311 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5312 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00005313 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005314 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
5315 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5316 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005317 if (NestedLoopCount == 0)
5318 return StmtError();
5319
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005320 if (!CurContext->isDependentContext()) {
5321 // Finalize the clauses that need pre-built expressions for CodeGen.
5322 for (auto C : Clauses) {
5323 if (auto LC = dyn_cast<OMPLinearClause>(C))
5324 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005325 B.NumIterations, *this, CurScope,
5326 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005327 return StmtError();
5328 }
5329 }
5330
Alexey Bataev66b15b52015-08-21 11:14:16 +00005331 // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
5332 // If both simdlen and safelen clauses are specified, the value of the simdlen
5333 // parameter must be less than or equal to the value of the safelen parameter.
5334 OMPSafelenClause *Safelen = nullptr;
5335 OMPSimdlenClause *Simdlen = nullptr;
5336 for (auto *Clause : Clauses) {
5337 if (Clause->getClauseKind() == OMPC_safelen)
5338 Safelen = cast<OMPSafelenClause>(Clause);
5339 else if (Clause->getClauseKind() == OMPC_simdlen)
5340 Simdlen = cast<OMPSimdlenClause>(Clause);
5341 if (Safelen && Simdlen)
5342 break;
5343 }
5344 if (Simdlen && Safelen &&
5345 checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
5346 Safelen->getSafelen()))
5347 return StmtError();
5348
Alexander Musmane4e893b2014-09-23 09:33:00 +00005349 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005350 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00005351 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005352}
5353
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005354StmtResult
5355Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
5356 Stmt *AStmt, SourceLocation StartLoc,
5357 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005358 if (!AStmt)
5359 return StmtError();
5360
5361 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005362 auto BaseStmt = AStmt;
5363 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
5364 BaseStmt = CS->getCapturedStmt();
5365 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
5366 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00005367 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005368 return StmtError();
5369 // All associated statements must be '#pragma omp section' except for
5370 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00005371 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005372 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5373 if (SectionStmt)
5374 Diag(SectionStmt->getLocStart(),
5375 diag::err_omp_parallel_sections_substmt_not_section);
5376 return StmtError();
5377 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005378 cast<OMPSectionDirective>(SectionStmt)
5379 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005380 }
5381 } else {
5382 Diag(AStmt->getLocStart(),
5383 diag::err_omp_parallel_sections_not_compound_stmt);
5384 return StmtError();
5385 }
5386
5387 getCurFunction()->setHasBranchProtectedScope();
5388
Alexey Bataev25e5b442015-09-15 12:52:43 +00005389 return OMPParallelSectionsDirective::Create(
5390 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005391}
5392
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005393StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
5394 Stmt *AStmt, SourceLocation StartLoc,
5395 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005396 if (!AStmt)
5397 return StmtError();
5398
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005399 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5400 // 1.2.2 OpenMP Language Terminology
5401 // Structured block - An executable statement with a single entry at the
5402 // top and a single exit at the bottom.
5403 // The point of exit cannot be a branch out of the structured block.
5404 // longjmp() and throw() must not violate the entry/exit criteria.
5405 CS->getCapturedDecl()->setNothrow();
5406
5407 getCurFunction()->setHasBranchProtectedScope();
5408
Alexey Bataev25e5b442015-09-15 12:52:43 +00005409 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5410 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005411}
5412
Alexey Bataev68446b72014-07-18 07:47:19 +00005413StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
5414 SourceLocation EndLoc) {
5415 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
5416}
5417
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005418StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
5419 SourceLocation EndLoc) {
5420 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
5421}
5422
Alexey Bataev2df347a2014-07-18 10:17:07 +00005423StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
5424 SourceLocation EndLoc) {
5425 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
5426}
5427
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005428StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
5429 SourceLocation StartLoc,
5430 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005431 if (!AStmt)
5432 return StmtError();
5433
5434 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005435
5436 getCurFunction()->setHasBranchProtectedScope();
5437
5438 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
5439}
5440
Alexey Bataev6125da92014-07-21 11:26:11 +00005441StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
5442 SourceLocation StartLoc,
5443 SourceLocation EndLoc) {
5444 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
5445 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
5446}
5447
Alexey Bataev346265e2015-09-25 10:37:12 +00005448StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
5449 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005450 SourceLocation StartLoc,
5451 SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00005452 OMPClause *DependFound = nullptr;
5453 OMPClause *DependSourceClause = nullptr;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005454 OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005455 bool ErrorFound = false;
Alexey Bataev346265e2015-09-25 10:37:12 +00005456 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005457 OMPSIMDClause *SC = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005458 for (auto *C : Clauses) {
5459 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
5460 DependFound = C;
5461 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
5462 if (DependSourceClause) {
5463 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
5464 << getOpenMPDirectiveName(OMPD_ordered)
5465 << getOpenMPClauseName(OMPC_depend) << 2;
5466 ErrorFound = true;
5467 } else
5468 DependSourceClause = C;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005469 if (DependSinkClause) {
5470 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5471 << 0;
5472 ErrorFound = true;
5473 }
5474 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
5475 if (DependSourceClause) {
5476 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5477 << 1;
5478 ErrorFound = true;
5479 }
5480 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00005481 }
5482 } else if (C->getClauseKind() == OMPC_threads)
Alexey Bataev346265e2015-09-25 10:37:12 +00005483 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005484 else if (C->getClauseKind() == OMPC_simd)
5485 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00005486 }
Alexey Bataeveb482352015-12-18 05:05:56 +00005487 if (!ErrorFound && !SC &&
5488 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005489 // OpenMP [2.8.1,simd Construct, Restrictions]
5490 // An ordered construct with the simd clause is the only OpenMP construct
5491 // that can appear in the simd region.
5492 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00005493 ErrorFound = true;
5494 } else if (DependFound && (TC || SC)) {
5495 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
5496 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
5497 ErrorFound = true;
5498 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
5499 Diag(DependFound->getLocStart(),
5500 diag::err_omp_ordered_directive_without_param);
5501 ErrorFound = true;
5502 } else if (TC || Clauses.empty()) {
5503 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
5504 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
5505 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
5506 << (TC != nullptr);
5507 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
5508 ErrorFound = true;
5509 }
5510 }
5511 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005512 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00005513
5514 if (AStmt) {
5515 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5516
5517 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005518 }
Alexey Bataev346265e2015-09-25 10:37:12 +00005519
5520 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005521}
5522
Alexey Bataev1d160b12015-03-13 12:27:31 +00005523namespace {
5524/// \brief Helper class for checking expression in 'omp atomic [update]'
5525/// construct.
5526class OpenMPAtomicUpdateChecker {
5527 /// \brief Error results for atomic update expressions.
5528 enum ExprAnalysisErrorCode {
5529 /// \brief A statement is not an expression statement.
5530 NotAnExpression,
5531 /// \brief Expression is not builtin binary or unary operation.
5532 NotABinaryOrUnaryExpression,
5533 /// \brief Unary operation is not post-/pre- increment/decrement operation.
5534 NotAnUnaryIncDecExpression,
5535 /// \brief An expression is not of scalar type.
5536 NotAScalarType,
5537 /// \brief A binary operation is not an assignment operation.
5538 NotAnAssignmentOp,
5539 /// \brief RHS part of the binary operation is not a binary expression.
5540 NotABinaryExpression,
5541 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
5542 /// expression.
5543 NotABinaryOperator,
5544 /// \brief RHS binary operation does not have reference to the updated LHS
5545 /// part.
5546 NotAnUpdateExpression,
5547 /// \brief No errors is found.
5548 NoError
5549 };
5550 /// \brief Reference to Sema.
5551 Sema &SemaRef;
5552 /// \brief A location for note diagnostics (when error is found).
5553 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005554 /// \brief 'x' lvalue part of the source atomic expression.
5555 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005556 /// \brief 'expr' rvalue part of the source atomic expression.
5557 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005558 /// \brief Helper expression of the form
5559 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5560 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5561 Expr *UpdateExpr;
5562 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
5563 /// important for non-associative operations.
5564 bool IsXLHSInRHSPart;
5565 BinaryOperatorKind Op;
5566 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005567 /// \brief true if the source expression is a postfix unary operation, false
5568 /// if it is a prefix unary operation.
5569 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005570
5571public:
5572 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00005573 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00005574 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00005575 /// \brief Check specified statement that it is suitable for 'atomic update'
5576 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00005577 /// expression. If DiagId and NoteId == 0, then only check is performed
5578 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00005579 /// \param DiagId Diagnostic which should be emitted if error is found.
5580 /// \param NoteId Diagnostic note for the main error message.
5581 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00005582 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005583 /// \brief Return the 'x' lvalue part of the source atomic expression.
5584 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00005585 /// \brief Return the 'expr' rvalue part of the source atomic expression.
5586 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00005587 /// \brief Return the update expression used in calculation of the updated
5588 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5589 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5590 Expr *getUpdateExpr() const { return UpdateExpr; }
5591 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5592 /// false otherwise.
5593 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5594
Alexey Bataevb78ca832015-04-01 03:33:17 +00005595 /// \brief true if the source expression is a postfix unary operation, false
5596 /// if it is a prefix unary operation.
5597 bool isPostfixUpdate() const { return IsPostfixUpdate; }
5598
Alexey Bataev1d160b12015-03-13 12:27:31 +00005599private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00005600 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5601 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005602};
5603} // namespace
5604
5605bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5606 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5607 ExprAnalysisErrorCode ErrorFound = NoError;
5608 SourceLocation ErrorLoc, NoteLoc;
5609 SourceRange ErrorRange, NoteRange;
5610 // Allowed constructs are:
5611 // x = x binop expr;
5612 // x = expr binop x;
5613 if (AtomicBinOp->getOpcode() == BO_Assign) {
5614 X = AtomicBinOp->getLHS();
5615 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5616 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5617 if (AtomicInnerBinOp->isMultiplicativeOp() ||
5618 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5619 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005620 Op = AtomicInnerBinOp->getOpcode();
5621 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005622 auto *LHS = AtomicInnerBinOp->getLHS();
5623 auto *RHS = AtomicInnerBinOp->getRHS();
5624 llvm::FoldingSetNodeID XId, LHSId, RHSId;
5625 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5626 /*Canonical=*/true);
5627 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5628 /*Canonical=*/true);
5629 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5630 /*Canonical=*/true);
5631 if (XId == LHSId) {
5632 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005633 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005634 } else if (XId == RHSId) {
5635 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005636 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005637 } else {
5638 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5639 ErrorRange = AtomicInnerBinOp->getSourceRange();
5640 NoteLoc = X->getExprLoc();
5641 NoteRange = X->getSourceRange();
5642 ErrorFound = NotAnUpdateExpression;
5643 }
5644 } else {
5645 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5646 ErrorRange = AtomicInnerBinOp->getSourceRange();
5647 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5648 NoteRange = SourceRange(NoteLoc, NoteLoc);
5649 ErrorFound = NotABinaryOperator;
5650 }
5651 } else {
5652 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5653 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5654 ErrorFound = NotABinaryExpression;
5655 }
5656 } else {
5657 ErrorLoc = AtomicBinOp->getExprLoc();
5658 ErrorRange = AtomicBinOp->getSourceRange();
5659 NoteLoc = AtomicBinOp->getOperatorLoc();
5660 NoteRange = SourceRange(NoteLoc, NoteLoc);
5661 ErrorFound = NotAnAssignmentOp;
5662 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005663 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005664 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5665 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5666 return true;
5667 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005668 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005669 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005670}
5671
5672bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5673 unsigned NoteId) {
5674 ExprAnalysisErrorCode ErrorFound = NoError;
5675 SourceLocation ErrorLoc, NoteLoc;
5676 SourceRange ErrorRange, NoteRange;
5677 // Allowed constructs are:
5678 // x++;
5679 // x--;
5680 // ++x;
5681 // --x;
5682 // x binop= expr;
5683 // x = x binop expr;
5684 // x = expr binop x;
5685 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5686 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5687 if (AtomicBody->getType()->isScalarType() ||
5688 AtomicBody->isInstantiationDependent()) {
5689 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5690 AtomicBody->IgnoreParenImpCasts())) {
5691 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00005692 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00005693 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00005694 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005695 E = AtomicCompAssignOp->getRHS();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005696 X = AtomicCompAssignOp->getLHS();
5697 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005698 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5699 AtomicBody->IgnoreParenImpCasts())) {
5700 // Check for Binary Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00005701 if(checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
5702 return true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005703 } else if (auto *AtomicUnaryOp =
Alexey Bataev1d160b12015-03-13 12:27:31 +00005704 dyn_cast<UnaryOperator>(AtomicBody->IgnoreParenImpCasts())) {
5705 // Check for Unary Operation
5706 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005707 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005708 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5709 OpLoc = AtomicUnaryOp->getOperatorLoc();
5710 X = AtomicUnaryOp->getSubExpr();
5711 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5712 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005713 } else {
5714 ErrorFound = NotAnUnaryIncDecExpression;
5715 ErrorLoc = AtomicUnaryOp->getExprLoc();
5716 ErrorRange = AtomicUnaryOp->getSourceRange();
5717 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5718 NoteRange = SourceRange(NoteLoc, NoteLoc);
5719 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005720 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005721 ErrorFound = NotABinaryOrUnaryExpression;
5722 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5723 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5724 }
5725 } else {
5726 ErrorFound = NotAScalarType;
5727 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5728 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5729 }
5730 } else {
5731 ErrorFound = NotAnExpression;
5732 NoteLoc = ErrorLoc = S->getLocStart();
5733 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5734 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005735 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005736 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5737 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5738 return true;
5739 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005740 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005741 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005742 // Build an update expression of form 'OpaqueValueExpr(x) binop
5743 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5744 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5745 auto *OVEX = new (SemaRef.getASTContext())
5746 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5747 auto *OVEExpr = new (SemaRef.getASTContext())
5748 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5749 auto Update =
5750 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5751 IsXLHSInRHSPart ? OVEExpr : OVEX);
5752 if (Update.isInvalid())
5753 return true;
5754 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5755 Sema::AA_Casting);
5756 if (Update.isInvalid())
5757 return true;
5758 UpdateExpr = Update.get();
5759 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00005760 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005761}
5762
Alexey Bataev0162e452014-07-22 10:10:35 +00005763StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5764 Stmt *AStmt,
5765 SourceLocation StartLoc,
5766 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005767 if (!AStmt)
5768 return StmtError();
5769
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005770 auto CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00005771 // 1.2.2 OpenMP Language Terminology
5772 // Structured block - An executable statement with a single entry at the
5773 // top and a single exit at the bottom.
5774 // The point of exit cannot be a branch out of the structured block.
5775 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00005776 OpenMPClauseKind AtomicKind = OMPC_unknown;
5777 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005778 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00005779 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00005780 C->getClauseKind() == OMPC_update ||
5781 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00005782 if (AtomicKind != OMPC_unknown) {
5783 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5784 << SourceRange(C->getLocStart(), C->getLocEnd());
5785 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5786 << getOpenMPClauseName(AtomicKind);
5787 } else {
5788 AtomicKind = C->getClauseKind();
5789 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005790 }
5791 }
5792 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005793
Alexey Bataev459dec02014-07-24 06:46:57 +00005794 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00005795 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5796 Body = EWC->getSubExpr();
5797
Alexey Bataev62cec442014-11-18 10:14:22 +00005798 Expr *X = nullptr;
5799 Expr *V = nullptr;
5800 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005801 Expr *UE = nullptr;
5802 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005803 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00005804 // OpenMP [2.12.6, atomic Construct]
5805 // In the next expressions:
5806 // * x and v (as applicable) are both l-value expressions with scalar type.
5807 // * During the execution of an atomic region, multiple syntactic
5808 // occurrences of x must designate the same storage location.
5809 // * Neither of v and expr (as applicable) may access the storage location
5810 // designated by x.
5811 // * Neither of x and expr (as applicable) may access the storage location
5812 // designated by v.
5813 // * expr is an expression with scalar type.
5814 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5815 // * binop, binop=, ++, and -- are not overloaded operators.
5816 // * The expression x binop expr must be numerically equivalent to x binop
5817 // (expr). This requirement is satisfied if the operators in expr have
5818 // precedence greater than binop, or by using parentheses around expr or
5819 // subexpressions of expr.
5820 // * The expression expr binop x must be numerically equivalent to (expr)
5821 // binop x. This requirement is satisfied if the operators in expr have
5822 // precedence equal to or greater than binop, or by using parentheses around
5823 // expr or subexpressions of expr.
5824 // * For forms that allow multiple occurrences of x, the number of times
5825 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00005826 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005827 enum {
5828 NotAnExpression,
5829 NotAnAssignmentOp,
5830 NotAScalarType,
5831 NotAnLValue,
5832 NoError
5833 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00005834 SourceLocation ErrorLoc, NoteLoc;
5835 SourceRange ErrorRange, NoteRange;
5836 // If clause is read:
5837 // v = x;
5838 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
5839 auto AtomicBinOp =
5840 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5841 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5842 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5843 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5844 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5845 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5846 if (!X->isLValue() || !V->isLValue()) {
5847 auto NotLValueExpr = X->isLValue() ? V : X;
5848 ErrorFound = NotAnLValue;
5849 ErrorLoc = AtomicBinOp->getExprLoc();
5850 ErrorRange = AtomicBinOp->getSourceRange();
5851 NoteLoc = NotLValueExpr->getExprLoc();
5852 NoteRange = NotLValueExpr->getSourceRange();
5853 }
5854 } else if (!X->isInstantiationDependent() ||
5855 !V->isInstantiationDependent()) {
5856 auto NotScalarExpr =
5857 (X->isInstantiationDependent() || X->getType()->isScalarType())
5858 ? V
5859 : X;
5860 ErrorFound = NotAScalarType;
5861 ErrorLoc = AtomicBinOp->getExprLoc();
5862 ErrorRange = AtomicBinOp->getSourceRange();
5863 NoteLoc = NotScalarExpr->getExprLoc();
5864 NoteRange = NotScalarExpr->getSourceRange();
5865 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005866 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00005867 ErrorFound = NotAnAssignmentOp;
5868 ErrorLoc = AtomicBody->getExprLoc();
5869 ErrorRange = AtomicBody->getSourceRange();
5870 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5871 : AtomicBody->getExprLoc();
5872 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5873 : AtomicBody->getSourceRange();
5874 }
5875 } else {
5876 ErrorFound = NotAnExpression;
5877 NoteLoc = ErrorLoc = Body->getLocStart();
5878 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005879 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005880 if (ErrorFound != NoError) {
5881 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5882 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005883 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5884 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00005885 return StmtError();
5886 } else if (CurContext->isDependentContext())
5887 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00005888 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005889 enum {
5890 NotAnExpression,
5891 NotAnAssignmentOp,
5892 NotAScalarType,
5893 NotAnLValue,
5894 NoError
5895 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005896 SourceLocation ErrorLoc, NoteLoc;
5897 SourceRange ErrorRange, NoteRange;
5898 // If clause is write:
5899 // x = expr;
5900 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
5901 auto AtomicBinOp =
5902 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5903 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00005904 X = AtomicBinOp->getLHS();
5905 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00005906 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5907 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5908 if (!X->isLValue()) {
5909 ErrorFound = NotAnLValue;
5910 ErrorLoc = AtomicBinOp->getExprLoc();
5911 ErrorRange = AtomicBinOp->getSourceRange();
5912 NoteLoc = X->getExprLoc();
5913 NoteRange = X->getSourceRange();
5914 }
5915 } else if (!X->isInstantiationDependent() ||
5916 !E->isInstantiationDependent()) {
5917 auto NotScalarExpr =
5918 (X->isInstantiationDependent() || X->getType()->isScalarType())
5919 ? E
5920 : X;
5921 ErrorFound = NotAScalarType;
5922 ErrorLoc = AtomicBinOp->getExprLoc();
5923 ErrorRange = AtomicBinOp->getSourceRange();
5924 NoteLoc = NotScalarExpr->getExprLoc();
5925 NoteRange = NotScalarExpr->getSourceRange();
5926 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005927 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00005928 ErrorFound = NotAnAssignmentOp;
5929 ErrorLoc = AtomicBody->getExprLoc();
5930 ErrorRange = AtomicBody->getSourceRange();
5931 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5932 : AtomicBody->getExprLoc();
5933 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5934 : AtomicBody->getSourceRange();
5935 }
5936 } else {
5937 ErrorFound = NotAnExpression;
5938 NoteLoc = ErrorLoc = Body->getLocStart();
5939 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005940 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00005941 if (ErrorFound != NoError) {
5942 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
5943 << ErrorRange;
5944 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5945 << NoteRange;
5946 return StmtError();
5947 } else if (CurContext->isDependentContext())
5948 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00005949 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005950 // If clause is update:
5951 // x++;
5952 // x--;
5953 // ++x;
5954 // --x;
5955 // x binop= expr;
5956 // x = x binop expr;
5957 // x = expr binop x;
5958 OpenMPAtomicUpdateChecker Checker(*this);
5959 if (Checker.checkStatement(
5960 Body, (AtomicKind == OMPC_update)
5961 ? diag::err_omp_atomic_update_not_expression_statement
5962 : diag::err_omp_atomic_not_expression_statement,
5963 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00005964 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005965 if (!CurContext->isDependentContext()) {
5966 E = Checker.getExpr();
5967 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005968 UE = Checker.getUpdateExpr();
5969 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00005970 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005971 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005972 enum {
5973 NotAnAssignmentOp,
5974 NotACompoundStatement,
5975 NotTwoSubstatements,
5976 NotASpecificExpression,
5977 NoError
5978 } ErrorFound = NoError;
5979 SourceLocation ErrorLoc, NoteLoc;
5980 SourceRange ErrorRange, NoteRange;
5981 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5982 // If clause is a capture:
5983 // v = x++;
5984 // v = x--;
5985 // v = ++x;
5986 // v = --x;
5987 // v = x binop= expr;
5988 // v = x = x binop expr;
5989 // v = x = expr binop x;
5990 auto *AtomicBinOp =
5991 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5992 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5993 V = AtomicBinOp->getLHS();
5994 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5995 OpenMPAtomicUpdateChecker Checker(*this);
5996 if (Checker.checkStatement(
5997 Body, diag::err_omp_atomic_capture_not_expression_statement,
5998 diag::note_omp_atomic_update))
5999 return StmtError();
6000 E = Checker.getExpr();
6001 X = Checker.getX();
6002 UE = Checker.getUpdateExpr();
6003 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6004 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00006005 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006006 ErrorLoc = AtomicBody->getExprLoc();
6007 ErrorRange = AtomicBody->getSourceRange();
6008 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6009 : AtomicBody->getExprLoc();
6010 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6011 : AtomicBody->getSourceRange();
6012 ErrorFound = NotAnAssignmentOp;
6013 }
6014 if (ErrorFound != NoError) {
6015 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
6016 << ErrorRange;
6017 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6018 return StmtError();
6019 } else if (CurContext->isDependentContext()) {
6020 UE = V = E = X = nullptr;
6021 }
6022 } else {
6023 // If clause is a capture:
6024 // { v = x; x = expr; }
6025 // { v = x; x++; }
6026 // { v = x; x--; }
6027 // { v = x; ++x; }
6028 // { v = x; --x; }
6029 // { v = x; x binop= expr; }
6030 // { v = x; x = x binop expr; }
6031 // { v = x; x = expr binop x; }
6032 // { x++; v = x; }
6033 // { x--; v = x; }
6034 // { ++x; v = x; }
6035 // { --x; v = x; }
6036 // { x binop= expr; v = x; }
6037 // { x = x binop expr; v = x; }
6038 // { x = expr binop x; v = x; }
6039 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
6040 // Check that this is { expr1; expr2; }
6041 if (CS->size() == 2) {
6042 auto *First = CS->body_front();
6043 auto *Second = CS->body_back();
6044 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
6045 First = EWC->getSubExpr()->IgnoreParenImpCasts();
6046 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
6047 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
6048 // Need to find what subexpression is 'v' and what is 'x'.
6049 OpenMPAtomicUpdateChecker Checker(*this);
6050 bool IsUpdateExprFound = !Checker.checkStatement(Second);
6051 BinaryOperator *BinOp = nullptr;
6052 if (IsUpdateExprFound) {
6053 BinOp = dyn_cast<BinaryOperator>(First);
6054 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6055 }
6056 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6057 // { v = x; x++; }
6058 // { v = x; x--; }
6059 // { v = x; ++x; }
6060 // { v = x; --x; }
6061 // { v = x; x binop= expr; }
6062 // { v = x; x = x binop expr; }
6063 // { v = x; x = expr binop x; }
6064 // Check that the first expression has form v = x.
6065 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6066 llvm::FoldingSetNodeID XId, PossibleXId;
6067 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6068 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6069 IsUpdateExprFound = XId == PossibleXId;
6070 if (IsUpdateExprFound) {
6071 V = BinOp->getLHS();
6072 X = Checker.getX();
6073 E = Checker.getExpr();
6074 UE = Checker.getUpdateExpr();
6075 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00006076 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006077 }
6078 }
6079 if (!IsUpdateExprFound) {
6080 IsUpdateExprFound = !Checker.checkStatement(First);
6081 BinOp = nullptr;
6082 if (IsUpdateExprFound) {
6083 BinOp = dyn_cast<BinaryOperator>(Second);
6084 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6085 }
6086 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6087 // { x++; v = x; }
6088 // { x--; v = x; }
6089 // { ++x; v = x; }
6090 // { --x; v = x; }
6091 // { x binop= expr; v = x; }
6092 // { x = x binop expr; v = x; }
6093 // { x = expr binop x; v = x; }
6094 // Check that the second expression has form v = x.
6095 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6096 llvm::FoldingSetNodeID XId, PossibleXId;
6097 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6098 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6099 IsUpdateExprFound = XId == PossibleXId;
6100 if (IsUpdateExprFound) {
6101 V = BinOp->getLHS();
6102 X = Checker.getX();
6103 E = Checker.getExpr();
6104 UE = Checker.getUpdateExpr();
6105 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00006106 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006107 }
6108 }
6109 }
6110 if (!IsUpdateExprFound) {
6111 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00006112 auto *FirstExpr = dyn_cast<Expr>(First);
6113 auto *SecondExpr = dyn_cast<Expr>(Second);
6114 if (!FirstExpr || !SecondExpr ||
6115 !(FirstExpr->isInstantiationDependent() ||
6116 SecondExpr->isInstantiationDependent())) {
6117 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
6118 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006119 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00006120 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
6121 : First->getLocStart();
6122 NoteRange = ErrorRange = FirstBinOp
6123 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00006124 : SourceRange(ErrorLoc, ErrorLoc);
6125 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00006126 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
6127 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
6128 ErrorFound = NotAnAssignmentOp;
6129 NoteLoc = ErrorLoc = SecondBinOp
6130 ? SecondBinOp->getOperatorLoc()
6131 : Second->getLocStart();
6132 NoteRange = ErrorRange =
6133 SecondBinOp ? SecondBinOp->getSourceRange()
6134 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00006135 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00006136 auto *PossibleXRHSInFirst =
6137 FirstBinOp->getRHS()->IgnoreParenImpCasts();
6138 auto *PossibleXLHSInSecond =
6139 SecondBinOp->getLHS()->IgnoreParenImpCasts();
6140 llvm::FoldingSetNodeID X1Id, X2Id;
6141 PossibleXRHSInFirst->Profile(X1Id, Context,
6142 /*Canonical=*/true);
6143 PossibleXLHSInSecond->Profile(X2Id, Context,
6144 /*Canonical=*/true);
6145 IsUpdateExprFound = X1Id == X2Id;
6146 if (IsUpdateExprFound) {
6147 V = FirstBinOp->getLHS();
6148 X = SecondBinOp->getLHS();
6149 E = SecondBinOp->getRHS();
6150 UE = nullptr;
6151 IsXLHSInRHSPart = false;
6152 IsPostfixUpdate = true;
6153 } else {
6154 ErrorFound = NotASpecificExpression;
6155 ErrorLoc = FirstBinOp->getExprLoc();
6156 ErrorRange = FirstBinOp->getSourceRange();
6157 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
6158 NoteRange = SecondBinOp->getRHS()->getSourceRange();
6159 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006160 }
6161 }
6162 }
6163 }
6164 } else {
6165 NoteLoc = ErrorLoc = Body->getLocStart();
6166 NoteRange = ErrorRange =
6167 SourceRange(Body->getLocStart(), Body->getLocStart());
6168 ErrorFound = NotTwoSubstatements;
6169 }
6170 } else {
6171 NoteLoc = ErrorLoc = Body->getLocStart();
6172 NoteRange = ErrorRange =
6173 SourceRange(Body->getLocStart(), Body->getLocStart());
6174 ErrorFound = NotACompoundStatement;
6175 }
6176 if (ErrorFound != NoError) {
6177 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
6178 << ErrorRange;
6179 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6180 return StmtError();
6181 } else if (CurContext->isDependentContext()) {
6182 UE = V = E = X = nullptr;
6183 }
Alexey Bataev459dec02014-07-24 06:46:57 +00006184 }
Alexey Bataevdea47612014-07-23 07:46:59 +00006185 }
Alexey Bataev0162e452014-07-22 10:10:35 +00006186
6187 getCurFunction()->setHasBranchProtectedScope();
6188
Alexey Bataev62cec442014-11-18 10:14:22 +00006189 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00006190 X, V, E, UE, IsXLHSInRHSPart,
6191 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00006192}
6193
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006194StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
6195 Stmt *AStmt,
6196 SourceLocation StartLoc,
6197 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006198 if (!AStmt)
6199 return StmtError();
6200
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006201 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6202 // 1.2.2 OpenMP Language Terminology
6203 // Structured block - An executable statement with a single entry at the
6204 // top and a single exit at the bottom.
6205 // The point of exit cannot be a branch out of the structured block.
6206 // longjmp() and throw() must not violate the entry/exit criteria.
6207 CS->getCapturedDecl()->setNothrow();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006208
Alexey Bataev13314bf2014-10-09 04:18:56 +00006209 // OpenMP [2.16, Nesting of Regions]
6210 // If specified, a teams construct must be contained within a target
6211 // construct. That target construct must contain no statements or directives
6212 // outside of the teams construct.
6213 if (DSAStack->hasInnerTeamsRegion()) {
6214 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
6215 bool OMPTeamsFound = true;
6216 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
6217 auto I = CS->body_begin();
6218 while (I != CS->body_end()) {
6219 auto OED = dyn_cast<OMPExecutableDirective>(*I);
6220 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
6221 OMPTeamsFound = false;
6222 break;
6223 }
6224 ++I;
6225 }
6226 assert(I != CS->body_end() && "Not found statement");
6227 S = *I;
6228 }
6229 if (!OMPTeamsFound) {
6230 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
6231 Diag(DSAStack->getInnerTeamsRegionLoc(),
6232 diag::note_omp_nested_teams_construct_here);
6233 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
6234 << isa<OMPExecutableDirective>(S);
6235 return StmtError();
6236 }
6237 }
6238
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006239 getCurFunction()->setHasBranchProtectedScope();
6240
6241 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6242}
6243
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00006244StmtResult
6245Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
6246 Stmt *AStmt, SourceLocation StartLoc,
6247 SourceLocation EndLoc) {
6248 if (!AStmt)
6249 return StmtError();
6250
6251 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6252 // 1.2.2 OpenMP Language Terminology
6253 // Structured block - An executable statement with a single entry at the
6254 // top and a single exit at the bottom.
6255 // The point of exit cannot be a branch out of the structured block.
6256 // longjmp() and throw() must not violate the entry/exit criteria.
6257 CS->getCapturedDecl()->setNothrow();
6258
6259 getCurFunction()->setHasBranchProtectedScope();
6260
6261 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6262 AStmt);
6263}
6264
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006265StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
6266 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6267 SourceLocation EndLoc,
6268 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6269 if (!AStmt)
6270 return StmtError();
6271
6272 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6273 // 1.2.2 OpenMP Language Terminology
6274 // Structured block - An executable statement with a single entry at the
6275 // top and a single exit at the bottom.
6276 // The point of exit cannot be a branch out of the structured block.
6277 // longjmp() and throw() must not violate the entry/exit criteria.
6278 CS->getCapturedDecl()->setNothrow();
6279
6280 OMPLoopDirective::HelperExprs B;
6281 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6282 // define the nested loops number.
6283 unsigned NestedLoopCount =
6284 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
6285 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6286 VarsWithImplicitDSA, B);
6287 if (NestedLoopCount == 0)
6288 return StmtError();
6289
6290 assert((CurContext->isDependentContext() || B.builtAll()) &&
6291 "omp target parallel for loop exprs were not built");
6292
6293 if (!CurContext->isDependentContext()) {
6294 // Finalize the clauses that need pre-built expressions for CodeGen.
6295 for (auto C : Clauses) {
6296 if (auto LC = dyn_cast<OMPLinearClause>(C))
6297 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006298 B.NumIterations, *this, CurScope,
6299 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006300 return StmtError();
6301 }
6302 }
6303
6304 getCurFunction()->setHasBranchProtectedScope();
6305 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
6306 NestedLoopCount, Clauses, AStmt,
6307 B, DSAStack->isCancelRegion());
6308}
6309
Samuel Antaodf67fc42016-01-19 19:15:56 +00006310/// \brief Check for existence of a map clause in the list of clauses.
6311static bool HasMapClause(ArrayRef<OMPClause *> Clauses) {
6312 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
6313 I != E; ++I) {
6314 if (*I != nullptr && (*I)->getClauseKind() == OMPC_map) {
6315 return true;
6316 }
6317 }
6318
6319 return false;
6320}
6321
Michael Wong65f367f2015-07-21 13:44:28 +00006322StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
6323 Stmt *AStmt,
6324 SourceLocation StartLoc,
6325 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006326 if (!AStmt)
6327 return StmtError();
6328
6329 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6330
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00006331 // OpenMP [2.10.1, Restrictions, p. 97]
6332 // At least one map clause must appear on the directive.
6333 if (!HasMapClause(Clauses)) {
6334 Diag(StartLoc, diag::err_omp_no_map_for_directive) <<
6335 getOpenMPDirectiveName(OMPD_target_data);
6336 return StmtError();
6337 }
6338
Michael Wong65f367f2015-07-21 13:44:28 +00006339 getCurFunction()->setHasBranchProtectedScope();
6340
6341 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6342 AStmt);
6343}
6344
Samuel Antaodf67fc42016-01-19 19:15:56 +00006345StmtResult
6346Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
6347 SourceLocation StartLoc,
6348 SourceLocation EndLoc) {
6349 // OpenMP [2.10.2, Restrictions, p. 99]
6350 // At least one map clause must appear on the directive.
6351 if (!HasMapClause(Clauses)) {
6352 Diag(StartLoc, diag::err_omp_no_map_for_directive)
6353 << getOpenMPDirectiveName(OMPD_target_enter_data);
6354 return StmtError();
6355 }
6356
6357 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
6358 Clauses);
6359}
6360
Samuel Antao72590762016-01-19 20:04:50 +00006361StmtResult
6362Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
6363 SourceLocation StartLoc,
6364 SourceLocation EndLoc) {
6365 // OpenMP [2.10.3, Restrictions, p. 102]
6366 // At least one map clause must appear on the directive.
6367 if (!HasMapClause(Clauses)) {
6368 Diag(StartLoc, diag::err_omp_no_map_for_directive)
6369 << getOpenMPDirectiveName(OMPD_target_exit_data);
6370 return StmtError();
6371 }
6372
6373 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
6374}
6375
Alexey Bataev13314bf2014-10-09 04:18:56 +00006376StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
6377 Stmt *AStmt, SourceLocation StartLoc,
6378 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006379 if (!AStmt)
6380 return StmtError();
6381
Alexey Bataev13314bf2014-10-09 04:18:56 +00006382 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6383 // 1.2.2 OpenMP Language Terminology
6384 // Structured block - An executable statement with a single entry at the
6385 // top and a single exit at the bottom.
6386 // The point of exit cannot be a branch out of the structured block.
6387 // longjmp() and throw() must not violate the entry/exit criteria.
6388 CS->getCapturedDecl()->setNothrow();
6389
6390 getCurFunction()->setHasBranchProtectedScope();
6391
6392 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6393}
6394
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006395StmtResult
6396Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
6397 SourceLocation EndLoc,
6398 OpenMPDirectiveKind CancelRegion) {
6399 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
6400 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
6401 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
6402 << getOpenMPDirectiveName(CancelRegion);
6403 return StmtError();
6404 }
6405 if (DSAStack->isParentNowaitRegion()) {
6406 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
6407 return StmtError();
6408 }
6409 if (DSAStack->isParentOrderedRegion()) {
6410 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
6411 return StmtError();
6412 }
6413 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
6414 CancelRegion);
6415}
6416
Alexey Bataev87933c72015-09-18 08:07:34 +00006417StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
6418 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00006419 SourceLocation EndLoc,
6420 OpenMPDirectiveKind CancelRegion) {
6421 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
6422 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
6423 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
6424 << getOpenMPDirectiveName(CancelRegion);
6425 return StmtError();
6426 }
6427 if (DSAStack->isParentNowaitRegion()) {
6428 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
6429 return StmtError();
6430 }
6431 if (DSAStack->isParentOrderedRegion()) {
6432 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
6433 return StmtError();
6434 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006435 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00006436 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6437 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00006438}
6439
Alexey Bataev382967a2015-12-08 12:06:20 +00006440static bool checkGrainsizeNumTasksClauses(Sema &S,
6441 ArrayRef<OMPClause *> Clauses) {
6442 OMPClause *PrevClause = nullptr;
6443 bool ErrorFound = false;
6444 for (auto *C : Clauses) {
6445 if (C->getClauseKind() == OMPC_grainsize ||
6446 C->getClauseKind() == OMPC_num_tasks) {
6447 if (!PrevClause)
6448 PrevClause = C;
6449 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
6450 S.Diag(C->getLocStart(),
6451 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
6452 << getOpenMPClauseName(C->getClauseKind())
6453 << getOpenMPClauseName(PrevClause->getClauseKind());
6454 S.Diag(PrevClause->getLocStart(),
6455 diag::note_omp_previous_grainsize_num_tasks)
6456 << getOpenMPClauseName(PrevClause->getClauseKind());
6457 ErrorFound = true;
6458 }
6459 }
6460 }
6461 return ErrorFound;
6462}
6463
Alexey Bataev49f6e782015-12-01 04:18:41 +00006464StmtResult Sema::ActOnOpenMPTaskLoopDirective(
6465 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6466 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006467 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00006468 if (!AStmt)
6469 return StmtError();
6470
6471 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6472 OMPLoopDirective::HelperExprs B;
6473 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6474 // define the nested loops number.
6475 unsigned NestedLoopCount =
6476 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006477 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00006478 VarsWithImplicitDSA, B);
6479 if (NestedLoopCount == 0)
6480 return StmtError();
6481
6482 assert((CurContext->isDependentContext() || B.builtAll()) &&
6483 "omp for loop exprs were not built");
6484
Alexey Bataev382967a2015-12-08 12:06:20 +00006485 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6486 // The grainsize clause and num_tasks clause are mutually exclusive and may
6487 // not appear on the same taskloop directive.
6488 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6489 return StmtError();
6490
Alexey Bataev49f6e782015-12-01 04:18:41 +00006491 getCurFunction()->setHasBranchProtectedScope();
6492 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
6493 NestedLoopCount, Clauses, AStmt, B);
6494}
6495
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006496StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
6497 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6498 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006499 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006500 if (!AStmt)
6501 return StmtError();
6502
6503 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6504 OMPLoopDirective::HelperExprs B;
6505 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6506 // define the nested loops number.
6507 unsigned NestedLoopCount =
6508 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
6509 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6510 VarsWithImplicitDSA, B);
6511 if (NestedLoopCount == 0)
6512 return StmtError();
6513
6514 assert((CurContext->isDependentContext() || B.builtAll()) &&
6515 "omp for loop exprs were not built");
6516
Alexey Bataev5a3af132016-03-29 08:58:54 +00006517 if (!CurContext->isDependentContext()) {
6518 // Finalize the clauses that need pre-built expressions for CodeGen.
6519 for (auto C : Clauses) {
6520 if (auto LC = dyn_cast<OMPLinearClause>(C))
6521 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006522 B.NumIterations, *this, CurScope,
6523 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006524 return StmtError();
6525 }
6526 }
6527
Alexey Bataev382967a2015-12-08 12:06:20 +00006528 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6529 // The grainsize clause and num_tasks clause are mutually exclusive and may
6530 // not appear on the same taskloop directive.
6531 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6532 return StmtError();
6533
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006534 getCurFunction()->setHasBranchProtectedScope();
6535 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
6536 NestedLoopCount, Clauses, AStmt, B);
6537}
6538
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006539StmtResult Sema::ActOnOpenMPDistributeDirective(
6540 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6541 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006542 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006543 if (!AStmt)
6544 return StmtError();
6545
6546 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6547 OMPLoopDirective::HelperExprs B;
6548 // In presence of clause 'collapse' with number of loops, it will
6549 // define the nested loops number.
6550 unsigned NestedLoopCount =
6551 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
6552 nullptr /*ordered not a clause on distribute*/, AStmt,
6553 *this, *DSAStack, VarsWithImplicitDSA, B);
6554 if (NestedLoopCount == 0)
6555 return StmtError();
6556
6557 assert((CurContext->isDependentContext() || B.builtAll()) &&
6558 "omp for loop exprs were not built");
6559
6560 getCurFunction()->setHasBranchProtectedScope();
6561 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
6562 NestedLoopCount, Clauses, AStmt, B);
6563}
6564
Alexey Bataeved09d242014-05-28 05:53:51 +00006565OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006566 SourceLocation StartLoc,
6567 SourceLocation LParenLoc,
6568 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006569 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006570 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00006571 case OMPC_final:
6572 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
6573 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00006574 case OMPC_num_threads:
6575 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
6576 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006577 case OMPC_safelen:
6578 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
6579 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00006580 case OMPC_simdlen:
6581 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
6582 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00006583 case OMPC_collapse:
6584 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
6585 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006586 case OMPC_ordered:
6587 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
6588 break;
Michael Wonge710d542015-08-07 16:16:36 +00006589 case OMPC_device:
6590 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
6591 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00006592 case OMPC_num_teams:
6593 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
6594 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006595 case OMPC_thread_limit:
6596 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
6597 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00006598 case OMPC_priority:
6599 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
6600 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006601 case OMPC_grainsize:
6602 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
6603 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00006604 case OMPC_num_tasks:
6605 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
6606 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00006607 case OMPC_hint:
6608 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
6609 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006610 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006611 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006612 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006613 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006614 case OMPC_private:
6615 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00006616 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006617 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00006618 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00006619 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006620 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006621 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006622 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00006623 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006624 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006625 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006626 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006627 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006628 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006629 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006630 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006631 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006632 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006633 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00006634 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006635 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006636 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00006637 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00006638 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006639 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006640 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006641 case OMPC_uniform:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006642 llvm_unreachable("Clause is not allowed.");
6643 }
6644 return Res;
6645}
6646
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006647OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
6648 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006649 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006650 SourceLocation NameModifierLoc,
6651 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006652 SourceLocation EndLoc) {
6653 Expr *ValExpr = Condition;
6654 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6655 !Condition->isInstantiationDependent() &&
6656 !Condition->containsUnexpandedParameterPack()) {
6657 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
Alexey Bataeved09d242014-05-28 05:53:51 +00006658 Condition->getExprLoc(), Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006659 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006660 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006661
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006662 ValExpr = Val.get();
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006663 }
6664
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006665 return new (Context) OMPIfClause(NameModifier, ValExpr, StartLoc, LParenLoc,
6666 NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006667}
6668
Alexey Bataev3778b602014-07-17 07:32:53 +00006669OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
6670 SourceLocation StartLoc,
6671 SourceLocation LParenLoc,
6672 SourceLocation EndLoc) {
6673 Expr *ValExpr = Condition;
6674 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6675 !Condition->isInstantiationDependent() &&
6676 !Condition->containsUnexpandedParameterPack()) {
6677 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
6678 Condition->getExprLoc(), Condition);
6679 if (Val.isInvalid())
6680 return nullptr;
6681
6682 ValExpr = Val.get();
6683 }
6684
6685 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
6686}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006687ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
6688 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00006689 if (!Op)
6690 return ExprError();
6691
6692 class IntConvertDiagnoser : public ICEConvertDiagnoser {
6693 public:
6694 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00006695 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00006696 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
6697 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006698 return S.Diag(Loc, diag::err_omp_not_integral) << T;
6699 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006700 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
6701 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006702 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
6703 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006704 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
6705 QualType T,
6706 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006707 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
6708 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006709 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
6710 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006711 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00006712 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00006713 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006714 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
6715 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006716 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
6717 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006718 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
6719 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006720 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00006721 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00006722 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006723 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
6724 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006725 llvm_unreachable("conversion functions are permitted");
6726 }
6727 } ConvertDiagnoser;
6728 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
6729}
6730
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006731static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00006732 OpenMPClauseKind CKind,
6733 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006734 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
6735 !ValExpr->isInstantiationDependent()) {
6736 SourceLocation Loc = ValExpr->getExprLoc();
6737 ExprResult Value =
6738 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
6739 if (Value.isInvalid())
6740 return false;
6741
6742 ValExpr = Value.get();
6743 // The expression must evaluate to a non-negative integer value.
6744 llvm::APSInt Result;
6745 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00006746 Result.isSigned() &&
6747 !((!StrictlyPositive && Result.isNonNegative()) ||
6748 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006749 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00006750 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
6751 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006752 return false;
6753 }
6754 }
6755 return true;
6756}
6757
Alexey Bataev568a8332014-03-06 06:15:19 +00006758OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
6759 SourceLocation StartLoc,
6760 SourceLocation LParenLoc,
6761 SourceLocation EndLoc) {
6762 Expr *ValExpr = NumThreads;
Alexey Bataev568a8332014-03-06 06:15:19 +00006763
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006764 // OpenMP [2.5, Restrictions]
6765 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00006766 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
6767 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006768 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00006769
Alexey Bataeved09d242014-05-28 05:53:51 +00006770 return new (Context)
6771 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00006772}
6773
Alexey Bataev62c87d22014-03-21 04:51:18 +00006774ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006775 OpenMPClauseKind CKind,
6776 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00006777 if (!E)
6778 return ExprError();
6779 if (E->isValueDependent() || E->isTypeDependent() ||
6780 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006781 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006782 llvm::APSInt Result;
6783 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
6784 if (ICE.isInvalid())
6785 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006786 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
6787 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00006788 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006789 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
6790 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00006791 return ExprError();
6792 }
Alexander Musman09184fe2014-09-30 05:29:28 +00006793 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
6794 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
6795 << E->getSourceRange();
6796 return ExprError();
6797 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006798 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
6799 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00006800 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006801 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00006802 return ICE;
6803}
6804
6805OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
6806 SourceLocation LParenLoc,
6807 SourceLocation EndLoc) {
6808 // OpenMP [2.8.1, simd construct, Description]
6809 // The parameter of the safelen clause must be a constant
6810 // positive integer expression.
6811 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
6812 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006813 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006814 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006815 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00006816}
6817
Alexey Bataev66b15b52015-08-21 11:14:16 +00006818OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
6819 SourceLocation LParenLoc,
6820 SourceLocation EndLoc) {
6821 // OpenMP [2.8.1, simd construct, Description]
6822 // The parameter of the simdlen clause must be a constant
6823 // positive integer expression.
6824 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
6825 if (Simdlen.isInvalid())
6826 return nullptr;
6827 return new (Context)
6828 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
6829}
6830
Alexander Musman64d33f12014-06-04 07:53:32 +00006831OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
6832 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00006833 SourceLocation LParenLoc,
6834 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00006835 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00006836 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00006837 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00006838 // The parameter of the collapse clause must be a constant
6839 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00006840 ExprResult NumForLoopsResult =
6841 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
6842 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00006843 return nullptr;
6844 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00006845 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00006846}
6847
Alexey Bataev10e775f2015-07-30 11:36:16 +00006848OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
6849 SourceLocation EndLoc,
6850 SourceLocation LParenLoc,
6851 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00006852 // OpenMP [2.7.1, loop construct, Description]
6853 // OpenMP [2.8.1, simd construct, Description]
6854 // OpenMP [2.9.6, distribute construct, Description]
6855 // The parameter of the ordered clause must be a constant
6856 // positive integer expression if any.
6857 if (NumForLoops && LParenLoc.isValid()) {
6858 ExprResult NumForLoopsResult =
6859 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
6860 if (NumForLoopsResult.isInvalid())
6861 return nullptr;
6862 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00006863 } else
6864 NumForLoops = nullptr;
6865 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00006866 return new (Context)
6867 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
6868}
6869
Alexey Bataeved09d242014-05-28 05:53:51 +00006870OMPClause *Sema::ActOnOpenMPSimpleClause(
6871 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
6872 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006873 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006874 switch (Kind) {
6875 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00006876 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00006877 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
6878 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006879 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006880 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00006881 Res = ActOnOpenMPProcBindClause(
6882 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
6883 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006884 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006885 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00006886 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00006887 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00006888 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00006889 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00006890 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006891 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006892 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006893 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00006894 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00006895 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00006896 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00006897 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006898 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006899 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006900 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006901 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00006902 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006903 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006904 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006905 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006906 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006907 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006908 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006909 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006910 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006911 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006912 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00006913 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00006914 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006915 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006916 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00006917 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006918 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00006919 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006920 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00006921 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00006922 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00006923 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00006924 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006925 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006926 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006927 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006928 llvm_unreachable("Clause is not allowed.");
6929 }
6930 return Res;
6931}
6932
Alexey Bataev6402bca2015-12-28 07:25:51 +00006933static std::string
6934getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
6935 ArrayRef<unsigned> Exclude = llvm::None) {
6936 std::string Values;
6937 unsigned Bound = Last >= 2 ? Last - 2 : 0;
6938 unsigned Skipped = Exclude.size();
6939 auto S = Exclude.begin(), E = Exclude.end();
6940 for (unsigned i = First; i < Last; ++i) {
6941 if (std::find(S, E, i) != E) {
6942 --Skipped;
6943 continue;
6944 }
6945 Values += "'";
6946 Values += getOpenMPSimpleClauseTypeName(K, i);
6947 Values += "'";
6948 if (i == Bound - Skipped)
6949 Values += " or ";
6950 else if (i != Bound + 1 - Skipped)
6951 Values += ", ";
6952 }
6953 return Values;
6954}
6955
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006956OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
6957 SourceLocation KindKwLoc,
6958 SourceLocation StartLoc,
6959 SourceLocation LParenLoc,
6960 SourceLocation EndLoc) {
6961 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00006962 static_assert(OMPC_DEFAULT_unknown > 0,
6963 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006964 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00006965 << getListOfPossibleValues(OMPC_default, /*First=*/0,
6966 /*Last=*/OMPC_DEFAULT_unknown)
6967 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006968 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006969 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00006970 switch (Kind) {
6971 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006972 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00006973 break;
6974 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006975 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00006976 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006977 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006978 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00006979 break;
6980 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006981 return new (Context)
6982 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006983}
6984
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006985OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
6986 SourceLocation KindKwLoc,
6987 SourceLocation StartLoc,
6988 SourceLocation LParenLoc,
6989 SourceLocation EndLoc) {
6990 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006991 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00006992 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
6993 /*Last=*/OMPC_PROC_BIND_unknown)
6994 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006995 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006996 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006997 return new (Context)
6998 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006999}
7000
Alexey Bataev56dafe82014-06-20 07:16:17 +00007001OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007002 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007003 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00007004 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007005 SourceLocation EndLoc) {
7006 OMPClause *Res = nullptr;
7007 switch (Kind) {
7008 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00007009 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
7010 assert(Argument.size() == NumberOfElements &&
7011 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007012 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007013 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
7014 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
7015 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
7016 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
7017 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007018 break;
7019 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00007020 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
7021 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
7022 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
7023 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007024 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00007025 case OMPC_dist_schedule:
7026 Res = ActOnOpenMPDistScheduleClause(
7027 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
7028 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
7029 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007030 case OMPC_defaultmap:
7031 enum { Modifier, DefaultmapKind };
7032 Res = ActOnOpenMPDefaultmapClause(
7033 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
7034 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
7035 StartLoc, LParenLoc, ArgumentLoc[Modifier],
7036 ArgumentLoc[DefaultmapKind], EndLoc);
7037 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00007038 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007039 case OMPC_num_threads:
7040 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007041 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007042 case OMPC_collapse:
7043 case OMPC_default:
7044 case OMPC_proc_bind:
7045 case OMPC_private:
7046 case OMPC_firstprivate:
7047 case OMPC_lastprivate:
7048 case OMPC_shared:
7049 case OMPC_reduction:
7050 case OMPC_linear:
7051 case OMPC_aligned:
7052 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007053 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007054 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007055 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007056 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007057 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007058 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007059 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007060 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007061 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007062 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007063 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007064 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007065 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007066 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007067 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007068 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007069 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007070 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007071 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007072 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007073 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007074 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007075 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007076 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007077 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007078 case OMPC_uniform:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007079 llvm_unreachable("Clause is not allowed.");
7080 }
7081 return Res;
7082}
7083
Alexey Bataev6402bca2015-12-28 07:25:51 +00007084static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
7085 OpenMPScheduleClauseModifier M2,
7086 SourceLocation M1Loc, SourceLocation M2Loc) {
7087 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
7088 SmallVector<unsigned, 2> Excluded;
7089 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
7090 Excluded.push_back(M2);
7091 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
7092 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
7093 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
7094 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
7095 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
7096 << getListOfPossibleValues(OMPC_schedule,
7097 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
7098 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7099 Excluded)
7100 << getOpenMPClauseName(OMPC_schedule);
7101 return true;
7102 }
7103 return false;
7104}
7105
Alexey Bataev56dafe82014-06-20 07:16:17 +00007106OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007107 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007108 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00007109 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
7110 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
7111 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
7112 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
7113 return nullptr;
7114 // OpenMP, 2.7.1, Loop Construct, Restrictions
7115 // Either the monotonic modifier or the nonmonotonic modifier can be specified
7116 // but not both.
7117 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
7118 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
7119 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
7120 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
7121 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
7122 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
7123 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
7124 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
7125 return nullptr;
7126 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00007127 if (Kind == OMPC_SCHEDULE_unknown) {
7128 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00007129 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
7130 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
7131 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7132 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7133 Exclude);
7134 } else {
7135 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7136 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007137 }
7138 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
7139 << Values << getOpenMPClauseName(OMPC_schedule);
7140 return nullptr;
7141 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00007142 // OpenMP, 2.7.1, Loop Construct, Restrictions
7143 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
7144 // schedule(guided).
7145 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
7146 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
7147 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
7148 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
7149 diag::err_omp_schedule_nonmonotonic_static);
7150 return nullptr;
7151 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00007152 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00007153 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00007154 if (ChunkSize) {
7155 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
7156 !ChunkSize->isInstantiationDependent() &&
7157 !ChunkSize->containsUnexpandedParameterPack()) {
7158 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
7159 ExprResult Val =
7160 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
7161 if (Val.isInvalid())
7162 return nullptr;
7163
7164 ValExpr = Val.get();
7165
7166 // OpenMP [2.7.1, Restrictions]
7167 // chunk_size must be a loop invariant integer expression with a positive
7168 // value.
7169 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00007170 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
7171 if (Result.isSigned() && !Result.isStrictlyPositive()) {
7172 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00007173 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00007174 return nullptr;
7175 }
7176 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007177 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7178 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7179 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007180 }
7181 }
7182 }
7183
Alexey Bataev6402bca2015-12-28 07:25:51 +00007184 return new (Context)
7185 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00007186 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007187}
7188
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007189OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
7190 SourceLocation StartLoc,
7191 SourceLocation EndLoc) {
7192 OMPClause *Res = nullptr;
7193 switch (Kind) {
7194 case OMPC_ordered:
7195 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
7196 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00007197 case OMPC_nowait:
7198 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
7199 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007200 case OMPC_untied:
7201 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
7202 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007203 case OMPC_mergeable:
7204 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
7205 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007206 case OMPC_read:
7207 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
7208 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00007209 case OMPC_write:
7210 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
7211 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00007212 case OMPC_update:
7213 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
7214 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00007215 case OMPC_capture:
7216 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
7217 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007218 case OMPC_seq_cst:
7219 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
7220 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00007221 case OMPC_threads:
7222 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
7223 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007224 case OMPC_simd:
7225 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
7226 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00007227 case OMPC_nogroup:
7228 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
7229 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007230 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007231 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007232 case OMPC_num_threads:
7233 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007234 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007235 case OMPC_collapse:
7236 case OMPC_schedule:
7237 case OMPC_private:
7238 case OMPC_firstprivate:
7239 case OMPC_lastprivate:
7240 case OMPC_shared:
7241 case OMPC_reduction:
7242 case OMPC_linear:
7243 case OMPC_aligned:
7244 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007245 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007246 case OMPC_default:
7247 case OMPC_proc_bind:
7248 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007249 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007250 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007251 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007252 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007253 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007254 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007255 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007256 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00007257 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007258 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007259 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007260 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007261 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007262 case OMPC_uniform:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007263 llvm_unreachable("Clause is not allowed.");
7264 }
7265 return Res;
7266}
7267
Alexey Bataev236070f2014-06-20 11:19:47 +00007268OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
7269 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007270 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00007271 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
7272}
7273
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007274OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
7275 SourceLocation EndLoc) {
7276 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
7277}
7278
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007279OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
7280 SourceLocation EndLoc) {
7281 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
7282}
7283
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007284OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
7285 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007286 return new (Context) OMPReadClause(StartLoc, EndLoc);
7287}
7288
Alexey Bataevdea47612014-07-23 07:46:59 +00007289OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
7290 SourceLocation EndLoc) {
7291 return new (Context) OMPWriteClause(StartLoc, EndLoc);
7292}
7293
Alexey Bataev67a4f222014-07-23 10:25:33 +00007294OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
7295 SourceLocation EndLoc) {
7296 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
7297}
7298
Alexey Bataev459dec02014-07-24 06:46:57 +00007299OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
7300 SourceLocation EndLoc) {
7301 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
7302}
7303
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007304OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
7305 SourceLocation EndLoc) {
7306 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
7307}
7308
Alexey Bataev346265e2015-09-25 10:37:12 +00007309OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
7310 SourceLocation EndLoc) {
7311 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
7312}
7313
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007314OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
7315 SourceLocation EndLoc) {
7316 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
7317}
7318
Alexey Bataevb825de12015-12-07 10:51:44 +00007319OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
7320 SourceLocation EndLoc) {
7321 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
7322}
7323
Alexey Bataevc5e02582014-06-16 07:08:35 +00007324OMPClause *Sema::ActOnOpenMPVarListClause(
7325 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
7326 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
7327 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007328 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00007329 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
7330 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
7331 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007332 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007333 switch (Kind) {
7334 case OMPC_private:
7335 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7336 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007337 case OMPC_firstprivate:
7338 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7339 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007340 case OMPC_lastprivate:
7341 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7342 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00007343 case OMPC_shared:
7344 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
7345 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00007346 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00007347 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
7348 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00007349 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00007350 case OMPC_linear:
7351 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00007352 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00007353 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007354 case OMPC_aligned:
7355 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
7356 ColonLoc, EndLoc);
7357 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007358 case OMPC_copyin:
7359 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
7360 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00007361 case OMPC_copyprivate:
7362 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7363 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00007364 case OMPC_flush:
7365 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
7366 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007367 case OMPC_depend:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007368 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
7369 StartLoc, LParenLoc, EndLoc);
7370 break;
7371 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00007372 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
7373 DepLinMapLoc, ColonLoc, VarList, StartLoc,
7374 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007375 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007376 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007377 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00007378 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00007379 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007380 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00007381 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007382 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007383 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007384 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007385 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007386 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007387 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007388 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007389 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007390 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007391 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007392 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007393 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007394 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00007395 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007396 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007397 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007398 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007399 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007400 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007401 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007402 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007403 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007404 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007405 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007406 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007407 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007408 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007409 llvm_unreachable("Clause is not allowed.");
7410 }
7411 return Res;
7412}
7413
Alexey Bataev90c228f2016-02-08 09:29:13 +00007414ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00007415 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00007416 ExprResult Res = BuildDeclRefExpr(
7417 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
7418 if (!Res.isUsable())
7419 return ExprError();
7420 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
7421 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
7422 if (!Res.isUsable())
7423 return ExprError();
7424 }
7425 if (VK != VK_LValue && Res.get()->isGLValue()) {
7426 Res = DefaultLvalueConversion(Res.get());
7427 if (!Res.isUsable())
7428 return ExprError();
7429 }
7430 return Res;
7431}
7432
Alexey Bataev60da77e2016-02-29 05:54:20 +00007433static std::pair<ValueDecl *, bool>
7434getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
7435 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007436 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
7437 RefExpr->containsUnexpandedParameterPack())
7438 return std::make_pair(nullptr, true);
7439
Alexey Bataevd985eda2016-02-10 11:29:16 +00007440 // OpenMP [3.1, C/C++]
7441 // A list item is a variable name.
7442 // OpenMP [2.9.3.3, Restrictions, p.1]
7443 // A variable that is part of another variable (as an array or
7444 // structure element) cannot appear in a private clause.
7445 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00007446 enum {
7447 NoArrayExpr = -1,
7448 ArraySubscript = 0,
7449 OMPArraySection = 1
7450 } IsArrayExpr = NoArrayExpr;
7451 if (AllowArraySection) {
7452 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
7453 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
7454 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7455 Base = TempASE->getBase()->IgnoreParenImpCasts();
7456 RefExpr = Base;
7457 IsArrayExpr = ArraySubscript;
7458 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
7459 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
7460 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
7461 Base = TempOASE->getBase()->IgnoreParenImpCasts();
7462 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7463 Base = TempASE->getBase()->IgnoreParenImpCasts();
7464 RefExpr = Base;
7465 IsArrayExpr = OMPArraySection;
7466 }
7467 }
7468 ELoc = RefExpr->getExprLoc();
7469 ERange = RefExpr->getSourceRange();
7470 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00007471 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
7472 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
7473 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
7474 (S.getCurrentThisType().isNull() || !ME ||
7475 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
7476 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00007477 if (IsArrayExpr != NoArrayExpr)
7478 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
7479 << ERange;
7480 else {
7481 S.Diag(ELoc,
7482 AllowArraySection
7483 ? diag::err_omp_expected_var_name_member_expr_or_array_item
7484 : diag::err_omp_expected_var_name_member_expr)
7485 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
7486 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007487 return std::make_pair(nullptr, false);
7488 }
7489 return std::make_pair(DE ? DE->getDecl() : ME->getMemberDecl(), false);
7490}
7491
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007492OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
7493 SourceLocation StartLoc,
7494 SourceLocation LParenLoc,
7495 SourceLocation EndLoc) {
7496 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00007497 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00007498 for (auto &RefExpr : VarList) {
7499 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007500 SourceLocation ELoc;
7501 SourceRange ERange;
7502 Expr *SimpleRefExpr = RefExpr;
7503 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007504 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007505 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007506 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007507 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007508 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007509 ValueDecl *D = Res.first;
7510 if (!D)
7511 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007512
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007513 QualType Type = D->getType();
7514 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007515
7516 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7517 // A variable that appears in a private clause must not have an incomplete
7518 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007519 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007520 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007521 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007522
Alexey Bataev758e55e2013-09-06 18:03:48 +00007523 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7524 // in a Construct]
7525 // Variables with the predetermined data-sharing attributes may not be
7526 // listed in data-sharing attributes clauses, except for the cases
7527 // listed below. For these exceptions only, listing a predetermined
7528 // variable in a data-sharing attribute clause is allowed and overrides
7529 // the variable's predetermined data-sharing attributes.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007530 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007531 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00007532 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7533 << getOpenMPClauseName(OMPC_private);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007534 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007535 continue;
7536 }
7537
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007538 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00007539 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00007540 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007541 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7542 << getOpenMPClauseName(OMPC_private) << Type
7543 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7544 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007545 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007546 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007547 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007548 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007549 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007550 continue;
7551 }
7552
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007553 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
7554 // A list item cannot appear in both a map clause and a data-sharing
7555 // attribute clause on the same construct
7556 if (DSAStack->getCurrentDirective() == OMPD_target) {
7557 if(DSAStack->checkMapInfoForVar(VD, /* CurrentRegionOnly = */ true,
7558 [&](Expr *RE) -> bool {return true;})) {
7559 Diag(ELoc, diag::err_omp_variable_in_map_and_dsa)
7560 << getOpenMPClauseName(OMPC_private)
7561 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7562 ReportOriginalDSA(*this, DSAStack, D, DVar);
7563 continue;
7564 }
7565 }
7566
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007567 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
7568 // A variable of class type (or array thereof) that appears in a private
7569 // clause requires an accessible, unambiguous default constructor for the
7570 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00007571 // Generate helper private variable and initialize it with the default
7572 // value. The address of the original variable is replaced by the address of
7573 // the new private variable in CodeGen. This new variable is not added to
7574 // IdResolver, so the code in the OpenMP region uses original variable for
7575 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007576 Type = Type.getUnqualifiedType();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007577 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7578 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00007579 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007580 if (VDPrivate->isInvalidDecl())
7581 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007582 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007583 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007584
Alexey Bataev90c228f2016-02-08 09:29:13 +00007585 DeclRefExpr *Ref = nullptr;
7586 if (!VD)
Alexey Bataev61205072016-03-02 04:57:40 +00007587 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00007588 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
7589 Vars.push_back(VD ? RefExpr->IgnoreParens() : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007590 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007591 }
7592
Alexey Bataeved09d242014-05-28 05:53:51 +00007593 if (Vars.empty())
7594 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007595
Alexey Bataev03b340a2014-10-21 03:16:40 +00007596 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
7597 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007598}
7599
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007600namespace {
7601class DiagsUninitializedSeveretyRAII {
7602private:
7603 DiagnosticsEngine &Diags;
7604 SourceLocation SavedLoc;
7605 bool IsIgnored;
7606
7607public:
7608 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
7609 bool IsIgnored)
7610 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
7611 if (!IsIgnored) {
7612 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
7613 /*Map*/ diag::Severity::Ignored, Loc);
7614 }
7615 }
7616 ~DiagsUninitializedSeveretyRAII() {
7617 if (!IsIgnored)
7618 Diags.popMappings(SavedLoc);
7619 }
7620};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007621}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007622
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007623OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
7624 SourceLocation StartLoc,
7625 SourceLocation LParenLoc,
7626 SourceLocation EndLoc) {
7627 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007628 SmallVector<Expr *, 8> PrivateCopies;
7629 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00007630 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007631 bool IsImplicitClause =
7632 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
7633 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
7634
Alexey Bataeved09d242014-05-28 05:53:51 +00007635 for (auto &RefExpr : VarList) {
7636 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007637 SourceLocation ELoc;
7638 SourceRange ERange;
7639 Expr *SimpleRefExpr = RefExpr;
7640 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007641 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007642 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007643 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007644 PrivateCopies.push_back(nullptr);
7645 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007646 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007647 ValueDecl *D = Res.first;
7648 if (!D)
7649 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007650
Alexey Bataev60da77e2016-02-29 05:54:20 +00007651 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00007652 QualType Type = D->getType();
7653 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007654
7655 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7656 // A variable that appears in a private clause must not have an incomplete
7657 // type or a reference type.
7658 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00007659 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007660 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007661 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007662
7663 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
7664 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00007665 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007666 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007667 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007668
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007669 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00007670 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007671 if (!IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007672 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev005248a2016-02-25 05:25:57 +00007673 TopDVar = DVar;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007674 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007675 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
7676 // A list item that specifies a given variable may not appear in more
7677 // than one clause on the same directive, except that a variable may be
7678 // specified in both firstprivate and lastprivate clauses.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007679 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevf29276e2014-06-18 04:14:57 +00007680 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007681 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00007682 << getOpenMPClauseName(DVar.CKind)
7683 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007684 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007685 continue;
7686 }
7687
7688 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7689 // in a Construct]
7690 // Variables with the predetermined data-sharing attributes may not be
7691 // listed in data-sharing attributes clauses, except for the cases
7692 // listed below. For these exceptions only, listing a predetermined
7693 // variable in a data-sharing attribute clause is allowed and overrides
7694 // the variable's predetermined data-sharing attributes.
7695 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7696 // in a Construct, C/C++, p.2]
7697 // Variables with const-qualified type having no mutable member may be
7698 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00007699 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007700 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
7701 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00007702 << getOpenMPClauseName(DVar.CKind)
7703 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007704 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007705 continue;
7706 }
7707
Alexey Bataevf29276e2014-06-18 04:14:57 +00007708 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007709 // OpenMP [2.9.3.4, Restrictions, p.2]
7710 // A list item that is private within a parallel region must not appear
7711 // in a firstprivate clause on a worksharing construct if any of the
7712 // worksharing regions arising from the worksharing construct ever bind
7713 // to any of the parallel regions arising from the parallel construct.
Alexey Bataev549210e2014-06-24 04:39:47 +00007714 if (isOpenMPWorksharingDirective(CurrDir) &&
7715 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007716 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007717 if (DVar.CKind != OMPC_shared &&
7718 (isOpenMPParallelDirective(DVar.DKind) ||
7719 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00007720 Diag(ELoc, diag::err_omp_required_access)
7721 << getOpenMPClauseName(OMPC_firstprivate)
7722 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007723 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00007724 continue;
7725 }
7726 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007727 // OpenMP [2.9.3.4, Restrictions, p.3]
7728 // A list item that appears in a reduction clause of a parallel construct
7729 // must not appear in a firstprivate clause on a worksharing or task
7730 // construct if any of the worksharing or task regions arising from the
7731 // worksharing or task construct ever bind to any of the parallel regions
7732 // arising from the parallel construct.
7733 // OpenMP [2.9.3.4, Restrictions, p.4]
7734 // A list item that appears in a reduction clause in worksharing
7735 // construct must not appear in a firstprivate clause in a task construct
7736 // encountered during execution of any of the worksharing regions arising
7737 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00007738 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007739 DVar =
Alexey Bataevd985eda2016-02-10 11:29:16 +00007740 DSAStack->hasInnermostDSA(D, MatchesAnyClause(OMPC_reduction),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007741 [](OpenMPDirectiveKind K) -> bool {
7742 return isOpenMPParallelDirective(K) ||
7743 isOpenMPWorksharingDirective(K);
7744 },
7745 false);
7746 if (DVar.CKind == OMPC_reduction &&
7747 (isOpenMPParallelDirective(DVar.DKind) ||
7748 isOpenMPWorksharingDirective(DVar.DKind))) {
7749 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
7750 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007751 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007752 continue;
7753 }
7754 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007755
7756 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
7757 // A list item that is private within a teams region must not appear in a
7758 // firstprivate clause on a distribute construct if any of the distribute
7759 // regions arising from the distribute construct ever bind to any of the
7760 // teams regions arising from the teams construct.
7761 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
7762 // A list item that appears in a reduction clause of a teams construct
7763 // must not appear in a firstprivate clause on a distribute construct if
7764 // any of the distribute regions arising from the distribute construct
7765 // ever bind to any of the teams regions arising from the teams construct.
7766 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
7767 // A list item may appear in a firstprivate or lastprivate clause but not
7768 // both.
7769 if (CurrDir == OMPD_distribute) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007770 DVar = DSAStack->hasInnermostDSA(D, MatchesAnyClause(OMPC_private),
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007771 [](OpenMPDirectiveKind K) -> bool {
7772 return isOpenMPTeamsDirective(K);
7773 },
7774 false);
7775 if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) {
7776 Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007777 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007778 continue;
7779 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007780 DVar = DSAStack->hasInnermostDSA(D, MatchesAnyClause(OMPC_reduction),
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007781 [](OpenMPDirectiveKind K) -> bool {
7782 return isOpenMPTeamsDirective(K);
7783 },
7784 false);
7785 if (DVar.CKind == OMPC_reduction &&
7786 isOpenMPTeamsDirective(DVar.DKind)) {
7787 Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007788 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007789 continue;
7790 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007791 DVar = DSAStack->getTopDSA(D, false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007792 if (DVar.CKind == OMPC_lastprivate) {
7793 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007794 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007795 continue;
7796 }
7797 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007798 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
7799 // A list item cannot appear in both a map clause and a data-sharing
7800 // attribute clause on the same construct
7801 if (CurrDir == OMPD_target) {
7802 if(DSAStack->checkMapInfoForVar(VD, /* CurrentRegionOnly = */ true,
7803 [&](Expr *RE) -> bool {return true;})) {
7804 Diag(ELoc, diag::err_omp_variable_in_map_and_dsa)
7805 << getOpenMPClauseName(OMPC_firstprivate)
7806 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7807 ReportOriginalDSA(*this, DSAStack, D, DVar);
7808 continue;
7809 }
7810 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007811 }
7812
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007813 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00007814 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00007815 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007816 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7817 << getOpenMPClauseName(OMPC_firstprivate) << Type
7818 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7819 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00007820 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007821 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00007822 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007823 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00007824 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007825 continue;
7826 }
7827
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007828 Type = Type.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00007829 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7830 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007831 // Generate helper private variable and initialize it with the value of the
7832 // original variable. The address of the original variable is replaced by
7833 // the address of the new private variable in the CodeGen. This new variable
7834 // is not added to IdResolver, so the code in the OpenMP region uses
7835 // original variable for proper diagnostics and variable capturing.
7836 Expr *VDInitRefExpr = nullptr;
7837 // For arrays generate initializer for single element and replace it by the
7838 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007839 if (Type->isArrayType()) {
7840 auto VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00007841 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007842 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007843 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007844 ElemType = ElemType.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00007845 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007846 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00007847 InitializedEntity Entity =
7848 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007849 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
7850
7851 InitializationSequence InitSeq(*this, Entity, Kind, Init);
7852 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
7853 if (Result.isInvalid())
7854 VDPrivate->setInvalidDecl();
7855 else
7856 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00007857 // Remove temp variable declaration.
7858 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007859 } else {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007860 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
7861 ".firstprivate.temp");
7862 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
7863 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00007864 AddInitializerToDecl(VDPrivate,
7865 DefaultLvalueConversion(VDInitRefExpr).get(),
7866 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007867 }
7868 if (VDPrivate->isInvalidDecl()) {
7869 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007870 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007871 diag::note_omp_task_predetermined_firstprivate_here);
7872 }
7873 continue;
7874 }
7875 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00007876 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00007877 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
7878 RefExpr->getExprLoc());
7879 DeclRefExpr *Ref = nullptr;
Alexey Bataev417089f2016-02-17 13:19:37 +00007880 if (!VD) {
Alexey Bataev005248a2016-02-25 05:25:57 +00007881 if (TopDVar.CKind == OMPC_lastprivate)
7882 Ref = TopDVar.PrivateCopy;
7883 else {
Alexey Bataev61205072016-03-02 04:57:40 +00007884 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataev005248a2016-02-25 05:25:57 +00007885 if (!IsOpenMPCapturedDecl(D))
7886 ExprCaptures.push_back(Ref->getDecl());
7887 }
Alexey Bataev417089f2016-02-17 13:19:37 +00007888 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007889 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
7890 Vars.push_back(VD ? RefExpr->IgnoreParens() : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007891 PrivateCopies.push_back(VDPrivateRefExpr);
7892 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007893 }
7894
Alexey Bataeved09d242014-05-28 05:53:51 +00007895 if (Vars.empty())
7896 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007897
7898 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00007899 Vars, PrivateCopies, Inits,
7900 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007901}
7902
Alexander Musman1bb328c2014-06-04 13:06:39 +00007903OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
7904 SourceLocation StartLoc,
7905 SourceLocation LParenLoc,
7906 SourceLocation EndLoc) {
7907 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00007908 SmallVector<Expr *, 8> SrcExprs;
7909 SmallVector<Expr *, 8> DstExprs;
7910 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00007911 SmallVector<Decl *, 4> ExprCaptures;
7912 SmallVector<Expr *, 4> ExprPostUpdates;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007913 for (auto &RefExpr : VarList) {
7914 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007915 SourceLocation ELoc;
7916 SourceRange ERange;
7917 Expr *SimpleRefExpr = RefExpr;
7918 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00007919 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00007920 // It will be analyzed later.
7921 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00007922 SrcExprs.push_back(nullptr);
7923 DstExprs.push_back(nullptr);
7924 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007925 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00007926 ValueDecl *D = Res.first;
7927 if (!D)
7928 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007929
Alexey Bataev74caaf22016-02-20 04:09:36 +00007930 QualType Type = D->getType();
7931 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007932
7933 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
7934 // A variable that appears in a lastprivate clause must not have an
7935 // incomplete type or a reference type.
7936 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00007937 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00007938 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007939 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00007940
7941 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
7942 // in a Construct]
7943 // Variables with the predetermined data-sharing attributes may not be
7944 // listed in data-sharing attributes clauses, except for the cases
7945 // listed below.
Alexey Bataev74caaf22016-02-20 04:09:36 +00007946 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007947 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
7948 DVar.CKind != OMPC_firstprivate &&
7949 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
7950 Diag(ELoc, diag::err_omp_wrong_dsa)
7951 << getOpenMPClauseName(DVar.CKind)
7952 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev74caaf22016-02-20 04:09:36 +00007953 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007954 continue;
7955 }
7956
Alexey Bataevf29276e2014-06-18 04:14:57 +00007957 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
7958 // OpenMP [2.14.3.5, Restrictions, p.2]
7959 // A list item that is private within a parallel region, or that appears in
7960 // the reduction clause of a parallel construct, must not appear in a
7961 // lastprivate clause on a worksharing construct if any of the corresponding
7962 // worksharing regions ever binds to any of the corresponding parallel
7963 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00007964 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00007965 if (isOpenMPWorksharingDirective(CurrDir) &&
7966 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00007967 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00007968 if (DVar.CKind != OMPC_shared) {
7969 Diag(ELoc, diag::err_omp_required_access)
7970 << getOpenMPClauseName(OMPC_lastprivate)
7971 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev74caaf22016-02-20 04:09:36 +00007972 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00007973 continue;
7974 }
7975 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00007976
7977 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
7978 // A list item may appear in a firstprivate or lastprivate clause but not
7979 // both.
7980 if (CurrDir == OMPD_distribute) {
7981 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
7982 if (DVar.CKind == OMPC_firstprivate) {
7983 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
7984 ReportOriginalDSA(*this, DSAStack, D, DVar);
7985 continue;
7986 }
7987 }
7988
Alexander Musman1bb328c2014-06-04 13:06:39 +00007989 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00007990 // A variable of class type (or array thereof) that appears in a
7991 // lastprivate clause requires an accessible, unambiguous default
7992 // constructor for the class type, unless the list item is also specified
7993 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00007994 // A variable of class type (or array thereof) that appears in a
7995 // lastprivate clause requires an accessible, unambiguous copy assignment
7996 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00007997 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00007998 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00007999 Type.getUnqualifiedType(), ".lastprivate.src",
Alexey Bataev74caaf22016-02-20 04:09:36 +00008000 D->hasAttrs() ? &D->getAttrs() : nullptr);
8001 auto *PseudoSrcExpr =
8002 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00008003 auto *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00008004 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00008005 D->hasAttrs() ? &D->getAttrs() : nullptr);
8006 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00008007 // For arrays generate assignment operation for single element and replace
8008 // it by the original array element in CodeGen.
Alexey Bataev74caaf22016-02-20 04:09:36 +00008009 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
Alexey Bataev38e89532015-04-16 04:54:05 +00008010 PseudoDstExpr, PseudoSrcExpr);
8011 if (AssignmentOp.isInvalid())
8012 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00008013 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00008014 /*DiscardedValue=*/true);
8015 if (AssignmentOp.isInvalid())
8016 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008017
Alexey Bataev74caaf22016-02-20 04:09:36 +00008018 DeclRefExpr *Ref = nullptr;
Alexey Bataev005248a2016-02-25 05:25:57 +00008019 if (!VD) {
8020 if (TopDVar.CKind == OMPC_firstprivate)
8021 Ref = TopDVar.PrivateCopy;
8022 else {
Alexey Bataev61205072016-03-02 04:57:40 +00008023 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00008024 if (!IsOpenMPCapturedDecl(D))
8025 ExprCaptures.push_back(Ref->getDecl());
8026 }
8027 if (TopDVar.CKind == OMPC_firstprivate ||
8028 (!IsOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008029 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008030 ExprResult RefRes = DefaultLvalueConversion(Ref);
8031 if (!RefRes.isUsable())
8032 continue;
8033 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00008034 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
8035 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00008036 if (!PostUpdateRes.isUsable())
8037 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00008038 ExprPostUpdates.push_back(
8039 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00008040 }
8041 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00008042 if (TopDVar.CKind != OMPC_firstprivate)
Alexey Bataev74caaf22016-02-20 04:09:36 +00008043 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
8044 Vars.push_back(VD ? RefExpr->IgnoreParens() : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00008045 SrcExprs.push_back(PseudoSrcExpr);
8046 DstExprs.push_back(PseudoDstExpr);
8047 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00008048 }
8049
8050 if (Vars.empty())
8051 return nullptr;
8052
8053 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00008054 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008055 buildPreInits(Context, ExprCaptures),
8056 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00008057}
8058
Alexey Bataev758e55e2013-09-06 18:03:48 +00008059OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
8060 SourceLocation StartLoc,
8061 SourceLocation LParenLoc,
8062 SourceLocation EndLoc) {
8063 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00008064 for (auto &RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008065 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
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);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008070 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00008071 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008072 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008073 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008074 ValueDecl *D = Res.first;
8075 if (!D)
8076 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008077
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008078 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008079 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8080 // in a Construct]
8081 // Variables with the predetermined data-sharing attributes may not be
8082 // listed in data-sharing attributes clauses, except for the cases
8083 // listed below. For these exceptions only, listing a predetermined
8084 // variable in a data-sharing attribute clause is allowed and overrides
8085 // the variable's predetermined data-sharing attributes.
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008086 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00008087 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
8088 DVar.RefExpr) {
8089 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8090 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008091 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008092 continue;
8093 }
8094
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008095 DeclRefExpr *Ref = nullptr;
Alexey Bataev1efd1662016-03-29 10:59:56 +00008096 if (!VD && IsOpenMPCapturedDecl(D))
Alexey Bataev61205072016-03-02 04:57:40 +00008097 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008098 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataev1efd1662016-03-29 10:59:56 +00008099 Vars.push_back((VD || !Ref) ? RefExpr->IgnoreParens() : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008100 }
8101
Alexey Bataeved09d242014-05-28 05:53:51 +00008102 if (Vars.empty())
8103 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008104
8105 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
8106}
8107
Alexey Bataevc5e02582014-06-16 07:08:35 +00008108namespace {
8109class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
8110 DSAStackTy *Stack;
8111
8112public:
8113 bool VisitDeclRefExpr(DeclRefExpr *E) {
8114 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008115 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008116 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
8117 return false;
8118 if (DVar.CKind != OMPC_unknown)
8119 return true;
Alexey Bataevf29276e2014-06-18 04:14:57 +00008120 DSAStackTy::DSAVarData DVarPrivate =
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008121 Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008122 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00008123 return true;
8124 return false;
8125 }
8126 return false;
8127 }
8128 bool VisitStmt(Stmt *S) {
8129 for (auto Child : S->children()) {
8130 if (Child && Visit(Child))
8131 return true;
8132 }
8133 return false;
8134 }
Alexey Bataev23b69422014-06-18 07:08:49 +00008135 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00008136};
Alexey Bataev23b69422014-06-18 07:08:49 +00008137} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00008138
Alexey Bataev60da77e2016-02-29 05:54:20 +00008139namespace {
8140// Transform MemberExpression for specified FieldDecl of current class to
8141// DeclRefExpr to specified OMPCapturedExprDecl.
8142class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
8143 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
8144 ValueDecl *Field;
8145 DeclRefExpr *CapturedExpr;
8146
8147public:
8148 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
8149 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
8150
8151 ExprResult TransformMemberExpr(MemberExpr *E) {
8152 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
8153 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00008154 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008155 return CapturedExpr;
8156 }
8157 return BaseTransform::TransformMemberExpr(E);
8158 }
8159 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
8160};
8161} // namespace
8162
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008163template <typename T>
8164static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
8165 const llvm::function_ref<T(ValueDecl *)> &Gen) {
8166 for (auto &Set : Lookups) {
8167 for (auto *D : Set) {
8168 if (auto Res = Gen(cast<ValueDecl>(D)))
8169 return Res;
8170 }
8171 }
8172 return T();
8173}
8174
8175static ExprResult
8176buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
8177 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
8178 const DeclarationNameInfo &ReductionId, QualType Ty,
8179 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
8180 if (ReductionIdScopeSpec.isInvalid())
8181 return ExprError();
8182 SmallVector<UnresolvedSet<8>, 4> Lookups;
8183 if (S) {
8184 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
8185 Lookup.suppressDiagnostics();
8186 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
8187 auto *D = Lookup.getRepresentativeDecl();
8188 do {
8189 S = S->getParent();
8190 } while (S && !S->isDeclScope(D));
8191 if (S)
8192 S = S->getParent();
8193 Lookups.push_back(UnresolvedSet<8>());
8194 Lookups.back().append(Lookup.begin(), Lookup.end());
8195 Lookup.clear();
8196 }
8197 } else if (auto *ULE =
8198 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
8199 Lookups.push_back(UnresolvedSet<8>());
8200 Decl *PrevD = nullptr;
8201 for(auto *D : ULE->decls()) {
8202 if (D == PrevD)
8203 Lookups.push_back(UnresolvedSet<8>());
8204 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
8205 Lookups.back().addDecl(DRD);
8206 PrevD = D;
8207 }
8208 }
8209 if (Ty->isDependentType() || Ty->isInstantiationDependentType() ||
8210 Ty->containsUnexpandedParameterPack() ||
8211 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
8212 return !D->isInvalidDecl() &&
8213 (D->getType()->isDependentType() ||
8214 D->getType()->isInstantiationDependentType() ||
8215 D->getType()->containsUnexpandedParameterPack());
8216 })) {
8217 UnresolvedSet<8> ResSet;
8218 for (auto &Set : Lookups) {
8219 ResSet.append(Set.begin(), Set.end());
8220 // The last item marks the end of all declarations at the specified scope.
8221 ResSet.addDecl(Set[Set.size() - 1]);
8222 }
8223 return UnresolvedLookupExpr::Create(
8224 SemaRef.Context, /*NamingClass=*/nullptr,
8225 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
8226 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
8227 }
8228 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8229 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
8230 if (!D->isInvalidDecl() &&
8231 SemaRef.Context.hasSameType(D->getType(), Ty))
8232 return D;
8233 return nullptr;
8234 }))
8235 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8236 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8237 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
8238 if (!D->isInvalidDecl() &&
8239 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
8240 !Ty.isMoreQualifiedThan(D->getType()))
8241 return D;
8242 return nullptr;
8243 })) {
8244 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8245 /*DetectVirtual=*/false);
8246 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
8247 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
8248 VD->getType().getUnqualifiedType()))) {
8249 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
8250 /*DiagID=*/0) !=
8251 Sema::AR_inaccessible) {
8252 SemaRef.BuildBasePathArray(Paths, BasePath);
8253 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8254 }
8255 }
8256 }
8257 }
8258 if (ReductionIdScopeSpec.isSet()) {
8259 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
8260 return ExprError();
8261 }
8262 return ExprEmpty();
8263}
8264
Alexey Bataevc5e02582014-06-16 07:08:35 +00008265OMPClause *Sema::ActOnOpenMPReductionClause(
8266 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
8267 SourceLocation ColonLoc, SourceLocation EndLoc,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008268 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
8269 ArrayRef<Expr *> UnresolvedReductions) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00008270 auto DN = ReductionId.getName();
8271 auto OOK = DN.getCXXOverloadedOperator();
8272 BinaryOperatorKind BOK = BO_Comma;
8273
8274 // OpenMP [2.14.3.6, reduction clause]
8275 // C
8276 // reduction-identifier is either an identifier or one of the following
8277 // operators: +, -, *, &, |, ^, && and ||
8278 // C++
8279 // reduction-identifier is either an id-expression or one of the following
8280 // operators: +, -, *, &, |, ^, && and ||
8281 // FIXME: Only 'min' and 'max' identifiers are supported for now.
8282 switch (OOK) {
8283 case OO_Plus:
8284 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008285 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008286 break;
8287 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008288 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008289 break;
8290 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008291 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008292 break;
8293 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008294 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008295 break;
8296 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008297 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008298 break;
8299 case OO_AmpAmp:
8300 BOK = BO_LAnd;
8301 break;
8302 case OO_PipePipe:
8303 BOK = BO_LOr;
8304 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008305 case OO_New:
8306 case OO_Delete:
8307 case OO_Array_New:
8308 case OO_Array_Delete:
8309 case OO_Slash:
8310 case OO_Percent:
8311 case OO_Tilde:
8312 case OO_Exclaim:
8313 case OO_Equal:
8314 case OO_Less:
8315 case OO_Greater:
8316 case OO_LessEqual:
8317 case OO_GreaterEqual:
8318 case OO_PlusEqual:
8319 case OO_MinusEqual:
8320 case OO_StarEqual:
8321 case OO_SlashEqual:
8322 case OO_PercentEqual:
8323 case OO_CaretEqual:
8324 case OO_AmpEqual:
8325 case OO_PipeEqual:
8326 case OO_LessLess:
8327 case OO_GreaterGreater:
8328 case OO_LessLessEqual:
8329 case OO_GreaterGreaterEqual:
8330 case OO_EqualEqual:
8331 case OO_ExclaimEqual:
8332 case OO_PlusPlus:
8333 case OO_MinusMinus:
8334 case OO_Comma:
8335 case OO_ArrowStar:
8336 case OO_Arrow:
8337 case OO_Call:
8338 case OO_Subscript:
8339 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +00008340 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008341 case NUM_OVERLOADED_OPERATORS:
8342 llvm_unreachable("Unexpected reduction identifier");
8343 case OO_None:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008344 if (auto II = DN.getAsIdentifierInfo()) {
8345 if (II->isStr("max"))
8346 BOK = BO_GT;
8347 else if (II->isStr("min"))
8348 BOK = BO_LT;
8349 }
8350 break;
8351 }
8352 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008353 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +00008354 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008355 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008356
8357 SmallVector<Expr *, 8> Vars;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008358 SmallVector<Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008359 SmallVector<Expr *, 8> LHSs;
8360 SmallVector<Expr *, 8> RHSs;
8361 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev61205072016-03-02 04:57:40 +00008362 SmallVector<Decl *, 4> ExprCaptures;
8363 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008364 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
8365 bool FirstIter = true;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008366 for (auto RefExpr : VarList) {
8367 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +00008368 // OpenMP [2.1, C/C++]
8369 // A list item is a variable or array section, subject to the restrictions
8370 // specified in Section 2.4 on page 42 and in each of the sections
8371 // describing clauses and directives for which a list appears.
8372 // OpenMP [2.14.3.3, Restrictions, p.1]
8373 // A variable that is part of another variable (as an array or
8374 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008375 if (!FirstIter && IR != ER)
8376 ++IR;
8377 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008378 SourceLocation ELoc;
8379 SourceRange ERange;
8380 Expr *SimpleRefExpr = RefExpr;
8381 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8382 /*AllowArraySection=*/true);
8383 if (Res.second) {
8384 // It will be analyzed later.
8385 Vars.push_back(RefExpr);
8386 Privates.push_back(nullptr);
8387 LHSs.push_back(nullptr);
8388 RHSs.push_back(nullptr);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008389 // Try to find 'declare reduction' corresponding construct before using
8390 // builtin/overloaded operators.
8391 QualType Type = Context.DependentTy;
8392 CXXCastPath BasePath;
8393 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8394 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8395 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8396 if (CurContext->isDependentContext() &&
8397 (DeclareReductionRef.isUnset() ||
8398 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
8399 ReductionOps.push_back(DeclareReductionRef.get());
8400 else
8401 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008402 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00008403 ValueDecl *D = Res.first;
8404 if (!D)
8405 continue;
8406
Alexey Bataeva1764212015-09-30 09:22:36 +00008407 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008408 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
8409 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
8410 if (ASE)
Alexey Bataev31300ed2016-02-04 11:27:03 +00008411 Type = ASE->getType().getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008412 else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008413 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
8414 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
8415 Type = ATy->getElementType();
8416 else
8417 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00008418 Type = Type.getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008419 } else
8420 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
8421 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +00008422
Alexey Bataevc5e02582014-06-16 07:08:35 +00008423 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8424 // A variable that appears in a private clause must not have an incomplete
8425 // type or a reference type.
8426 if (RequireCompleteType(ELoc, Type,
8427 diag::err_omp_reduction_incomplete_type))
8428 continue;
8429 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +00008430 // A list item that appears in a reduction clause must not be
8431 // const-qualified.
8432 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008433 Diag(ELoc, diag::err_omp_const_reduction_list_item)
Alexey Bataevc5e02582014-06-16 07:08:35 +00008434 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008435 if (!ASE && !OASE) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008436 bool IsDecl = !VD ||
8437 VD->isThisDeclarationADefinition(Context) ==
8438 VarDecl::DeclarationOnly;
8439 Diag(D->getLocation(),
Alexey Bataeva1764212015-09-30 09:22:36 +00008440 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +00008441 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +00008442 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00008443 continue;
8444 }
8445 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
8446 // If a list-item is a reference type then it must bind to the same object
8447 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +00008448 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008449 VarDecl *VDDef = VD->getDefinition();
Alexey Bataev31300ed2016-02-04 11:27:03 +00008450 if (VD->getType()->isReferenceType() && VDDef) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008451 DSARefChecker Check(DSAStack);
8452 if (Check.Visit(VDDef->getInit())) {
8453 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
8454 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
8455 continue;
8456 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00008457 }
8458 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008459
Alexey Bataevc5e02582014-06-16 07:08:35 +00008460 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8461 // in a Construct]
8462 // Variables with the predetermined data-sharing attributes may not be
8463 // listed in data-sharing attributes clauses, except for the cases
8464 // listed below. For these exceptions only, listing a predetermined
8465 // variable in a data-sharing attribute clause is allowed and overrides
8466 // the variable's predetermined data-sharing attributes.
8467 // OpenMP [2.14.3.6, Restrictions, p.3]
8468 // Any number of reduction clauses can be specified on the directive,
8469 // but a list item can appear only once in the reduction clauses for that
8470 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +00008471 DSAStackTy::DSAVarData DVar;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008472 DVar = DSAStack->getTopDSA(D, false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008473 if (DVar.CKind == OMPC_reduction) {
8474 Diag(ELoc, diag::err_omp_once_referenced)
8475 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008476 if (DVar.RefExpr)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008477 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008478 } else if (DVar.CKind != OMPC_unknown) {
8479 Diag(ELoc, diag::err_omp_wrong_dsa)
8480 << getOpenMPClauseName(DVar.CKind)
8481 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008482 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008483 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008484 }
8485
8486 // OpenMP [2.14.3.6, Restrictions, p.1]
8487 // A list item that appears in a reduction clause of a worksharing
8488 // construct must be shared in the parallel regions to which any of the
8489 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008490 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8491 if (isOpenMPWorksharingDirective(CurrDir) &&
8492 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008493 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008494 if (DVar.CKind != OMPC_shared) {
8495 Diag(ELoc, diag::err_omp_required_access)
8496 << getOpenMPClauseName(OMPC_reduction)
8497 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008498 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008499 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +00008500 }
8501 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008502
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008503 // Try to find 'declare reduction' corresponding construct before using
8504 // builtin/overloaded operators.
8505 CXXCastPath BasePath;
8506 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8507 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8508 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8509 if (DeclareReductionRef.isInvalid())
8510 continue;
8511 if (CurContext->isDependentContext() &&
8512 (DeclareReductionRef.isUnset() ||
8513 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
8514 Vars.push_back(RefExpr);
8515 Privates.push_back(nullptr);
8516 LHSs.push_back(nullptr);
8517 RHSs.push_back(nullptr);
8518 ReductionOps.push_back(DeclareReductionRef.get());
8519 continue;
8520 }
8521 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
8522 // Not allowed reduction identifier is found.
8523 Diag(ReductionId.getLocStart(),
8524 diag::err_omp_unknown_reduction_identifier)
8525 << Type << ReductionIdRange;
8526 continue;
8527 }
8528
8529 // OpenMP [2.14.3.6, reduction clause, Restrictions]
8530 // The type of a list item that appears in a reduction clause must be valid
8531 // for the reduction-identifier. For a max or min reduction in C, the type
8532 // of the list item must be an allowed arithmetic data type: char, int,
8533 // float, double, or _Bool, possibly modified with long, short, signed, or
8534 // unsigned. For a max or min reduction in C++, the type of the list item
8535 // must be an allowed arithmetic data type: char, wchar_t, int, float,
8536 // double, or bool, possibly modified with long, short, signed, or unsigned.
8537 if (DeclareReductionRef.isUnset()) {
8538 if ((BOK == BO_GT || BOK == BO_LT) &&
8539 !(Type->isScalarType() ||
8540 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
8541 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
8542 << getLangOpts().CPlusPlus;
8543 if (!ASE && !OASE) {
8544 bool IsDecl = !VD ||
8545 VD->isThisDeclarationADefinition(Context) ==
8546 VarDecl::DeclarationOnly;
8547 Diag(D->getLocation(),
8548 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8549 << D;
8550 }
8551 continue;
8552 }
8553 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
8554 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
8555 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
8556 if (!ASE && !OASE) {
8557 bool IsDecl = !VD ||
8558 VD->isThisDeclarationADefinition(Context) ==
8559 VarDecl::DeclarationOnly;
8560 Diag(D->getLocation(),
8561 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8562 << D;
8563 }
8564 continue;
8565 }
8566 }
8567
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008568 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008569 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
Alexey Bataev60da77e2016-02-29 05:54:20 +00008570 D->hasAttrs() ? &D->getAttrs() : nullptr);
8571 auto *RHSVD = buildVarDecl(*this, ELoc, Type, D->getName(),
8572 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008573 auto PrivateTy = Type;
Alexey Bataev1189bd02016-01-26 12:20:39 +00008574 if (OASE ||
Alexey Bataev60da77e2016-02-29 05:54:20 +00008575 (!ASE &&
8576 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00008577 // For arays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008578 // Create pseudo array type for private copy. The size for this array will
8579 // be generated during codegen.
8580 // For array subscripts or single variables Private Ty is the same as Type
8581 // (type of the variable or single array element).
8582 PrivateTy = Context.getVariableArrayType(
8583 Type, new (Context) OpaqueValueExpr(SourceLocation(),
8584 Context.getSizeType(), VK_RValue),
8585 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +00008586 } else if (!ASE && !OASE &&
8587 Context.getAsArrayType(D->getType().getNonReferenceType()))
8588 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008589 // Private copy.
Alexey Bataev60da77e2016-02-29 05:54:20 +00008590 auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, D->getName(),
8591 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008592 // Add initializer for private variable.
8593 Expr *Init = nullptr;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008594 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
8595 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
8596 if (DeclareReductionRef.isUsable()) {
8597 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
8598 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
8599 if (DRD->getInitializer()) {
8600 Init = DRDRef;
8601 RHSVD->setInit(DRDRef);
8602 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008603 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008604 } else {
8605 switch (BOK) {
8606 case BO_Add:
8607 case BO_Xor:
8608 case BO_Or:
8609 case BO_LOr:
8610 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
8611 if (Type->isScalarType() || Type->isAnyComplexType())
8612 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
8613 break;
8614 case BO_Mul:
8615 case BO_LAnd:
8616 if (Type->isScalarType() || Type->isAnyComplexType()) {
8617 // '*' and '&&' reduction ops - initializer is '1'.
8618 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00008619 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008620 break;
8621 case BO_And: {
8622 // '&' reduction op - initializer is '~0'.
8623 QualType OrigType = Type;
8624 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
8625 Type = ComplexTy->getElementType();
8626 if (Type->isRealFloatingType()) {
8627 llvm::APFloat InitValue =
8628 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
8629 /*isIEEE=*/true);
8630 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
8631 Type, ELoc);
8632 } else if (Type->isScalarType()) {
8633 auto Size = Context.getTypeSize(Type);
8634 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
8635 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
8636 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
8637 }
8638 if (Init && OrigType->isAnyComplexType()) {
8639 // Init = 0xFFFF + 0xFFFFi;
8640 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
8641 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
8642 }
8643 Type = OrigType;
8644 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008645 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008646 case BO_LT:
8647 case BO_GT: {
8648 // 'min' reduction op - initializer is 'Largest representable number in
8649 // the reduction list item type'.
8650 // 'max' reduction op - initializer is 'Least representable number in
8651 // the reduction list item type'.
8652 if (Type->isIntegerType() || Type->isPointerType()) {
8653 bool IsSigned = Type->hasSignedIntegerRepresentation();
8654 auto Size = Context.getTypeSize(Type);
8655 QualType IntTy =
8656 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
8657 llvm::APInt InitValue =
8658 (BOK != BO_LT)
8659 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
8660 : llvm::APInt::getMinValue(Size)
8661 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
8662 : llvm::APInt::getMaxValue(Size);
8663 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
8664 if (Type->isPointerType()) {
8665 // Cast to pointer type.
8666 auto CastExpr = BuildCStyleCastExpr(
8667 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
8668 SourceLocation(), Init);
8669 if (CastExpr.isInvalid())
8670 continue;
8671 Init = CastExpr.get();
8672 }
8673 } else if (Type->isRealFloatingType()) {
8674 llvm::APFloat InitValue = llvm::APFloat::getLargest(
8675 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
8676 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
8677 Type, ELoc);
8678 }
8679 break;
8680 }
8681 case BO_PtrMemD:
8682 case BO_PtrMemI:
8683 case BO_MulAssign:
8684 case BO_Div:
8685 case BO_Rem:
8686 case BO_Sub:
8687 case BO_Shl:
8688 case BO_Shr:
8689 case BO_LE:
8690 case BO_GE:
8691 case BO_EQ:
8692 case BO_NE:
8693 case BO_AndAssign:
8694 case BO_XorAssign:
8695 case BO_OrAssign:
8696 case BO_Assign:
8697 case BO_AddAssign:
8698 case BO_SubAssign:
8699 case BO_DivAssign:
8700 case BO_RemAssign:
8701 case BO_ShlAssign:
8702 case BO_ShrAssign:
8703 case BO_Comma:
8704 llvm_unreachable("Unexpected reduction operation");
8705 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008706 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008707 if (Init && DeclareReductionRef.isUnset()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008708 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
8709 /*TypeMayContainAuto=*/false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008710 } else if (!Init)
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008711 ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008712 if (RHSVD->isInvalidDecl())
8713 continue;
8714 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008715 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
8716 << ReductionIdRange;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008717 bool IsDecl =
8718 !VD ||
8719 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8720 Diag(D->getLocation(),
8721 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8722 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008723 continue;
8724 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008725 // Store initializer for single element in private copy. Will be used during
8726 // codegen.
8727 PrivateVD->setInit(RHSVD->getInit());
8728 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008729 auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008730 ExprResult ReductionOp;
8731 if (DeclareReductionRef.isUsable()) {
8732 QualType RedTy = DeclareReductionRef.get()->getType();
8733 QualType PtrRedTy = Context.getPointerType(RedTy);
8734 ExprResult LHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
8735 ExprResult RHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
8736 if (!BasePath.empty()) {
8737 LHS = DefaultLvalueConversion(LHS.get());
8738 RHS = DefaultLvalueConversion(RHS.get());
8739 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
8740 CK_UncheckedDerivedToBase, LHS.get(),
8741 &BasePath, LHS.get()->getValueKind());
8742 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
8743 CK_UncheckedDerivedToBase, RHS.get(),
8744 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008745 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008746 FunctionProtoType::ExtProtoInfo EPI;
8747 QualType Params[] = {PtrRedTy, PtrRedTy};
8748 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
8749 auto *OVE = new (Context) OpaqueValueExpr(
8750 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
8751 DefaultLvalueConversion(DeclareReductionRef.get()).get());
8752 Expr *Args[] = {LHS.get(), RHS.get()};
8753 ReductionOp = new (Context)
8754 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
8755 } else {
8756 ReductionOp = BuildBinOp(DSAStack->getCurScope(),
8757 ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
8758 if (ReductionOp.isUsable()) {
8759 if (BOK != BO_LT && BOK != BO_GT) {
8760 ReductionOp =
8761 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
8762 BO_Assign, LHSDRE, ReductionOp.get());
8763 } else {
8764 auto *ConditionalOp = new (Context) ConditionalOperator(
8765 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
8766 RHSDRE, Type, VK_LValue, OK_Ordinary);
8767 ReductionOp =
8768 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
8769 BO_Assign, LHSDRE, ConditionalOp);
8770 }
8771 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
8772 }
8773 if (ReductionOp.isInvalid())
8774 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008775 }
8776
Alexey Bataev60da77e2016-02-29 05:54:20 +00008777 DeclRefExpr *Ref = nullptr;
8778 Expr *VarsExpr = RefExpr->IgnoreParens();
8779 if (!VD) {
8780 if (ASE || OASE) {
8781 TransformExprToCaptures RebuildToCapture(*this, D);
8782 VarsExpr =
8783 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
8784 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +00008785 } else {
8786 VarsExpr = Ref =
8787 buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +00008788 }
8789 if (!IsOpenMPCapturedDecl(D)) {
8790 ExprCaptures.push_back(Ref->getDecl());
8791 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
8792 ExprResult RefRes = DefaultLvalueConversion(Ref);
8793 if (!RefRes.isUsable())
8794 continue;
8795 ExprResult PostUpdateRes =
8796 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
8797 SimpleRefExpr, RefRes.get());
8798 if (!PostUpdateRes.isUsable())
8799 continue;
8800 ExprPostUpdates.push_back(
8801 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +00008802 }
8803 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00008804 }
8805 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
8806 Vars.push_back(VarsExpr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008807 Privates.push_back(PrivateDRE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008808 LHSs.push_back(LHSDRE);
8809 RHSs.push_back(RHSDRE);
8810 ReductionOps.push_back(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008811 }
8812
8813 if (Vars.empty())
8814 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +00008815
Alexey Bataevc5e02582014-06-16 07:08:35 +00008816 return OMPReductionClause::Create(
8817 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008818 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008819 LHSs, RHSs, ReductionOps, buildPreInits(Context, ExprCaptures),
8820 buildPostUpdate(*this, ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +00008821}
8822
Alexey Bataevecba70f2016-04-12 11:02:11 +00008823bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
8824 SourceLocation LinLoc) {
8825 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
8826 LinKind == OMPC_LINEAR_unknown) {
8827 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
8828 return true;
8829 }
8830 return false;
8831}
8832
8833bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
8834 OpenMPLinearClauseKind LinKind,
8835 QualType Type) {
8836 auto *VD = dyn_cast_or_null<VarDecl>(D);
8837 // A variable must not have an incomplete type or a reference type.
8838 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
8839 return true;
8840 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
8841 !Type->isReferenceType()) {
8842 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
8843 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
8844 return true;
8845 }
8846 Type = Type.getNonReferenceType();
8847
8848 // A list item must not be const-qualified.
8849 if (Type.isConstant(Context)) {
8850 Diag(ELoc, diag::err_omp_const_variable)
8851 << getOpenMPClauseName(OMPC_linear);
8852 if (D) {
8853 bool IsDecl =
8854 !VD ||
8855 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8856 Diag(D->getLocation(),
8857 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8858 << D;
8859 }
8860 return true;
8861 }
8862
8863 // A list item must be of integral or pointer type.
8864 Type = Type.getUnqualifiedType().getCanonicalType();
8865 const auto *Ty = Type.getTypePtrOrNull();
8866 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
8867 !Ty->isPointerType())) {
8868 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
8869 if (D) {
8870 bool IsDecl =
8871 !VD ||
8872 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8873 Diag(D->getLocation(),
8874 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8875 << D;
8876 }
8877 return true;
8878 }
8879 return false;
8880}
8881
Alexey Bataev182227b2015-08-20 10:54:39 +00008882OMPClause *Sema::ActOnOpenMPLinearClause(
8883 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
8884 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
8885 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +00008886 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008887 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +00008888 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +00008889 SmallVector<Decl *, 4> ExprCaptures;
8890 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +00008891 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +00008892 LinKind = OMPC_LINEAR_val;
Alexey Bataeved09d242014-05-28 05:53:51 +00008893 for (auto &RefExpr : VarList) {
8894 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008895 SourceLocation ELoc;
8896 SourceRange ERange;
8897 Expr *SimpleRefExpr = RefExpr;
8898 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8899 /*AllowArraySection=*/false);
8900 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +00008901 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008902 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008903 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +00008904 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00008905 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008906 ValueDecl *D = Res.first;
8907 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +00008908 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +00008909
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008910 QualType Type = D->getType();
8911 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +00008912
8913 // OpenMP [2.14.3.7, linear clause]
8914 // A list-item cannot appear in more than one linear clause.
8915 // A list-item that appears in a linear clause cannot appear in any
8916 // other data-sharing attribute clause.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008917 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00008918 if (DVar.RefExpr) {
8919 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8920 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008921 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00008922 continue;
8923 }
8924
Alexey Bataevecba70f2016-04-12 11:02:11 +00008925 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +00008926 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00008927 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +00008928
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008929 // Build private copy of original var.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008930 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
8931 D->hasAttrs() ? &D->getAttrs() : nullptr);
8932 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +00008933 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008934 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008935 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008936 DeclRefExpr *Ref = nullptr;
Alexey Bataev78849fb2016-03-09 09:49:00 +00008937 if (!VD) {
8938 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
8939 if (!IsOpenMPCapturedDecl(D)) {
8940 ExprCaptures.push_back(Ref->getDecl());
8941 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
8942 ExprResult RefRes = DefaultLvalueConversion(Ref);
8943 if (!RefRes.isUsable())
8944 continue;
8945 ExprResult PostUpdateRes =
8946 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
8947 SimpleRefExpr, RefRes.get());
8948 if (!PostUpdateRes.isUsable())
8949 continue;
8950 ExprPostUpdates.push_back(
8951 IgnoredValueConversions(PostUpdateRes.get()).get());
8952 }
8953 }
8954 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008955 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008956 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008957 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008958 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008959 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008960 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
8961 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
8962
8963 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
8964 Vars.push_back(VD ? RefExpr->IgnoreParens() : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008965 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +00008966 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00008967 }
8968
8969 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008970 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00008971
8972 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00008973 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00008974 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
8975 !Step->isInstantiationDependent() &&
8976 !Step->containsUnexpandedParameterPack()) {
8977 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00008978 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00008979 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008980 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008981 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00008982
Alexander Musman3276a272015-03-21 10:12:56 +00008983 // Build var to save the step value.
8984 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00008985 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +00008986 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +00008987 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +00008988 ExprResult CalcStep =
8989 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008990 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +00008991
Alexander Musman8dba6642014-04-22 13:09:42 +00008992 // Warn about zero linear step (it would be probably better specified as
8993 // making corresponding variables 'const').
8994 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00008995 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
8996 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00008997 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
8998 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00008999 if (!IsConstant && CalcStep.isUsable()) {
9000 // Calculate the step beforehand instead of doing this on each iteration.
9001 // (This is not used if the number of iterations may be kfold-ed).
9002 CalcStepExpr = CalcStep.get();
9003 }
Alexander Musman8dba6642014-04-22 13:09:42 +00009004 }
9005
Alexey Bataev182227b2015-08-20 10:54:39 +00009006 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
9007 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009008 StepExpr, CalcStepExpr,
9009 buildPreInits(Context, ExprCaptures),
9010 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +00009011}
9012
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009013static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
9014 Expr *NumIterations, Sema &SemaRef,
9015 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +00009016 // Walk the vars and build update/final expressions for the CodeGen.
9017 SmallVector<Expr *, 8> Updates;
9018 SmallVector<Expr *, 8> Finals;
9019 Expr *Step = Clause.getStep();
9020 Expr *CalcStep = Clause.getCalcStep();
9021 // OpenMP [2.14.3.7, linear clause]
9022 // If linear-step is not specified it is assumed to be 1.
9023 if (Step == nullptr)
9024 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00009025 else if (CalcStep) {
Alexander Musman3276a272015-03-21 10:12:56 +00009026 Step = cast<BinaryOperator>(CalcStep)->getLHS();
Alexey Bataev5a3af132016-03-29 08:58:54 +00009027 }
Alexander Musman3276a272015-03-21 10:12:56 +00009028 bool HasErrors = false;
9029 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009030 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009031 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +00009032 for (auto &RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009033 SourceLocation ELoc;
9034 SourceRange ERange;
9035 Expr *SimpleRefExpr = RefExpr;
9036 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
9037 /*AllowArraySection=*/false);
9038 ValueDecl *D = Res.first;
9039 if (Res.second || !D) {
9040 Updates.push_back(nullptr);
9041 Finals.push_back(nullptr);
9042 HasErrors = true;
9043 continue;
9044 }
9045 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) {
9046 D = cast<MemberExpr>(CED->getInit()->IgnoreParenImpCasts())
9047 ->getMemberDecl();
9048 }
9049 auto &&Info = Stack->isLoopControlVariable(D);
Alexander Musman3276a272015-03-21 10:12:56 +00009050 Expr *InitExpr = *CurInit;
9051
9052 // Build privatized reference to the current linear var.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009053 auto DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009054 Expr *CapturedRef;
9055 if (LinKind == OMPC_LINEAR_uval)
9056 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
9057 else
9058 CapturedRef =
9059 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
9060 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
9061 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00009062
9063 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009064 ExprResult Update;
9065 if (!Info.first) {
9066 Update =
9067 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
9068 InitExpr, IV, Step, /* Subtract */ false);
9069 } else
9070 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009071 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
9072 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00009073
9074 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009075 ExprResult Final;
9076 if (!Info.first) {
9077 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
9078 InitExpr, NumIterations, Step,
9079 /* Subtract */ false);
9080 } else
9081 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009082 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
9083 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009084
Alexander Musman3276a272015-03-21 10:12:56 +00009085 if (!Update.isUsable() || !Final.isUsable()) {
9086 Updates.push_back(nullptr);
9087 Finals.push_back(nullptr);
9088 HasErrors = true;
9089 } else {
9090 Updates.push_back(Update.get());
9091 Finals.push_back(Final.get());
9092 }
Richard Trieucc3949d2016-02-18 22:34:54 +00009093 ++CurInit;
9094 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00009095 }
9096 Clause.setUpdates(Updates);
9097 Clause.setFinals(Finals);
9098 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00009099}
9100
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009101OMPClause *Sema::ActOnOpenMPAlignedClause(
9102 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
9103 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
9104
9105 SmallVector<Expr *, 8> Vars;
9106 for (auto &RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +00009107 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9108 SourceLocation ELoc;
9109 SourceRange ERange;
9110 Expr *SimpleRefExpr = RefExpr;
9111 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9112 /*AllowArraySection=*/false);
9113 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009114 // It will be analyzed later.
9115 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009116 }
Alexey Bataev1efd1662016-03-29 10:59:56 +00009117 ValueDecl *D = Res.first;
9118 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009119 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009120
Alexey Bataev1efd1662016-03-29 10:59:56 +00009121 QualType QType = D->getType();
9122 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009123
9124 // OpenMP [2.8.1, simd construct, Restrictions]
9125 // The type of list items appearing in the aligned clause must be
9126 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009127 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009128 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +00009129 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009130 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +00009131 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009132 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +00009133 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009134 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +00009135 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009136 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +00009137 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009138 continue;
9139 }
9140
9141 // OpenMP [2.8.1, simd construct, Restrictions]
9142 // A list-item cannot appear in more than one aligned clause.
Alexey Bataev1efd1662016-03-29 10:59:56 +00009143 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00009144 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009145 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
9146 << getOpenMPClauseName(OMPC_aligned);
9147 continue;
9148 }
9149
Alexey Bataev1efd1662016-03-29 10:59:56 +00009150 DeclRefExpr *Ref = nullptr;
9151 if (!VD && IsOpenMPCapturedDecl(D))
9152 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
9153 Vars.push_back(DefaultFunctionArrayConversion(
9154 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
9155 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009156 }
9157
9158 // OpenMP [2.8.1, simd construct, Description]
9159 // The parameter of the aligned clause, alignment, must be a constant
9160 // positive integer expression.
9161 // If no optional parameter is specified, implementation-defined default
9162 // alignments for SIMD instructions on the target platforms are assumed.
9163 if (Alignment != nullptr) {
9164 ExprResult AlignResult =
9165 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
9166 if (AlignResult.isInvalid())
9167 return nullptr;
9168 Alignment = AlignResult.get();
9169 }
9170 if (Vars.empty())
9171 return nullptr;
9172
9173 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
9174 EndLoc, Vars, Alignment);
9175}
9176
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009177OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
9178 SourceLocation StartLoc,
9179 SourceLocation LParenLoc,
9180 SourceLocation EndLoc) {
9181 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009182 SmallVector<Expr *, 8> SrcExprs;
9183 SmallVector<Expr *, 8> DstExprs;
9184 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +00009185 for (auto &RefExpr : VarList) {
9186 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
9187 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009188 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009189 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009190 SrcExprs.push_back(nullptr);
9191 DstExprs.push_back(nullptr);
9192 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009193 continue;
9194 }
9195
Alexey Bataeved09d242014-05-28 05:53:51 +00009196 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009197 // OpenMP [2.1, C/C++]
9198 // A list item is a variable name.
9199 // OpenMP [2.14.4.1, Restrictions, p.1]
9200 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +00009201 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009202 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009203 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
9204 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009205 continue;
9206 }
9207
9208 Decl *D = DE->getDecl();
9209 VarDecl *VD = cast<VarDecl>(D);
9210
9211 QualType Type = VD->getType();
9212 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
9213 // It will be analyzed later.
9214 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009215 SrcExprs.push_back(nullptr);
9216 DstExprs.push_back(nullptr);
9217 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009218 continue;
9219 }
9220
9221 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
9222 // A list item that appears in a copyin clause must be threadprivate.
9223 if (!DSAStack->isThreadPrivate(VD)) {
9224 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +00009225 << getOpenMPClauseName(OMPC_copyin)
9226 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009227 continue;
9228 }
9229
9230 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9231 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +00009232 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009233 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009234 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009235 auto *SrcVD =
9236 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
9237 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00009238 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009239 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
9240 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009241 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
9242 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009243 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009244 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009245 // For arrays generate assignment operation for single element and replace
9246 // it by the original array element in CodeGen.
9247 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
9248 PseudoDstExpr, PseudoSrcExpr);
9249 if (AssignmentOp.isInvalid())
9250 continue;
9251 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
9252 /*DiscardedValue=*/true);
9253 if (AssignmentOp.isInvalid())
9254 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009255
9256 DSAStack->addDSA(VD, DE, OMPC_copyin);
9257 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009258 SrcExprs.push_back(PseudoSrcExpr);
9259 DstExprs.push_back(PseudoDstExpr);
9260 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009261 }
9262
Alexey Bataeved09d242014-05-28 05:53:51 +00009263 if (Vars.empty())
9264 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009265
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009266 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9267 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009268}
9269
Alexey Bataevbae9a792014-06-27 10:37:06 +00009270OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
9271 SourceLocation StartLoc,
9272 SourceLocation LParenLoc,
9273 SourceLocation EndLoc) {
9274 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +00009275 SmallVector<Expr *, 8> SrcExprs;
9276 SmallVector<Expr *, 8> DstExprs;
9277 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009278 for (auto &RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +00009279 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9280 SourceLocation ELoc;
9281 SourceRange ERange;
9282 Expr *SimpleRefExpr = RefExpr;
9283 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9284 /*AllowArraySection=*/false);
9285 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00009286 // It will be analyzed later.
9287 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +00009288 SrcExprs.push_back(nullptr);
9289 DstExprs.push_back(nullptr);
9290 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009291 }
Alexey Bataeve122da12016-03-17 10:50:17 +00009292 ValueDecl *D = Res.first;
9293 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +00009294 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009295
Alexey Bataeve122da12016-03-17 10:50:17 +00009296 QualType Type = D->getType();
9297 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009298
9299 // OpenMP [2.14.4.2, Restrictions, p.2]
9300 // A list item that appears in a copyprivate clause may not appear in a
9301 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +00009302 if (!VD || !DSAStack->isThreadPrivate(VD)) {
9303 auto DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +00009304 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
9305 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00009306 Diag(ELoc, diag::err_omp_wrong_dsa)
9307 << getOpenMPClauseName(DVar.CKind)
9308 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve122da12016-03-17 10:50:17 +00009309 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009310 continue;
9311 }
9312
9313 // OpenMP [2.11.4.2, Restrictions, p.1]
9314 // All list items that appear in a copyprivate clause must be either
9315 // threadprivate or private in the enclosing context.
9316 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +00009317 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009318 if (DVar.CKind == OMPC_shared) {
9319 Diag(ELoc, diag::err_omp_required_access)
9320 << getOpenMPClauseName(OMPC_copyprivate)
9321 << "threadprivate or private in the enclosing context";
Alexey Bataeve122da12016-03-17 10:50:17 +00009322 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009323 continue;
9324 }
9325 }
9326 }
9327
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009328 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009329 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009330 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009331 << getOpenMPClauseName(OMPC_copyprivate) << Type
9332 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009333 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +00009334 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009335 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +00009336 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009337 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +00009338 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009339 continue;
9340 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009341
Alexey Bataevbae9a792014-06-27 10:37:06 +00009342 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9343 // A variable of class type (or array thereof) that appears in a
9344 // copyin clause requires an accessible, unambiguous copy assignment
9345 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009346 Type = Context.getBaseElementType(Type.getNonReferenceType())
9347 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +00009348 auto *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +00009349 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
9350 D->hasAttrs() ? &D->getAttrs() : nullptr);
9351 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
Alexey Bataev420d45b2015-04-14 05:11:24 +00009352 auto *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +00009353 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
9354 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev420d45b2015-04-14 05:11:24 +00009355 auto *PseudoDstExpr =
Alexey Bataeve122da12016-03-17 10:50:17 +00009356 buildDeclRefExpr(*this, DstVD, Type, ELoc);
9357 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
Alexey Bataeva63048e2015-03-23 06:18:07 +00009358 PseudoDstExpr, PseudoSrcExpr);
9359 if (AssignmentOp.isInvalid())
9360 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +00009361 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +00009362 /*DiscardedValue=*/true);
9363 if (AssignmentOp.isInvalid())
9364 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009365
9366 // No need to mark vars as copyprivate, they are already threadprivate or
9367 // implicitly private.
Alexey Bataeve122da12016-03-17 10:50:17 +00009368 assert(VD || IsOpenMPCapturedDecl(D));
9369 Vars.push_back(
9370 VD ? RefExpr->IgnoreParens()
9371 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +00009372 SrcExprs.push_back(PseudoSrcExpr);
9373 DstExprs.push_back(PseudoDstExpr);
9374 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +00009375 }
9376
9377 if (Vars.empty())
9378 return nullptr;
9379
Alexey Bataeva63048e2015-03-23 06:18:07 +00009380 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9381 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009382}
9383
Alexey Bataev6125da92014-07-21 11:26:11 +00009384OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
9385 SourceLocation StartLoc,
9386 SourceLocation LParenLoc,
9387 SourceLocation EndLoc) {
9388 if (VarList.empty())
9389 return nullptr;
9390
9391 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
9392}
Alexey Bataevdea47612014-07-23 07:46:59 +00009393
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009394OMPClause *
9395Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
9396 SourceLocation DepLoc, SourceLocation ColonLoc,
9397 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9398 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00009399 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009400 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +00009401 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009402 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +00009403 return nullptr;
9404 }
9405 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009406 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
9407 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +00009408 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009409 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009410 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
9411 /*Last=*/OMPC_DEPEND_unknown, Except)
9412 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009413 return nullptr;
9414 }
9415 SmallVector<Expr *, 8> Vars;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009416 llvm::APSInt DepCounter(/*BitWidth=*/32);
9417 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
9418 if (DepKind == OMPC_DEPEND_sink) {
9419 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
9420 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
9421 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009422 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009423 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009424 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
9425 DSAStack->getParentOrderedRegionParam()) {
9426 for (auto &RefExpr : VarList) {
9427 assert(RefExpr && "NULL expr in OpenMP shared clause.");
9428 if (isa<DependentScopeDeclRefExpr>(RefExpr) ||
9429 (DepKind == OMPC_DEPEND_sink && CurContext->isDependentContext())) {
9430 // It will be analyzed later.
9431 Vars.push_back(RefExpr);
9432 continue;
9433 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009434
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009435 SourceLocation ELoc = RefExpr->getExprLoc();
9436 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
9437 if (DepKind == OMPC_DEPEND_sink) {
9438 if (DepCounter >= TotalDepCount) {
9439 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
9440 continue;
9441 }
9442 ++DepCounter;
9443 // OpenMP [2.13.9, Summary]
9444 // depend(dependence-type : vec), where dependence-type is:
9445 // 'sink' and where vec is the iteration vector, which has the form:
9446 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
9447 // where n is the value specified by the ordered clause in the loop
9448 // directive, xi denotes the loop iteration variable of the i-th nested
9449 // loop associated with the loop directive, and di is a constant
9450 // non-negative integer.
9451 SimpleExpr = SimpleExpr->IgnoreImplicit();
9452 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
9453 if (!DE) {
9454 OverloadedOperatorKind OOK = OO_None;
9455 SourceLocation OOLoc;
9456 Expr *LHS, *RHS;
9457 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
9458 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
9459 OOLoc = BO->getOperatorLoc();
9460 LHS = BO->getLHS()->IgnoreParenImpCasts();
9461 RHS = BO->getRHS()->IgnoreParenImpCasts();
9462 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
9463 OOK = OCE->getOperator();
9464 OOLoc = OCE->getOperatorLoc();
9465 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9466 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
9467 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
9468 OOK = MCE->getMethodDecl()
9469 ->getNameInfo()
9470 .getName()
9471 .getCXXOverloadedOperator();
9472 OOLoc = MCE->getCallee()->getExprLoc();
9473 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
9474 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9475 } else {
9476 Diag(ELoc, diag::err_omp_depend_sink_wrong_expr);
9477 continue;
9478 }
9479 DE = dyn_cast<DeclRefExpr>(LHS);
9480 if (!DE) {
9481 Diag(LHS->getExprLoc(),
9482 diag::err_omp_depend_sink_expected_loop_iteration)
9483 << DSAStack->getParentLoopControlVariable(
9484 DepCounter.getZExtValue());
9485 continue;
9486 }
9487 if (OOK != OO_Plus && OOK != OO_Minus) {
9488 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
9489 continue;
9490 }
9491 ExprResult Res = VerifyPositiveIntegerConstantInClause(
9492 RHS, OMPC_depend, /*StrictlyPositive=*/false);
9493 if (Res.isInvalid())
9494 continue;
9495 }
9496 auto *VD = dyn_cast<VarDecl>(DE->getDecl());
9497 if (!CurContext->isDependentContext() &&
9498 DSAStack->getParentOrderedRegionParam() &&
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00009499 (!VD ||
9500 DepCounter != DSAStack->isParentLoopControlVariable(VD).first)) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009501 Diag(DE->getExprLoc(),
9502 diag::err_omp_depend_sink_expected_loop_iteration)
9503 << DSAStack->getParentLoopControlVariable(
9504 DepCounter.getZExtValue());
9505 continue;
9506 }
9507 } else {
9508 // OpenMP [2.11.1.1, Restrictions, p.3]
9509 // A variable that is part of another variable (such as a field of a
9510 // structure) but is not an array element or an array section cannot
9511 // appear in a depend clause.
9512 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
9513 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
9514 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
9515 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
9516 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
Alexey Bataev31300ed2016-02-04 11:27:03 +00009517 (ASE &&
9518 !ASE->getBase()
9519 ->getType()
9520 .getNonReferenceType()
9521 ->isPointerType() &&
9522 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009523 Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item)
9524 << 0 << RefExpr->getSourceRange();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009525 continue;
9526 }
9527 }
9528
9529 Vars.push_back(RefExpr->IgnoreParenImpCasts());
9530 }
9531
9532 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
9533 TotalDepCount > VarList.size() &&
9534 DSAStack->getParentOrderedRegionParam()) {
9535 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
9536 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
9537 }
9538 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
9539 Vars.empty())
9540 return nullptr;
9541 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009542
9543 return OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, DepKind,
9544 DepLoc, ColonLoc, Vars);
9545}
Michael Wonge710d542015-08-07 16:16:36 +00009546
9547OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
9548 SourceLocation LParenLoc,
9549 SourceLocation EndLoc) {
9550 Expr *ValExpr = Device;
Michael Wonge710d542015-08-07 16:16:36 +00009551
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009552 // OpenMP [2.9.1, Restrictions]
9553 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00009554 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
9555 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009556 return nullptr;
9557
Michael Wonge710d542015-08-07 16:16:36 +00009558 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9559}
Kelvin Li0bff7af2015-11-23 05:32:03 +00009560
9561static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
9562 DSAStackTy *Stack, CXXRecordDecl *RD) {
9563 if (!RD || RD->isInvalidDecl())
9564 return true;
9565
Alexey Bataevc9bd03d2015-12-17 06:55:08 +00009566 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
9567 if (auto *CTD = CTSD->getSpecializedTemplate())
9568 RD = CTD->getTemplatedDecl();
Kelvin Li0bff7af2015-11-23 05:32:03 +00009569 auto QTy = SemaRef.Context.getRecordType(RD);
9570 if (RD->isDynamicClass()) {
9571 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9572 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
9573 return false;
9574 }
9575 auto *DC = RD;
9576 bool IsCorrect = true;
9577 for (auto *I : DC->decls()) {
9578 if (I) {
9579 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
9580 if (MD->isStatic()) {
9581 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9582 SemaRef.Diag(MD->getLocation(),
9583 diag::note_omp_static_member_in_target);
9584 IsCorrect = false;
9585 }
9586 } else if (auto *VD = dyn_cast<VarDecl>(I)) {
9587 if (VD->isStaticDataMember()) {
9588 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9589 SemaRef.Diag(VD->getLocation(),
9590 diag::note_omp_static_member_in_target);
9591 IsCorrect = false;
9592 }
9593 }
9594 }
9595 }
9596
9597 for (auto &I : RD->bases()) {
9598 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
9599 I.getType()->getAsCXXRecordDecl()))
9600 IsCorrect = false;
9601 }
9602 return IsCorrect;
9603}
9604
9605static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
9606 DSAStackTy *Stack, QualType QTy) {
9607 NamedDecl *ND;
9608 if (QTy->isIncompleteType(&ND)) {
9609 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
9610 return false;
9611 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
9612 if (!RD->isInvalidDecl() &&
9613 !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
9614 return false;
9615 }
9616 return true;
9617}
9618
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009619/// \brief Return true if it can be proven that the provided array expression
9620/// (array section or array subscript) does NOT specify the whole size of the
9621/// array whose base type is \a BaseQTy.
9622static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
9623 const Expr *E,
9624 QualType BaseQTy) {
9625 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
9626
9627 // If this is an array subscript, it refers to the whole size if the size of
9628 // the dimension is constant and equals 1. Also, an array section assumes the
9629 // format of an array subscript if no colon is used.
9630 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
9631 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
9632 return ATy->getSize().getSExtValue() != 1;
9633 // Size can't be evaluated statically.
9634 return false;
9635 }
9636
9637 assert(OASE && "Expecting array section if not an array subscript.");
9638 auto *LowerBound = OASE->getLowerBound();
9639 auto *Length = OASE->getLength();
9640
9641 // If there is a lower bound that does not evaluates to zero, we are not
9642 // convering the whole dimension.
9643 if (LowerBound) {
9644 llvm::APSInt ConstLowerBound;
9645 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
9646 return false; // Can't get the integer value as a constant.
9647 if (ConstLowerBound.getSExtValue())
9648 return true;
9649 }
9650
9651 // If we don't have a length we covering the whole dimension.
9652 if (!Length)
9653 return false;
9654
9655 // If the base is a pointer, we don't have a way to get the size of the
9656 // pointee.
9657 if (BaseQTy->isPointerType())
9658 return false;
9659
9660 // We can only check if the length is the same as the size of the dimension
9661 // if we have a constant array.
9662 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
9663 if (!CATy)
9664 return false;
9665
9666 llvm::APSInt ConstLength;
9667 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
9668 return false; // Can't get the integer value as a constant.
9669
9670 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
9671}
9672
9673// Return true if it can be proven that the provided array expression (array
9674// section or array subscript) does NOT specify a single element of the array
9675// whose base type is \a BaseQTy.
9676static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
9677 const Expr *E,
9678 QualType BaseQTy) {
9679 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
9680
9681 // An array subscript always refer to a single element. Also, an array section
9682 // assumes the format of an array subscript if no colon is used.
9683 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
9684 return false;
9685
9686 assert(OASE && "Expecting array section if not an array subscript.");
9687 auto *Length = OASE->getLength();
9688
9689 // If we don't have a length we have to check if the array has unitary size
9690 // for this dimension. Also, we should always expect a length if the base type
9691 // is pointer.
9692 if (!Length) {
9693 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
9694 return ATy->getSize().getSExtValue() != 1;
9695 // We cannot assume anything.
9696 return false;
9697 }
9698
9699 // Check if the length evaluates to 1.
9700 llvm::APSInt ConstLength;
9701 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
9702 return false; // Can't get the integer value as a constant.
9703
9704 return ConstLength.getSExtValue() != 1;
9705}
9706
Samuel Antao5de996e2016-01-22 20:21:36 +00009707// Return the expression of the base of the map clause or null if it cannot
9708// be determined and do all the necessary checks to see if the expression is
9709// valid as a standalone map clause expression.
9710static Expr *CheckMapClauseExpressionBase(Sema &SemaRef, Expr *E) {
9711 SourceLocation ELoc = E->getExprLoc();
9712 SourceRange ERange = E->getSourceRange();
9713
9714 // The base of elements of list in a map clause have to be either:
9715 // - a reference to variable or field.
9716 // - a member expression.
9717 // - an array expression.
9718 //
9719 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
9720 // reference to 'r'.
9721 //
9722 // If we have:
9723 //
9724 // struct SS {
9725 // Bla S;
9726 // foo() {
9727 // #pragma omp target map (S.Arr[:12]);
9728 // }
9729 // }
9730 //
9731 // We want to retrieve the member expression 'this->S';
9732
9733 Expr *RelevantExpr = nullptr;
9734
Samuel Antao5de996e2016-01-22 20:21:36 +00009735 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
9736 // If a list item is an array section, it must specify contiguous storage.
9737 //
9738 // For this restriction it is sufficient that we make sure only references
9739 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009740 // exist except in the rightmost expression (unless they cover the whole
9741 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +00009742 //
9743 // r.ArrS[3:5].Arr[6:7]
9744 //
9745 // r.ArrS[3:5].x
9746 //
9747 // but these would be valid:
9748 // r.ArrS[3].Arr[6:7]
9749 //
9750 // r.ArrS[3].x
9751
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009752 bool AllowUnitySizeArraySection = true;
9753 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +00009754
Dmitry Polukhin644a9252016-03-11 07:58:34 +00009755 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009756 E = E->IgnoreParenImpCasts();
9757
9758 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
9759 if (!isa<VarDecl>(CurE->getDecl()))
9760 break;
9761
9762 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009763
9764 // If we got a reference to a declaration, we should not expect any array
9765 // section before that.
9766 AllowUnitySizeArraySection = false;
9767 AllowWholeSizeArraySection = false;
Samuel Antao5de996e2016-01-22 20:21:36 +00009768 continue;
9769 }
9770
9771 if (auto *CurE = dyn_cast<MemberExpr>(E)) {
9772 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
9773
9774 if (isa<CXXThisExpr>(BaseE))
9775 // We found a base expression: this->Val.
9776 RelevantExpr = CurE;
9777 else
9778 E = BaseE;
9779
9780 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
9781 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
9782 << CurE->getSourceRange();
9783 break;
9784 }
9785
9786 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
9787
9788 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
9789 // A bit-field cannot appear in a map clause.
9790 //
9791 if (FD->isBitField()) {
9792 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_map_clause)
9793 << CurE->getSourceRange();
9794 break;
9795 }
9796
9797 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9798 // If the type of a list item is a reference to a type T then the type
9799 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009800 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +00009801
9802 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
9803 // A list item cannot be a variable that is a member of a structure with
9804 // a union type.
9805 //
9806 if (auto *RT = CurType->getAs<RecordType>())
9807 if (RT->isUnionType()) {
9808 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
9809 << CurE->getSourceRange();
9810 break;
9811 }
9812
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009813 // If we got a member expression, we should not expect any array section
9814 // before that:
9815 //
9816 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
9817 // If a list item is an element of a structure, only the rightmost symbol
9818 // of the variable reference can be an array section.
9819 //
9820 AllowUnitySizeArraySection = false;
9821 AllowWholeSizeArraySection = false;
Samuel Antao5de996e2016-01-22 20:21:36 +00009822 continue;
9823 }
9824
9825 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
9826 E = CurE->getBase()->IgnoreParenImpCasts();
9827
9828 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
9829 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
9830 << 0 << CurE->getSourceRange();
9831 break;
9832 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009833
9834 // If we got an array subscript that express the whole dimension we
9835 // can have any array expressions before. If it only expressing part of
9836 // the dimension, we can only have unitary-size array expressions.
9837 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
9838 E->getType()))
9839 AllowWholeSizeArraySection = false;
Samuel Antao5de996e2016-01-22 20:21:36 +00009840 continue;
9841 }
9842
9843 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009844 E = CurE->getBase()->IgnoreParenImpCasts();
9845
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009846 auto CurType =
9847 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
9848
Samuel Antao5de996e2016-01-22 20:21:36 +00009849 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9850 // If the type of a list item is a reference to a type T then the type
9851 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +00009852 if (CurType->isReferenceType())
9853 CurType = CurType->getPointeeType();
9854
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009855 bool IsPointer = CurType->isAnyPointerType();
9856
9857 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009858 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
9859 << 0 << CurE->getSourceRange();
9860 break;
9861 }
9862
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009863 bool NotWhole =
9864 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
9865 bool NotUnity =
9866 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
9867
9868 if (AllowWholeSizeArraySection && AllowUnitySizeArraySection) {
9869 // Any array section is currently allowed.
9870 //
9871 // If this array section refers to the whole dimension we can still
9872 // accept other array sections before this one, except if the base is a
9873 // pointer. Otherwise, only unitary sections are accepted.
9874 if (NotWhole || IsPointer)
9875 AllowWholeSizeArraySection = false;
9876 } else if ((AllowUnitySizeArraySection && NotUnity) ||
9877 (AllowWholeSizeArraySection && NotWhole)) {
9878 // A unity or whole array section is not allowed and that is not
9879 // compatible with the properties of the current array section.
9880 SemaRef.Diag(
9881 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
9882 << CurE->getSourceRange();
9883 break;
9884 }
Samuel Antao5de996e2016-01-22 20:21:36 +00009885 continue;
9886 }
9887
9888 // If nothing else worked, this is not a valid map clause expression.
9889 SemaRef.Diag(ELoc,
9890 diag::err_omp_expected_named_var_member_or_array_expression)
9891 << ERange;
9892 break;
9893 }
9894
9895 return RelevantExpr;
9896}
9897
9898// Return true if expression E associated with value VD has conflicts with other
9899// map information.
9900static bool CheckMapConflicts(Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD,
9901 Expr *E, bool CurrentRegionOnly) {
9902 assert(VD && E);
9903
9904 // Types used to organize the components of a valid map clause.
9905 typedef std::pair<Expr *, ValueDecl *> MapExpressionComponent;
9906 typedef SmallVector<MapExpressionComponent, 4> MapExpressionComponents;
9907
9908 // Helper to extract the components in the map clause expression E and store
9909 // them into MEC. This assumes that E is a valid map clause expression, i.e.
9910 // it has already passed the single clause checks.
9911 auto ExtractMapExpressionComponents = [](Expr *TE,
9912 MapExpressionComponents &MEC) {
9913 while (true) {
9914 TE = TE->IgnoreParenImpCasts();
9915
9916 if (auto *CurE = dyn_cast<DeclRefExpr>(TE)) {
9917 MEC.push_back(
9918 MapExpressionComponent(CurE, cast<VarDecl>(CurE->getDecl())));
9919 break;
9920 }
9921
9922 if (auto *CurE = dyn_cast<MemberExpr>(TE)) {
9923 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
9924
9925 MEC.push_back(MapExpressionComponent(
9926 CurE, cast<FieldDecl>(CurE->getMemberDecl())));
9927 if (isa<CXXThisExpr>(BaseE))
9928 break;
9929
9930 TE = BaseE;
9931 continue;
9932 }
9933
9934 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(TE)) {
9935 MEC.push_back(MapExpressionComponent(CurE, nullptr));
9936 TE = CurE->getBase()->IgnoreParenImpCasts();
9937 continue;
9938 }
9939
9940 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(TE)) {
9941 MEC.push_back(MapExpressionComponent(CurE, nullptr));
9942 TE = CurE->getBase()->IgnoreParenImpCasts();
9943 continue;
9944 }
9945
9946 llvm_unreachable(
9947 "Expecting only valid map clause expressions at this point!");
9948 }
9949 };
9950
9951 SourceLocation ELoc = E->getExprLoc();
9952 SourceRange ERange = E->getSourceRange();
9953
9954 // In order to easily check the conflicts we need to match each component of
9955 // the expression under test with the components of the expressions that are
9956 // already in the stack.
9957
9958 MapExpressionComponents CurComponents;
9959 ExtractMapExpressionComponents(E, CurComponents);
9960
9961 assert(!CurComponents.empty() && "Map clause expression with no components!");
9962 assert(CurComponents.back().second == VD &&
9963 "Map clause expression with unexpected base!");
9964
9965 // Variables to help detecting enclosing problems in data environment nests.
9966 bool IsEnclosedByDataEnvironmentExpr = false;
9967 Expr *EnclosingExpr = nullptr;
9968
9969 bool FoundError =
9970 DSAS->checkMapInfoForVar(VD, CurrentRegionOnly, [&](Expr *RE) -> bool {
9971 MapExpressionComponents StackComponents;
9972 ExtractMapExpressionComponents(RE, StackComponents);
9973 assert(!StackComponents.empty() &&
9974 "Map clause expression with no components!");
9975 assert(StackComponents.back().second == VD &&
9976 "Map clause expression with unexpected base!");
9977
9978 // Expressions must start from the same base. Here we detect at which
9979 // point both expressions diverge from each other and see if we can
9980 // detect if the memory referred to both expressions is contiguous and
9981 // do not overlap.
9982 auto CI = CurComponents.rbegin();
9983 auto CE = CurComponents.rend();
9984 auto SI = StackComponents.rbegin();
9985 auto SE = StackComponents.rend();
9986 for (; CI != CE && SI != SE; ++CI, ++SI) {
9987
9988 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
9989 // At most one list item can be an array item derived from a given
9990 // variable in map clauses of the same construct.
9991 if (CurrentRegionOnly && (isa<ArraySubscriptExpr>(CI->first) ||
9992 isa<OMPArraySectionExpr>(CI->first)) &&
9993 (isa<ArraySubscriptExpr>(SI->first) ||
9994 isa<OMPArraySectionExpr>(SI->first))) {
9995 SemaRef.Diag(CI->first->getExprLoc(),
9996 diag::err_omp_multiple_array_items_in_map_clause)
9997 << CI->first->getSourceRange();
9998 ;
9999 SemaRef.Diag(SI->first->getExprLoc(), diag::note_used_here)
10000 << SI->first->getSourceRange();
10001 return true;
10002 }
10003
10004 // Do both expressions have the same kind?
10005 if (CI->first->getStmtClass() != SI->first->getStmtClass())
10006 break;
10007
10008 // Are we dealing with different variables/fields?
10009 if (CI->second != SI->second)
10010 break;
10011 }
10012
10013 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10014 // List items of map clauses in the same construct must not share
10015 // original storage.
10016 //
10017 // If the expressions are exactly the same or one is a subset of the
10018 // other, it means they are sharing storage.
10019 if (CI == CE && SI == SE) {
10020 if (CurrentRegionOnly) {
10021 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10022 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10023 << RE->getSourceRange();
10024 return true;
10025 } else {
10026 // If we find the same expression in the enclosing data environment,
10027 // that is legal.
10028 IsEnclosedByDataEnvironmentExpr = true;
10029 return false;
10030 }
10031 }
10032
10033 QualType DerivedType = std::prev(CI)->first->getType();
10034 SourceLocation DerivedLoc = std::prev(CI)->first->getExprLoc();
10035
10036 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10037 // If the type of a list item is a reference to a type T then the type
10038 // will be considered to be T for all purposes of this clause.
10039 if (DerivedType->isReferenceType())
10040 DerivedType = DerivedType->getPointeeType();
10041
10042 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
10043 // A variable for which the type is pointer and an array section
10044 // derived from that variable must not appear as list items of map
10045 // clauses of the same construct.
10046 //
10047 // Also, cover one of the cases in:
10048 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10049 // If any part of the original storage of a list item has corresponding
10050 // storage in the device data environment, all of the original storage
10051 // must have corresponding storage in the device data environment.
10052 //
10053 if (DerivedType->isAnyPointerType()) {
10054 if (CI == CE || SI == SE) {
10055 SemaRef.Diag(
10056 DerivedLoc,
10057 diag::err_omp_pointer_mapped_along_with_derived_section)
10058 << DerivedLoc;
10059 } else {
10060 assert(CI != CE && SI != SE);
10061 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
10062 << DerivedLoc;
10063 }
10064 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10065 << RE->getSourceRange();
10066 return true;
10067 }
10068
10069 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10070 // List items of map clauses in the same construct must not share
10071 // original storage.
10072 //
10073 // An expression is a subset of the other.
10074 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
10075 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10076 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10077 << RE->getSourceRange();
10078 return true;
10079 }
10080
10081 // The current expression uses the same base as other expression in the
10082 // data environment but does not contain it completelly.
10083 if (!CurrentRegionOnly && SI != SE)
10084 EnclosingExpr = RE;
10085
10086 // The current expression is a subset of the expression in the data
10087 // environment.
10088 IsEnclosedByDataEnvironmentExpr |=
10089 (!CurrentRegionOnly && CI != CE && SI == SE);
10090
10091 return false;
10092 });
10093
10094 if (CurrentRegionOnly)
10095 return FoundError;
10096
10097 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10098 // If any part of the original storage of a list item has corresponding
10099 // storage in the device data environment, all of the original storage must
10100 // have corresponding storage in the device data environment.
10101 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
10102 // If a list item is an element of a structure, and a different element of
10103 // the structure has a corresponding list item in the device data environment
10104 // prior to a task encountering the construct associated with the map clause,
10105 // then the list item must also have a correspnding list item in the device
10106 // data environment prior to the task encountering the construct.
10107 //
10108 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
10109 SemaRef.Diag(ELoc,
10110 diag::err_omp_original_storage_is_shared_and_does_not_contain)
10111 << ERange;
10112 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
10113 << EnclosingExpr->getSourceRange();
10114 return true;
10115 }
10116
10117 return FoundError;
10118}
10119
Samuel Antao23abd722016-01-19 20:40:49 +000010120OMPClause *
10121Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
10122 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
10123 SourceLocation MapLoc, SourceLocation ColonLoc,
10124 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10125 SourceLocation LParenLoc, SourceLocation EndLoc) {
Kelvin Li0bff7af2015-11-23 05:32:03 +000010126 SmallVector<Expr *, 4> Vars;
10127
10128 for (auto &RE : VarList) {
10129 assert(RE && "Null expr in omp map");
10130 if (isa<DependentScopeDeclRefExpr>(RE)) {
10131 // It will be analyzed later.
10132 Vars.push_back(RE);
10133 continue;
10134 }
10135 SourceLocation ELoc = RE->getExprLoc();
10136
Kelvin Li0bff7af2015-11-23 05:32:03 +000010137 auto *VE = RE->IgnoreParenLValueCasts();
10138
10139 if (VE->isValueDependent() || VE->isTypeDependent() ||
10140 VE->isInstantiationDependent() ||
10141 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010142 // We can only analyze this information once the missing information is
10143 // resolved.
Kelvin Li0bff7af2015-11-23 05:32:03 +000010144 Vars.push_back(RE);
10145 continue;
10146 }
10147
10148 auto *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000010149
Samuel Antao5de996e2016-01-22 20:21:36 +000010150 if (!RE->IgnoreParenImpCasts()->isLValue()) {
10151 Diag(ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
10152 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000010153 continue;
10154 }
10155
Samuel Antao5de996e2016-01-22 20:21:36 +000010156 // Obtain the array or member expression bases if required.
10157 auto *BE = CheckMapClauseExpressionBase(*this, SimpleExpr);
10158 if (!BE)
10159 continue;
10160
10161 // If the base is a reference to a variable, we rely on that variable for
10162 // the following checks. If it is a 'this' expression we rely on the field.
10163 ValueDecl *D = nullptr;
10164 if (auto *DRE = dyn_cast<DeclRefExpr>(BE)) {
10165 D = DRE->getDecl();
10166 } else {
10167 auto *ME = cast<MemberExpr>(BE);
10168 assert(isa<CXXThisExpr>(ME->getBase()) && "Unexpected expression!");
10169 D = ME->getMemberDecl();
Kelvin Li0bff7af2015-11-23 05:32:03 +000010170 }
10171 assert(D && "Null decl on map clause.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010172
Samuel Antao5de996e2016-01-22 20:21:36 +000010173 auto *VD = dyn_cast<VarDecl>(D);
10174 auto *FD = dyn_cast<FieldDecl>(D);
10175
10176 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000010177 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000010178
10179 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
10180 // threadprivate variables cannot appear in a map clause.
10181 if (VD && DSAStack->isThreadPrivate(VD)) {
Kelvin Li0bff7af2015-11-23 05:32:03 +000010182 auto DVar = DSAStack->getTopDSA(VD, false);
10183 Diag(ELoc, diag::err_omp_threadprivate_in_map);
10184 ReportOriginalDSA(*this, DSAStack, VD, DVar);
10185 continue;
10186 }
10187
Samuel Antao5de996e2016-01-22 20:21:36 +000010188 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
10189 // A list item cannot appear in both a map clause and a data-sharing
10190 // attribute clause on the same construct.
10191 //
10192 // TODO: Implement this check - it cannot currently be tested because of
10193 // missing implementation of the other data sharing clauses in target
10194 // directives.
Kelvin Li0bff7af2015-11-23 05:32:03 +000010195
Samuel Antao5de996e2016-01-22 20:21:36 +000010196 // Check conflicts with other map clause expressions. We check the conflicts
10197 // with the current construct separately from the enclosing data
10198 // environment, because the restrictions are different.
10199 if (CheckMapConflicts(*this, DSAStack, D, SimpleExpr,
10200 /*CurrentRegionOnly=*/true))
10201 break;
10202 if (CheckMapConflicts(*this, DSAStack, D, SimpleExpr,
10203 /*CurrentRegionOnly=*/false))
10204 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000010205
Samuel Antao5de996e2016-01-22 20:21:36 +000010206 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10207 // If the type of a list item is a reference to a type T then the type will
10208 // be considered to be T for all purposes of this clause.
10209 QualType Type = D->getType();
10210 if (Type->isReferenceType())
10211 Type = Type->getPointeeType();
10212
10213 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000010214 // A list item must have a mappable type.
10215 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), *this,
10216 DSAStack, Type))
10217 continue;
10218
Samuel Antaodf67fc42016-01-19 19:15:56 +000010219 // target enter data
10220 // OpenMP [2.10.2, Restrictions, p. 99]
10221 // A map-type must be specified in all map clauses and must be either
10222 // to or alloc.
10223 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
10224 if (DKind == OMPD_target_enter_data &&
10225 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
10226 Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
Samuel Antao23abd722016-01-19 20:40:49 +000010227 << (IsMapTypeImplicit ? 1 : 0)
10228 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
Samuel Antaodf67fc42016-01-19 19:15:56 +000010229 << getOpenMPDirectiveName(DKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000010230 continue;
Samuel Antaodf67fc42016-01-19 19:15:56 +000010231 }
10232
Samuel Antao72590762016-01-19 20:04:50 +000010233 // target exit_data
10234 // OpenMP [2.10.3, Restrictions, p. 102]
10235 // A map-type must be specified in all map clauses and must be either
10236 // from, release, or delete.
10237 DKind = DSAStack->getCurrentDirective();
10238 if (DKind == OMPD_target_exit_data &&
10239 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
10240 MapType == OMPC_MAP_delete)) {
10241 Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
Samuel Antao23abd722016-01-19 20:40:49 +000010242 << (IsMapTypeImplicit ? 1 : 0)
10243 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
Samuel Antao72590762016-01-19 20:04:50 +000010244 << getOpenMPDirectiveName(DKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000010245 continue;
Samuel Antao72590762016-01-19 20:04:50 +000010246 }
10247
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010248 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10249 // A list item cannot appear in both a map clause and a data-sharing
10250 // attribute clause on the same construct
10251 if (DKind == OMPD_target && VD) {
10252 auto DVar = DSAStack->getTopDSA(VD, false);
10253 if (isOpenMPPrivate(DVar.CKind)) {
10254 Diag(ELoc, diag::err_omp_variable_in_map_and_dsa)
10255 << getOpenMPClauseName(DVar.CKind)
10256 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
10257 ReportOriginalDSA(*this, DSAStack, D, DVar);
10258 continue;
10259 }
10260 }
10261
Kelvin Li0bff7af2015-11-23 05:32:03 +000010262 Vars.push_back(RE);
Samuel Antao5de996e2016-01-22 20:21:36 +000010263 DSAStack->addExprToVarMapInfo(D, RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010264 }
Kelvin Li0bff7af2015-11-23 05:32:03 +000010265
Samuel Antao5de996e2016-01-22 20:21:36 +000010266 // We need to produce a map clause even if we don't have variables so that
10267 // other diagnostics related with non-existing map clauses are accurate.
Kelvin Li0bff7af2015-11-23 05:32:03 +000010268 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
Samuel Antao23abd722016-01-19 20:40:49 +000010269 MapTypeModifier, MapType, IsMapTypeImplicit,
10270 MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010271}
Kelvin Li099bb8c2015-11-24 20:50:12 +000010272
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010273QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
10274 TypeResult ParsedType) {
10275 assert(ParsedType.isUsable());
10276
10277 QualType ReductionType = GetTypeFromParser(ParsedType.get());
10278 if (ReductionType.isNull())
10279 return QualType();
10280
10281 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
10282 // A type name in a declare reduction directive cannot be a function type, an
10283 // array type, a reference type, or a type qualified with const, volatile or
10284 // restrict.
10285 if (ReductionType.hasQualifiers()) {
10286 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
10287 return QualType();
10288 }
10289
10290 if (ReductionType->isFunctionType()) {
10291 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
10292 return QualType();
10293 }
10294 if (ReductionType->isReferenceType()) {
10295 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
10296 return QualType();
10297 }
10298 if (ReductionType->isArrayType()) {
10299 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
10300 return QualType();
10301 }
10302 return ReductionType;
10303}
10304
10305Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
10306 Scope *S, DeclContext *DC, DeclarationName Name,
10307 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
10308 AccessSpecifier AS, Decl *PrevDeclInScope) {
10309 SmallVector<Decl *, 8> Decls;
10310 Decls.reserve(ReductionTypes.size());
10311
10312 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
10313 ForRedeclaration);
10314 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
10315 // A reduction-identifier may not be re-declared in the current scope for the
10316 // same type or for a type that is compatible according to the base language
10317 // rules.
10318 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
10319 OMPDeclareReductionDecl *PrevDRD = nullptr;
10320 bool InCompoundScope = true;
10321 if (S != nullptr) {
10322 // Find previous declaration with the same name not referenced in other
10323 // declarations.
10324 FunctionScopeInfo *ParentFn = getEnclosingFunction();
10325 InCompoundScope =
10326 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
10327 LookupName(Lookup, S);
10328 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
10329 /*AllowInlineNamespace=*/false);
10330 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
10331 auto Filter = Lookup.makeFilter();
10332 while (Filter.hasNext()) {
10333 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
10334 if (InCompoundScope) {
10335 auto I = UsedAsPrevious.find(PrevDecl);
10336 if (I == UsedAsPrevious.end())
10337 UsedAsPrevious[PrevDecl] = false;
10338 if (auto *D = PrevDecl->getPrevDeclInScope())
10339 UsedAsPrevious[D] = true;
10340 }
10341 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
10342 PrevDecl->getLocation();
10343 }
10344 Filter.done();
10345 if (InCompoundScope) {
10346 for (auto &PrevData : UsedAsPrevious) {
10347 if (!PrevData.second) {
10348 PrevDRD = PrevData.first;
10349 break;
10350 }
10351 }
10352 }
10353 } else if (PrevDeclInScope != nullptr) {
10354 auto *PrevDRDInScope = PrevDRD =
10355 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
10356 do {
10357 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
10358 PrevDRDInScope->getLocation();
10359 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
10360 } while (PrevDRDInScope != nullptr);
10361 }
10362 for (auto &TyData : ReductionTypes) {
10363 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
10364 bool Invalid = false;
10365 if (I != PreviousRedeclTypes.end()) {
10366 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
10367 << TyData.first;
10368 Diag(I->second, diag::note_previous_definition);
10369 Invalid = true;
10370 }
10371 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
10372 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
10373 Name, TyData.first, PrevDRD);
10374 DC->addDecl(DRD);
10375 DRD->setAccess(AS);
10376 Decls.push_back(DRD);
10377 if (Invalid)
10378 DRD->setInvalidDecl();
10379 else
10380 PrevDRD = DRD;
10381 }
10382
10383 return DeclGroupPtrTy::make(
10384 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
10385}
10386
10387void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
10388 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10389
10390 // Enter new function scope.
10391 PushFunctionScope();
10392 getCurFunction()->setHasBranchProtectedScope();
10393 getCurFunction()->setHasOMPDeclareReductionCombiner();
10394
10395 if (S != nullptr)
10396 PushDeclContext(S, DRD);
10397 else
10398 CurContext = DRD;
10399
10400 PushExpressionEvaluationContext(PotentiallyEvaluated);
10401
10402 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010403 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
10404 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
10405 // uses semantics of argument handles by value, but it should be passed by
10406 // reference. C lang does not support references, so pass all parameters as
10407 // pointers.
10408 // Create 'T omp_in;' variable.
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010409 auto *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010410 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010411 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
10412 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
10413 // uses semantics of argument handles by value, but it should be passed by
10414 // reference. C lang does not support references, so pass all parameters as
10415 // pointers.
10416 // Create 'T omp_out;' variable.
10417 auto *OmpOutParm =
10418 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
10419 if (S != nullptr) {
10420 PushOnScopeChains(OmpInParm, S);
10421 PushOnScopeChains(OmpOutParm, S);
10422 } else {
10423 DRD->addDecl(OmpInParm);
10424 DRD->addDecl(OmpOutParm);
10425 }
10426}
10427
10428void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
10429 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10430 DiscardCleanupsInEvaluationContext();
10431 PopExpressionEvaluationContext();
10432
10433 PopDeclContext();
10434 PopFunctionScopeInfo();
10435
10436 if (Combiner != nullptr)
10437 DRD->setCombiner(Combiner);
10438 else
10439 DRD->setInvalidDecl();
10440}
10441
10442void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
10443 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10444
10445 // Enter new function scope.
10446 PushFunctionScope();
10447 getCurFunction()->setHasBranchProtectedScope();
10448
10449 if (S != nullptr)
10450 PushDeclContext(S, DRD);
10451 else
10452 CurContext = DRD;
10453
10454 PushExpressionEvaluationContext(PotentiallyEvaluated);
10455
10456 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010457 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
10458 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
10459 // uses semantics of argument handles by value, but it should be passed by
10460 // reference. C lang does not support references, so pass all parameters as
10461 // pointers.
10462 // Create 'T omp_priv;' variable.
10463 auto *OmpPrivParm =
10464 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010465 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
10466 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
10467 // uses semantics of argument handles by value, but it should be passed by
10468 // reference. C lang does not support references, so pass all parameters as
10469 // pointers.
10470 // Create 'T omp_orig;' variable.
10471 auto *OmpOrigParm =
10472 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010473 if (S != nullptr) {
10474 PushOnScopeChains(OmpPrivParm, S);
10475 PushOnScopeChains(OmpOrigParm, S);
10476 } else {
10477 DRD->addDecl(OmpPrivParm);
10478 DRD->addDecl(OmpOrigParm);
10479 }
10480}
10481
10482void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D,
10483 Expr *Initializer) {
10484 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10485 DiscardCleanupsInEvaluationContext();
10486 PopExpressionEvaluationContext();
10487
10488 PopDeclContext();
10489 PopFunctionScopeInfo();
10490
10491 if (Initializer != nullptr)
10492 DRD->setInitializer(Initializer);
10493 else
10494 DRD->setInvalidDecl();
10495}
10496
10497Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
10498 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
10499 for (auto *D : DeclReductions.get()) {
10500 if (IsValid) {
10501 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10502 if (S != nullptr)
10503 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
10504 } else
10505 D->setInvalidDecl();
10506 }
10507 return DeclReductions;
10508}
10509
Kelvin Li099bb8c2015-11-24 20:50:12 +000010510OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
10511 SourceLocation StartLoc,
10512 SourceLocation LParenLoc,
10513 SourceLocation EndLoc) {
10514 Expr *ValExpr = NumTeams;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010515
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010516 // OpenMP [teams Constrcut, Restrictions]
10517 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000010518 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
10519 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010520 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010521
10522 return new (Context) OMPNumTeamsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10523}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010524
10525OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
10526 SourceLocation StartLoc,
10527 SourceLocation LParenLoc,
10528 SourceLocation EndLoc) {
10529 Expr *ValExpr = ThreadLimit;
10530
10531 // OpenMP [teams Constrcut, Restrictions]
10532 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000010533 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
10534 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010535 return nullptr;
10536
10537 return new (Context) OMPThreadLimitClause(ValExpr, StartLoc, LParenLoc,
10538 EndLoc);
10539}
Alexey Bataeva0569352015-12-01 10:17:31 +000010540
10541OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
10542 SourceLocation StartLoc,
10543 SourceLocation LParenLoc,
10544 SourceLocation EndLoc) {
10545 Expr *ValExpr = Priority;
10546
10547 // OpenMP [2.9.1, task Constrcut]
10548 // The priority-value is a non-negative numerical scalar expression.
10549 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
10550 /*StrictlyPositive=*/false))
10551 return nullptr;
10552
10553 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10554}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010555
10556OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
10557 SourceLocation StartLoc,
10558 SourceLocation LParenLoc,
10559 SourceLocation EndLoc) {
10560 Expr *ValExpr = Grainsize;
10561
10562 // OpenMP [2.9.2, taskloop Constrcut]
10563 // The parameter of the grainsize clause must be a positive integer
10564 // expression.
10565 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
10566 /*StrictlyPositive=*/true))
10567 return nullptr;
10568
10569 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10570}
Alexey Bataev382967a2015-12-08 12:06:20 +000010571
10572OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
10573 SourceLocation StartLoc,
10574 SourceLocation LParenLoc,
10575 SourceLocation EndLoc) {
10576 Expr *ValExpr = NumTasks;
10577
10578 // OpenMP [2.9.2, taskloop Constrcut]
10579 // The parameter of the num_tasks clause must be a positive integer
10580 // expression.
10581 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
10582 /*StrictlyPositive=*/true))
10583 return nullptr;
10584
10585 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10586}
10587
Alexey Bataev28c75412015-12-15 08:19:24 +000010588OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
10589 SourceLocation LParenLoc,
10590 SourceLocation EndLoc) {
10591 // OpenMP [2.13.2, critical construct, Description]
10592 // ... where hint-expression is an integer constant expression that evaluates
10593 // to a valid lock hint.
10594 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
10595 if (HintExpr.isInvalid())
10596 return nullptr;
10597 return new (Context)
10598 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
10599}
10600
Carlo Bertollib4adf552016-01-15 18:50:31 +000010601OMPClause *Sema::ActOnOpenMPDistScheduleClause(
10602 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
10603 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
10604 SourceLocation EndLoc) {
10605 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
10606 std::string Values;
10607 Values += "'";
10608 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
10609 Values += "'";
10610 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
10611 << Values << getOpenMPClauseName(OMPC_dist_schedule);
10612 return nullptr;
10613 }
10614 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000010615 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000010616 if (ChunkSize) {
10617 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
10618 !ChunkSize->isInstantiationDependent() &&
10619 !ChunkSize->containsUnexpandedParameterPack()) {
10620 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
10621 ExprResult Val =
10622 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
10623 if (Val.isInvalid())
10624 return nullptr;
10625
10626 ValExpr = Val.get();
10627
10628 // OpenMP [2.7.1, Restrictions]
10629 // chunk_size must be a loop invariant integer expression with a positive
10630 // value.
10631 llvm::APSInt Result;
10632 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
10633 if (Result.isSigned() && !Result.isStrictlyPositive()) {
10634 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
10635 << "dist_schedule" << ChunkSize->getSourceRange();
10636 return nullptr;
10637 }
10638 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
Alexey Bataev5a3af132016-03-29 08:58:54 +000010639 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
10640 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
10641 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000010642 }
10643 }
10644 }
10645
10646 return new (Context)
10647 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000010648 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000010649}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010650
10651OMPClause *Sema::ActOnOpenMPDefaultmapClause(
10652 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
10653 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
10654 SourceLocation KindLoc, SourceLocation EndLoc) {
10655 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
10656 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom ||
10657 Kind != OMPC_DEFAULTMAP_scalar) {
10658 std::string Value;
10659 SourceLocation Loc;
10660 Value += "'";
10661 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
10662 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
10663 OMPC_DEFAULTMAP_MODIFIER_tofrom);
10664 Loc = MLoc;
10665 } else {
10666 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
10667 OMPC_DEFAULTMAP_scalar);
10668 Loc = KindLoc;
10669 }
10670 Value += "'";
10671 Diag(Loc, diag::err_omp_unexpected_clause_value)
10672 << Value << getOpenMPClauseName(OMPC_defaultmap);
10673 return nullptr;
10674 }
10675
10676 return new (Context)
10677 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
10678}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010679
10680bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
10681 DeclContext *CurLexicalContext = getCurLexicalContext();
10682 if (!CurLexicalContext->isFileContext() &&
10683 !CurLexicalContext->isExternCContext() &&
10684 !CurLexicalContext->isExternCXXContext()) {
10685 Diag(Loc, diag::err_omp_region_not_file_context);
10686 return false;
10687 }
10688 if (IsInOpenMPDeclareTargetContext) {
10689 Diag(Loc, diag::err_omp_enclosed_declare_target);
10690 return false;
10691 }
10692
10693 IsInOpenMPDeclareTargetContext = true;
10694 return true;
10695}
10696
10697void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
10698 assert(IsInOpenMPDeclareTargetContext &&
10699 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
10700
10701 IsInOpenMPDeclareTargetContext = false;
10702}
10703
10704static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
10705 Sema &SemaRef, Decl *D) {
10706 if (!D)
10707 return;
10708 Decl *LD = nullptr;
10709 if (isa<TagDecl>(D)) {
10710 LD = cast<TagDecl>(D)->getDefinition();
10711 } else if (isa<VarDecl>(D)) {
10712 LD = cast<VarDecl>(D)->getDefinition();
10713
10714 // If this is an implicit variable that is legal and we do not need to do
10715 // anything.
10716 if (cast<VarDecl>(D)->isImplicit()) {
10717 D->addAttr(OMPDeclareTargetDeclAttr::CreateImplicit(SemaRef.Context));
10718 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
10719 ML->DeclarationMarkedOpenMPDeclareTarget(D);
10720 return;
10721 }
10722
10723 } else if (isa<FunctionDecl>(D)) {
10724 const FunctionDecl *FD = nullptr;
10725 if (cast<FunctionDecl>(D)->hasBody(FD))
10726 LD = const_cast<FunctionDecl *>(FD);
10727
10728 // If the definition is associated with the current declaration in the
10729 // target region (it can be e.g. a lambda) that is legal and we do not need
10730 // to do anything else.
10731 if (LD == D) {
10732 D->addAttr(OMPDeclareTargetDeclAttr::CreateImplicit(SemaRef.Context));
10733 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
10734 ML->DeclarationMarkedOpenMPDeclareTarget(D);
10735 return;
10736 }
10737 }
10738 if (!LD)
10739 LD = D;
10740 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
10741 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
10742 // Outlined declaration is not declared target.
10743 if (LD->isOutOfLine()) {
10744 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
10745 SemaRef.Diag(SL, diag::note_used_here) << SR;
10746 } else {
10747 DeclContext *DC = LD->getDeclContext();
10748 while (DC) {
10749 if (isa<FunctionDecl>(DC) &&
10750 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
10751 break;
10752 DC = DC->getParent();
10753 }
10754 if (DC)
10755 return;
10756
10757 // Is not declared in target context.
10758 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
10759 SemaRef.Diag(SL, diag::note_used_here) << SR;
10760 }
10761 // Mark decl as declared target to prevent further diagnostic.
10762 D->addAttr(OMPDeclareTargetDeclAttr::CreateImplicit(SemaRef.Context));
10763 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
10764 ML->DeclarationMarkedOpenMPDeclareTarget(D);
10765 }
10766}
10767
10768static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
10769 Sema &SemaRef, DSAStackTy *Stack,
10770 ValueDecl *VD) {
10771 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
10772 return true;
10773 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
10774 return false;
10775 return true;
10776}
10777
10778void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
10779 if (!D || D->isInvalidDecl())
10780 return;
10781 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
10782 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
10783 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
10784 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10785 if (DSAStack->isThreadPrivate(VD)) {
10786 Diag(SL, diag::err_omp_threadprivate_in_target);
10787 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
10788 return;
10789 }
10790 }
10791 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
10792 // Problem if any with var declared with incomplete type will be reported
10793 // as normal, so no need to check it here.
10794 if ((E || !VD->getType()->isIncompleteType()) &&
10795 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
10796 // Mark decl as declared target to prevent further diagnostic.
10797 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
10798 VD->addAttr(OMPDeclareTargetDeclAttr::CreateImplicit(Context));
10799 if (ASTMutationListener *ML = Context.getASTMutationListener())
10800 ML->DeclarationMarkedOpenMPDeclareTarget(VD);
10801 }
10802 return;
10803 }
10804 }
10805 if (!E) {
10806 // Checking declaration inside declare target region.
10807 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
10808 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
10809 D->addAttr(OMPDeclareTargetDeclAttr::CreateImplicit(Context));
10810 if (ASTMutationListener *ML = Context.getASTMutationListener())
10811 ML->DeclarationMarkedOpenMPDeclareTarget(D);
10812 }
10813 return;
10814 }
10815 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
10816}