blob: 9b75001ea9853ba70507598fd970cb4f7fb25d98 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
Alexey Bataeva769e072013-03-22 06:34:35 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// \brief This file implements semantic analysis for OpenMP directives and
Alexey Bataev6f6f3b42013-05-13 04:18:18 +000011/// clauses.
Alexey Bataeva769e072013-03-22 06:34:35 +000012///
13//===----------------------------------------------------------------------===//
14
Alexey Bataevb08f89f2015-08-14 12:25:37 +000015#include "TreeTransform.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000016#include "clang/AST/ASTContext.h"
Alexey Bataev97720002014-11-11 04:05:39 +000017#include "clang/AST/ASTMutationListener.h"
Alexey Bataeva839ddd2016-03-17 10:19:46 +000018#include "clang/AST/CXXInheritance.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000019#include "clang/AST/Decl.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000020#include "clang/AST/DeclCXX.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000021#include "clang/AST/DeclOpenMP.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000022#include "clang/AST/StmtCXX.h"
23#include "clang/AST/StmtOpenMP.h"
24#include "clang/AST/StmtVisitor.h"
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000025#include "clang/AST/TypeOrdering.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000026#include "clang/Basic/OpenMPKinds.h"
Samuel Antaof8b50122015-07-13 22:54:53 +000027#include "clang/Basic/TargetInfo.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000028#include "clang/Lex/Preprocessor.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000029#include "clang/Sema/Initialization.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000030#include "clang/Sema/Lookup.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000031#include "clang/Sema/Scope.h"
32#include "clang/Sema/ScopeInfo.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000033#include "clang/Sema/SemaInternal.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000034using namespace clang;
35
Alexey Bataev758e55e2013-09-06 18:03:48 +000036//===----------------------------------------------------------------------===//
37// Stack of data-sharing attributes for variables
38//===----------------------------------------------------------------------===//
39
40namespace {
41/// \brief Default data sharing attributes, which can be applied to directive.
42enum DefaultDataSharingAttributes {
Alexey Bataeved09d242014-05-28 05:53:51 +000043 DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
44 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
45 DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'.
Alexey Bataev758e55e2013-09-06 18:03:48 +000046};
Alexey Bataev7ff55242014-06-19 09:13:45 +000047
Alexey Bataev758e55e2013-09-06 18:03:48 +000048/// \brief Stack for tracking declarations used in OpenMP directives and
49/// clauses and their data-sharing attributes.
Alexey Bataev7ace49d2016-05-17 08:55:33 +000050class DSAStackTy final {
Alexey Bataev758e55e2013-09-06 18:03:48 +000051public:
Alexey Bataev7ace49d2016-05-17 08:55:33 +000052 struct DSAVarData final {
53 OpenMPDirectiveKind DKind = OMPD_unknown;
54 OpenMPClauseKind CKind = OMPC_unknown;
55 Expr *RefExpr = nullptr;
56 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000057 SourceLocation ImplicitDSALoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000058 DSAVarData() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +000059 };
Alexey Bataev8b427062016-05-25 12:36:08 +000060 typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>
61 OperatorOffsetTy;
Alexey Bataeved09d242014-05-28 05:53:51 +000062
Alexey Bataev758e55e2013-09-06 18:03:48 +000063private:
Alexey Bataev7ace49d2016-05-17 08:55:33 +000064 struct DSAInfo final {
65 OpenMPClauseKind Attributes = OMPC_unknown;
66 /// Pointer to a reference expression and a flag which shows that the
67 /// variable is marked as lastprivate(true) or not (false).
68 llvm::PointerIntPair<Expr *, 1, bool> RefExpr;
69 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000070 };
Alexey Bataev90c228f2016-02-08 09:29:13 +000071 typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy;
72 typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +000073 typedef std::pair<unsigned, VarDecl *> LCDeclInfo;
74 typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy;
Samuel Antao6890b092016-07-28 14:25:09 +000075 /// Struct that associates a component with the clause kind where they are
76 /// found.
77 struct MappedExprComponentTy {
78 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
79 OpenMPClauseKind Kind = OMPC_unknown;
80 };
81 typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy>
Samuel Antao90927002016-04-26 14:54:23 +000082 MappedExprComponentsTy;
Alexey Bataev28c75412015-12-15 08:19:24 +000083 typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
84 CriticalsWithHintsTy;
Alexey Bataev8b427062016-05-25 12:36:08 +000085 typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>
86 DoacrossDependMapTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +000087
Alexey Bataev7ace49d2016-05-17 08:55:33 +000088 struct SharingMapTy final {
Alexey Bataev758e55e2013-09-06 18:03:48 +000089 DeclSAMapTy SharingMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000090 AlignedMapTy AlignedMap;
Samuel Antao90927002016-04-26 14:54:23 +000091 MappedExprComponentsTy MappedExprComponents;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000092 LoopControlVariablesMapTy LCVMap;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000093 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
Alexey Bataevbae9a792014-06-27 10:37:06 +000094 SourceLocation DefaultAttrLoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000095 OpenMPDirectiveKind Directive = OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +000096 DeclarationNameInfo DirectiveName;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000097 Scope *CurScope = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000098 SourceLocation ConstructLoc;
Alexey Bataev8b427062016-05-25 12:36:08 +000099 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
100 /// get the data (loop counters etc.) about enclosing loop-based construct.
101 /// This data is required during codegen.
102 DoacrossDependMapTy DoacrossDepends;
Alexey Bataev346265e2015-09-25 10:37:12 +0000103 /// \brief first argument (Expr *) contains optional argument of the
104 /// 'ordered' clause, the second one is true if the regions has 'ordered'
105 /// clause, false otherwise.
106 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000107 bool NowaitRegion = false;
108 bool CancelRegion = false;
109 unsigned AssociatedLoops = 1;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000110 SourceLocation InnerTeamsRegionLoc;
Alexey Bataeved09d242014-05-28 05:53:51 +0000111 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000112 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000113 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
114 ConstructLoc(Loc) {}
115 SharingMapTy() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +0000116 };
117
Axel Naumann323862e2016-02-03 10:45:22 +0000118 typedef SmallVector<SharingMapTy, 4> StackTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000119
120 /// \brief Stack of used declaration and their data-sharing attributes.
121 StackTy Stack;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000122 /// \brief true, if check for DSA must be from parent directive, false, if
123 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000124 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000125 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000126 bool ForceCapturing = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000127 CriticalsWithHintsTy Criticals;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000128
129 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
130
David Majnemer9d168222016-08-05 17:44:54 +0000131 DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D);
Alexey Bataevec3da872014-01-31 05:15:34 +0000132
133 /// \brief Checks if the variable is a local for OpenMP region.
134 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
Alexey Bataeved09d242014-05-28 05:53:51 +0000135
Alexey Bataev758e55e2013-09-06 18:03:48 +0000136public:
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000137 explicit DSAStackTy(Sema &S) : Stack(1), SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000138
Alexey Bataevaac108a2015-06-23 04:51:00 +0000139 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
140 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000141
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000142 bool isForceVarCapturing() const { return ForceCapturing; }
143 void setForceVarCapturing(bool V) { ForceCapturing = V; }
144
Alexey Bataev758e55e2013-09-06 18:03:48 +0000145 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000146 Scope *CurScope, SourceLocation Loc) {
147 Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
148 Stack.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000149 }
150
151 void pop() {
152 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
153 Stack.pop_back();
154 }
155
Alexey Bataev28c75412015-12-15 08:19:24 +0000156 void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
157 Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
158 }
159 const std::pair<OMPCriticalDirective *, llvm::APSInt>
160 getCriticalWithHint(const DeclarationNameInfo &Name) const {
161 auto I = Criticals.find(Name.getAsString());
162 if (I != Criticals.end())
163 return I->second;
164 return std::make_pair(nullptr, llvm::APSInt());
165 }
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000166 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000167 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000168 /// for diagnostics.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000169 Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000170
Alexey Bataev9c821032015-04-30 04:23:23 +0000171 /// \brief Register specified variable as loop control variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000172 void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
Alexey Bataev9c821032015-04-30 04:23:23 +0000173 /// \brief Check if the specified variable is a loop control variable for
174 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000175 /// \return The index of the loop control variable in the list of associated
176 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000177 LCDeclInfo isLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000178 /// \brief Check if the specified variable is a loop control variable for
179 /// parent region.
180 /// \return The index of the loop control variable in the list of associated
181 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000182 LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000183 /// \brief Get the loop control variable for the I-th loop (or nullptr) in
184 /// parent directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000185 ValueDecl *getParentLoopControlVariable(unsigned I);
Alexey Bataev9c821032015-04-30 04:23:23 +0000186
Alexey Bataev758e55e2013-09-06 18:03:48 +0000187 /// \brief Adds explicit data sharing attribute to the specified declaration.
Alexey Bataev90c228f2016-02-08 09:29:13 +0000188 void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
189 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000190
Alexey Bataev758e55e2013-09-06 18:03:48 +0000191 /// \brief Returns data sharing attributes from top of the stack for the
192 /// specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000193 DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000194 /// \brief Returns data-sharing attributes for the specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000195 DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000196 /// \brief Checks if the specified variables has data-sharing attributes which
197 /// match specified \a CPred predicate in any directive which matches \a DPred
198 /// predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000199 DSAVarData hasDSA(ValueDecl *D,
200 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
201 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
202 bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000203 /// \brief Checks if the specified variables has data-sharing attributes which
204 /// match specified \a CPred predicate in any innermost directive which
205 /// matches \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000206 DSAVarData
207 hasInnermostDSA(ValueDecl *D,
208 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
209 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
210 bool FromParent);
Alexey Bataevaac108a2015-06-23 04:51:00 +0000211 /// \brief Checks if the specified variables has explicit data-sharing
212 /// attributes which match specified \a CPred predicate at the specified
213 /// OpenMP region.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000214 bool hasExplicitDSA(ValueDecl *D,
Alexey Bataevaac108a2015-06-23 04:51:00 +0000215 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000216 unsigned Level, bool NotLastprivate = false);
Samuel Antao4be30e92015-10-02 17:14:03 +0000217
218 /// \brief Returns true if the directive at level \Level matches in the
219 /// specified \a DPred predicate.
220 bool hasExplicitDirective(
221 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
222 unsigned Level);
223
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000224 /// \brief Finds a directive which matches specified \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000225 bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind,
226 const DeclarationNameInfo &,
227 SourceLocation)> &DPred,
228 bool FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000229
Alexey Bataev758e55e2013-09-06 18:03:48 +0000230 /// \brief Returns currently analyzed directive.
231 OpenMPDirectiveKind getCurrentDirective() const {
232 return Stack.back().Directive;
233 }
Alexey Bataev549210e2014-06-24 04:39:47 +0000234 /// \brief Returns parent directive.
235 OpenMPDirectiveKind getParentDirective() const {
236 if (Stack.size() > 2)
237 return Stack[Stack.size() - 2].Directive;
238 return OMPD_unknown;
239 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000240
241 /// \brief Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000242 void setDefaultDSANone(SourceLocation Loc) {
243 Stack.back().DefaultAttr = DSA_none;
244 Stack.back().DefaultAttrLoc = Loc;
245 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000246 /// \brief Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000247 void setDefaultDSAShared(SourceLocation Loc) {
248 Stack.back().DefaultAttr = DSA_shared;
249 Stack.back().DefaultAttrLoc = Loc;
250 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000251
252 DefaultDataSharingAttributes getDefaultDSA() const {
253 return Stack.back().DefaultAttr;
254 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000255 SourceLocation getDefaultDSALocation() const {
256 return Stack.back().DefaultAttrLoc;
257 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000258
Alexey Bataevf29276e2014-06-18 04:14:57 +0000259 /// \brief Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000260 bool isThreadPrivate(VarDecl *D) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000261 DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000262 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000263 }
264
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000265 /// \brief Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataev346265e2015-09-25 10:37:12 +0000266 void setOrderedRegion(bool IsOrdered, Expr *Param) {
267 Stack.back().OrderedRegion.setInt(IsOrdered);
268 Stack.back().OrderedRegion.setPointer(Param);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000269 }
270 /// \brief Returns true, if parent region is ordered (has associated
271 /// 'ordered' clause), false - otherwise.
272 bool isParentOrderedRegion() const {
273 if (Stack.size() > 2)
Alexey Bataev346265e2015-09-25 10:37:12 +0000274 return Stack[Stack.size() - 2].OrderedRegion.getInt();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000275 return false;
276 }
Alexey Bataev346265e2015-09-25 10:37:12 +0000277 /// \brief Returns optional parameter for the ordered region.
278 Expr *getParentOrderedRegionParam() const {
279 if (Stack.size() > 2)
280 return Stack[Stack.size() - 2].OrderedRegion.getPointer();
281 return nullptr;
282 }
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000283 /// \brief Marks current region as nowait (it has a 'nowait' clause).
284 void setNowaitRegion(bool IsNowait = true) {
285 Stack.back().NowaitRegion = IsNowait;
286 }
287 /// \brief Returns true, if parent region is nowait (has associated
288 /// 'nowait' clause), false - otherwise.
289 bool isParentNowaitRegion() const {
290 if (Stack.size() > 2)
291 return Stack[Stack.size() - 2].NowaitRegion;
292 return false;
293 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000294 /// \brief Marks parent region as cancel region.
295 void setParentCancelRegion(bool Cancel = true) {
296 if (Stack.size() > 2)
297 Stack[Stack.size() - 2].CancelRegion =
298 Stack[Stack.size() - 2].CancelRegion || Cancel;
299 }
300 /// \brief Return true if current region has inner cancel construct.
David Majnemer9d168222016-08-05 17:44:54 +0000301 bool isCancelRegion() const { return Stack.back().CancelRegion; }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000302
Alexey Bataev9c821032015-04-30 04:23:23 +0000303 /// \brief Set collapse value for the region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000304 void setAssociatedLoops(unsigned Val) { Stack.back().AssociatedLoops = Val; }
Alexey Bataev9c821032015-04-30 04:23:23 +0000305 /// \brief Return collapse value for region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000306 unsigned getAssociatedLoops() const { return Stack.back().AssociatedLoops; }
Alexey Bataev9c821032015-04-30 04:23:23 +0000307
Alexey Bataev13314bf2014-10-09 04:18:56 +0000308 /// \brief Marks current target region as one with closely nested teams
309 /// region.
310 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
311 if (Stack.size() > 2)
312 Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
313 }
314 /// \brief Returns true, if current region has closely nested teams region.
315 bool hasInnerTeamsRegion() const {
316 return getInnerTeamsRegionLoc().isValid();
317 }
318 /// \brief Returns location of the nested teams region (if any).
319 SourceLocation getInnerTeamsRegionLoc() const {
320 if (Stack.size() > 1)
321 return Stack.back().InnerTeamsRegionLoc;
322 return SourceLocation();
323 }
324
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000325 Scope *getCurScope() const { return Stack.back().CurScope; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000326 Scope *getCurScope() { return Stack.back().CurScope; }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000327 SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000328
Samuel Antao4c8035b2016-12-12 18:00:20 +0000329 /// Do the check specified in \a Check to all component lists and return true
330 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000331 bool checkMappableExprComponentListsForDecl(
332 ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000333 const llvm::function_ref<
334 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
335 OpenMPClauseKind)> &Check) {
Samuel Antao5de996e2016-01-22 20:21:36 +0000336 auto SI = Stack.rbegin();
337 auto SE = Stack.rend();
338
339 if (SI == SE)
340 return false;
341
342 if (CurrentRegionOnly) {
343 SE = std::next(SI);
344 } else {
345 ++SI;
346 }
347
348 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000349 auto MI = SI->MappedExprComponents.find(VD);
350 if (MI != SI->MappedExprComponents.end())
Samuel Antao6890b092016-07-28 14:25:09 +0000351 for (auto &L : MI->second.Components)
352 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000353 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000354 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000355 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000356 }
357
Samuel Antao4c8035b2016-12-12 18:00:20 +0000358 /// Create a new mappable expression component list associated with a given
359 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000360 void addMappableExpressionComponents(
361 ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000362 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
363 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao90927002016-04-26 14:54:23 +0000364 assert(Stack.size() > 1 &&
365 "Not expecting to retrieve components from a empty stack!");
366 auto &MEC = Stack.back().MappedExprComponents[VD];
367 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000368 MEC.Components.resize(MEC.Components.size() + 1);
369 MEC.Components.back().append(Components.begin(), Components.end());
370 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000371 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000372
373 unsigned getNestingLevel() const {
374 assert(Stack.size() > 1);
375 return Stack.size() - 2;
376 }
Alexey Bataev8b427062016-05-25 12:36:08 +0000377 void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) {
378 assert(Stack.size() > 2);
379 assert(isOpenMPWorksharingDirective(Stack[Stack.size() - 2].Directive));
380 Stack[Stack.size() - 2].DoacrossDepends.insert({C, OpsOffs});
381 }
382 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
383 getDoacrossDependClauses() const {
384 assert(Stack.size() > 1);
385 if (isOpenMPWorksharingDirective(Stack[Stack.size() - 1].Directive)) {
386 auto &Ref = Stack[Stack.size() - 1].DoacrossDepends;
387 return llvm::make_range(Ref.begin(), Ref.end());
388 }
389 return llvm::make_range(Stack[0].DoacrossDepends.end(),
390 Stack[0].DoacrossDepends.end());
391 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000392};
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000393bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
Alexey Bataev35aaee62016-04-13 13:36:48 +0000394 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
395 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000396}
Alexey Bataeved09d242014-05-28 05:53:51 +0000397} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000398
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000399static ValueDecl *getCanonicalDecl(ValueDecl *D) {
400 auto *VD = dyn_cast<VarDecl>(D);
401 auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000402 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000403 VD = VD->getCanonicalDecl();
404 D = VD;
405 } else {
406 assert(FD);
407 FD = FD->getCanonicalDecl();
408 D = FD;
409 }
410 return D;
411}
412
David Majnemer9d168222016-08-05 17:44:54 +0000413DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000414 ValueDecl *D) {
415 D = getCanonicalDecl(D);
416 auto *VD = dyn_cast<VarDecl>(D);
417 auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000418 DSAVarData DVar;
Alexey Bataevdf9b1592014-06-25 04:09:13 +0000419 if (Iter == std::prev(Stack.rend())) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000420 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
421 // in a region but not in construct]
422 // File-scope or namespace-scope variables referenced in called routines
423 // in the region are shared unless they appear in a threadprivate
424 // directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000425 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000426 DVar.CKind = OMPC_shared;
427
428 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
429 // in a region but not in construct]
430 // Variables with static storage duration that are declared in called
431 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000432 if (VD && VD->hasGlobalStorage())
433 DVar.CKind = OMPC_shared;
434
435 // Non-static data members are shared by default.
436 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000437 DVar.CKind = OMPC_shared;
438
Alexey Bataev758e55e2013-09-06 18:03:48 +0000439 return DVar;
440 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000441
Alexey Bataev758e55e2013-09-06 18:03:48 +0000442 DVar.DKind = Iter->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +0000443 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
444 // in a Construct, C/C++, predetermined, p.1]
445 // Variables with automatic storage duration that are declared in a scope
446 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000447 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
448 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000449 DVar.CKind = OMPC_private;
450 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000451 }
452
Alexey Bataev758e55e2013-09-06 18:03:48 +0000453 // Explicitly specified attributes and local variables with predetermined
454 // attributes.
455 if (Iter->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000456 DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000457 DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000458 DVar.CKind = Iter->SharingMap[D].Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000459 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000460 return DVar;
461 }
462
463 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
464 // in a Construct, C/C++, implicitly determined, p.1]
465 // In a parallel or task construct, the data-sharing attributes of these
466 // variables are determined by the default clause, if present.
467 switch (Iter->DefaultAttr) {
468 case DSA_shared:
469 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000470 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000471 return DVar;
472 case DSA_none:
473 return DVar;
474 case DSA_unspecified:
475 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
476 // in a Construct, implicitly determined, p.2]
477 // In a parallel construct, if no default clause is present, these
478 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000479 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000480 if (isOpenMPParallelDirective(DVar.DKind) ||
481 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000482 DVar.CKind = OMPC_shared;
483 return DVar;
484 }
485
486 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
487 // in a Construct, implicitly determined, p.4]
488 // In a task construct, if no default clause is present, a variable that in
489 // the enclosing context is determined to be shared by all implicit tasks
490 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000491 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000492 DSAVarData DVarTemp;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000493 for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000494 I != EE; ++I) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000495 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000496 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000497 // In a task construct, if no default clause is present, a variable
498 // whose data-sharing attribute is not determined by the rules above is
499 // firstprivate.
500 DVarTemp = getDSA(I, D);
501 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000502 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000503 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000504 return DVar;
505 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000506 if (isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000507 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000508 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000509 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000510 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000511 return DVar;
512 }
513 }
514 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
515 // in a Construct, implicitly determined, p.3]
516 // For constructs other than task, if no default clause is present, these
517 // variables inherit their data-sharing attributes from the enclosing
518 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000519 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000520}
521
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000522Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000523 assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000524 D = getCanonicalDecl(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000525 auto It = Stack.back().AlignedMap.find(D);
526 if (It == Stack.back().AlignedMap.end()) {
527 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
528 Stack.back().AlignedMap[D] = NewDE;
529 return nullptr;
530 } else {
531 assert(It->second && "Unexpected nullptr expr in the aligned map");
532 return It->second;
533 }
534 return nullptr;
535}
536
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000537void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
Alexey Bataev9c821032015-04-30 04:23:23 +0000538 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000539 D = getCanonicalDecl(D);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000540 Stack.back().LCVMap.insert(
541 std::make_pair(D, LCDeclInfo(Stack.back().LCVMap.size() + 1, Capture)));
Alexey Bataev9c821032015-04-30 04:23:23 +0000542}
543
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000544DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
Alexey Bataev9c821032015-04-30 04:23:23 +0000545 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000546 D = getCanonicalDecl(D);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000547 return Stack.back().LCVMap.count(D) > 0 ? Stack.back().LCVMap[D]
548 : LCDeclInfo(0, nullptr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000549}
550
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000551DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000552 assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000553 D = getCanonicalDecl(D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000554 return Stack[Stack.size() - 2].LCVMap.count(D) > 0
555 ? Stack[Stack.size() - 2].LCVMap[D]
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000556 : LCDeclInfo(0, nullptr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000557}
558
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000559ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000560 assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
561 if (Stack[Stack.size() - 2].LCVMap.size() < I)
562 return nullptr;
563 for (auto &Pair : Stack[Stack.size() - 2].LCVMap) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000564 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000565 return Pair.first;
566 }
567 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +0000568}
569
Alexey Bataev90c228f2016-02-08 09:29:13 +0000570void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
571 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000572 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000573 if (A == OMPC_threadprivate) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000574 auto &Data = Stack[0].SharingMap[D];
575 Data.Attributes = A;
576 Data.RefExpr.setPointer(E);
577 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000578 } else {
579 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000580 auto &Data = Stack.back().SharingMap[D];
581 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
582 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
583 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
584 (isLoopControlVariable(D).first && A == OMPC_private));
585 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
586 Data.RefExpr.setInt(/*IntVal=*/true);
587 return;
588 }
589 const bool IsLastprivate =
590 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
591 Data.Attributes = A;
592 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
593 Data.PrivateCopy = PrivateCopy;
594 if (PrivateCopy) {
595 auto &Data = Stack.back().SharingMap[PrivateCopy->getDecl()];
596 Data.Attributes = A;
597 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
598 Data.PrivateCopy = nullptr;
599 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000600 }
601}
602
Alexey Bataeved09d242014-05-28 05:53:51 +0000603bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000604 D = D->getCanonicalDecl();
Alexey Bataevec3da872014-01-31 05:15:34 +0000605 if (Stack.size() > 2) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000606 reverse_iterator I = Iter, E = std::prev(Stack.rend());
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000607 Scope *TopScope = nullptr;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000608 while (I != E && !isParallelOrTaskRegion(I->Directive)) {
Alexey Bataevec3da872014-01-31 05:15:34 +0000609 ++I;
610 }
Alexey Bataeved09d242014-05-28 05:53:51 +0000611 if (I == E)
612 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000613 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000614 Scope *CurScope = getCurScope();
615 while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000616 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000617 }
618 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000619 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000620 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000621}
622
Alexey Bataev39f915b82015-05-08 10:41:21 +0000623/// \brief Build a variable declaration for OpenMP loop iteration variable.
624static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000625 StringRef Name, const AttrVec *Attrs = nullptr) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000626 DeclContext *DC = SemaRef.CurContext;
627 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
628 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
629 VarDecl *Decl =
630 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000631 if (Attrs) {
632 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
633 I != E; ++I)
634 Decl->addAttr(*I);
635 }
Alexey Bataev39f915b82015-05-08 10:41:21 +0000636 Decl->setImplicit();
637 return Decl;
638}
639
640static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
641 SourceLocation Loc,
642 bool RefersToCapture = false) {
643 D->setReferenced();
644 D->markUsed(S.Context);
645 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
646 SourceLocation(), D, RefersToCapture, Loc, Ty,
647 VK_LValue);
648}
649
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000650DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
651 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000652 DSAVarData DVar;
653
654 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
655 // in a Construct, C/C++, predetermined, p.1]
656 // Variables appearing in threadprivate directives are threadprivate.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000657 auto *VD = dyn_cast<VarDecl>(D);
658 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
659 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
Samuel Antaof8b50122015-07-13 22:54:53 +0000660 SemaRef.getLangOpts().OpenMPUseTLS &&
661 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000662 (VD && VD->getStorageClass() == SC_Register &&
663 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
664 addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
Alexey Bataev39f915b82015-05-08 10:41:21 +0000665 D->getLocation()),
Alexey Bataevf2453a02015-05-06 07:25:08 +0000666 OMPC_threadprivate);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000667 }
668 if (Stack[0].SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000669 DVar.RefExpr = Stack[0].SharingMap[D].RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000670 DVar.CKind = OMPC_threadprivate;
671 return DVar;
672 }
673
Dmitry Polukhin0b0da292016-04-06 11:38:59 +0000674 if (Stack.size() == 1) {
675 // Not in OpenMP execution region and top scope was already checked.
676 return DVar;
677 }
678
Alexey Bataev758e55e2013-09-06 18:03:48 +0000679 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000680 // in a Construct, C/C++, predetermined, p.4]
681 // Static data members are shared.
682 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
683 // in a Construct, C/C++, predetermined, p.7]
684 // Variables with static storage duration that are declared in a scope
685 // inside the construct are shared.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000686 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000687 if (VD && VD->isStaticDataMember()) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000688 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000689 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
Alexey Bataevec3da872014-01-31 05:15:34 +0000690 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000691
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000692 DVar.CKind = OMPC_shared;
693 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000694 }
695
696 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000697 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
698 Type = SemaRef.getASTContext().getBaseElementType(Type);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000699 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
700 // in a Construct, C/C++, predetermined, p.6]
701 // Variables with const qualified type having no mutable member are
702 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000703 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +0000704 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataevc9bd03d2015-12-17 06:55:08 +0000705 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
706 if (auto *CTD = CTSD->getSpecializedTemplate())
707 RD = CTD->getTemplatedDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000708 if (IsConstant &&
Alexey Bataev4bcad7f2016-02-10 10:50:12 +0000709 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
710 RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000711 // Variables with const-qualified type having no mutable member may be
712 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000713 DSAVarData DVarTemp = hasDSA(
714 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
715 MatchesAlways, FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000716 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
717 return DVar;
718
Alexey Bataev758e55e2013-09-06 18:03:48 +0000719 DVar.CKind = OMPC_shared;
720 return DVar;
721 }
722
Alexey Bataev758e55e2013-09-06 18:03:48 +0000723 // Explicitly specified attributes and local variables with predetermined
724 // attributes.
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000725 auto StartI = std::next(Stack.rbegin());
726 auto EndI = std::prev(Stack.rend());
727 if (FromParent && StartI != EndI) {
728 StartI = std::next(StartI);
729 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000730 auto I = std::prev(StartI);
731 if (I->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000732 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000733 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000734 DVar.CKind = I->SharingMap[D].Attributes;
735 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000736 }
737
738 return DVar;
739}
740
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000741DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
742 bool FromParent) {
743 D = getCanonicalDecl(D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000744 auto StartI = Stack.rbegin();
745 auto EndI = std::prev(Stack.rend());
746 if (FromParent && StartI != EndI) {
747 StartI = std::next(StartI);
748 }
749 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000750}
751
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000752DSAStackTy::DSAVarData
753DSAStackTy::hasDSA(ValueDecl *D,
754 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
755 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
756 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000757 D = getCanonicalDecl(D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000758 auto StartI = std::next(Stack.rbegin());
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000759 auto EndI = Stack.rend();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000760 if (FromParent && StartI != EndI) {
761 StartI = std::next(StartI);
762 }
763 for (auto I = StartI, EE = EndI; I != EE; ++I) {
764 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000765 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000766 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000767 if (CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000768 return DVar;
769 }
770 return DSAVarData();
771}
772
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000773DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
774 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
775 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
776 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000777 D = getCanonicalDecl(D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000778 auto StartI = std::next(Stack.rbegin());
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000779 auto EndI = Stack.rend();
Alexey Bataeve3978122016-07-19 05:06:39 +0000780 if (FromParent && StartI != EndI)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000781 StartI = std::next(StartI);
Alexey Bataeve3978122016-07-19 05:06:39 +0000782 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataevc5e02582014-06-16 07:08:35 +0000783 return DSAVarData();
Alexey Bataeve3978122016-07-19 05:06:39 +0000784 DSAVarData DVar = getDSA(StartI, D);
785 return CPred(DVar.CKind) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +0000786}
787
Alexey Bataevaac108a2015-06-23 04:51:00 +0000788bool DSAStackTy::hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000789 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000790 unsigned Level, bool NotLastprivate) {
Alexey Bataevaac108a2015-06-23 04:51:00 +0000791 if (CPred(ClauseKindMode))
792 return true;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000793 D = getCanonicalDecl(D);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000794 auto StartI = std::next(Stack.begin());
795 auto EndI = Stack.end();
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +0000796 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +0000797 return false;
798 std::advance(StartI, Level);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000799 return (StartI->SharingMap.count(D) > 0) &&
800 StartI->SharingMap[D].RefExpr.getPointer() &&
801 CPred(StartI->SharingMap[D].Attributes) &&
802 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
Alexey Bataevaac108a2015-06-23 04:51:00 +0000803}
804
Samuel Antao4be30e92015-10-02 17:14:03 +0000805bool DSAStackTy::hasExplicitDirective(
806 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
807 unsigned Level) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000808 auto StartI = std::next(Stack.begin());
809 auto EndI = Stack.end();
Samuel Antao4be30e92015-10-02 17:14:03 +0000810 if (std::distance(StartI, EndI) <= (int)Level)
811 return false;
812 std::advance(StartI, Level);
813 return DPred(StartI->Directive);
814}
815
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000816bool DSAStackTy::hasDirective(
817 const llvm::function_ref<bool(OpenMPDirectiveKind,
818 const DeclarationNameInfo &, SourceLocation)>
819 &DPred,
820 bool FromParent) {
Samuel Antaof0d79752016-05-27 15:21:27 +0000821 // We look only in the enclosing region.
822 if (Stack.size() < 2)
823 return false;
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000824 auto StartI = std::next(Stack.rbegin());
825 auto EndI = std::prev(Stack.rend());
826 if (FromParent && StartI != EndI) {
827 StartI = std::next(StartI);
828 }
829 for (auto I = StartI, EE = EndI; I != EE; ++I) {
830 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
831 return true;
832 }
833 return false;
834}
835
Alexey Bataev758e55e2013-09-06 18:03:48 +0000836void Sema::InitDataSharingAttributesStack() {
837 VarDataSharingAttributesStack = new DSAStackTy(*this);
838}
839
840#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
841
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000842bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000843 assert(LangOpts.OpenMP && "OpenMP is not allowed");
844
845 auto &Ctx = getASTContext();
846 bool IsByRef = true;
847
848 // Find the directive that is associated with the provided scope.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000849 auto Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000850
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000851 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000852 // This table summarizes how a given variable should be passed to the device
853 // given its type and the clauses where it appears. This table is based on
854 // the description in OpenMP 4.5 [2.10.4, target Construct] and
855 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
856 //
857 // =========================================================================
858 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
859 // | |(tofrom:scalar)| | pvt | | | |
860 // =========================================================================
861 // | scl | | | | - | | bycopy|
862 // | scl | | - | x | - | - | bycopy|
863 // | scl | | x | - | - | - | null |
864 // | scl | x | | | - | | byref |
865 // | scl | x | - | x | - | - | bycopy|
866 // | scl | x | x | - | - | - | null |
867 // | scl | | - | - | - | x | byref |
868 // | scl | x | - | - | - | x | byref |
869 //
870 // | agg | n.a. | | | - | | byref |
871 // | agg | n.a. | - | x | - | - | byref |
872 // | agg | n.a. | x | - | - | - | null |
873 // | agg | n.a. | - | - | - | x | byref |
874 // | agg | n.a. | - | - | - | x[] | byref |
875 //
876 // | ptr | n.a. | | | - | | bycopy|
877 // | ptr | n.a. | - | x | - | - | bycopy|
878 // | ptr | n.a. | x | - | - | - | null |
879 // | ptr | n.a. | - | - | - | x | byref |
880 // | ptr | n.a. | - | - | - | x[] | bycopy|
881 // | ptr | n.a. | - | - | x | | bycopy|
882 // | ptr | n.a. | - | - | x | x | bycopy|
883 // | ptr | n.a. | - | - | x | x[] | bycopy|
884 // =========================================================================
885 // Legend:
886 // scl - scalar
887 // ptr - pointer
888 // agg - aggregate
889 // x - applies
890 // - - invalid in this combination
891 // [] - mapped with an array section
892 // byref - should be mapped by reference
893 // byval - should be mapped by value
894 // null - initialize a local variable to null on the device
895 //
896 // Observations:
897 // - All scalar declarations that show up in a map clause have to be passed
898 // by reference, because they may have been mapped in the enclosing data
899 // environment.
900 // - If the scalar value does not fit the size of uintptr, it has to be
901 // passed by reference, regardless the result in the table above.
902 // - For pointers mapped by value that have either an implicit map or an
903 // array section, the runtime library may pass the NULL value to the
904 // device instead of the value passed to it by the compiler.
905
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000906 if (Ty->isReferenceType())
907 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +0000908
909 // Locate map clauses and see if the variable being captured is referred to
910 // in any of those clauses. Here we only care about variables, not fields,
911 // because fields are part of aggregates.
912 bool IsVariableUsedInMapClause = false;
913 bool IsVariableAssociatedWithSection = false;
914
915 DSAStack->checkMappableExprComponentListsForDecl(
916 D, /*CurrentRegionOnly=*/true,
917 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +0000918 MapExprComponents,
919 OpenMPClauseKind WhereFoundClauseKind) {
920 // Only the map clause information influences how a variable is
921 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +0000922 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +0000923 if (WhereFoundClauseKind != OMPC_map)
924 return false;
Samuel Antao86ace552016-04-27 22:40:57 +0000925
926 auto EI = MapExprComponents.rbegin();
927 auto EE = MapExprComponents.rend();
928
929 assert(EI != EE && "Invalid map expression!");
930
931 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
932 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
933
934 ++EI;
935 if (EI == EE)
936 return false;
937
938 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
939 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
940 isa<MemberExpr>(EI->getAssociatedExpression())) {
941 IsVariableAssociatedWithSection = true;
942 // There is nothing more we need to know about this variable.
943 return true;
944 }
945
946 // Keep looking for more map info.
947 return false;
948 });
949
950 if (IsVariableUsedInMapClause) {
951 // If variable is identified in a map clause it is always captured by
952 // reference except if it is a pointer that is dereferenced somehow.
953 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
954 } else {
955 // By default, all the data that has a scalar type is mapped by copy.
956 IsByRef = !Ty->isScalarType();
957 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000958 }
959
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000960 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
961 IsByRef = !DSAStack->hasExplicitDSA(
962 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
963 Level, /*NotLastprivate=*/true);
964 }
965
Samuel Antao86ace552016-04-27 22:40:57 +0000966 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000967 // and alignment, because the runtime library only deals with uintptr types.
968 // If it does not fit the uintptr size, we need to pass the data by reference
969 // instead.
970 if (!IsByRef &&
971 (Ctx.getTypeSizeInChars(Ty) >
972 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000973 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000974 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000975 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000976
977 return IsByRef;
978}
979
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000980unsigned Sema::getOpenMPNestingLevel() const {
981 assert(getLangOpts().OpenMP);
982 return DSAStack->getNestingLevel();
983}
984
Alexey Bataev90c228f2016-02-08 09:29:13 +0000985VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
Alexey Bataevf841bd92014-12-16 07:00:22 +0000986 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000987 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +0000988
989 // If we are attempting to capture a global variable in a directive with
990 // 'target' we return true so that this global is also mapped to the device.
991 //
992 // FIXME: If the declaration is enclosed in a 'declare target' directive,
993 // then it should not be captured. Therefore, an extra check has to be
994 // inserted here once support for 'declare target' is added.
995 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000996 auto *VD = dyn_cast<VarDecl>(D);
997 if (VD && !VD->hasLocalStorage()) {
Samuel Antao4be30e92015-10-02 17:14:03 +0000998 if (DSAStack->getCurrentDirective() == OMPD_target &&
Alexey Bataev90c228f2016-02-08 09:29:13 +0000999 !DSAStack->isClauseParsingMode())
1000 return VD;
Samuel Antaof0d79752016-05-27 15:21:27 +00001001 if (DSAStack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001002 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1003 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001004 return isOpenMPTargetExecutionDirective(K);
Samuel Antao4be30e92015-10-02 17:14:03 +00001005 },
Alexey Bataev90c228f2016-02-08 09:29:13 +00001006 false))
1007 return VD;
Samuel Antao4be30e92015-10-02 17:14:03 +00001008 }
1009
Alexey Bataev48977c32015-08-04 08:10:48 +00001010 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1011 (!DSAStack->isClauseParsingMode() ||
1012 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001013 auto &&Info = DSAStack->isLoopControlVariable(D);
1014 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001015 (VD && VD->hasLocalStorage() &&
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001016 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001017 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001018 return VD ? VD : Info.second;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001019 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001020 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001021 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001022 DVarPrivate = DSAStack->hasDSA(
1023 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1024 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +00001025 if (DVarPrivate.CKind != OMPC_unknown)
1026 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001027 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001028 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001029}
1030
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001031bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001032 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1033 return DSAStack->hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001034 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
Alexey Bataevaac108a2015-06-23 04:51:00 +00001035}
1036
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001037bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
Samuel Antao4be30e92015-10-02 17:14:03 +00001038 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1039 // Return true if the current level is no longer enclosed in a target region.
1040
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001041 auto *VD = dyn_cast<VarDecl>(D);
1042 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001043 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1044 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001045}
1046
Alexey Bataeved09d242014-05-28 05:53:51 +00001047void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001048
1049void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1050 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001051 Scope *CurScope, SourceLocation Loc) {
1052 DSAStack->push(DKind, DirName, CurScope, Loc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001053 PushExpressionEvaluationContext(PotentiallyEvaluated);
1054}
1055
Alexey Bataevaac108a2015-06-23 04:51:00 +00001056void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1057 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001058}
1059
Alexey Bataevaac108a2015-06-23 04:51:00 +00001060void Sema::EndOpenMPClause() {
1061 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001062}
1063
Alexey Bataev758e55e2013-09-06 18:03:48 +00001064void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001065 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1066 // A variable of class type (or array thereof) that appears in a lastprivate
1067 // clause requires an accessible, unambiguous default constructor for the
1068 // class type, unless the list item is also specified in a firstprivate
1069 // clause.
David Majnemer9d168222016-08-05 17:44:54 +00001070 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001071 for (auto *C : D->clauses()) {
1072 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1073 SmallVector<Expr *, 8> PrivateCopies;
1074 for (auto *DE : Clause->varlists()) {
1075 if (DE->isValueDependent() || DE->isTypeDependent()) {
1076 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001077 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001078 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001079 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataev005248a2016-02-25 05:25:57 +00001080 VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1081 QualType Type = VD->getType().getNonReferenceType();
1082 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001083 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001084 // Generate helper private variable and initialize it with the
1085 // default value. The address of the original variable is replaced
1086 // by the address of the new private variable in CodeGen. This new
1087 // variable is not added to IdResolver, so the code in the OpenMP
1088 // region uses original variable for proper diagnostics.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001089 auto *VDPrivate = buildVarDecl(
1090 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev005248a2016-02-25 05:25:57 +00001091 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev38e89532015-04-16 04:54:05 +00001092 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
1093 if (VDPrivate->isInvalidDecl())
1094 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001095 PrivateCopies.push_back(buildDeclRefExpr(
1096 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001097 } else {
1098 // The variable is also a firstprivate, so initialization sequence
1099 // for private copy is generated already.
1100 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001101 }
1102 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001103 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001104 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001105 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001106 }
1107 }
1108 }
1109
Alexey Bataev758e55e2013-09-06 18:03:48 +00001110 DSAStack->pop();
1111 DiscardCleanupsInEvaluationContext();
1112 PopExpressionEvaluationContext();
1113}
1114
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001115static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1116 Expr *NumIterations, Sema &SemaRef,
1117 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001118
Alexey Bataeva769e072013-03-22 06:34:35 +00001119namespace {
1120
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001121class VarDeclFilterCCC : public CorrectionCandidateCallback {
1122private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001123 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001124
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001125public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001126 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001127 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001128 NamedDecl *ND = Candidate.getCorrectionDecl();
David Majnemer9d168222016-08-05 17:44:54 +00001129 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001130 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001131 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1132 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001133 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001134 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001135 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001136};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001137
1138class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1139private:
1140 Sema &SemaRef;
1141
1142public:
1143 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1144 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1145 NamedDecl *ND = Candidate.getCorrectionDecl();
1146 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
1147 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1148 SemaRef.getCurScope());
1149 }
1150 return false;
1151 }
1152};
1153
Alexey Bataeved09d242014-05-28 05:53:51 +00001154} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001155
1156ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1157 CXXScopeSpec &ScopeSpec,
1158 const DeclarationNameInfo &Id) {
1159 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1160 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1161
1162 if (Lookup.isAmbiguous())
1163 return ExprError();
1164
1165 VarDecl *VD;
1166 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001167 if (TypoCorrection Corrected = CorrectTypo(
1168 Id, LookupOrdinaryName, CurScope, nullptr,
1169 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001170 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001171 PDiag(Lookup.empty()
1172 ? diag::err_undeclared_var_use_suggest
1173 : diag::err_omp_expected_var_arg_suggest)
1174 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001175 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001176 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001177 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1178 : diag::err_omp_expected_var_arg)
1179 << Id.getName();
1180 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001181 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001182 } else {
1183 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00001184 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001185 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1186 return ExprError();
1187 }
1188 }
1189 Lookup.suppressDiagnostics();
1190
1191 // OpenMP [2.9.2, Syntax, C/C++]
1192 // Variables must be file-scope, namespace-scope, or static block-scope.
1193 if (!VD->hasGlobalStorage()) {
1194 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001195 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1196 bool IsDecl =
1197 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001198 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00001199 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1200 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001201 return ExprError();
1202 }
1203
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001204 VarDecl *CanonicalVD = VD->getCanonicalDecl();
1205 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001206 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1207 // A threadprivate directive for file-scope variables must appear outside
1208 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001209 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1210 !getCurLexicalContext()->isTranslationUnit()) {
1211 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001212 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1213 bool IsDecl =
1214 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1215 Diag(VD->getLocation(),
1216 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1217 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001218 return ExprError();
1219 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001220 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1221 // A threadprivate directive for static class member variables must appear
1222 // in the class definition, in the same scope in which the member
1223 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001224 if (CanonicalVD->isStaticDataMember() &&
1225 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1226 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001227 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1228 bool IsDecl =
1229 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1230 Diag(VD->getLocation(),
1231 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1232 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001233 return ExprError();
1234 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001235 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1236 // A threadprivate directive for namespace-scope variables must appear
1237 // outside any definition or declaration other than the namespace
1238 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001239 if (CanonicalVD->getDeclContext()->isNamespace() &&
1240 (!getCurLexicalContext()->isFileContext() ||
1241 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1242 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001243 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1244 bool IsDecl =
1245 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1246 Diag(VD->getLocation(),
1247 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1248 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001249 return ExprError();
1250 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001251 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1252 // A threadprivate directive for static block-scope variables must appear
1253 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001254 if (CanonicalVD->isStaticLocal() && CurScope &&
1255 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001256 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001257 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1258 bool IsDecl =
1259 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1260 Diag(VD->getLocation(),
1261 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1262 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001263 return ExprError();
1264 }
1265
1266 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1267 // A threadprivate directive must lexically precede all references to any
1268 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001269 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001270 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +00001271 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001272 return ExprError();
1273 }
1274
1275 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00001276 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1277 SourceLocation(), VD,
1278 /*RefersToEnclosingVariableOrCapture=*/false,
1279 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001280}
1281
Alexey Bataeved09d242014-05-28 05:53:51 +00001282Sema::DeclGroupPtrTy
1283Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1284 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001285 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001286 CurContext->addDecl(D);
1287 return DeclGroupPtrTy::make(DeclGroupRef(D));
1288 }
David Blaikie0403cb12016-01-15 23:43:25 +00001289 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00001290}
1291
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001292namespace {
1293class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1294 Sema &SemaRef;
1295
1296public:
1297 bool VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer9d168222016-08-05 17:44:54 +00001298 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001299 if (VD->hasLocalStorage()) {
1300 SemaRef.Diag(E->getLocStart(),
1301 diag::err_omp_local_var_in_threadprivate_init)
1302 << E->getSourceRange();
1303 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1304 << VD << VD->getSourceRange();
1305 return true;
1306 }
1307 }
1308 return false;
1309 }
1310 bool VisitStmt(const Stmt *S) {
1311 for (auto Child : S->children()) {
1312 if (Child && Visit(Child))
1313 return true;
1314 }
1315 return false;
1316 }
Alexey Bataev23b69422014-06-18 07:08:49 +00001317 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001318};
1319} // namespace
1320
Alexey Bataeved09d242014-05-28 05:53:51 +00001321OMPThreadPrivateDecl *
1322Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001323 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00001324 for (auto &RefExpr : VarList) {
1325 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001326 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1327 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00001328
Alexey Bataev376b4a42016-02-09 09:41:09 +00001329 // Mark variable as used.
1330 VD->setReferenced();
1331 VD->markUsed(Context);
1332
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001333 QualType QType = VD->getType();
1334 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1335 // It will be analyzed later.
1336 Vars.push_back(DE);
1337 continue;
1338 }
1339
Alexey Bataeva769e072013-03-22 06:34:35 +00001340 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1341 // A threadprivate variable must not have an incomplete type.
1342 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001343 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001344 continue;
1345 }
1346
1347 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1348 // A threadprivate variable must not have a reference type.
1349 if (VD->getType()->isReferenceType()) {
1350 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001351 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1352 bool IsDecl =
1353 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1354 Diag(VD->getLocation(),
1355 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1356 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001357 continue;
1358 }
1359
Samuel Antaof8b50122015-07-13 22:54:53 +00001360 // Check if this is a TLS variable. If TLS is not being supported, produce
1361 // the corresponding diagnostic.
1362 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1363 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1364 getLangOpts().OpenMPUseTLS &&
1365 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00001366 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1367 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00001368 Diag(ILoc, diag::err_omp_var_thread_local)
1369 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00001370 bool IsDecl =
1371 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1372 Diag(VD->getLocation(),
1373 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1374 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001375 continue;
1376 }
1377
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001378 // Check if initial value of threadprivate variable reference variable with
1379 // local storage (it is not supported by runtime).
1380 if (auto Init = VD->getAnyInitializer()) {
1381 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001382 if (Checker.Visit(Init))
1383 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001384 }
1385
Alexey Bataeved09d242014-05-28 05:53:51 +00001386 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00001387 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00001388 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1389 Context, SourceRange(Loc, Loc)));
1390 if (auto *ML = Context.getASTMutationListener())
1391 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00001392 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001393 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001394 if (!Vars.empty()) {
1395 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1396 Vars);
1397 D->setAccess(AS_public);
1398 }
1399 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00001400}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001401
Alexey Bataev7ff55242014-06-19 09:13:45 +00001402static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001403 const ValueDecl *D, DSAStackTy::DSAVarData DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00001404 bool IsLoopIterVar = false) {
1405 if (DVar.RefExpr) {
1406 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1407 << getOpenMPClauseName(DVar.CKind);
1408 return;
1409 }
1410 enum {
1411 PDSA_StaticMemberShared,
1412 PDSA_StaticLocalVarShared,
1413 PDSA_LoopIterVarPrivate,
1414 PDSA_LoopIterVarLinear,
1415 PDSA_LoopIterVarLastprivate,
1416 PDSA_ConstVarShared,
1417 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001418 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001419 PDSA_LocalVarPrivate,
1420 PDSA_Implicit
1421 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001422 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001423 auto ReportLoc = D->getLocation();
1424 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00001425 if (IsLoopIterVar) {
1426 if (DVar.CKind == OMPC_private)
1427 Reason = PDSA_LoopIterVarPrivate;
1428 else if (DVar.CKind == OMPC_lastprivate)
1429 Reason = PDSA_LoopIterVarLastprivate;
1430 else
1431 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00001432 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1433 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001434 Reason = PDSA_TaskVarFirstprivate;
1435 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001436 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001437 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001438 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001439 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001440 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001441 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001442 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00001443 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001444 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001445 ReportHint = true;
1446 Reason = PDSA_LocalVarPrivate;
1447 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001448 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001449 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001450 << Reason << ReportHint
1451 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1452 } else if (DVar.ImplicitDSALoc.isValid()) {
1453 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1454 << getOpenMPClauseName(DVar.CKind);
1455 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001456}
1457
Alexey Bataev758e55e2013-09-06 18:03:48 +00001458namespace {
1459class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1460 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001461 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001462 bool ErrorFound;
1463 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001464 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001465 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataeved09d242014-05-28 05:53:51 +00001466
Alexey Bataev758e55e2013-09-06 18:03:48 +00001467public:
1468 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001469 if (E->isTypeDependent() || E->isValueDependent() ||
1470 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1471 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001472 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001473 // Skip internally declared variables.
Alexey Bataeved09d242014-05-28 05:53:51 +00001474 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1475 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001476
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001477 auto DVar = Stack->getTopDSA(VD, false);
1478 // Check if the variable has explicit DSA set and stop analysis if it so.
David Majnemer9d168222016-08-05 17:44:54 +00001479 if (DVar.RefExpr)
1480 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001481
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001482 auto ELoc = E->getExprLoc();
1483 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001484 // The default(none) clause requires that each variable that is referenced
1485 // in the construct, and does not have a predetermined data-sharing
1486 // attribute, must have its data-sharing attribute explicitly determined
1487 // by being listed in a data-sharing attribute clause.
1488 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001489 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001490 VarsWithInheritedDSA.count(VD) == 0) {
1491 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001492 return;
1493 }
1494
1495 // OpenMP [2.9.3.6, Restrictions, p.2]
1496 // A list item that appears in a reduction clause of the innermost
1497 // enclosing worksharing or parallel construct may not be accessed in an
1498 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001499 DVar = Stack->hasInnermostDSA(
1500 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1501 [](OpenMPDirectiveKind K) -> bool {
1502 return isOpenMPParallelDirective(K) ||
1503 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1504 },
1505 false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001506 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00001507 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001508 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1509 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001510 return;
1511 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001512
1513 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001514 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001515 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1516 !Stack->isLoopControlVariable(VD).first)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001517 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001518 }
1519 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001520 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001521 if (E->isTypeDependent() || E->isValueDependent() ||
1522 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1523 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001524 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
1525 if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
1526 auto DVar = Stack->getTopDSA(FD, false);
1527 // Check if the variable has explicit DSA set and stop analysis if it
1528 // so.
1529 if (DVar.RefExpr)
1530 return;
1531
1532 auto ELoc = E->getExprLoc();
1533 auto DKind = Stack->getCurrentDirective();
1534 // OpenMP [2.9.3.6, Restrictions, p.2]
1535 // A list item that appears in a reduction clause of the innermost
1536 // enclosing worksharing or parallel construct may not be accessed in
Alexey Bataevd985eda2016-02-10 11:29:16 +00001537 // an explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001538 DVar = Stack->hasInnermostDSA(
1539 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1540 [](OpenMPDirectiveKind K) -> bool {
1541 return isOpenMPParallelDirective(K) ||
1542 isOpenMPWorksharingDirective(K) ||
1543 isOpenMPTeamsDirective(K);
1544 },
1545 false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001546 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001547 ErrorFound = true;
1548 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1549 ReportOriginalDSA(SemaRef, Stack, FD, DVar);
1550 return;
1551 }
1552
1553 // Define implicit data-sharing attributes for task.
1554 DVar = Stack->getImplicitDSA(FD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001555 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1556 !Stack->isLoopControlVariable(FD).first)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001557 ImplicitFirstprivate.push_back(E);
1558 }
Alexey Bataev7fcacd82016-11-28 15:55:15 +00001559 } else
1560 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001561 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001562 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001563 for (auto *C : S->clauses()) {
1564 // Skip analysis of arguments of implicitly defined firstprivate clause
1565 // for task directives.
1566 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1567 for (auto *CC : C->children()) {
1568 if (CC)
1569 Visit(CC);
1570 }
1571 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001572 }
1573 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001574 for (auto *C : S->children()) {
1575 if (C && !isa<OMPExecutableDirective>(C))
1576 Visit(C);
1577 }
Alexey Bataeved09d242014-05-28 05:53:51 +00001578 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001579
1580 bool isErrorFound() { return ErrorFound; }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001581 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001582 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
Alexey Bataev4acb8592014-07-07 13:01:15 +00001583 return VarsWithInheritedDSA;
1584 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001585
Alexey Bataev7ff55242014-06-19 09:13:45 +00001586 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1587 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00001588};
Alexey Bataeved09d242014-05-28 05:53:51 +00001589} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00001590
Alexey Bataevbae9a792014-06-27 10:37:06 +00001591void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001592 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00001593 case OMPD_parallel:
1594 case OMPD_parallel_for:
1595 case OMPD_parallel_for_simd:
1596 case OMPD_parallel_sections:
1597 case OMPD_teams: {
Alexey Bataev9959db52014-05-06 10:08:46 +00001598 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001599 QualType KmpInt32PtrTy =
1600 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001601 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001602 std::make_pair(".global_tid.", KmpInt32PtrTy),
1603 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1604 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001605 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001606 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1607 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001608 break;
1609 }
Kelvin Li70a12c52016-07-13 21:51:49 +00001610 case OMPD_simd:
1611 case OMPD_for:
1612 case OMPD_for_simd:
1613 case OMPD_sections:
1614 case OMPD_section:
1615 case OMPD_single:
1616 case OMPD_master:
1617 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00001618 case OMPD_taskgroup:
1619 case OMPD_distribute:
Kelvin Li70a12c52016-07-13 21:51:49 +00001620 case OMPD_ordered:
1621 case OMPD_atomic:
1622 case OMPD_target_data:
1623 case OMPD_target:
1624 case OMPD_target_parallel:
1625 case OMPD_target_parallel_for:
Kelvin Li986330c2016-07-20 22:57:10 +00001626 case OMPD_target_parallel_for_simd:
1627 case OMPD_target_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001628 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001629 std::make_pair(StringRef(), QualType()) // __context with shared vars
1630 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001631 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1632 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001633 break;
1634 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001635 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001636 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001637 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1638 FunctionProtoType::ExtProtoInfo EPI;
1639 EPI.Variadic = true;
1640 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001641 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001642 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataev48591dd2016-04-20 04:01:36 +00001643 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1644 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
1645 std::make_pair(".copy_fn.",
1646 Context.getPointerType(CopyFnType).withConst()),
1647 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001648 std::make_pair(StringRef(), QualType()) // __context with shared vars
1649 };
1650 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1651 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001652 // Mark this captured region as inlined, because we don't use outlined
1653 // function directly.
1654 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1655 AlwaysInlineAttr::CreateImplicit(
1656 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001657 break;
1658 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00001659 case OMPD_taskloop:
1660 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00001661 QualType KmpInt32Ty =
1662 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1663 QualType KmpUInt64Ty =
1664 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
1665 QualType KmpInt64Ty =
1666 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
1667 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1668 FunctionProtoType::ExtProtoInfo EPI;
1669 EPI.Variadic = true;
1670 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00001671 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00001672 std::make_pair(".global_tid.", KmpInt32Ty),
1673 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1674 std::make_pair(".privates.",
1675 Context.VoidPtrTy.withConst().withRestrict()),
1676 std::make_pair(
1677 ".copy_fn.",
1678 Context.getPointerType(CopyFnType).withConst().withRestrict()),
1679 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1680 std::make_pair(".lb.", KmpUInt64Ty),
1681 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
1682 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataev49f6e782015-12-01 04:18:41 +00001683 std::make_pair(StringRef(), QualType()) // __context with shared vars
1684 };
1685 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1686 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00001687 // Mark this captured region as inlined, because we don't use outlined
1688 // function directly.
1689 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1690 AlwaysInlineAttr::CreateImplicit(
1691 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev49f6e782015-12-01 04:18:41 +00001692 break;
1693 }
Kelvin Li4a39add2016-07-05 05:00:15 +00001694 case OMPD_distribute_parallel_for_simd:
Kelvin Li787f3fc2016-07-06 04:45:38 +00001695 case OMPD_distribute_simd:
Kelvin Li02532872016-08-05 14:37:37 +00001696 case OMPD_distribute_parallel_for:
Kelvin Li4e325f72016-10-25 12:50:55 +00001697 case OMPD_teams_distribute:
Kelvin Li579e41c2016-11-30 23:51:03 +00001698 case OMPD_teams_distribute_simd:
Kelvin Li7ade93f2016-12-09 03:24:30 +00001699 case OMPD_teams_distribute_parallel_for_simd:
1700 case OMPD_teams_distribute_parallel_for: {
Carlo Bertolli9925f152016-06-27 14:55:37 +00001701 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1702 QualType KmpInt32PtrTy =
1703 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1704 Sema::CapturedParamNameType Params[] = {
1705 std::make_pair(".global_tid.", KmpInt32PtrTy),
1706 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1707 std::make_pair(".previous.lb.", Context.getSizeType()),
1708 std::make_pair(".previous.ub.", Context.getSizeType()),
1709 std::make_pair(StringRef(), QualType()) // __context with shared vars
1710 };
1711 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1712 Params);
1713 break;
1714 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001715 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001716 case OMPD_taskyield:
1717 case OMPD_barrier:
1718 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001719 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00001720 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00001721 case OMPD_flush:
Samuel Antaodf67fc42016-01-19 19:15:56 +00001722 case OMPD_target_enter_data:
Samuel Antao72590762016-01-19 20:04:50 +00001723 case OMPD_target_exit_data:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00001724 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00001725 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001726 case OMPD_declare_target:
1727 case OMPD_end_declare_target:
Samuel Antao686c70c2016-05-26 17:30:50 +00001728 case OMPD_target_update:
Alexey Bataev9959db52014-05-06 10:08:46 +00001729 llvm_unreachable("OpenMP Directive is not allowed");
1730 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001731 llvm_unreachable("Unknown OpenMP directive");
1732 }
1733}
1734
Alexey Bataev3392d762016-02-16 11:18:12 +00001735static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00001736 Expr *CaptureExpr, bool WithInit,
1737 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001738 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00001739 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00001740 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00001741 QualType Ty = Init->getType();
1742 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
1743 if (S.getLangOpts().CPlusPlus)
1744 Ty = C.getLValueReferenceType(Ty);
1745 else {
1746 Ty = C.getPointerType(Ty);
1747 ExprResult Res =
1748 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
1749 if (!Res.isUsable())
1750 return nullptr;
1751 Init = Res.get();
1752 }
Alexey Bataev61205072016-03-02 04:57:40 +00001753 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00001754 }
1755 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001756 if (!WithInit)
1757 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
Alexey Bataev4244be22016-02-11 05:35:55 +00001758 S.CurContext->addHiddenDecl(CED);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001759 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false,
1760 /*TypeMayContainAuto=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00001761 return CED;
1762}
1763
Alexey Bataev61205072016-03-02 04:57:40 +00001764static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
1765 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00001766 OMPCapturedExprDecl *CD;
1767 if (auto *VD = S.IsOpenMPCapturedDecl(D))
1768 CD = cast<OMPCapturedExprDecl>(VD);
1769 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00001770 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
1771 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001772 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00001773 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00001774}
1775
Alexey Bataev5a3af132016-03-29 08:58:54 +00001776static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
1777 if (!Ref) {
1778 auto *CD =
1779 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
1780 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
1781 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
1782 CaptureExpr->getExprLoc());
1783 }
1784 ExprResult Res = Ref;
1785 if (!S.getLangOpts().CPlusPlus &&
1786 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
1787 Ref->getType()->isPointerType())
1788 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
1789 if (!Res.isUsable())
1790 return ExprError();
1791 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00001792}
1793
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001794StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1795 ArrayRef<OMPClause *> Clauses) {
1796 if (!S.isUsable()) {
1797 ActOnCapturedRegionError();
1798 return StmtError();
1799 }
Alexey Bataev993d2802015-12-28 06:23:08 +00001800
1801 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00001802 OMPScheduleClause *SC = nullptr;
Alexey Bataev993d2802015-12-28 06:23:08 +00001803 SmallVector<OMPLinearClause *, 4> LCs;
Alexey Bataev040d5402015-05-12 08:35:28 +00001804 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001805 for (auto *Clause : Clauses) {
Alexey Bataev16dc7b62015-05-20 03:46:04 +00001806 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001807 Clause->getClauseKind() == OMPC_copyprivate ||
1808 (getLangOpts().OpenMPUseTLS &&
1809 getASTContext().getTargetInfo().isTLSSupported() &&
1810 Clause->getClauseKind() == OMPC_copyin)) {
1811 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00001812 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001813 for (auto *VarRef : Clause->children()) {
1814 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00001815 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001816 }
1817 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001818 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001819 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
Alexey Bataev040d5402015-05-12 08:35:28 +00001820 // Mark all variables in private list clauses as used in inner region.
1821 // Required for proper codegen of combined directives.
1822 // TODO: add processing for other clauses.
Alexey Bataev3392d762016-02-16 11:18:12 +00001823 if (auto *C = OMPClauseWithPreInit::get(Clause)) {
Alexey Bataev005248a2016-02-25 05:25:57 +00001824 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
1825 for (auto *D : DS->decls())
Alexey Bataev3392d762016-02-16 11:18:12 +00001826 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
1827 }
Alexey Bataev4244be22016-02-11 05:35:55 +00001828 }
Alexey Bataev005248a2016-02-25 05:25:57 +00001829 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
1830 if (auto *E = C->getPostUpdateExpr())
1831 MarkDeclarationsReferencedInExpr(E);
1832 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001833 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001834 if (Clause->getClauseKind() == OMPC_schedule)
1835 SC = cast<OMPScheduleClause>(Clause);
1836 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00001837 OC = cast<OMPOrderedClause>(Clause);
1838 else if (Clause->getClauseKind() == OMPC_linear)
1839 LCs.push_back(cast<OMPLinearClause>(Clause));
1840 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001841 bool ErrorFound = false;
1842 // OpenMP, 2.7.1 Loop Construct, Restrictions
1843 // The nonmonotonic modifier cannot be specified if an ordered clause is
1844 // specified.
1845 if (SC &&
1846 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
1847 SC->getSecondScheduleModifier() ==
1848 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
1849 OC) {
1850 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
1851 ? SC->getFirstScheduleModifierLoc()
1852 : SC->getSecondScheduleModifierLoc(),
1853 diag::err_omp_schedule_nonmonotonic_ordered)
1854 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1855 ErrorFound = true;
1856 }
Alexey Bataev993d2802015-12-28 06:23:08 +00001857 if (!LCs.empty() && OC && OC->getNumForLoops()) {
1858 for (auto *C : LCs) {
1859 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
1860 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1861 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001862 ErrorFound = true;
1863 }
Alexey Bataev113438c2015-12-30 12:06:23 +00001864 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
1865 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
1866 OC->getNumForLoops()) {
1867 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
1868 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
1869 ErrorFound = true;
1870 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001871 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00001872 ActOnCapturedRegionError();
1873 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001874 }
1875 return ActOnCapturedRegionEnd(S.get());
1876}
1877
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001878static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1879 OpenMPDirectiveKind CurrentRegion,
1880 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001881 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001882 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001883 if (Stack->getCurScope()) {
1884 auto ParentRegion = Stack->getParentDirective();
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001885 auto OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00001886 bool NestingProhibited = false;
1887 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00001888 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001889 enum {
1890 NoRecommend,
1891 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00001892 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00001893 ShouldBeInTargetRegion,
1894 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001895 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00001896 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001897 // OpenMP [2.16, Nesting of Regions]
1898 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00001899 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00001900 // An ordered construct with the simd clause is the only OpenMP
1901 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00001902 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00001903 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
1904 // message.
1905 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
1906 ? diag::err_omp_prohibited_region_simd
1907 : diag::warn_omp_nesting_simd);
1908 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00001909 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001910 if (ParentRegion == OMPD_atomic) {
1911 // OpenMP [2.16, Nesting of Regions]
1912 // OpenMP constructs may not be nested inside an atomic region.
1913 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1914 return true;
1915 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001916 if (CurrentRegion == OMPD_section) {
1917 // OpenMP [2.7.2, sections Construct, Restrictions]
1918 // Orphaned section directives are prohibited. That is, the section
1919 // directives must appear within the sections construct and must not be
1920 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001921 if (ParentRegion != OMPD_sections &&
1922 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001923 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
1924 << (ParentRegion != OMPD_unknown)
1925 << getOpenMPDirectiveName(ParentRegion);
1926 return true;
1927 }
1928 return false;
1929 }
Kelvin Li2b51f722016-07-26 04:32:50 +00001930 // Allow some constructs (except teams) to be orphaned (they could be
David Majnemer9d168222016-08-05 17:44:54 +00001931 // used in functions, called from OpenMP regions with the required
Kelvin Li2b51f722016-07-26 04:32:50 +00001932 // preconditions).
1933 if (ParentRegion == OMPD_unknown && !isOpenMPTeamsDirective(CurrentRegion))
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001934 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00001935 if (CurrentRegion == OMPD_cancellation_point ||
1936 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001937 // OpenMP [2.16, Nesting of Regions]
1938 // A cancellation point construct for which construct-type-clause is
1939 // taskgroup must be nested inside a task construct. A cancellation
1940 // point construct for which construct-type-clause is not taskgroup must
1941 // be closely nested inside an OpenMP construct that matches the type
1942 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00001943 // A cancel construct for which construct-type-clause is taskgroup must be
1944 // nested inside a task construct. A cancel construct for which
1945 // construct-type-clause is not taskgroup must be closely nested inside an
1946 // OpenMP construct that matches the type specified in
1947 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001948 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00001949 !((CancelRegion == OMPD_parallel &&
1950 (ParentRegion == OMPD_parallel ||
1951 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00001952 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00001953 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
1954 ParentRegion == OMPD_target_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001955 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
1956 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00001957 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
1958 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001959 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00001960 // OpenMP [2.16, Nesting of Regions]
1961 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001962 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00001963 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00001964 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001965 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
1966 // OpenMP [2.16, Nesting of Regions]
1967 // A critical region may not be nested (closely or otherwise) inside a
1968 // critical region with the same name. Note that this restriction is not
1969 // sufficient to prevent deadlock.
1970 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00001971 bool DeadLock = Stack->hasDirective(
1972 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
1973 const DeclarationNameInfo &DNI,
1974 SourceLocation Loc) -> bool {
1975 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
1976 PreviousCriticalLoc = Loc;
1977 return true;
1978 } else
1979 return false;
1980 },
1981 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001982 if (DeadLock) {
1983 SemaRef.Diag(StartLoc,
1984 diag::err_omp_prohibited_region_critical_same_name)
1985 << CurrentName.getName();
1986 if (PreviousCriticalLoc.isValid())
1987 SemaRef.Diag(PreviousCriticalLoc,
1988 diag::note_omp_previous_critical_region);
1989 return true;
1990 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001991 } else if (CurrentRegion == OMPD_barrier) {
1992 // OpenMP [2.16, Nesting of Regions]
1993 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001994 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00001995 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
1996 isOpenMPTaskingDirective(ParentRegion) ||
1997 ParentRegion == OMPD_master ||
1998 ParentRegion == OMPD_critical ||
1999 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00002000 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00002001 !isOpenMPParallelDirective(CurrentRegion) &&
2002 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002003 // OpenMP [2.16, Nesting of Regions]
2004 // A worksharing region may not be closely nested inside a worksharing,
2005 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002006 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2007 isOpenMPTaskingDirective(ParentRegion) ||
2008 ParentRegion == OMPD_master ||
2009 ParentRegion == OMPD_critical ||
2010 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002011 Recommend = ShouldBeInParallelRegion;
2012 } else if (CurrentRegion == OMPD_ordered) {
2013 // OpenMP [2.16, Nesting of Regions]
2014 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002015 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002016 // An ordered region must be closely nested inside a loop region (or
2017 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002018 // OpenMP [2.8.1,simd Construct, Restrictions]
2019 // An ordered construct with the simd clause is the only OpenMP construct
2020 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002021 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002022 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002023 !(isOpenMPSimdDirective(ParentRegion) ||
2024 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002025 Recommend = ShouldBeInOrderedRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002026 } else if (isOpenMPTeamsDirective(CurrentRegion)) {
2027 // OpenMP [2.16, Nesting of Regions]
2028 // If specified, a teams construct must be contained within a target
2029 // construct.
2030 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00002031 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002032 Recommend = ShouldBeInTargetRegion;
2033 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2034 }
Kelvin Li02532872016-08-05 14:37:37 +00002035 if (!NestingProhibited && ParentRegion == OMPD_teams) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002036 // OpenMP [2.16, Nesting of Regions]
2037 // distribute, parallel, parallel sections, parallel workshare, and the
2038 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2039 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002040 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2041 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002042 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002043 }
David Majnemer9d168222016-08-05 17:44:54 +00002044 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00002045 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002046 // OpenMP 4.5 [2.17 Nesting of Regions]
2047 // The region associated with the distribute construct must be strictly
2048 // nested inside a teams region
Kelvin Li02532872016-08-05 14:37:37 +00002049 NestingProhibited = ParentRegion != OMPD_teams;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002050 Recommend = ShouldBeInTeamsRegion;
2051 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002052 if (!NestingProhibited &&
2053 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2054 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2055 // OpenMP 4.5 [2.17 Nesting of Regions]
2056 // If a target, target update, target data, target enter data, or
2057 // target exit data construct is encountered during execution of a
2058 // target region, the behavior is unspecified.
2059 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002060 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2061 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002062 if (isOpenMPTargetExecutionDirective(K)) {
2063 OffendingRegion = K;
2064 return true;
2065 } else
2066 return false;
2067 },
2068 false /* don't skip top directive */);
2069 CloseNesting = false;
2070 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002071 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00002072 if (OrphanSeen) {
2073 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2074 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2075 } else {
2076 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2077 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2078 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2079 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002080 return true;
2081 }
2082 }
2083 return false;
2084}
2085
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002086static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2087 ArrayRef<OMPClause *> Clauses,
2088 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2089 bool ErrorFound = false;
2090 unsigned NamedModifiersNumber = 0;
2091 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2092 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002093 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002094 for (const auto *C : Clauses) {
2095 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2096 // At most one if clause without a directive-name-modifier can appear on
2097 // the directive.
2098 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2099 if (FoundNameModifiers[CurNM]) {
2100 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2101 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2102 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2103 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002104 } else if (CurNM != OMPD_unknown) {
2105 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002106 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002107 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002108 FoundNameModifiers[CurNM] = IC;
2109 if (CurNM == OMPD_unknown)
2110 continue;
2111 // Check if the specified name modifier is allowed for the current
2112 // directive.
2113 // At most one if clause with the particular directive-name-modifier can
2114 // appear on the directive.
2115 bool MatchFound = false;
2116 for (auto NM : AllowedNameModifiers) {
2117 if (CurNM == NM) {
2118 MatchFound = true;
2119 break;
2120 }
2121 }
2122 if (!MatchFound) {
2123 S.Diag(IC->getNameModifierLoc(),
2124 diag::err_omp_wrong_if_directive_name_modifier)
2125 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2126 ErrorFound = true;
2127 }
2128 }
2129 }
2130 // If any if clause on the directive includes a directive-name-modifier then
2131 // all if clauses on the directive must include a directive-name-modifier.
2132 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2133 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2134 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2135 diag::err_omp_no_more_if_clause);
2136 } else {
2137 std::string Values;
2138 std::string Sep(", ");
2139 unsigned AllowedCnt = 0;
2140 unsigned TotalAllowedNum =
2141 AllowedNameModifiers.size() - NamedModifiersNumber;
2142 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2143 ++Cnt) {
2144 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2145 if (!FoundNameModifiers[NM]) {
2146 Values += "'";
2147 Values += getOpenMPDirectiveName(NM);
2148 Values += "'";
2149 if (AllowedCnt + 2 == TotalAllowedNum)
2150 Values += " or ";
2151 else if (AllowedCnt + 1 != TotalAllowedNum)
2152 Values += Sep;
2153 ++AllowedCnt;
2154 }
2155 }
2156 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2157 diag::err_omp_unnamed_if_clause)
2158 << (TotalAllowedNum > 1) << Values;
2159 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002160 for (auto Loc : NameModifierLoc) {
2161 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2162 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002163 ErrorFound = true;
2164 }
2165 return ErrorFound;
2166}
2167
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002168StmtResult Sema::ActOnOpenMPExecutableDirective(
2169 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2170 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2171 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002172 StmtResult Res = StmtError();
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002173 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
2174 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002175 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002176
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002177 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002178 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002179 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002180 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00002181 if (AStmt) {
2182 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2183
2184 // Check default data sharing attributes for referenced variables.
2185 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
2186 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
2187 if (DSAChecker.isErrorFound())
2188 return StmtError();
2189 // Generate list of implicitly defined firstprivate variables.
2190 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00002191
2192 if (!DSAChecker.getImplicitFirstprivate().empty()) {
2193 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2194 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
2195 SourceLocation(), SourceLocation())) {
2196 ClausesWithImplicit.push_back(Implicit);
2197 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2198 DSAChecker.getImplicitFirstprivate().size();
2199 } else
2200 ErrorFound = true;
2201 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002202 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002203
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002204 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002205 switch (Kind) {
2206 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00002207 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2208 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002209 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002210 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002211 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002212 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2213 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002214 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002215 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002216 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2217 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002218 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00002219 case OMPD_for_simd:
2220 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2221 EndLoc, VarsWithInheritedDSA);
2222 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002223 case OMPD_sections:
2224 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2225 EndLoc);
2226 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002227 case OMPD_section:
2228 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00002229 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002230 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2231 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002232 case OMPD_single:
2233 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2234 EndLoc);
2235 break;
Alexander Musman80c22892014-07-17 08:54:58 +00002236 case OMPD_master:
2237 assert(ClausesWithImplicit.empty() &&
2238 "No clauses are allowed for 'omp master' directive");
2239 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2240 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002241 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00002242 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2243 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002244 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002245 case OMPD_parallel_for:
2246 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2247 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002248 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002249 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00002250 case OMPD_parallel_for_simd:
2251 Res = ActOnOpenMPParallelForSimdDirective(
2252 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002253 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002254 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002255 case OMPD_parallel_sections:
2256 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2257 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002258 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002259 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002260 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002261 Res =
2262 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002263 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002264 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00002265 case OMPD_taskyield:
2266 assert(ClausesWithImplicit.empty() &&
2267 "No clauses are allowed for 'omp taskyield' directive");
2268 assert(AStmt == nullptr &&
2269 "No associated statement allowed for 'omp taskyield' directive");
2270 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2271 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002272 case OMPD_barrier:
2273 assert(ClausesWithImplicit.empty() &&
2274 "No clauses are allowed for 'omp barrier' directive");
2275 assert(AStmt == nullptr &&
2276 "No associated statement allowed for 'omp barrier' directive");
2277 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2278 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00002279 case OMPD_taskwait:
2280 assert(ClausesWithImplicit.empty() &&
2281 "No clauses are allowed for 'omp taskwait' directive");
2282 assert(AStmt == nullptr &&
2283 "No associated statement allowed for 'omp taskwait' directive");
2284 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2285 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002286 case OMPD_taskgroup:
2287 assert(ClausesWithImplicit.empty() &&
2288 "No clauses are allowed for 'omp taskgroup' directive");
2289 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
2290 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00002291 case OMPD_flush:
2292 assert(AStmt == nullptr &&
2293 "No associated statement allowed for 'omp flush' directive");
2294 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2295 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002296 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00002297 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2298 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002299 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00002300 case OMPD_atomic:
2301 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2302 EndLoc);
2303 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002304 case OMPD_teams:
2305 Res =
2306 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2307 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002308 case OMPD_target:
2309 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2310 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002311 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002312 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002313 case OMPD_target_parallel:
2314 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2315 StartLoc, EndLoc);
2316 AllowedNameModifiers.push_back(OMPD_target);
2317 AllowedNameModifiers.push_back(OMPD_parallel);
2318 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002319 case OMPD_target_parallel_for:
2320 Res = ActOnOpenMPTargetParallelForDirective(
2321 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2322 AllowedNameModifiers.push_back(OMPD_target);
2323 AllowedNameModifiers.push_back(OMPD_parallel);
2324 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002325 case OMPD_cancellation_point:
2326 assert(ClausesWithImplicit.empty() &&
2327 "No clauses are allowed for 'omp cancellation point' directive");
2328 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2329 "cancellation point' directive");
2330 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2331 break;
Alexey Bataev80909872015-07-02 11:25:17 +00002332 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00002333 assert(AStmt == nullptr &&
2334 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00002335 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2336 CancelRegion);
2337 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00002338 break;
Michael Wong65f367f2015-07-21 13:44:28 +00002339 case OMPD_target_data:
2340 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2341 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002342 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00002343 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00002344 case OMPD_target_enter_data:
2345 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
2346 EndLoc);
2347 AllowedNameModifiers.push_back(OMPD_target_enter_data);
2348 break;
Samuel Antao72590762016-01-19 20:04:50 +00002349 case OMPD_target_exit_data:
2350 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
2351 EndLoc);
2352 AllowedNameModifiers.push_back(OMPD_target_exit_data);
2353 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00002354 case OMPD_taskloop:
2355 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
2356 EndLoc, VarsWithInheritedDSA);
2357 AllowedNameModifiers.push_back(OMPD_taskloop);
2358 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002359 case OMPD_taskloop_simd:
2360 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2361 EndLoc, VarsWithInheritedDSA);
2362 AllowedNameModifiers.push_back(OMPD_taskloop);
2363 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002364 case OMPD_distribute:
2365 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
2366 EndLoc, VarsWithInheritedDSA);
2367 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00002368 case OMPD_target_update:
2369 assert(!AStmt && "Statement is not allowed for target update");
2370 Res =
2371 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc);
2372 AllowedNameModifiers.push_back(OMPD_target_update);
2373 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00002374 case OMPD_distribute_parallel_for:
2375 Res = ActOnOpenMPDistributeParallelForDirective(
2376 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2377 AllowedNameModifiers.push_back(OMPD_parallel);
2378 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00002379 case OMPD_distribute_parallel_for_simd:
2380 Res = ActOnOpenMPDistributeParallelForSimdDirective(
2381 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2382 AllowedNameModifiers.push_back(OMPD_parallel);
2383 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00002384 case OMPD_distribute_simd:
2385 Res = ActOnOpenMPDistributeSimdDirective(
2386 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2387 break;
Kelvin Lia579b912016-07-14 02:54:56 +00002388 case OMPD_target_parallel_for_simd:
2389 Res = ActOnOpenMPTargetParallelForSimdDirective(
2390 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2391 AllowedNameModifiers.push_back(OMPD_target);
2392 AllowedNameModifiers.push_back(OMPD_parallel);
2393 break;
Kelvin Li986330c2016-07-20 22:57:10 +00002394 case OMPD_target_simd:
2395 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2396 EndLoc, VarsWithInheritedDSA);
2397 AllowedNameModifiers.push_back(OMPD_target);
2398 break;
Kelvin Li02532872016-08-05 14:37:37 +00002399 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00002400 Res = ActOnOpenMPTeamsDistributeDirective(
2401 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00002402 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00002403 case OMPD_teams_distribute_simd:
2404 Res = ActOnOpenMPTeamsDistributeSimdDirective(
2405 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2406 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00002407 case OMPD_teams_distribute_parallel_for_simd:
2408 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
2409 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2410 AllowedNameModifiers.push_back(OMPD_parallel);
2411 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00002412 case OMPD_teams_distribute_parallel_for:
2413 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
2414 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2415 AllowedNameModifiers.push_back(OMPD_parallel);
2416 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002417 case OMPD_declare_target:
2418 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002419 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002420 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002421 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002422 llvm_unreachable("OpenMP Directive is not allowed");
2423 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002424 llvm_unreachable("Unknown OpenMP directive");
2425 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002426
Alexey Bataev4acb8592014-07-07 13:01:15 +00002427 for (auto P : VarsWithInheritedDSA) {
2428 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2429 << P.first << P.second->getSourceRange();
2430 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002431 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
2432
2433 if (!AllowedNameModifiers.empty())
2434 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
2435 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002436
Alexey Bataeved09d242014-05-28 05:53:51 +00002437 if (ErrorFound)
2438 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002439 return Res;
2440}
2441
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002442Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
2443 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00002444 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00002445 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
2446 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00002447 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00002448 assert(Linears.size() == LinModifiers.size());
2449 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00002450 if (!DG || DG.get().isNull())
2451 return DeclGroupPtrTy();
2452
2453 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00002454 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002455 return DG;
2456 }
2457 auto *ADecl = DG.get().getSingleDecl();
2458 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
2459 ADecl = FTD->getTemplatedDecl();
2460
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002461 auto *FD = dyn_cast<FunctionDecl>(ADecl);
2462 if (!FD) {
2463 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002464 return DeclGroupPtrTy();
2465 }
2466
Alexey Bataev2af33e32016-04-07 12:45:37 +00002467 // OpenMP [2.8.2, declare simd construct, Description]
2468 // The parameter of the simdlen clause must be a constant positive integer
2469 // expression.
2470 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002471 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00002472 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002473 // OpenMP [2.8.2, declare simd construct, Description]
2474 // The special this pointer can be used as if was one of the arguments to the
2475 // function in any of the linear, aligned, or uniform clauses.
2476 // The uniform clause declares one or more arguments to have an invariant
2477 // value for all concurrent invocations of the function in the execution of a
2478 // single SIMD loop.
Alexey Bataevecba70f2016-04-12 11:02:11 +00002479 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
2480 Expr *UniformedLinearThis = nullptr;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002481 for (auto *E : Uniforms) {
2482 E = E->IgnoreParenImpCasts();
2483 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2484 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
2485 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2486 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00002487 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
2488 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002489 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002490 }
2491 if (isa<CXXThisExpr>(E)) {
2492 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002493 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002494 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002495 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2496 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00002497 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00002498 // OpenMP [2.8.2, declare simd construct, Description]
2499 // The aligned clause declares that the object to which each list item points
2500 // is aligned to the number of bytes expressed in the optional parameter of
2501 // the aligned clause.
2502 // The special this pointer can be used as if was one of the arguments to the
2503 // function in any of the linear, aligned, or uniform clauses.
2504 // The type of list items appearing in the aligned clause must be array,
2505 // pointer, reference to array, or reference to pointer.
2506 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
2507 Expr *AlignedThis = nullptr;
2508 for (auto *E : Aligneds) {
2509 E = E->IgnoreParenImpCasts();
2510 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2511 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2512 auto *CanonPVD = PVD->getCanonicalDecl();
2513 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2514 FD->getParamDecl(PVD->getFunctionScopeIndex())
2515 ->getCanonicalDecl() == CanonPVD) {
2516 // OpenMP [2.8.1, simd construct, Restrictions]
2517 // A list-item cannot appear in more than one aligned clause.
2518 if (AlignedArgs.count(CanonPVD) > 0) {
2519 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2520 << 1 << E->getSourceRange();
2521 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
2522 diag::note_omp_explicit_dsa)
2523 << getOpenMPClauseName(OMPC_aligned);
2524 continue;
2525 }
2526 AlignedArgs[CanonPVD] = E;
2527 QualType QTy = PVD->getType()
2528 .getNonReferenceType()
2529 .getUnqualifiedType()
2530 .getCanonicalType();
2531 const Type *Ty = QTy.getTypePtrOrNull();
2532 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
2533 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
2534 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
2535 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
2536 }
2537 continue;
2538 }
2539 }
2540 if (isa<CXXThisExpr>(E)) {
2541 if (AlignedThis) {
2542 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2543 << 2 << E->getSourceRange();
2544 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
2545 << getOpenMPClauseName(OMPC_aligned);
2546 }
2547 AlignedThis = E;
2548 continue;
2549 }
2550 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2551 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2552 }
2553 // The optional parameter of the aligned clause, alignment, must be a constant
2554 // positive integer expression. If no optional parameter is specified,
2555 // implementation-defined default alignments for SIMD instructions on the
2556 // target platforms are assumed.
2557 SmallVector<Expr *, 4> NewAligns;
2558 for (auto *E : Alignments) {
2559 ExprResult Align;
2560 if (E)
2561 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
2562 NewAligns.push_back(Align.get());
2563 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00002564 // OpenMP [2.8.2, declare simd construct, Description]
2565 // The linear clause declares one or more list items to be private to a SIMD
2566 // lane and to have a linear relationship with respect to the iteration space
2567 // of a loop.
2568 // The special this pointer can be used as if was one of the arguments to the
2569 // function in any of the linear, aligned, or uniform clauses.
2570 // When a linear-step expression is specified in a linear clause it must be
2571 // either a constant integer expression or an integer-typed parameter that is
2572 // specified in a uniform clause on the directive.
2573 llvm::DenseMap<Decl *, Expr *> LinearArgs;
2574 const bool IsUniformedThis = UniformedLinearThis != nullptr;
2575 auto MI = LinModifiers.begin();
2576 for (auto *E : Linears) {
2577 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
2578 ++MI;
2579 E = E->IgnoreParenImpCasts();
2580 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2581 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2582 auto *CanonPVD = PVD->getCanonicalDecl();
2583 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2584 FD->getParamDecl(PVD->getFunctionScopeIndex())
2585 ->getCanonicalDecl() == CanonPVD) {
2586 // OpenMP [2.15.3.7, linear Clause, Restrictions]
2587 // A list-item cannot appear in more than one linear clause.
2588 if (LinearArgs.count(CanonPVD) > 0) {
2589 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2590 << getOpenMPClauseName(OMPC_linear)
2591 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
2592 Diag(LinearArgs[CanonPVD]->getExprLoc(),
2593 diag::note_omp_explicit_dsa)
2594 << getOpenMPClauseName(OMPC_linear);
2595 continue;
2596 }
2597 // Each argument can appear in at most one uniform or linear clause.
2598 if (UniformedArgs.count(CanonPVD) > 0) {
2599 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2600 << getOpenMPClauseName(OMPC_linear)
2601 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
2602 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
2603 diag::note_omp_explicit_dsa)
2604 << getOpenMPClauseName(OMPC_uniform);
2605 continue;
2606 }
2607 LinearArgs[CanonPVD] = E;
2608 if (E->isValueDependent() || E->isTypeDependent() ||
2609 E->isInstantiationDependent() ||
2610 E->containsUnexpandedParameterPack())
2611 continue;
2612 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
2613 PVD->getOriginalType());
2614 continue;
2615 }
2616 }
2617 if (isa<CXXThisExpr>(E)) {
2618 if (UniformedLinearThis) {
2619 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2620 << getOpenMPClauseName(OMPC_linear)
2621 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
2622 << E->getSourceRange();
2623 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
2624 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
2625 : OMPC_linear);
2626 continue;
2627 }
2628 UniformedLinearThis = E;
2629 if (E->isValueDependent() || E->isTypeDependent() ||
2630 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
2631 continue;
2632 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
2633 E->getType());
2634 continue;
2635 }
2636 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2637 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2638 }
2639 Expr *Step = nullptr;
2640 Expr *NewStep = nullptr;
2641 SmallVector<Expr *, 4> NewSteps;
2642 for (auto *E : Steps) {
2643 // Skip the same step expression, it was checked already.
2644 if (Step == E || !E) {
2645 NewSteps.push_back(E ? NewStep : nullptr);
2646 continue;
2647 }
2648 Step = E;
2649 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
2650 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2651 auto *CanonPVD = PVD->getCanonicalDecl();
2652 if (UniformedArgs.count(CanonPVD) == 0) {
2653 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
2654 << Step->getSourceRange();
2655 } else if (E->isValueDependent() || E->isTypeDependent() ||
2656 E->isInstantiationDependent() ||
2657 E->containsUnexpandedParameterPack() ||
2658 CanonPVD->getType()->hasIntegerRepresentation())
2659 NewSteps.push_back(Step);
2660 else {
2661 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
2662 << Step->getSourceRange();
2663 }
2664 continue;
2665 }
2666 NewStep = Step;
2667 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
2668 !Step->isInstantiationDependent() &&
2669 !Step->containsUnexpandedParameterPack()) {
2670 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
2671 .get();
2672 if (NewStep)
2673 NewStep = VerifyIntegerConstantExpression(NewStep).get();
2674 }
2675 NewSteps.push_back(NewStep);
2676 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002677 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
2678 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00002679 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00002680 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
2681 const_cast<Expr **>(Linears.data()), Linears.size(),
2682 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
2683 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002684 ADecl->addAttr(NewAttr);
2685 return ConvertDeclToDeclGroup(ADecl);
2686}
2687
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002688StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2689 Stmt *AStmt,
2690 SourceLocation StartLoc,
2691 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002692 if (!AStmt)
2693 return StmtError();
2694
Alexey Bataev9959db52014-05-06 10:08:46 +00002695 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2696 // 1.2.2 OpenMP Language Terminology
2697 // Structured block - An executable statement with a single entry at the
2698 // top and a single exit at the bottom.
2699 // The point of exit cannot be a branch out of the structured block.
2700 // longjmp() and throw() must not violate the entry/exit criteria.
2701 CS->getCapturedDecl()->setNothrow();
2702
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002703 getCurFunction()->setHasBranchProtectedScope();
2704
Alexey Bataev25e5b442015-09-15 12:52:43 +00002705 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
2706 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002707}
2708
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002709namespace {
2710/// \brief Helper class for checking canonical form of the OpenMP loops and
2711/// extracting iteration space of each loop in the loop nest, that will be used
2712/// for IR generation.
2713class OpenMPIterationSpaceChecker {
2714 /// \brief Reference to Sema.
2715 Sema &SemaRef;
2716 /// \brief A location for diagnostics (when there is no some better location).
2717 SourceLocation DefaultLoc;
2718 /// \brief A location for diagnostics (when increment is not compatible).
2719 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002720 /// \brief A source location for referring to loop init later.
2721 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002722 /// \brief A source location for referring to condition later.
2723 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002724 /// \brief A source location for referring to increment later.
2725 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002726 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002727 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002728 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002729 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002730 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002731 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002732 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002733 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002734 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002735 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002736 /// \brief This flag is true when condition is one of:
2737 /// Var < UB
2738 /// Var <= UB
2739 /// UB > Var
2740 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002741 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002742 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002743 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002744 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002745 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002746
2747public:
2748 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002749 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002750 /// \brief Check init-expr for canonical loop form and save loop counter
2751 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00002752 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002753 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2754 /// for less/greater and for strict/non-strict comparison.
2755 bool CheckCond(Expr *S);
2756 /// \brief Check incr-expr for canonical loop form and return true if it
2757 /// does not conform, otherwise save loop step (#Step).
2758 bool CheckInc(Expr *S);
2759 /// \brief Return the loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002760 ValueDecl *GetLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002761 /// \brief Return the reference expression to loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002762 Expr *GetLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002763 /// \brief Source range of the loop init.
2764 SourceRange GetInitSrcRange() const { return InitSrcRange; }
2765 /// \brief Source range of the loop condition.
2766 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2767 /// \brief Source range of the loop increment.
2768 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2769 /// \brief True if the step should be subtracted.
2770 bool ShouldSubtractStep() const { return SubtractStep; }
2771 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00002772 Expr *
2773 BuildNumIterations(Scope *S, const bool LimitedType,
2774 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00002775 /// \brief Build the precondition expression for the loops.
Alexey Bataev5a3af132016-03-29 08:58:54 +00002776 Expr *BuildPreCond(Scope *S, Expr *Cond,
2777 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002778 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002779 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
2780 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00002781 /// \brief Build reference expression to the private counter be used for
2782 /// codegen.
2783 Expr *BuildPrivateCounterVar() const;
David Majnemer9d168222016-08-05 17:44:54 +00002784 /// \brief Build initialization of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002785 Expr *BuildCounterInit() const;
2786 /// \brief Build step of the counter be used for codegen.
2787 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002788 /// \brief Return true if any expression is dependent.
2789 bool Dependent() const;
2790
2791private:
2792 /// \brief Check the right-hand side of an assignment in the increment
2793 /// expression.
2794 bool CheckIncRHS(Expr *RHS);
2795 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002796 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002797 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00002798 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00002799 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002800 /// \brief Helper to set loop increment.
2801 bool SetStep(Expr *NewStep, bool Subtract);
2802};
2803
2804bool OpenMPIterationSpaceChecker::Dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002805 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002806 assert(!LB && !UB && !Step);
2807 return false;
2808 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002809 return LCDecl->getType()->isDependentType() ||
2810 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
2811 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002812}
2813
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002814static Expr *getExprAsWritten(Expr *E) {
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002815 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
2816 E = ExprTemp->getSubExpr();
2817
2818 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2819 E = MTE->GetTemporaryExpr();
2820
2821 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
2822 E = Binder->getSubExpr();
2823
2824 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2825 E = ICE->getSubExprAsWritten();
2826 return E->IgnoreParens();
2827}
2828
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002829bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
2830 Expr *NewLCRefExpr,
2831 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002832 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002833 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002834 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002835 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002836 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002837 LCDecl = getCanonicalDecl(NewLCDecl);
2838 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002839 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
2840 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00002841 if ((Ctor->isCopyOrMoveConstructor() ||
2842 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2843 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002844 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002845 LB = NewLB;
2846 return false;
2847}
2848
2849bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00002850 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002851 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002852 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
2853 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002854 if (!NewUB)
2855 return true;
2856 UB = NewUB;
2857 TestIsLessOp = LessOp;
2858 TestIsStrictOp = StrictOp;
2859 ConditionSrcRange = SR;
2860 ConditionLoc = SL;
2861 return false;
2862}
2863
2864bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2865 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002866 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002867 if (!NewStep)
2868 return true;
2869 if (!NewStep->isValueDependent()) {
2870 // Check that the step is integer expression.
2871 SourceLocation StepLoc = NewStep->getLocStart();
2872 ExprResult Val =
2873 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2874 if (Val.isInvalid())
2875 return true;
2876 NewStep = Val.get();
2877
2878 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2879 // If test-expr is of form var relational-op b and relational-op is < or
2880 // <= then incr-expr must cause var to increase on each iteration of the
2881 // loop. If test-expr is of form var relational-op b and relational-op is
2882 // > or >= then incr-expr must cause var to decrease on each iteration of
2883 // the loop.
2884 // If test-expr is of form b relational-op var and relational-op is < or
2885 // <= then incr-expr must cause var to decrease on each iteration of the
2886 // loop. If test-expr is of form b relational-op var and relational-op is
2887 // > or >= then incr-expr must cause var to increase on each iteration of
2888 // the loop.
2889 llvm::APSInt Result;
2890 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
2891 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
2892 bool IsConstNeg =
2893 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002894 bool IsConstPos =
2895 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002896 bool IsConstZero = IsConstant && !Result.getBoolValue();
2897 if (UB && (IsConstZero ||
2898 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00002899 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002900 SemaRef.Diag(NewStep->getExprLoc(),
2901 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002902 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002903 SemaRef.Diag(ConditionLoc,
2904 diag::note_omp_loop_cond_requres_compatible_incr)
2905 << TestIsLessOp << ConditionSrcRange;
2906 return true;
2907 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002908 if (TestIsLessOp == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00002909 NewStep =
2910 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
2911 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00002912 Subtract = !Subtract;
2913 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002914 }
2915
2916 Step = NewStep;
2917 SubtractStep = Subtract;
2918 return false;
2919}
2920
Alexey Bataev9c821032015-04-30 04:23:23 +00002921bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002922 // Check init-expr for canonical loop form and save loop counter
2923 // variable - #Var and its initialization value - #LB.
2924 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
2925 // var = lb
2926 // integer-type var = lb
2927 // random-access-iterator-type var = lb
2928 // pointer-type var = lb
2929 //
2930 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00002931 if (EmitDiags) {
2932 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
2933 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002934 return true;
2935 }
Tim Shen4a05bb82016-06-21 20:29:17 +00002936 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
2937 if (!ExprTemp->cleanupsHaveSideEffects())
2938 S = ExprTemp->getSubExpr();
2939
Alexander Musmana5f070a2014-10-01 06:03:56 +00002940 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002941 if (Expr *E = dyn_cast<Expr>(S))
2942 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00002943 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002944 if (BO->getOpcode() == BO_Assign) {
2945 auto *LHS = BO->getLHS()->IgnoreParens();
2946 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
2947 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
2948 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
2949 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
2950 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
2951 }
2952 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
2953 if (ME->isArrow() &&
2954 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
2955 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
2956 }
2957 }
David Majnemer9d168222016-08-05 17:44:54 +00002958 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002959 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00002960 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00002961 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002962 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00002963 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002964 SemaRef.Diag(S->getLocStart(),
2965 diag::ext_omp_loop_not_canonical_init)
2966 << S->getSourceRange();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002967 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002968 }
2969 }
2970 }
David Majnemer9d168222016-08-05 17:44:54 +00002971 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002972 if (CE->getOperator() == OO_Equal) {
2973 auto *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00002974 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002975 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
2976 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
2977 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
2978 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
2979 }
2980 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
2981 if (ME->isArrow() &&
2982 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
2983 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
2984 }
2985 }
2986 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002987
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002988 if (Dependent() || SemaRef.CurContext->isDependentContext())
2989 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00002990 if (EmitDiags) {
2991 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
2992 << S->getSourceRange();
2993 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002994 return true;
2995}
2996
Alexey Bataev23b69422014-06-18 07:08:49 +00002997/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002998/// variable (which may be the loop variable) if possible.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002999static const ValueDecl *GetInitLCDecl(Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003000 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00003001 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003002 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003003 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3004 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003005 if ((Ctor->isCopyOrMoveConstructor() ||
3006 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3007 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003008 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003009 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
3010 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
3011 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
3012 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3013 return getCanonicalDecl(ME->getMemberDecl());
3014 return getCanonicalDecl(VD);
3015 }
3016 }
3017 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3018 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3019 return getCanonicalDecl(ME->getMemberDecl());
3020 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003021}
3022
3023bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3024 // Check test-expr for canonical form, save upper-bound UB, flags for
3025 // less/greater and for strict/non-strict comparison.
3026 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3027 // var relational-op b
3028 // b relational-op var
3029 //
3030 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003031 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003032 return true;
3033 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003034 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003035 SourceLocation CondLoc = S->getLocStart();
David Majnemer9d168222016-08-05 17:44:54 +00003036 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003037 if (BO->isRelationalOp()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003038 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003039 return SetUB(BO->getRHS(),
3040 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3041 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3042 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003043 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003044 return SetUB(BO->getLHS(),
3045 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3046 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3047 BO->getSourceRange(), BO->getOperatorLoc());
3048 }
David Majnemer9d168222016-08-05 17:44:54 +00003049 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003050 if (CE->getNumArgs() == 2) {
3051 auto Op = CE->getOperator();
3052 switch (Op) {
3053 case OO_Greater:
3054 case OO_GreaterEqual:
3055 case OO_Less:
3056 case OO_LessEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003057 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003058 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3059 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3060 CE->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003061 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003062 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3063 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3064 CE->getOperatorLoc());
3065 break;
3066 default:
3067 break;
3068 }
3069 }
3070 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003071 if (Dependent() || SemaRef.CurContext->isDependentContext())
3072 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003073 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003074 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003075 return true;
3076}
3077
3078bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3079 // RHS of canonical loop form increment can be:
3080 // var + incr
3081 // incr + var
3082 // var - incr
3083 //
3084 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00003085 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003086 if (BO->isAdditiveOp()) {
3087 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003088 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003089 return SetStep(BO->getRHS(), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003090 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003091 return SetStep(BO->getLHS(), false);
3092 }
David Majnemer9d168222016-08-05 17:44:54 +00003093 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003094 bool IsAdd = CE->getOperator() == OO_Plus;
3095 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003096 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003097 return SetStep(CE->getArg(1), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003098 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003099 return SetStep(CE->getArg(0), false);
3100 }
3101 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003102 if (Dependent() || SemaRef.CurContext->isDependentContext())
3103 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003104 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003105 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003106 return true;
3107}
3108
3109bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3110 // Check incr-expr for canonical loop form and return true if it
3111 // does not conform.
3112 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3113 // ++var
3114 // var++
3115 // --var
3116 // var--
3117 // var += incr
3118 // var -= incr
3119 // var = var + incr
3120 // var = incr + var
3121 // var = var - incr
3122 //
3123 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003124 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003125 return true;
3126 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003127 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3128 if (!ExprTemp->cleanupsHaveSideEffects())
3129 S = ExprTemp->getSubExpr();
3130
Alexander Musmana5f070a2014-10-01 06:03:56 +00003131 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003132 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003133 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003134 if (UO->isIncrementDecrementOp() &&
3135 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003136 return SetStep(SemaRef
3137 .ActOnIntegerConstant(UO->getLocStart(),
3138 (UO->isDecrementOp() ? -1 : 1))
3139 .get(),
3140 false);
3141 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003142 switch (BO->getOpcode()) {
3143 case BO_AddAssign:
3144 case BO_SubAssign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003145 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003146 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3147 break;
3148 case BO_Assign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003149 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003150 return CheckIncRHS(BO->getRHS());
3151 break;
3152 default:
3153 break;
3154 }
David Majnemer9d168222016-08-05 17:44:54 +00003155 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003156 switch (CE->getOperator()) {
3157 case OO_PlusPlus:
3158 case OO_MinusMinus:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003159 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003160 return SetStep(SemaRef
3161 .ActOnIntegerConstant(
3162 CE->getLocStart(),
3163 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3164 .get(),
3165 false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003166 break;
3167 case OO_PlusEqual:
3168 case OO_MinusEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003169 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003170 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3171 break;
3172 case OO_Equal:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003173 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003174 return CheckIncRHS(CE->getArg(1));
3175 break;
3176 default:
3177 break;
3178 }
3179 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003180 if (Dependent() || SemaRef.CurContext->isDependentContext())
3181 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003182 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003183 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003184 return true;
3185}
Alexander Musmana5f070a2014-10-01 06:03:56 +00003186
Alexey Bataev5a3af132016-03-29 08:58:54 +00003187static ExprResult
3188tryBuildCapture(Sema &SemaRef, Expr *Capture,
3189 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00003190 if (SemaRef.CurContext->isDependentContext())
3191 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003192 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3193 return SemaRef.PerformImplicitConversion(
3194 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3195 /*AllowExplicit=*/true);
3196 auto I = Captures.find(Capture);
3197 if (I != Captures.end())
3198 return buildCapture(SemaRef, Capture, I->second);
3199 DeclRefExpr *Ref = nullptr;
3200 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3201 Captures[Capture] = Ref;
3202 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003203}
3204
Alexander Musmana5f070a2014-10-01 06:03:56 +00003205/// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003206Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3207 Scope *S, const bool LimitedType,
3208 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003209 ExprResult Diff;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003210 auto VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003211 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003212 SemaRef.getLangOpts().CPlusPlus) {
3213 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003214 auto *UBExpr = TestIsLessOp ? UB : LB;
3215 auto *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00003216 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3217 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003218 if (!Upper || !Lower)
3219 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003220
3221 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3222
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003223 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003224 // BuildBinOp already emitted error, this one is to point user to upper
3225 // and lower bound, and to tell what is passed to 'operator-'.
3226 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3227 << Upper->getSourceRange() << Lower->getSourceRange();
3228 return nullptr;
3229 }
3230 }
3231
3232 if (!Diff.isUsable())
3233 return nullptr;
3234
3235 // Upper - Lower [- 1]
3236 if (TestIsStrictOp)
3237 Diff = SemaRef.BuildBinOp(
3238 S, DefaultLoc, BO_Sub, Diff.get(),
3239 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3240 if (!Diff.isUsable())
3241 return nullptr;
3242
3243 // Upper - Lower [- 1] + Step
Alexey Bataev5a3af132016-03-29 08:58:54 +00003244 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3245 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003246 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003247 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003248 if (!Diff.isUsable())
3249 return nullptr;
3250
3251 // Parentheses (for dumping/debugging purposes only).
3252 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3253 if (!Diff.isUsable())
3254 return nullptr;
3255
3256 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003257 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003258 if (!Diff.isUsable())
3259 return nullptr;
3260
Alexander Musman174b3ca2014-10-06 11:16:29 +00003261 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003262 QualType Type = Diff.get()->getType();
3263 auto &C = SemaRef.Context;
3264 bool UseVarType = VarType->hasIntegerRepresentation() &&
3265 C.getTypeSize(Type) > C.getTypeSize(VarType);
3266 if (!Type->isIntegerType() || UseVarType) {
3267 unsigned NewSize =
3268 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3269 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3270 : Type->hasSignedIntegerRepresentation();
3271 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00003272 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3273 Diff = SemaRef.PerformImplicitConversion(
3274 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3275 if (!Diff.isUsable())
3276 return nullptr;
3277 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003278 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003279 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00003280 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3281 if (NewSize != C.getTypeSize(Type)) {
3282 if (NewSize < C.getTypeSize(Type)) {
3283 assert(NewSize == 64 && "incorrect loop var size");
3284 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3285 << InitSrcRange << ConditionSrcRange;
3286 }
3287 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003288 NewSize, Type->hasSignedIntegerRepresentation() ||
3289 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00003290 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3291 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3292 Sema::AA_Converting, true);
3293 if (!Diff.isUsable())
3294 return nullptr;
3295 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003296 }
3297 }
3298
Alexander Musmana5f070a2014-10-01 06:03:56 +00003299 return Diff.get();
3300}
3301
Alexey Bataev5a3af132016-03-29 08:58:54 +00003302Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3303 Scope *S, Expr *Cond,
3304 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003305 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3306 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3307 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003308
Alexey Bataev5a3af132016-03-29 08:58:54 +00003309 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3310 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3311 if (!NewLB.isUsable() || !NewUB.isUsable())
3312 return nullptr;
3313
Alexey Bataev62dbb972015-04-22 11:59:37 +00003314 auto CondExpr = SemaRef.BuildBinOp(
3315 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3316 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003317 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003318 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003319 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
3320 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00003321 CondExpr = SemaRef.PerformImplicitConversion(
3322 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3323 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003324 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00003325 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3326 // Otherwise use original loop conditon and evaluate it in runtime.
3327 return CondExpr.isUsable() ? CondExpr.get() : Cond;
3328}
3329
Alexander Musmana5f070a2014-10-01 06:03:56 +00003330/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003331DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003332 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003333 auto *VD = dyn_cast<VarDecl>(LCDecl);
3334 if (!VD) {
3335 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
3336 auto *Ref = buildDeclRefExpr(
3337 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003338 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
3339 // If the loop control decl is explicitly marked as private, do not mark it
3340 // as captured again.
3341 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
3342 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003343 return Ref;
3344 }
3345 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00003346 DefaultLoc);
3347}
3348
3349Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003350 if (LCDecl && !LCDecl->isInvalidDecl()) {
3351 auto Type = LCDecl->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00003352 auto *PrivateVar =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003353 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
3354 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00003355 if (PrivateVar->isInvalidDecl())
3356 return nullptr;
3357 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3358 }
3359 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003360}
3361
Samuel Antao4c8035b2016-12-12 18:00:20 +00003362/// \brief Build initialization of the counter to be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003363Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3364
3365/// \brief Build step of the counter be used for codegen.
3366Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3367
3368/// \brief Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003369struct LoopIterationSpace final {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003370 /// \brief Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003371 Expr *PreCond = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003372 /// \brief This expression calculates the number of iterations in the loop.
3373 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003374 Expr *NumIterations = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003375 /// \brief The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003376 Expr *CounterVar = nullptr;
Alexey Bataeva8899172015-08-06 12:30:57 +00003377 /// \brief Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003378 Expr *PrivateCounterVar = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003379 /// \brief This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00003380 Expr *CounterInit = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003381 /// \brief This is step for the #CounterVar used to generate its update:
3382 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00003383 Expr *CounterStep = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003384 /// \brief Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00003385 bool Subtract = false;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003386 /// \brief Source range of the loop init.
3387 SourceRange InitSrcRange;
3388 /// \brief Source range of the loop condition.
3389 SourceRange CondSrcRange;
3390 /// \brief Source range of the loop increment.
3391 SourceRange IncSrcRange;
3392};
3393
Alexey Bataev23b69422014-06-18 07:08:49 +00003394} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003395
Alexey Bataev9c821032015-04-30 04:23:23 +00003396void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
3397 assert(getLangOpts().OpenMP && "OpenMP is not active.");
3398 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003399 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
3400 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00003401 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
3402 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003403 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
3404 if (auto *D = ISC.GetLoopDecl()) {
3405 auto *VD = dyn_cast<VarDecl>(D);
3406 if (!VD) {
3407 if (auto *Private = IsOpenMPCapturedDecl(D))
3408 VD = Private;
3409 else {
3410 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
3411 /*WithInit=*/false);
3412 VD = cast<VarDecl>(Ref->getDecl());
3413 }
3414 }
3415 DSAStack->addLoopControlVariable(D, VD);
3416 }
3417 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003418 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00003419 }
3420}
3421
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003422/// \brief Called on a for stmt to check and extract its iteration space
3423/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00003424static bool CheckOpenMPIterationSpace(
3425 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3426 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003427 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003428 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003429 LoopIterationSpace &ResultIterSpace,
3430 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003431 // OpenMP [2.6, Canonical Loop Form]
3432 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00003433 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003434 if (!For) {
3435 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003436 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
3437 << getOpenMPDirectiveName(DKind) << NestedLoopCount
3438 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
3439 if (NestedLoopCount > 1) {
3440 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
3441 SemaRef.Diag(DSA.getConstructLoc(),
3442 diag::note_omp_collapse_ordered_expr)
3443 << 2 << CollapseLoopCountExpr->getSourceRange()
3444 << OrderedLoopCountExpr->getSourceRange();
3445 else if (CollapseLoopCountExpr)
3446 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3447 diag::note_omp_collapse_ordered_expr)
3448 << 0 << CollapseLoopCountExpr->getSourceRange();
3449 else
3450 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3451 diag::note_omp_collapse_ordered_expr)
3452 << 1 << OrderedLoopCountExpr->getSourceRange();
3453 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003454 return true;
3455 }
3456 assert(For->getBody());
3457
3458 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3459
3460 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003461 auto Init = For->getInit();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003462 if (ISC.CheckInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003463 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003464
3465 bool HasErrors = false;
3466
3467 // Check loop variable's type.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003468 if (auto *LCDecl = ISC.GetLoopDecl()) {
3469 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003470
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003471 // OpenMP [2.6, Canonical Loop Form]
3472 // Var is one of the following:
3473 // A variable of signed or unsigned integer type.
3474 // For C++, a variable of a random access iterator type.
3475 // For C, a variable of a pointer type.
3476 auto VarType = LCDecl->getType().getNonReferenceType();
3477 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
3478 !VarType->isPointerType() &&
3479 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
3480 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
3481 << SemaRef.getLangOpts().CPlusPlus;
3482 HasErrors = true;
3483 }
3484
3485 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
3486 // a Construct
3487 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3488 // parallel for construct is (are) private.
3489 // The loop iteration variable in the associated for-loop of a simd
3490 // construct with just one associated for-loop is linear with a
3491 // constant-linear-step that is the increment of the associated for-loop.
3492 // Exclude loop var from the list of variables with implicitly defined data
3493 // sharing attributes.
3494 VarsWithImplicitDSA.erase(LCDecl);
3495
3496 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
3497 // in a Construct, C/C++].
3498 // The loop iteration variable in the associated for-loop of a simd
3499 // construct with just one associated for-loop may be listed in a linear
3500 // clause with a constant-linear-step that is the increment of the
3501 // associated for-loop.
3502 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3503 // parallel for construct may be listed in a private or lastprivate clause.
3504 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
3505 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
3506 // declared in the loop and it is predetermined as a private.
3507 auto PredeterminedCKind =
3508 isOpenMPSimdDirective(DKind)
3509 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
3510 : OMPC_private;
3511 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3512 DVar.CKind != PredeterminedCKind) ||
3513 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
3514 isOpenMPDistributeDirective(DKind)) &&
3515 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3516 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
3517 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
3518 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
3519 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
3520 << getOpenMPClauseName(PredeterminedCKind);
3521 if (DVar.RefExpr == nullptr)
3522 DVar.CKind = PredeterminedCKind;
3523 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
3524 HasErrors = true;
3525 } else if (LoopDeclRefExpr != nullptr) {
3526 // Make the loop iteration variable private (for worksharing constructs),
3527 // linear (for simd directives with the only one associated loop) or
3528 // lastprivate (for simd directives with several collapsed or ordered
3529 // loops).
3530 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003531 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
3532 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003533 /*FromParent=*/false);
3534 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
3535 }
3536
3537 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
3538
3539 // Check test-expr.
3540 HasErrors |= ISC.CheckCond(For->getCond());
3541
3542 // Check incr-expr.
3543 HasErrors |= ISC.CheckInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003544 }
3545
Alexander Musmana5f070a2014-10-01 06:03:56 +00003546 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003547 return HasErrors;
3548
Alexander Musmana5f070a2014-10-01 06:03:56 +00003549 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003550 ResultIterSpace.PreCond =
3551 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexander Musman174b3ca2014-10-06 11:16:29 +00003552 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00003553 DSA.getCurScope(),
3554 (isOpenMPWorksharingDirective(DKind) ||
3555 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
3556 Captures);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003557 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
Alexey Bataeva8899172015-08-06 12:30:57 +00003558 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003559 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
3560 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
3561 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
3562 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
3563 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
3564 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
3565
Alexey Bataev62dbb972015-04-22 11:59:37 +00003566 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
3567 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003568 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00003569 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003570 ResultIterSpace.CounterInit == nullptr ||
3571 ResultIterSpace.CounterStep == nullptr);
3572
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003573 return HasErrors;
3574}
3575
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003576/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003577static ExprResult
3578BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
3579 ExprResult Start,
3580 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003581 // Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003582 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
3583 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003584 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00003585 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00003586 VarRef.get()->getType())) {
3587 NewStart = SemaRef.PerformImplicitConversion(
3588 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
3589 /*AllowExplicit=*/true);
3590 if (!NewStart.isUsable())
3591 return ExprError();
3592 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003593
3594 auto Init =
3595 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3596 return Init;
3597}
3598
Alexander Musmana5f070a2014-10-01 06:03:56 +00003599/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003600static ExprResult
3601BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
3602 ExprResult VarRef, ExprResult Start, ExprResult Iter,
3603 ExprResult Step, bool Subtract,
3604 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003605 // Add parentheses (for debugging purposes only).
3606 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
3607 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
3608 !Step.isUsable())
3609 return ExprError();
3610
Alexey Bataev5a3af132016-03-29 08:58:54 +00003611 ExprResult NewStep = Step;
3612 if (Captures)
3613 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003614 if (NewStep.isInvalid())
3615 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003616 ExprResult Update =
3617 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003618 if (!Update.isUsable())
3619 return ExprError();
3620
Alexey Bataevc0214e02016-02-16 12:13:49 +00003621 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
3622 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003623 ExprResult NewStart = Start;
3624 if (Captures)
3625 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003626 if (NewStart.isInvalid())
3627 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003628
Alexey Bataevc0214e02016-02-16 12:13:49 +00003629 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
3630 ExprResult SavedUpdate = Update;
3631 ExprResult UpdateVal;
3632 if (VarRef.get()->getType()->isOverloadableType() ||
3633 NewStart.get()->getType()->isOverloadableType() ||
3634 Update.get()->getType()->isOverloadableType()) {
3635 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3636 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3637 Update =
3638 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3639 if (Update.isUsable()) {
3640 UpdateVal =
3641 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
3642 VarRef.get(), SavedUpdate.get());
3643 if (UpdateVal.isUsable()) {
3644 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
3645 UpdateVal.get());
3646 }
3647 }
3648 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3649 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003650
Alexey Bataevc0214e02016-02-16 12:13:49 +00003651 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
3652 if (!Update.isUsable() || !UpdateVal.isUsable()) {
3653 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
3654 NewStart.get(), SavedUpdate.get());
3655 if (!Update.isUsable())
3656 return ExprError();
3657
Alexey Bataev11481f52016-02-17 10:29:05 +00003658 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
3659 VarRef.get()->getType())) {
3660 Update = SemaRef.PerformImplicitConversion(
3661 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
3662 if (!Update.isUsable())
3663 return ExprError();
3664 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00003665
3666 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
3667 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003668 return Update;
3669}
3670
3671/// \brief Convert integer expression \a E to make it have at least \a Bits
3672/// bits.
David Majnemer9d168222016-08-05 17:44:54 +00003673static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003674 if (E == nullptr)
3675 return ExprError();
3676 auto &C = SemaRef.Context;
3677 QualType OldType = E->getType();
3678 unsigned HasBits = C.getTypeSize(OldType);
3679 if (HasBits >= Bits)
3680 return ExprResult(E);
3681 // OK to convert to signed, because new type has more bits than old.
3682 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
3683 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
3684 true);
3685}
3686
3687/// \brief Check if the given expression \a E is a constant integer that fits
3688/// into \a Bits bits.
3689static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
3690 if (E == nullptr)
3691 return false;
3692 llvm::APSInt Result;
3693 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
3694 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
3695 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003696}
3697
Alexey Bataev5a3af132016-03-29 08:58:54 +00003698/// Build preinits statement for the given declarations.
3699static Stmt *buildPreInits(ASTContext &Context,
3700 SmallVectorImpl<Decl *> &PreInits) {
3701 if (!PreInits.empty()) {
3702 return new (Context) DeclStmt(
3703 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
3704 SourceLocation(), SourceLocation());
3705 }
3706 return nullptr;
3707}
3708
3709/// Build preinits statement for the given declarations.
3710static Stmt *buildPreInits(ASTContext &Context,
3711 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3712 if (!Captures.empty()) {
3713 SmallVector<Decl *, 16> PreInits;
3714 for (auto &Pair : Captures)
3715 PreInits.push_back(Pair.second->getDecl());
3716 return buildPreInits(Context, PreInits);
3717 }
3718 return nullptr;
3719}
3720
3721/// Build postupdate expression for the given list of postupdates expressions.
3722static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
3723 Expr *PostUpdate = nullptr;
3724 if (!PostUpdates.empty()) {
3725 for (auto *E : PostUpdates) {
3726 Expr *ConvE = S.BuildCStyleCastExpr(
3727 E->getExprLoc(),
3728 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
3729 E->getExprLoc(), E)
3730 .get();
3731 PostUpdate = PostUpdate
3732 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
3733 PostUpdate, ConvE)
3734 .get()
3735 : ConvE;
3736 }
3737 }
3738 return PostUpdate;
3739}
3740
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003741/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00003742/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
3743/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003744static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00003745CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
3746 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
3747 DSAStackTy &DSA,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003748 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00003749 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003750 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003751 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003752 // Found 'collapse' clause - calculate collapse number.
3753 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003754 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003755 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00003756 }
3757 if (OrderedLoopCountExpr) {
3758 // Found 'ordered' clause - calculate collapse number.
3759 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003760 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
3761 if (Result.getLimitedValue() < NestedLoopCount) {
3762 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3763 diag::err_omp_wrong_ordered_loop_count)
3764 << OrderedLoopCountExpr->getSourceRange();
3765 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3766 diag::note_collapse_loop_count)
3767 << CollapseLoopCountExpr->getSourceRange();
3768 }
3769 NestedLoopCount = Result.getLimitedValue();
3770 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003771 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003772 // This is helper routine for loop directives (e.g., 'for', 'simd',
3773 // 'for simd', etc.).
Alexey Bataev5a3af132016-03-29 08:58:54 +00003774 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003775 SmallVector<LoopIterationSpace, 4> IterSpaces;
3776 IterSpaces.resize(NestedLoopCount);
3777 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003778 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003779 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003780 NestedLoopCount, CollapseLoopCountExpr,
3781 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003782 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00003783 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003784 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003785 // OpenMP [2.8.1, simd construct, Restrictions]
3786 // All loops associated with the construct must be perfectly nested; that
3787 // is, there must be no intervening code nor any OpenMP directive between
3788 // any two loops.
3789 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003790 }
3791
Alexander Musmana5f070a2014-10-01 06:03:56 +00003792 Built.clear(/* size */ NestedLoopCount);
3793
3794 if (SemaRef.CurContext->isDependentContext())
3795 return NestedLoopCount;
3796
3797 // An example of what is generated for the following code:
3798 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00003799 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00003800 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003801 // for (k = 0; k < NK; ++k)
3802 // for (j = J0; j < NJ; j+=2) {
3803 // <loop body>
3804 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003805 //
3806 // We generate the code below.
3807 // Note: the loop body may be outlined in CodeGen.
3808 // Note: some counters may be C++ classes, operator- is used to find number of
3809 // iterations and operator+= to calculate counter value.
3810 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
3811 // or i64 is currently supported).
3812 //
3813 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
3814 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
3815 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
3816 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
3817 // // similar updates for vars in clauses (e.g. 'linear')
3818 // <loop body (using local i and j)>
3819 // }
3820 // i = NI; // assign final values of counters
3821 // j = NJ;
3822 //
3823
3824 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
3825 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00003826 // Precondition tests if there is at least one iteration (all conditions are
3827 // true).
3828 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003829 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003830 ExprResult LastIteration32 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00003831 32 /* Bits */, SemaRef
3832 .PerformImplicitConversion(
3833 N0->IgnoreImpCasts(), N0->getType(),
3834 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003835 .get(),
3836 SemaRef);
3837 ExprResult LastIteration64 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00003838 64 /* Bits */, SemaRef
3839 .PerformImplicitConversion(
3840 N0->IgnoreImpCasts(), N0->getType(),
3841 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003842 .get(),
3843 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003844
3845 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
3846 return NestedLoopCount;
3847
3848 auto &C = SemaRef.Context;
3849 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
3850
3851 Scope *CurScope = DSA.getCurScope();
3852 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003853 if (PreCond.isUsable()) {
3854 PreCond = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_LAnd,
3855 PreCond.get(), IterSpaces[Cnt].PreCond);
3856 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003857 auto N = IterSpaces[Cnt].NumIterations;
3858 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
3859 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003860 LastIteration32 = SemaRef.BuildBinOp(
3861 CurScope, SourceLocation(), BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00003862 SemaRef
3863 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3864 Sema::AA_Converting,
3865 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003866 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003867 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003868 LastIteration64 = SemaRef.BuildBinOp(
3869 CurScope, SourceLocation(), BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00003870 SemaRef
3871 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3872 Sema::AA_Converting,
3873 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003874 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003875 }
3876
3877 // Choose either the 32-bit or 64-bit version.
3878 ExprResult LastIteration = LastIteration64;
3879 if (LastIteration32.isUsable() &&
3880 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
3881 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
3882 FitsInto(
3883 32 /* Bits */,
3884 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
3885 LastIteration64.get(), SemaRef)))
3886 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00003887 QualType VType = LastIteration.get()->getType();
3888 QualType RealVType = VType;
3889 QualType StrideVType = VType;
3890 if (isOpenMPTaskLoopDirective(DKind)) {
3891 VType =
3892 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3893 StrideVType =
3894 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3895 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003896
3897 if (!LastIteration.isUsable())
3898 return 0;
3899
3900 // Save the number of iterations.
3901 ExprResult NumIterations = LastIteration;
3902 {
3903 LastIteration = SemaRef.BuildBinOp(
3904 CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
3905 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3906 if (!LastIteration.isUsable())
3907 return 0;
3908 }
3909
3910 // Calculate the last iteration number beforehand instead of doing this on
3911 // each iteration. Do not do this if the number of iterations may be kfold-ed.
3912 llvm::APSInt Result;
3913 bool IsConstant =
3914 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
3915 ExprResult CalcLastIteration;
3916 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003917 ExprResult SaveRef =
3918 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003919 LastIteration = SaveRef;
3920
3921 // Prepare SaveRef + 1.
3922 NumIterations = SemaRef.BuildBinOp(
Alexey Bataev5a3af132016-03-29 08:58:54 +00003923 CurScope, SourceLocation(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00003924 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3925 if (!NumIterations.isUsable())
3926 return 0;
3927 }
3928
3929 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
3930
David Majnemer9d168222016-08-05 17:44:54 +00003931 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolli9925f152016-06-27 14:55:37 +00003932 ExprResult LB, UB, IL, ST, EUB, PrevLB, PrevUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003933 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
3934 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003935 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00003936 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
3937 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003938 SemaRef.AddInitializerToDecl(
3939 LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3940 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3941
3942 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00003943 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
3944 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003945 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
3946 /*DirectInit*/ false,
3947 /*TypeMayContainAuto*/ false);
3948
3949 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
3950 // This will be used to implement clause 'lastprivate'.
3951 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00003952 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
3953 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003954 SemaRef.AddInitializerToDecl(
3955 ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3956 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3957
3958 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00003959 VarDecl *STDecl =
3960 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
3961 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003962 SemaRef.AddInitializerToDecl(
3963 STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
3964 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3965
3966 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00003967 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00003968 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
3969 UB.get(), LastIteration.get());
3970 ExprResult CondOp = SemaRef.ActOnConditionalOp(
3971 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
3972 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
3973 CondOp.get());
3974 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
Carlo Bertolli9925f152016-06-27 14:55:37 +00003975
3976 // If we have a combined directive that combines 'distribute', 'for' or
3977 // 'simd' we need to be able to access the bounds of the schedule of the
3978 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
3979 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
3980 if (isOpenMPLoopBoundSharingDirective(DKind)) {
3981 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
3982
3983 // We expect to have at least 2 more parameters than the 'parallel'
3984 // directive does - the lower and upper bounds of the previous schedule.
3985 assert(CD->getNumParams() >= 4 &&
3986 "Unexpected number of parameters in loop combined directive");
3987
3988 // Set the proper type for the bounds given what we learned from the
3989 // enclosed loops.
3990 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
3991 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
3992
3993 // Previous lower and upper bounds are obtained from the region
3994 // parameters.
3995 PrevLB =
3996 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
3997 PrevUB =
3998 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
3999 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004000 }
4001
4002 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004003 ExprResult IV;
4004 ExprResult Init;
4005 {
Alexey Bataev7292c292016-04-25 12:22:29 +00004006 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4007 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00004008 Expr *RHS =
4009 (isOpenMPWorksharingDirective(DKind) ||
4010 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4011 ? LB.get()
4012 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004013 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4014 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004015 }
4016
Alexander Musmanc6388682014-12-15 07:07:06 +00004017 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004018 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00004019 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004020 (isOpenMPWorksharingDirective(DKind) ||
4021 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004022 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4023 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4024 NumIterations.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004025
4026 // Loop increment (IV = IV + 1)
4027 SourceLocation IncLoc;
4028 ExprResult Inc =
4029 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4030 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4031 if (!Inc.isUsable())
4032 return 0;
4033 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00004034 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4035 if (!Inc.isUsable())
4036 return 0;
4037
4038 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4039 // Used for directives with static scheduling.
4040 ExprResult NextLB, NextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004041 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4042 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004043 // LB + ST
4044 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4045 if (!NextLB.isUsable())
4046 return 0;
4047 // LB = LB + ST
4048 NextLB =
4049 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4050 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4051 if (!NextLB.isUsable())
4052 return 0;
4053 // UB + ST
4054 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4055 if (!NextUB.isUsable())
4056 return 0;
4057 // UB = UB + ST
4058 NextUB =
4059 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4060 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4061 if (!NextUB.isUsable())
4062 return 0;
4063 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004064
4065 // Build updates and final values of the loop counters.
4066 bool HasErrors = false;
4067 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004068 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004069 Built.Updates.resize(NestedLoopCount);
4070 Built.Finals.resize(NestedLoopCount);
Alexey Bataev8b427062016-05-25 12:36:08 +00004071 SmallVector<Expr *, 4> LoopMultipliers;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004072 {
4073 ExprResult Div;
4074 // Go from inner nested loop to outer.
4075 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4076 LoopIterationSpace &IS = IterSpaces[Cnt];
4077 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4078 // Build: Iter = (IV / Div) % IS.NumIters
4079 // where Div is product of previous iterations' IS.NumIters.
4080 ExprResult Iter;
4081 if (Div.isUsable()) {
4082 Iter =
4083 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4084 } else {
4085 Iter = IV;
4086 assert((Cnt == (int)NestedLoopCount - 1) &&
4087 "unusable div expected on first iteration only");
4088 }
4089
4090 if (Cnt != 0 && Iter.isUsable())
4091 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4092 IS.NumIterations);
4093 if (!Iter.isUsable()) {
4094 HasErrors = true;
4095 break;
4096 }
4097
Alexey Bataev39f915b82015-05-08 10:41:21 +00004098 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004099 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4100 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4101 IS.CounterVar->getExprLoc(),
4102 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004103 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004104 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004105 if (!Init.isUsable()) {
4106 HasErrors = true;
4107 break;
4108 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00004109 ExprResult Update = BuildCounterUpdate(
4110 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4111 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004112 if (!Update.isUsable()) {
4113 HasErrors = true;
4114 break;
4115 }
4116
4117 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4118 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00004119 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004120 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004121 if (!Final.isUsable()) {
4122 HasErrors = true;
4123 break;
4124 }
4125
4126 // Build Div for the next iteration: Div <- Div * IS.NumIters
4127 if (Cnt != 0) {
4128 if (Div.isUnset())
4129 Div = IS.NumIterations;
4130 else
4131 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4132 IS.NumIterations);
4133
4134 // Add parentheses (for debugging purposes only).
4135 if (Div.isUsable())
Alexey Bataev8b427062016-05-25 12:36:08 +00004136 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004137 if (!Div.isUsable()) {
4138 HasErrors = true;
4139 break;
4140 }
Alexey Bataev8b427062016-05-25 12:36:08 +00004141 LoopMultipliers.push_back(Div.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004142 }
4143 if (!Update.isUsable() || !Final.isUsable()) {
4144 HasErrors = true;
4145 break;
4146 }
4147 // Save results
4148 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00004149 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004150 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004151 Built.Updates[Cnt] = Update.get();
4152 Built.Finals[Cnt] = Final.get();
4153 }
4154 }
4155
4156 if (HasErrors)
4157 return 0;
4158
4159 // Save results
4160 Built.IterationVarRef = IV.get();
4161 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00004162 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004163 Built.CalcLastIteration =
4164 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004165 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00004166 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004167 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004168 Built.Init = Init.get();
4169 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004170 Built.LB = LB.get();
4171 Built.UB = UB.get();
4172 Built.IL = IL.get();
4173 Built.ST = ST.get();
4174 Built.EUB = EUB.get();
4175 Built.NLB = NextLB.get();
4176 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004177 Built.PrevLB = PrevLB.get();
4178 Built.PrevUB = PrevUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004179
Alexey Bataev8b427062016-05-25 12:36:08 +00004180 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4181 // Fill data for doacross depend clauses.
4182 for (auto Pair : DSA.getDoacrossDependClauses()) {
4183 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4184 Pair.first->setCounterValue(CounterVal);
4185 else {
4186 if (NestedLoopCount != Pair.second.size() ||
4187 NestedLoopCount != LoopMultipliers.size() + 1) {
4188 // Erroneous case - clause has some problems.
4189 Pair.first->setCounterValue(CounterVal);
4190 continue;
4191 }
4192 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4193 auto I = Pair.second.rbegin();
4194 auto IS = IterSpaces.rbegin();
4195 auto ILM = LoopMultipliers.rbegin();
4196 Expr *UpCounterVal = CounterVal;
4197 Expr *Multiplier = nullptr;
4198 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4199 if (I->first) {
4200 assert(IS->CounterStep);
4201 Expr *NormalizedOffset =
4202 SemaRef
4203 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4204 I->first, IS->CounterStep)
4205 .get();
4206 if (Multiplier) {
4207 NormalizedOffset =
4208 SemaRef
4209 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
4210 NormalizedOffset, Multiplier)
4211 .get();
4212 }
4213 assert(I->second == OO_Plus || I->second == OO_Minus);
4214 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
David Majnemer9d168222016-08-05 17:44:54 +00004215 UpCounterVal = SemaRef
4216 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
4217 UpCounterVal, NormalizedOffset)
4218 .get();
Alexey Bataev8b427062016-05-25 12:36:08 +00004219 }
4220 Multiplier = *ILM;
4221 ++I;
4222 ++IS;
4223 ++ILM;
4224 }
4225 Pair.first->setCounterValue(UpCounterVal);
4226 }
4227 }
4228
Alexey Bataevabfc0692014-06-25 06:52:00 +00004229 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004230}
4231
Alexey Bataev10e775f2015-07-30 11:36:16 +00004232static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004233 auto CollapseClauses =
4234 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4235 if (CollapseClauses.begin() != CollapseClauses.end())
4236 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004237 return nullptr;
4238}
4239
Alexey Bataev10e775f2015-07-30 11:36:16 +00004240static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004241 auto OrderedClauses =
4242 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4243 if (OrderedClauses.begin() != OrderedClauses.end())
4244 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004245 return nullptr;
4246}
4247
Kelvin Lic5609492016-07-15 04:39:07 +00004248static bool checkSimdlenSafelenSpecified(Sema &S,
4249 const ArrayRef<OMPClause *> Clauses) {
4250 OMPSafelenClause *Safelen = nullptr;
4251 OMPSimdlenClause *Simdlen = nullptr;
4252
4253 for (auto *Clause : Clauses) {
4254 if (Clause->getClauseKind() == OMPC_safelen)
4255 Safelen = cast<OMPSafelenClause>(Clause);
4256 else if (Clause->getClauseKind() == OMPC_simdlen)
4257 Simdlen = cast<OMPSimdlenClause>(Clause);
4258 if (Safelen && Simdlen)
4259 break;
4260 }
4261
4262 if (Simdlen && Safelen) {
4263 llvm::APSInt SimdlenRes, SafelenRes;
4264 auto SimdlenLength = Simdlen->getSimdlen();
4265 auto SafelenLength = Safelen->getSafelen();
4266 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
4267 SimdlenLength->isInstantiationDependent() ||
4268 SimdlenLength->containsUnexpandedParameterPack())
4269 return false;
4270 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
4271 SafelenLength->isInstantiationDependent() ||
4272 SafelenLength->containsUnexpandedParameterPack())
4273 return false;
4274 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
4275 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
4276 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
4277 // If both simdlen and safelen clauses are specified, the value of the
4278 // simdlen parameter must be less than or equal to the value of the safelen
4279 // parameter.
4280 if (SimdlenRes > SafelenRes) {
4281 S.Diag(SimdlenLength->getExprLoc(),
4282 diag::err_omp_wrong_simdlen_safelen_values)
4283 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
4284 return true;
4285 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00004286 }
4287 return false;
4288}
4289
Alexey Bataev4acb8592014-07-07 13:01:15 +00004290StmtResult Sema::ActOnOpenMPSimdDirective(
4291 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4292 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004293 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004294 if (!AStmt)
4295 return StmtError();
4296
4297 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004298 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004299 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4300 // define the nested loops number.
4301 unsigned NestedLoopCount = CheckOpenMPLoop(
4302 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4303 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004304 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004305 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004306
Alexander Musmana5f070a2014-10-01 06:03:56 +00004307 assert((CurContext->isDependentContext() || B.builtAll()) &&
4308 "omp simd loop exprs were not built");
4309
Alexander Musman3276a272015-03-21 10:12:56 +00004310 if (!CurContext->isDependentContext()) {
4311 // Finalize the clauses that need pre-built expressions for CodeGen.
4312 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004313 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00004314 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004315 B.NumIterations, *this, CurScope,
4316 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00004317 return StmtError();
4318 }
4319 }
4320
Kelvin Lic5609492016-07-15 04:39:07 +00004321 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004322 return StmtError();
4323
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004324 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004325 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4326 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004327}
4328
Alexey Bataev4acb8592014-07-07 13:01:15 +00004329StmtResult Sema::ActOnOpenMPForDirective(
4330 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4331 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004332 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004333 if (!AStmt)
4334 return StmtError();
4335
4336 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004337 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004338 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4339 // define the nested loops number.
4340 unsigned NestedLoopCount = CheckOpenMPLoop(
4341 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4342 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004343 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00004344 return StmtError();
4345
Alexander Musmana5f070a2014-10-01 06:03:56 +00004346 assert((CurContext->isDependentContext() || B.builtAll()) &&
4347 "omp for loop exprs were not built");
4348
Alexey Bataev54acd402015-08-04 11:18:19 +00004349 if (!CurContext->isDependentContext()) {
4350 // Finalize the clauses that need pre-built expressions for CodeGen.
4351 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004352 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004353 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004354 B.NumIterations, *this, CurScope,
4355 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004356 return StmtError();
4357 }
4358 }
4359
Alexey Bataevf29276e2014-06-18 04:14:57 +00004360 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004361 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004362 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00004363}
4364
Alexander Musmanf82886e2014-09-18 05:12:34 +00004365StmtResult Sema::ActOnOpenMPForSimdDirective(
4366 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4367 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004368 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004369 if (!AStmt)
4370 return StmtError();
4371
4372 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004373 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004374 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4375 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00004376 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004377 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
4378 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4379 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004380 if (NestedLoopCount == 0)
4381 return StmtError();
4382
Alexander Musmanc6388682014-12-15 07:07:06 +00004383 assert((CurContext->isDependentContext() || B.builtAll()) &&
4384 "omp for simd loop exprs were not built");
4385
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004386 if (!CurContext->isDependentContext()) {
4387 // Finalize the clauses that need pre-built expressions for CodeGen.
4388 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004389 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004390 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004391 B.NumIterations, *this, CurScope,
4392 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004393 return StmtError();
4394 }
4395 }
4396
Kelvin Lic5609492016-07-15 04:39:07 +00004397 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004398 return StmtError();
4399
Alexander Musmanf82886e2014-09-18 05:12:34 +00004400 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004401 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4402 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004403}
4404
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004405StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
4406 Stmt *AStmt,
4407 SourceLocation StartLoc,
4408 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004409 if (!AStmt)
4410 return StmtError();
4411
4412 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004413 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004414 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004415 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004416 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004417 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004418 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004419 return StmtError();
4420 // All associated statements must be '#pragma omp section' except for
4421 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004422 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004423 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4424 if (SectionStmt)
4425 Diag(SectionStmt->getLocStart(),
4426 diag::err_omp_sections_substmt_not_section);
4427 return StmtError();
4428 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004429 cast<OMPSectionDirective>(SectionStmt)
4430 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004431 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004432 } else {
4433 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
4434 return StmtError();
4435 }
4436
4437 getCurFunction()->setHasBranchProtectedScope();
4438
Alexey Bataev25e5b442015-09-15 12:52:43 +00004439 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4440 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004441}
4442
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004443StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
4444 SourceLocation StartLoc,
4445 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004446 if (!AStmt)
4447 return StmtError();
4448
4449 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004450
4451 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00004452 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004453
Alexey Bataev25e5b442015-09-15 12:52:43 +00004454 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
4455 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004456}
4457
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004458StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
4459 Stmt *AStmt,
4460 SourceLocation StartLoc,
4461 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004462 if (!AStmt)
4463 return StmtError();
4464
4465 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00004466
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004467 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00004468
Alexey Bataev3255bf32015-01-19 05:20:46 +00004469 // OpenMP [2.7.3, single Construct, Restrictions]
4470 // The copyprivate clause must not be used with the nowait clause.
4471 OMPClause *Nowait = nullptr;
4472 OMPClause *Copyprivate = nullptr;
4473 for (auto *Clause : Clauses) {
4474 if (Clause->getClauseKind() == OMPC_nowait)
4475 Nowait = Clause;
4476 else if (Clause->getClauseKind() == OMPC_copyprivate)
4477 Copyprivate = Clause;
4478 if (Copyprivate && Nowait) {
4479 Diag(Copyprivate->getLocStart(),
4480 diag::err_omp_single_copyprivate_with_nowait);
4481 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
4482 return StmtError();
4483 }
4484 }
4485
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004486 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4487}
4488
Alexander Musman80c22892014-07-17 08:54:58 +00004489StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
4490 SourceLocation StartLoc,
4491 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004492 if (!AStmt)
4493 return StmtError();
4494
4495 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00004496
4497 getCurFunction()->setHasBranchProtectedScope();
4498
4499 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
4500}
4501
Alexey Bataev28c75412015-12-15 08:19:24 +00004502StmtResult Sema::ActOnOpenMPCriticalDirective(
4503 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
4504 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004505 if (!AStmt)
4506 return StmtError();
4507
4508 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004509
Alexey Bataev28c75412015-12-15 08:19:24 +00004510 bool ErrorFound = false;
4511 llvm::APSInt Hint;
4512 SourceLocation HintLoc;
4513 bool DependentHint = false;
4514 for (auto *C : Clauses) {
4515 if (C->getClauseKind() == OMPC_hint) {
4516 if (!DirName.getName()) {
4517 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
4518 ErrorFound = true;
4519 }
4520 Expr *E = cast<OMPHintClause>(C)->getHint();
4521 if (E->isTypeDependent() || E->isValueDependent() ||
4522 E->isInstantiationDependent())
4523 DependentHint = true;
4524 else {
4525 Hint = E->EvaluateKnownConstInt(Context);
4526 HintLoc = C->getLocStart();
4527 }
4528 }
4529 }
4530 if (ErrorFound)
4531 return StmtError();
4532 auto Pair = DSAStack->getCriticalWithHint(DirName);
4533 if (Pair.first && DirName.getName() && !DependentHint) {
4534 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
4535 Diag(StartLoc, diag::err_omp_critical_with_hint);
4536 if (HintLoc.isValid()) {
4537 Diag(HintLoc, diag::note_omp_critical_hint_here)
4538 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
4539 } else
4540 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
4541 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
4542 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
4543 << 1
4544 << C->getHint()->EvaluateKnownConstInt(Context).toString(
4545 /*Radix=*/10, /*Signed=*/false);
4546 } else
4547 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
4548 }
4549 }
4550
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004551 getCurFunction()->setHasBranchProtectedScope();
4552
Alexey Bataev28c75412015-12-15 08:19:24 +00004553 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
4554 Clauses, AStmt);
4555 if (!Pair.first && DirName.getName() && !DependentHint)
4556 DSAStack->addCriticalWithHint(Dir, Hint);
4557 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004558}
4559
Alexey Bataev4acb8592014-07-07 13:01:15 +00004560StmtResult Sema::ActOnOpenMPParallelForDirective(
4561 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4562 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004563 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004564 if (!AStmt)
4565 return StmtError();
4566
Alexey Bataev4acb8592014-07-07 13:01:15 +00004567 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4568 // 1.2.2 OpenMP Language Terminology
4569 // Structured block - An executable statement with a single entry at the
4570 // top and a single exit at the bottom.
4571 // The point of exit cannot be a branch out of the structured block.
4572 // longjmp() and throw() must not violate the entry/exit criteria.
4573 CS->getCapturedDecl()->setNothrow();
4574
Alexander Musmanc6388682014-12-15 07:07:06 +00004575 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004576 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4577 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004578 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004579 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
4580 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4581 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004582 if (NestedLoopCount == 0)
4583 return StmtError();
4584
Alexander Musmana5f070a2014-10-01 06:03:56 +00004585 assert((CurContext->isDependentContext() || B.builtAll()) &&
4586 "omp parallel for loop exprs were not built");
4587
Alexey Bataev54acd402015-08-04 11:18:19 +00004588 if (!CurContext->isDependentContext()) {
4589 // Finalize the clauses that need pre-built expressions for CodeGen.
4590 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004591 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004592 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004593 B.NumIterations, *this, CurScope,
4594 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004595 return StmtError();
4596 }
4597 }
4598
Alexey Bataev4acb8592014-07-07 13:01:15 +00004599 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004600 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004601 NestedLoopCount, Clauses, AStmt, B,
4602 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00004603}
4604
Alexander Musmane4e893b2014-09-23 09:33:00 +00004605StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
4606 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4607 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004608 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004609 if (!AStmt)
4610 return StmtError();
4611
Alexander Musmane4e893b2014-09-23 09:33:00 +00004612 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4613 // 1.2.2 OpenMP Language Terminology
4614 // Structured block - An executable statement with a single entry at the
4615 // top and a single exit at the bottom.
4616 // The point of exit cannot be a branch out of the structured block.
4617 // longjmp() and throw() must not violate the entry/exit criteria.
4618 CS->getCapturedDecl()->setNothrow();
4619
Alexander Musmanc6388682014-12-15 07:07:06 +00004620 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004621 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4622 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00004623 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004624 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
4625 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4626 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004627 if (NestedLoopCount == 0)
4628 return StmtError();
4629
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004630 if (!CurContext->isDependentContext()) {
4631 // Finalize the clauses that need pre-built expressions for CodeGen.
4632 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004633 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004634 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004635 B.NumIterations, *this, CurScope,
4636 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004637 return StmtError();
4638 }
4639 }
4640
Kelvin Lic5609492016-07-15 04:39:07 +00004641 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004642 return StmtError();
4643
Alexander Musmane4e893b2014-09-23 09:33:00 +00004644 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004645 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00004646 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004647}
4648
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004649StmtResult
4650Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
4651 Stmt *AStmt, SourceLocation StartLoc,
4652 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004653 if (!AStmt)
4654 return StmtError();
4655
4656 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004657 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004658 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004659 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004660 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004661 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004662 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004663 return StmtError();
4664 // All associated statements must be '#pragma omp section' except for
4665 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004666 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004667 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4668 if (SectionStmt)
4669 Diag(SectionStmt->getLocStart(),
4670 diag::err_omp_parallel_sections_substmt_not_section);
4671 return StmtError();
4672 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004673 cast<OMPSectionDirective>(SectionStmt)
4674 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004675 }
4676 } else {
4677 Diag(AStmt->getLocStart(),
4678 diag::err_omp_parallel_sections_not_compound_stmt);
4679 return StmtError();
4680 }
4681
4682 getCurFunction()->setHasBranchProtectedScope();
4683
Alexey Bataev25e5b442015-09-15 12:52:43 +00004684 return OMPParallelSectionsDirective::Create(
4685 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004686}
4687
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004688StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
4689 Stmt *AStmt, SourceLocation StartLoc,
4690 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004691 if (!AStmt)
4692 return StmtError();
4693
David Majnemer9d168222016-08-05 17:44:54 +00004694 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004695 // 1.2.2 OpenMP Language Terminology
4696 // Structured block - An executable statement with a single entry at the
4697 // top and a single exit at the bottom.
4698 // The point of exit cannot be a branch out of the structured block.
4699 // longjmp() and throw() must not violate the entry/exit criteria.
4700 CS->getCapturedDecl()->setNothrow();
4701
4702 getCurFunction()->setHasBranchProtectedScope();
4703
Alexey Bataev25e5b442015-09-15 12:52:43 +00004704 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4705 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004706}
4707
Alexey Bataev68446b72014-07-18 07:47:19 +00004708StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
4709 SourceLocation EndLoc) {
4710 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
4711}
4712
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004713StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
4714 SourceLocation EndLoc) {
4715 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
4716}
4717
Alexey Bataev2df347a2014-07-18 10:17:07 +00004718StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
4719 SourceLocation EndLoc) {
4720 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
4721}
4722
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004723StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
4724 SourceLocation StartLoc,
4725 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004726 if (!AStmt)
4727 return StmtError();
4728
4729 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004730
4731 getCurFunction()->setHasBranchProtectedScope();
4732
4733 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
4734}
4735
Alexey Bataev6125da92014-07-21 11:26:11 +00004736StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
4737 SourceLocation StartLoc,
4738 SourceLocation EndLoc) {
4739 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
4740 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
4741}
4742
Alexey Bataev346265e2015-09-25 10:37:12 +00004743StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
4744 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004745 SourceLocation StartLoc,
4746 SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00004747 OMPClause *DependFound = nullptr;
4748 OMPClause *DependSourceClause = nullptr;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004749 OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00004750 bool ErrorFound = false;
Alexey Bataev346265e2015-09-25 10:37:12 +00004751 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004752 OMPSIMDClause *SC = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00004753 for (auto *C : Clauses) {
4754 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
4755 DependFound = C;
4756 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
4757 if (DependSourceClause) {
4758 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
4759 << getOpenMPDirectiveName(OMPD_ordered)
4760 << getOpenMPClauseName(OMPC_depend) << 2;
4761 ErrorFound = true;
4762 } else
4763 DependSourceClause = C;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004764 if (DependSinkClause) {
4765 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4766 << 0;
4767 ErrorFound = true;
4768 }
4769 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
4770 if (DependSourceClause) {
4771 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4772 << 1;
4773 ErrorFound = true;
4774 }
4775 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00004776 }
4777 } else if (C->getClauseKind() == OMPC_threads)
Alexey Bataev346265e2015-09-25 10:37:12 +00004778 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004779 else if (C->getClauseKind() == OMPC_simd)
4780 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00004781 }
Alexey Bataeveb482352015-12-18 05:05:56 +00004782 if (!ErrorFound && !SC &&
4783 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004784 // OpenMP [2.8.1,simd Construct, Restrictions]
4785 // An ordered construct with the simd clause is the only OpenMP construct
4786 // that can appear in the simd region.
4787 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00004788 ErrorFound = true;
4789 } else if (DependFound && (TC || SC)) {
4790 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
4791 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
4792 ErrorFound = true;
4793 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
4794 Diag(DependFound->getLocStart(),
4795 diag::err_omp_ordered_directive_without_param);
4796 ErrorFound = true;
4797 } else if (TC || Clauses.empty()) {
4798 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
4799 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
4800 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
4801 << (TC != nullptr);
4802 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
4803 ErrorFound = true;
4804 }
4805 }
4806 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004807 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00004808
4809 if (AStmt) {
4810 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4811
4812 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004813 }
Alexey Bataev346265e2015-09-25 10:37:12 +00004814
4815 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004816}
4817
Alexey Bataev1d160b12015-03-13 12:27:31 +00004818namespace {
4819/// \brief Helper class for checking expression in 'omp atomic [update]'
4820/// construct.
4821class OpenMPAtomicUpdateChecker {
4822 /// \brief Error results for atomic update expressions.
4823 enum ExprAnalysisErrorCode {
4824 /// \brief A statement is not an expression statement.
4825 NotAnExpression,
4826 /// \brief Expression is not builtin binary or unary operation.
4827 NotABinaryOrUnaryExpression,
4828 /// \brief Unary operation is not post-/pre- increment/decrement operation.
4829 NotAnUnaryIncDecExpression,
4830 /// \brief An expression is not of scalar type.
4831 NotAScalarType,
4832 /// \brief A binary operation is not an assignment operation.
4833 NotAnAssignmentOp,
4834 /// \brief RHS part of the binary operation is not a binary expression.
4835 NotABinaryExpression,
4836 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
4837 /// expression.
4838 NotABinaryOperator,
4839 /// \brief RHS binary operation does not have reference to the updated LHS
4840 /// part.
4841 NotAnUpdateExpression,
4842 /// \brief No errors is found.
4843 NoError
4844 };
4845 /// \brief Reference to Sema.
4846 Sema &SemaRef;
4847 /// \brief A location for note diagnostics (when error is found).
4848 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004849 /// \brief 'x' lvalue part of the source atomic expression.
4850 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004851 /// \brief 'expr' rvalue part of the source atomic expression.
4852 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004853 /// \brief Helper expression of the form
4854 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4855 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4856 Expr *UpdateExpr;
4857 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
4858 /// important for non-associative operations.
4859 bool IsXLHSInRHSPart;
4860 BinaryOperatorKind Op;
4861 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00004862 /// \brief true if the source expression is a postfix unary operation, false
4863 /// if it is a prefix unary operation.
4864 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004865
4866public:
4867 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00004868 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00004869 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00004870 /// \brief Check specified statement that it is suitable for 'atomic update'
4871 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00004872 /// expression. If DiagId and NoteId == 0, then only check is performed
4873 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00004874 /// \param DiagId Diagnostic which should be emitted if error is found.
4875 /// \param NoteId Diagnostic note for the main error message.
4876 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00004877 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00004878 /// \brief Return the 'x' lvalue part of the source atomic expression.
4879 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00004880 /// \brief Return the 'expr' rvalue part of the source atomic expression.
4881 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00004882 /// \brief Return the update expression used in calculation of the updated
4883 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4884 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4885 Expr *getUpdateExpr() const { return UpdateExpr; }
4886 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
4887 /// false otherwise.
4888 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
4889
Alexey Bataevb78ca832015-04-01 03:33:17 +00004890 /// \brief true if the source expression is a postfix unary operation, false
4891 /// if it is a prefix unary operation.
4892 bool isPostfixUpdate() const { return IsPostfixUpdate; }
4893
Alexey Bataev1d160b12015-03-13 12:27:31 +00004894private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00004895 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
4896 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00004897};
4898} // namespace
4899
4900bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
4901 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
4902 ExprAnalysisErrorCode ErrorFound = NoError;
4903 SourceLocation ErrorLoc, NoteLoc;
4904 SourceRange ErrorRange, NoteRange;
4905 // Allowed constructs are:
4906 // x = x binop expr;
4907 // x = expr binop x;
4908 if (AtomicBinOp->getOpcode() == BO_Assign) {
4909 X = AtomicBinOp->getLHS();
4910 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
4911 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
4912 if (AtomicInnerBinOp->isMultiplicativeOp() ||
4913 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
4914 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00004915 Op = AtomicInnerBinOp->getOpcode();
4916 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00004917 auto *LHS = AtomicInnerBinOp->getLHS();
4918 auto *RHS = AtomicInnerBinOp->getRHS();
4919 llvm::FoldingSetNodeID XId, LHSId, RHSId;
4920 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
4921 /*Canonical=*/true);
4922 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
4923 /*Canonical=*/true);
4924 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
4925 /*Canonical=*/true);
4926 if (XId == LHSId) {
4927 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004928 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004929 } else if (XId == RHSId) {
4930 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004931 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004932 } else {
4933 ErrorLoc = AtomicInnerBinOp->getExprLoc();
4934 ErrorRange = AtomicInnerBinOp->getSourceRange();
4935 NoteLoc = X->getExprLoc();
4936 NoteRange = X->getSourceRange();
4937 ErrorFound = NotAnUpdateExpression;
4938 }
4939 } else {
4940 ErrorLoc = AtomicInnerBinOp->getExprLoc();
4941 ErrorRange = AtomicInnerBinOp->getSourceRange();
4942 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
4943 NoteRange = SourceRange(NoteLoc, NoteLoc);
4944 ErrorFound = NotABinaryOperator;
4945 }
4946 } else {
4947 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
4948 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
4949 ErrorFound = NotABinaryExpression;
4950 }
4951 } else {
4952 ErrorLoc = AtomicBinOp->getExprLoc();
4953 ErrorRange = AtomicBinOp->getSourceRange();
4954 NoteLoc = AtomicBinOp->getOperatorLoc();
4955 NoteRange = SourceRange(NoteLoc, NoteLoc);
4956 ErrorFound = NotAnAssignmentOp;
4957 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00004958 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00004959 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
4960 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
4961 return true;
4962 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00004963 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00004964 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004965}
4966
4967bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
4968 unsigned NoteId) {
4969 ExprAnalysisErrorCode ErrorFound = NoError;
4970 SourceLocation ErrorLoc, NoteLoc;
4971 SourceRange ErrorRange, NoteRange;
4972 // Allowed constructs are:
4973 // x++;
4974 // x--;
4975 // ++x;
4976 // --x;
4977 // x binop= expr;
4978 // x = x binop expr;
4979 // x = expr binop x;
4980 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
4981 AtomicBody = AtomicBody->IgnoreParenImpCasts();
4982 if (AtomicBody->getType()->isScalarType() ||
4983 AtomicBody->isInstantiationDependent()) {
4984 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
4985 AtomicBody->IgnoreParenImpCasts())) {
4986 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00004987 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00004988 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00004989 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00004990 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00004991 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00004992 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004993 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
4994 AtomicBody->IgnoreParenImpCasts())) {
4995 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00004996 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00004997 return true;
David Majnemer9d168222016-08-05 17:44:54 +00004998 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
4999 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005000 // Check for Unary Operation
5001 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005002 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005003 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5004 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005005 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005006 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5007 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005008 } else {
5009 ErrorFound = NotAnUnaryIncDecExpression;
5010 ErrorLoc = AtomicUnaryOp->getExprLoc();
5011 ErrorRange = AtomicUnaryOp->getSourceRange();
5012 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5013 NoteRange = SourceRange(NoteLoc, NoteLoc);
5014 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005015 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005016 ErrorFound = NotABinaryOrUnaryExpression;
5017 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5018 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5019 }
5020 } else {
5021 ErrorFound = NotAScalarType;
5022 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5023 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5024 }
5025 } else {
5026 ErrorFound = NotAnExpression;
5027 NoteLoc = ErrorLoc = S->getLocStart();
5028 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5029 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005030 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005031 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5032 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5033 return true;
5034 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005035 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005036 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005037 // Build an update expression of form 'OpaqueValueExpr(x) binop
5038 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5039 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5040 auto *OVEX = new (SemaRef.getASTContext())
5041 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5042 auto *OVEExpr = new (SemaRef.getASTContext())
5043 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5044 auto Update =
5045 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5046 IsXLHSInRHSPart ? OVEExpr : OVEX);
5047 if (Update.isInvalid())
5048 return true;
5049 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5050 Sema::AA_Casting);
5051 if (Update.isInvalid())
5052 return true;
5053 UpdateExpr = Update.get();
5054 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00005055 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005056}
5057
Alexey Bataev0162e452014-07-22 10:10:35 +00005058StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5059 Stmt *AStmt,
5060 SourceLocation StartLoc,
5061 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005062 if (!AStmt)
5063 return StmtError();
5064
David Majnemer9d168222016-08-05 17:44:54 +00005065 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00005066 // 1.2.2 OpenMP Language Terminology
5067 // Structured block - An executable statement with a single entry at the
5068 // top and a single exit at the bottom.
5069 // The point of exit cannot be a branch out of the structured block.
5070 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00005071 OpenMPClauseKind AtomicKind = OMPC_unknown;
5072 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005073 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00005074 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00005075 C->getClauseKind() == OMPC_update ||
5076 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00005077 if (AtomicKind != OMPC_unknown) {
5078 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5079 << SourceRange(C->getLocStart(), C->getLocEnd());
5080 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5081 << getOpenMPClauseName(AtomicKind);
5082 } else {
5083 AtomicKind = C->getClauseKind();
5084 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005085 }
5086 }
5087 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005088
Alexey Bataev459dec02014-07-24 06:46:57 +00005089 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00005090 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5091 Body = EWC->getSubExpr();
5092
Alexey Bataev62cec442014-11-18 10:14:22 +00005093 Expr *X = nullptr;
5094 Expr *V = nullptr;
5095 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005096 Expr *UE = nullptr;
5097 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005098 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00005099 // OpenMP [2.12.6, atomic Construct]
5100 // In the next expressions:
5101 // * x and v (as applicable) are both l-value expressions with scalar type.
5102 // * During the execution of an atomic region, multiple syntactic
5103 // occurrences of x must designate the same storage location.
5104 // * Neither of v and expr (as applicable) may access the storage location
5105 // designated by x.
5106 // * Neither of x and expr (as applicable) may access the storage location
5107 // designated by v.
5108 // * expr is an expression with scalar type.
5109 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5110 // * binop, binop=, ++, and -- are not overloaded operators.
5111 // * The expression x binop expr must be numerically equivalent to x binop
5112 // (expr). This requirement is satisfied if the operators in expr have
5113 // precedence greater than binop, or by using parentheses around expr or
5114 // subexpressions of expr.
5115 // * The expression expr binop x must be numerically equivalent to (expr)
5116 // binop x. This requirement is satisfied if the operators in expr have
5117 // precedence equal to or greater than binop, or by using parentheses around
5118 // expr or subexpressions of expr.
5119 // * For forms that allow multiple occurrences of x, the number of times
5120 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00005121 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005122 enum {
5123 NotAnExpression,
5124 NotAnAssignmentOp,
5125 NotAScalarType,
5126 NotAnLValue,
5127 NoError
5128 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00005129 SourceLocation ErrorLoc, NoteLoc;
5130 SourceRange ErrorRange, NoteRange;
5131 // If clause is read:
5132 // v = x;
David Majnemer9d168222016-08-05 17:44:54 +00005133 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5134 auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00005135 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5136 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5137 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5138 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5139 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5140 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5141 if (!X->isLValue() || !V->isLValue()) {
5142 auto NotLValueExpr = X->isLValue() ? V : X;
5143 ErrorFound = NotAnLValue;
5144 ErrorLoc = AtomicBinOp->getExprLoc();
5145 ErrorRange = AtomicBinOp->getSourceRange();
5146 NoteLoc = NotLValueExpr->getExprLoc();
5147 NoteRange = NotLValueExpr->getSourceRange();
5148 }
5149 } else if (!X->isInstantiationDependent() ||
5150 !V->isInstantiationDependent()) {
5151 auto NotScalarExpr =
5152 (X->isInstantiationDependent() || X->getType()->isScalarType())
5153 ? V
5154 : X;
5155 ErrorFound = NotAScalarType;
5156 ErrorLoc = AtomicBinOp->getExprLoc();
5157 ErrorRange = AtomicBinOp->getSourceRange();
5158 NoteLoc = NotScalarExpr->getExprLoc();
5159 NoteRange = NotScalarExpr->getSourceRange();
5160 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005161 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00005162 ErrorFound = NotAnAssignmentOp;
5163 ErrorLoc = AtomicBody->getExprLoc();
5164 ErrorRange = AtomicBody->getSourceRange();
5165 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5166 : AtomicBody->getExprLoc();
5167 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5168 : AtomicBody->getSourceRange();
5169 }
5170 } else {
5171 ErrorFound = NotAnExpression;
5172 NoteLoc = ErrorLoc = Body->getLocStart();
5173 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005174 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005175 if (ErrorFound != NoError) {
5176 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5177 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005178 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5179 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00005180 return StmtError();
5181 } else if (CurContext->isDependentContext())
5182 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00005183 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005184 enum {
5185 NotAnExpression,
5186 NotAnAssignmentOp,
5187 NotAScalarType,
5188 NotAnLValue,
5189 NoError
5190 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005191 SourceLocation ErrorLoc, NoteLoc;
5192 SourceRange ErrorRange, NoteRange;
5193 // If clause is write:
5194 // x = expr;
David Majnemer9d168222016-08-05 17:44:54 +00005195 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5196 auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00005197 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5198 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00005199 X = AtomicBinOp->getLHS();
5200 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00005201 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5202 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5203 if (!X->isLValue()) {
5204 ErrorFound = NotAnLValue;
5205 ErrorLoc = AtomicBinOp->getExprLoc();
5206 ErrorRange = AtomicBinOp->getSourceRange();
5207 NoteLoc = X->getExprLoc();
5208 NoteRange = X->getSourceRange();
5209 }
5210 } else if (!X->isInstantiationDependent() ||
5211 !E->isInstantiationDependent()) {
5212 auto NotScalarExpr =
5213 (X->isInstantiationDependent() || X->getType()->isScalarType())
5214 ? E
5215 : X;
5216 ErrorFound = NotAScalarType;
5217 ErrorLoc = AtomicBinOp->getExprLoc();
5218 ErrorRange = AtomicBinOp->getSourceRange();
5219 NoteLoc = NotScalarExpr->getExprLoc();
5220 NoteRange = NotScalarExpr->getSourceRange();
5221 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005222 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00005223 ErrorFound = NotAnAssignmentOp;
5224 ErrorLoc = AtomicBody->getExprLoc();
5225 ErrorRange = AtomicBody->getSourceRange();
5226 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5227 : AtomicBody->getExprLoc();
5228 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5229 : AtomicBody->getSourceRange();
5230 }
5231 } else {
5232 ErrorFound = NotAnExpression;
5233 NoteLoc = ErrorLoc = Body->getLocStart();
5234 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005235 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00005236 if (ErrorFound != NoError) {
5237 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
5238 << ErrorRange;
5239 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5240 << NoteRange;
5241 return StmtError();
5242 } else if (CurContext->isDependentContext())
5243 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00005244 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005245 // If clause is update:
5246 // x++;
5247 // x--;
5248 // ++x;
5249 // --x;
5250 // x binop= expr;
5251 // x = x binop expr;
5252 // x = expr binop x;
5253 OpenMPAtomicUpdateChecker Checker(*this);
5254 if (Checker.checkStatement(
5255 Body, (AtomicKind == OMPC_update)
5256 ? diag::err_omp_atomic_update_not_expression_statement
5257 : diag::err_omp_atomic_not_expression_statement,
5258 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00005259 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005260 if (!CurContext->isDependentContext()) {
5261 E = Checker.getExpr();
5262 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005263 UE = Checker.getUpdateExpr();
5264 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00005265 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005266 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005267 enum {
5268 NotAnAssignmentOp,
5269 NotACompoundStatement,
5270 NotTwoSubstatements,
5271 NotASpecificExpression,
5272 NoError
5273 } ErrorFound = NoError;
5274 SourceLocation ErrorLoc, NoteLoc;
5275 SourceRange ErrorRange, NoteRange;
5276 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5277 // If clause is a capture:
5278 // v = x++;
5279 // v = x--;
5280 // v = ++x;
5281 // v = --x;
5282 // v = x binop= expr;
5283 // v = x = x binop expr;
5284 // v = x = expr binop x;
5285 auto *AtomicBinOp =
5286 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5287 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5288 V = AtomicBinOp->getLHS();
5289 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5290 OpenMPAtomicUpdateChecker Checker(*this);
5291 if (Checker.checkStatement(
5292 Body, diag::err_omp_atomic_capture_not_expression_statement,
5293 diag::note_omp_atomic_update))
5294 return StmtError();
5295 E = Checker.getExpr();
5296 X = Checker.getX();
5297 UE = Checker.getUpdateExpr();
5298 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5299 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00005300 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005301 ErrorLoc = AtomicBody->getExprLoc();
5302 ErrorRange = AtomicBody->getSourceRange();
5303 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5304 : AtomicBody->getExprLoc();
5305 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5306 : AtomicBody->getSourceRange();
5307 ErrorFound = NotAnAssignmentOp;
5308 }
5309 if (ErrorFound != NoError) {
5310 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
5311 << ErrorRange;
5312 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5313 return StmtError();
5314 } else if (CurContext->isDependentContext()) {
5315 UE = V = E = X = nullptr;
5316 }
5317 } else {
5318 // If clause is a capture:
5319 // { v = x; x = expr; }
5320 // { v = x; x++; }
5321 // { v = x; x--; }
5322 // { v = x; ++x; }
5323 // { v = x; --x; }
5324 // { v = x; x binop= expr; }
5325 // { v = x; x = x binop expr; }
5326 // { v = x; x = expr binop x; }
5327 // { x++; v = x; }
5328 // { x--; v = x; }
5329 // { ++x; v = x; }
5330 // { --x; v = x; }
5331 // { x binop= expr; v = x; }
5332 // { x = x binop expr; v = x; }
5333 // { x = expr binop x; v = x; }
5334 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
5335 // Check that this is { expr1; expr2; }
5336 if (CS->size() == 2) {
5337 auto *First = CS->body_front();
5338 auto *Second = CS->body_back();
5339 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
5340 First = EWC->getSubExpr()->IgnoreParenImpCasts();
5341 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
5342 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
5343 // Need to find what subexpression is 'v' and what is 'x'.
5344 OpenMPAtomicUpdateChecker Checker(*this);
5345 bool IsUpdateExprFound = !Checker.checkStatement(Second);
5346 BinaryOperator *BinOp = nullptr;
5347 if (IsUpdateExprFound) {
5348 BinOp = dyn_cast<BinaryOperator>(First);
5349 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5350 }
5351 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5352 // { v = x; x++; }
5353 // { v = x; x--; }
5354 // { v = x; ++x; }
5355 // { v = x; --x; }
5356 // { v = x; x binop= expr; }
5357 // { v = x; x = x binop expr; }
5358 // { v = x; x = expr binop x; }
5359 // Check that the first expression has form v = x.
5360 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5361 llvm::FoldingSetNodeID XId, PossibleXId;
5362 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5363 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5364 IsUpdateExprFound = XId == PossibleXId;
5365 if (IsUpdateExprFound) {
5366 V = BinOp->getLHS();
5367 X = Checker.getX();
5368 E = Checker.getExpr();
5369 UE = Checker.getUpdateExpr();
5370 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005371 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005372 }
5373 }
5374 if (!IsUpdateExprFound) {
5375 IsUpdateExprFound = !Checker.checkStatement(First);
5376 BinOp = nullptr;
5377 if (IsUpdateExprFound) {
5378 BinOp = dyn_cast<BinaryOperator>(Second);
5379 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5380 }
5381 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5382 // { x++; v = x; }
5383 // { x--; v = x; }
5384 // { ++x; v = x; }
5385 // { --x; v = x; }
5386 // { x binop= expr; v = x; }
5387 // { x = x binop expr; v = x; }
5388 // { x = expr binop x; v = x; }
5389 // Check that the second expression has form v = x.
5390 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5391 llvm::FoldingSetNodeID XId, PossibleXId;
5392 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5393 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5394 IsUpdateExprFound = XId == PossibleXId;
5395 if (IsUpdateExprFound) {
5396 V = BinOp->getLHS();
5397 X = Checker.getX();
5398 E = Checker.getExpr();
5399 UE = Checker.getUpdateExpr();
5400 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005401 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005402 }
5403 }
5404 }
5405 if (!IsUpdateExprFound) {
5406 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00005407 auto *FirstExpr = dyn_cast<Expr>(First);
5408 auto *SecondExpr = dyn_cast<Expr>(Second);
5409 if (!FirstExpr || !SecondExpr ||
5410 !(FirstExpr->isInstantiationDependent() ||
5411 SecondExpr->isInstantiationDependent())) {
5412 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
5413 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005414 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00005415 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
5416 : First->getLocStart();
5417 NoteRange = ErrorRange = FirstBinOp
5418 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00005419 : SourceRange(ErrorLoc, ErrorLoc);
5420 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005421 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
5422 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
5423 ErrorFound = NotAnAssignmentOp;
5424 NoteLoc = ErrorLoc = SecondBinOp
5425 ? SecondBinOp->getOperatorLoc()
5426 : Second->getLocStart();
5427 NoteRange = ErrorRange =
5428 SecondBinOp ? SecondBinOp->getSourceRange()
5429 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00005430 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005431 auto *PossibleXRHSInFirst =
5432 FirstBinOp->getRHS()->IgnoreParenImpCasts();
5433 auto *PossibleXLHSInSecond =
5434 SecondBinOp->getLHS()->IgnoreParenImpCasts();
5435 llvm::FoldingSetNodeID X1Id, X2Id;
5436 PossibleXRHSInFirst->Profile(X1Id, Context,
5437 /*Canonical=*/true);
5438 PossibleXLHSInSecond->Profile(X2Id, Context,
5439 /*Canonical=*/true);
5440 IsUpdateExprFound = X1Id == X2Id;
5441 if (IsUpdateExprFound) {
5442 V = FirstBinOp->getLHS();
5443 X = SecondBinOp->getLHS();
5444 E = SecondBinOp->getRHS();
5445 UE = nullptr;
5446 IsXLHSInRHSPart = false;
5447 IsPostfixUpdate = true;
5448 } else {
5449 ErrorFound = NotASpecificExpression;
5450 ErrorLoc = FirstBinOp->getExprLoc();
5451 ErrorRange = FirstBinOp->getSourceRange();
5452 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
5453 NoteRange = SecondBinOp->getRHS()->getSourceRange();
5454 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005455 }
5456 }
5457 }
5458 }
5459 } else {
5460 NoteLoc = ErrorLoc = Body->getLocStart();
5461 NoteRange = ErrorRange =
5462 SourceRange(Body->getLocStart(), Body->getLocStart());
5463 ErrorFound = NotTwoSubstatements;
5464 }
5465 } else {
5466 NoteLoc = ErrorLoc = Body->getLocStart();
5467 NoteRange = ErrorRange =
5468 SourceRange(Body->getLocStart(), Body->getLocStart());
5469 ErrorFound = NotACompoundStatement;
5470 }
5471 if (ErrorFound != NoError) {
5472 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
5473 << ErrorRange;
5474 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5475 return StmtError();
5476 } else if (CurContext->isDependentContext()) {
5477 UE = V = E = X = nullptr;
5478 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005479 }
Alexey Bataevdea47612014-07-23 07:46:59 +00005480 }
Alexey Bataev0162e452014-07-22 10:10:35 +00005481
5482 getCurFunction()->setHasBranchProtectedScope();
5483
Alexey Bataev62cec442014-11-18 10:14:22 +00005484 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00005485 X, V, E, UE, IsXLHSInRHSPart,
5486 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00005487}
5488
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005489StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
5490 Stmt *AStmt,
5491 SourceLocation StartLoc,
5492 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005493 if (!AStmt)
5494 return StmtError();
5495
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005496 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5497 // 1.2.2 OpenMP Language Terminology
5498 // Structured block - An executable statement with a single entry at the
5499 // top and a single exit at the bottom.
5500 // The point of exit cannot be a branch out of the structured block.
5501 // longjmp() and throw() must not violate the entry/exit criteria.
5502 CS->getCapturedDecl()->setNothrow();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005503
Alexey Bataev13314bf2014-10-09 04:18:56 +00005504 // OpenMP [2.16, Nesting of Regions]
5505 // If specified, a teams construct must be contained within a target
5506 // construct. That target construct must contain no statements or directives
5507 // outside of the teams construct.
5508 if (DSAStack->hasInnerTeamsRegion()) {
5509 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
5510 bool OMPTeamsFound = true;
5511 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
5512 auto I = CS->body_begin();
5513 while (I != CS->body_end()) {
David Majnemer9d168222016-08-05 17:44:54 +00005514 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00005515 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
5516 OMPTeamsFound = false;
5517 break;
5518 }
5519 ++I;
5520 }
5521 assert(I != CS->body_end() && "Not found statement");
5522 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00005523 } else {
5524 auto *OED = dyn_cast<OMPExecutableDirective>(S);
5525 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00005526 }
5527 if (!OMPTeamsFound) {
5528 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
5529 Diag(DSAStack->getInnerTeamsRegionLoc(),
5530 diag::note_omp_nested_teams_construct_here);
5531 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
5532 << isa<OMPExecutableDirective>(S);
5533 return StmtError();
5534 }
5535 }
5536
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005537 getCurFunction()->setHasBranchProtectedScope();
5538
5539 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5540}
5541
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005542StmtResult
5543Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
5544 Stmt *AStmt, SourceLocation StartLoc,
5545 SourceLocation EndLoc) {
5546 if (!AStmt)
5547 return StmtError();
5548
5549 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5550 // 1.2.2 OpenMP Language Terminology
5551 // Structured block - An executable statement with a single entry at the
5552 // top and a single exit at the bottom.
5553 // The point of exit cannot be a branch out of the structured block.
5554 // longjmp() and throw() must not violate the entry/exit criteria.
5555 CS->getCapturedDecl()->setNothrow();
5556
5557 getCurFunction()->setHasBranchProtectedScope();
5558
5559 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5560 AStmt);
5561}
5562
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005563StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
5564 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5565 SourceLocation EndLoc,
5566 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5567 if (!AStmt)
5568 return StmtError();
5569
5570 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5571 // 1.2.2 OpenMP Language Terminology
5572 // Structured block - An executable statement with a single entry at the
5573 // top and a single exit at the bottom.
5574 // The point of exit cannot be a branch out of the structured block.
5575 // longjmp() and throw() must not violate the entry/exit criteria.
5576 CS->getCapturedDecl()->setNothrow();
5577
5578 OMPLoopDirective::HelperExprs B;
5579 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5580 // define the nested loops number.
5581 unsigned NestedLoopCount =
5582 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
5583 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5584 VarsWithImplicitDSA, B);
5585 if (NestedLoopCount == 0)
5586 return StmtError();
5587
5588 assert((CurContext->isDependentContext() || B.builtAll()) &&
5589 "omp target parallel for loop exprs were not built");
5590
5591 if (!CurContext->isDependentContext()) {
5592 // Finalize the clauses that need pre-built expressions for CodeGen.
5593 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005594 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005595 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005596 B.NumIterations, *this, CurScope,
5597 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005598 return StmtError();
5599 }
5600 }
5601
5602 getCurFunction()->setHasBranchProtectedScope();
5603 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
5604 NestedLoopCount, Clauses, AStmt,
5605 B, DSAStack->isCancelRegion());
5606}
5607
Samuel Antaodf67fc42016-01-19 19:15:56 +00005608/// \brief Check for existence of a map clause in the list of clauses.
5609static bool HasMapClause(ArrayRef<OMPClause *> Clauses) {
5610 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
5611 I != E; ++I) {
5612 if (*I != nullptr && (*I)->getClauseKind() == OMPC_map) {
5613 return true;
5614 }
5615 }
5616
5617 return false;
5618}
5619
Michael Wong65f367f2015-07-21 13:44:28 +00005620StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
5621 Stmt *AStmt,
5622 SourceLocation StartLoc,
5623 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005624 if (!AStmt)
5625 return StmtError();
5626
5627 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5628
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005629 // OpenMP [2.10.1, Restrictions, p. 97]
5630 // At least one map clause must appear on the directive.
5631 if (!HasMapClause(Clauses)) {
David Majnemer9d168222016-08-05 17:44:54 +00005632 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5633 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005634 return StmtError();
5635 }
5636
Michael Wong65f367f2015-07-21 13:44:28 +00005637 getCurFunction()->setHasBranchProtectedScope();
5638
5639 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
5640 AStmt);
5641}
5642
Samuel Antaodf67fc42016-01-19 19:15:56 +00005643StmtResult
5644Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
5645 SourceLocation StartLoc,
5646 SourceLocation EndLoc) {
5647 // OpenMP [2.10.2, Restrictions, p. 99]
5648 // At least one map clause must appear on the directive.
5649 if (!HasMapClause(Clauses)) {
5650 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5651 << getOpenMPDirectiveName(OMPD_target_enter_data);
5652 return StmtError();
5653 }
5654
5655 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
5656 Clauses);
5657}
5658
Samuel Antao72590762016-01-19 20:04:50 +00005659StmtResult
5660Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
5661 SourceLocation StartLoc,
5662 SourceLocation EndLoc) {
5663 // OpenMP [2.10.3, Restrictions, p. 102]
5664 // At least one map clause must appear on the directive.
5665 if (!HasMapClause(Clauses)) {
5666 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5667 << getOpenMPDirectiveName(OMPD_target_exit_data);
5668 return StmtError();
5669 }
5670
5671 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
5672}
5673
Samuel Antao686c70c2016-05-26 17:30:50 +00005674StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
5675 SourceLocation StartLoc,
5676 SourceLocation EndLoc) {
Samuel Antao686c70c2016-05-26 17:30:50 +00005677 bool seenMotionClause = false;
Samuel Antao661c0902016-05-26 17:39:58 +00005678 for (auto *C : Clauses) {
Samuel Antaoec172c62016-05-26 17:49:04 +00005679 if (C->getClauseKind() == OMPC_to || C->getClauseKind() == OMPC_from)
Samuel Antao661c0902016-05-26 17:39:58 +00005680 seenMotionClause = true;
5681 }
Samuel Antao686c70c2016-05-26 17:30:50 +00005682 if (!seenMotionClause) {
5683 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
5684 return StmtError();
5685 }
5686 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses);
5687}
5688
Alexey Bataev13314bf2014-10-09 04:18:56 +00005689StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
5690 Stmt *AStmt, SourceLocation StartLoc,
5691 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005692 if (!AStmt)
5693 return StmtError();
5694
Alexey Bataev13314bf2014-10-09 04:18:56 +00005695 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5696 // 1.2.2 OpenMP Language Terminology
5697 // Structured block - An executable statement with a single entry at the
5698 // top and a single exit at the bottom.
5699 // The point of exit cannot be a branch out of the structured block.
5700 // longjmp() and throw() must not violate the entry/exit criteria.
5701 CS->getCapturedDecl()->setNothrow();
5702
5703 getCurFunction()->setHasBranchProtectedScope();
5704
5705 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5706}
5707
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005708StmtResult
5709Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
5710 SourceLocation EndLoc,
5711 OpenMPDirectiveKind CancelRegion) {
5712 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5713 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5714 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5715 << getOpenMPDirectiveName(CancelRegion);
5716 return StmtError();
5717 }
5718 if (DSAStack->isParentNowaitRegion()) {
5719 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
5720 return StmtError();
5721 }
5722 if (DSAStack->isParentOrderedRegion()) {
5723 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
5724 return StmtError();
5725 }
5726 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
5727 CancelRegion);
5728}
5729
Alexey Bataev87933c72015-09-18 08:07:34 +00005730StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
5731 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00005732 SourceLocation EndLoc,
5733 OpenMPDirectiveKind CancelRegion) {
5734 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5735 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5736 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5737 << getOpenMPDirectiveName(CancelRegion);
5738 return StmtError();
5739 }
5740 if (DSAStack->isParentNowaitRegion()) {
5741 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
5742 return StmtError();
5743 }
5744 if (DSAStack->isParentOrderedRegion()) {
5745 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
5746 return StmtError();
5747 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005748 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00005749 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5750 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00005751}
5752
Alexey Bataev382967a2015-12-08 12:06:20 +00005753static bool checkGrainsizeNumTasksClauses(Sema &S,
5754 ArrayRef<OMPClause *> Clauses) {
5755 OMPClause *PrevClause = nullptr;
5756 bool ErrorFound = false;
5757 for (auto *C : Clauses) {
5758 if (C->getClauseKind() == OMPC_grainsize ||
5759 C->getClauseKind() == OMPC_num_tasks) {
5760 if (!PrevClause)
5761 PrevClause = C;
5762 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
5763 S.Diag(C->getLocStart(),
5764 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
5765 << getOpenMPClauseName(C->getClauseKind())
5766 << getOpenMPClauseName(PrevClause->getClauseKind());
5767 S.Diag(PrevClause->getLocStart(),
5768 diag::note_omp_previous_grainsize_num_tasks)
5769 << getOpenMPClauseName(PrevClause->getClauseKind());
5770 ErrorFound = true;
5771 }
5772 }
5773 }
5774 return ErrorFound;
5775}
5776
Alexey Bataev49f6e782015-12-01 04:18:41 +00005777StmtResult Sema::ActOnOpenMPTaskLoopDirective(
5778 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5779 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005780 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00005781 if (!AStmt)
5782 return StmtError();
5783
5784 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5785 OMPLoopDirective::HelperExprs B;
5786 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5787 // define the nested loops number.
5788 unsigned NestedLoopCount =
5789 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005790 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00005791 VarsWithImplicitDSA, B);
5792 if (NestedLoopCount == 0)
5793 return StmtError();
5794
5795 assert((CurContext->isDependentContext() || B.builtAll()) &&
5796 "omp for loop exprs were not built");
5797
Alexey Bataev382967a2015-12-08 12:06:20 +00005798 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5799 // The grainsize clause and num_tasks clause are mutually exclusive and may
5800 // not appear on the same taskloop directive.
5801 if (checkGrainsizeNumTasksClauses(*this, Clauses))
5802 return StmtError();
5803
Alexey Bataev49f6e782015-12-01 04:18:41 +00005804 getCurFunction()->setHasBranchProtectedScope();
5805 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
5806 NestedLoopCount, Clauses, AStmt, B);
5807}
5808
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005809StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
5810 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5811 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005812 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005813 if (!AStmt)
5814 return StmtError();
5815
5816 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5817 OMPLoopDirective::HelperExprs B;
5818 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5819 // define the nested loops number.
5820 unsigned NestedLoopCount =
5821 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
5822 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
5823 VarsWithImplicitDSA, B);
5824 if (NestedLoopCount == 0)
5825 return StmtError();
5826
5827 assert((CurContext->isDependentContext() || B.builtAll()) &&
5828 "omp for loop exprs were not built");
5829
Alexey Bataev5a3af132016-03-29 08:58:54 +00005830 if (!CurContext->isDependentContext()) {
5831 // Finalize the clauses that need pre-built expressions for CodeGen.
5832 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005833 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00005834 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005835 B.NumIterations, *this, CurScope,
5836 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00005837 return StmtError();
5838 }
5839 }
5840
Alexey Bataev382967a2015-12-08 12:06:20 +00005841 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5842 // The grainsize clause and num_tasks clause are mutually exclusive and may
5843 // not appear on the same taskloop directive.
5844 if (checkGrainsizeNumTasksClauses(*this, Clauses))
5845 return StmtError();
5846
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005847 getCurFunction()->setHasBranchProtectedScope();
5848 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
5849 NestedLoopCount, Clauses, AStmt, B);
5850}
5851
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005852StmtResult Sema::ActOnOpenMPDistributeDirective(
5853 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5854 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005855 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005856 if (!AStmt)
5857 return StmtError();
5858
5859 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5860 OMPLoopDirective::HelperExprs B;
5861 // In presence of clause 'collapse' with number of loops, it will
5862 // define the nested loops number.
5863 unsigned NestedLoopCount =
5864 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
5865 nullptr /*ordered not a clause on distribute*/, AStmt,
5866 *this, *DSAStack, VarsWithImplicitDSA, B);
5867 if (NestedLoopCount == 0)
5868 return StmtError();
5869
5870 assert((CurContext->isDependentContext() || B.builtAll()) &&
5871 "omp for loop exprs were not built");
5872
5873 getCurFunction()->setHasBranchProtectedScope();
5874 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
5875 NestedLoopCount, Clauses, AStmt, B);
5876}
5877
Carlo Bertolli9925f152016-06-27 14:55:37 +00005878StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
5879 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5880 SourceLocation EndLoc,
5881 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5882 if (!AStmt)
5883 return StmtError();
5884
5885 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5886 // 1.2.2 OpenMP Language Terminology
5887 // Structured block - An executable statement with a single entry at the
5888 // top and a single exit at the bottom.
5889 // The point of exit cannot be a branch out of the structured block.
5890 // longjmp() and throw() must not violate the entry/exit criteria.
5891 CS->getCapturedDecl()->setNothrow();
5892
5893 OMPLoopDirective::HelperExprs B;
5894 // In presence of clause 'collapse' with number of loops, it will
5895 // define the nested loops number.
5896 unsigned NestedLoopCount = CheckOpenMPLoop(
5897 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
5898 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
5899 VarsWithImplicitDSA, B);
5900 if (NestedLoopCount == 0)
5901 return StmtError();
5902
5903 assert((CurContext->isDependentContext() || B.builtAll()) &&
5904 "omp for loop exprs were not built");
5905
5906 getCurFunction()->setHasBranchProtectedScope();
5907 return OMPDistributeParallelForDirective::Create(
5908 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
5909}
5910
Kelvin Li4a39add2016-07-05 05:00:15 +00005911StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
5912 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5913 SourceLocation EndLoc,
5914 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5915 if (!AStmt)
5916 return StmtError();
5917
5918 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5919 // 1.2.2 OpenMP Language Terminology
5920 // Structured block - An executable statement with a single entry at the
5921 // top and a single exit at the bottom.
5922 // The point of exit cannot be a branch out of the structured block.
5923 // longjmp() and throw() must not violate the entry/exit criteria.
5924 CS->getCapturedDecl()->setNothrow();
5925
5926 OMPLoopDirective::HelperExprs B;
5927 // In presence of clause 'collapse' with number of loops, it will
5928 // define the nested loops number.
5929 unsigned NestedLoopCount = CheckOpenMPLoop(
5930 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
5931 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
5932 VarsWithImplicitDSA, B);
5933 if (NestedLoopCount == 0)
5934 return StmtError();
5935
5936 assert((CurContext->isDependentContext() || B.builtAll()) &&
5937 "omp for loop exprs were not built");
5938
Kelvin Lic5609492016-07-15 04:39:07 +00005939 if (checkSimdlenSafelenSpecified(*this, Clauses))
5940 return StmtError();
5941
Kelvin Li4a39add2016-07-05 05:00:15 +00005942 getCurFunction()->setHasBranchProtectedScope();
5943 return OMPDistributeParallelForSimdDirective::Create(
5944 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
5945}
5946
Kelvin Li787f3fc2016-07-06 04:45:38 +00005947StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
5948 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5949 SourceLocation EndLoc,
5950 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5951 if (!AStmt)
5952 return StmtError();
5953
5954 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5955 // 1.2.2 OpenMP Language Terminology
5956 // Structured block - An executable statement with a single entry at the
5957 // top and a single exit at the bottom.
5958 // The point of exit cannot be a branch out of the structured block.
5959 // longjmp() and throw() must not violate the entry/exit criteria.
5960 CS->getCapturedDecl()->setNothrow();
5961
5962 OMPLoopDirective::HelperExprs B;
5963 // In presence of clause 'collapse' with number of loops, it will
5964 // define the nested loops number.
5965 unsigned NestedLoopCount =
5966 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
5967 nullptr /*ordered not a clause on distribute*/, AStmt,
5968 *this, *DSAStack, VarsWithImplicitDSA, B);
5969 if (NestedLoopCount == 0)
5970 return StmtError();
5971
5972 assert((CurContext->isDependentContext() || B.builtAll()) &&
5973 "omp for loop exprs were not built");
5974
Kelvin Lic5609492016-07-15 04:39:07 +00005975 if (checkSimdlenSafelenSpecified(*this, Clauses))
5976 return StmtError();
5977
Kelvin Li787f3fc2016-07-06 04:45:38 +00005978 getCurFunction()->setHasBranchProtectedScope();
5979 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
5980 NestedLoopCount, Clauses, AStmt, B);
5981}
5982
Kelvin Lia579b912016-07-14 02:54:56 +00005983StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
5984 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5985 SourceLocation EndLoc,
5986 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5987 if (!AStmt)
5988 return StmtError();
5989
5990 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5991 // 1.2.2 OpenMP Language Terminology
5992 // Structured block - An executable statement with a single entry at the
5993 // top and a single exit at the bottom.
5994 // The point of exit cannot be a branch out of the structured block.
5995 // longjmp() and throw() must not violate the entry/exit criteria.
5996 CS->getCapturedDecl()->setNothrow();
5997
5998 OMPLoopDirective::HelperExprs B;
5999 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6000 // define the nested loops number.
6001 unsigned NestedLoopCount = CheckOpenMPLoop(
6002 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
6003 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6004 VarsWithImplicitDSA, B);
6005 if (NestedLoopCount == 0)
6006 return StmtError();
6007
6008 assert((CurContext->isDependentContext() || B.builtAll()) &&
6009 "omp target parallel for simd loop exprs were not built");
6010
6011 if (!CurContext->isDependentContext()) {
6012 // Finalize the clauses that need pre-built expressions for CodeGen.
6013 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006014 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00006015 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6016 B.NumIterations, *this, CurScope,
6017 DSAStack))
6018 return StmtError();
6019 }
6020 }
Kelvin Lic5609492016-07-15 04:39:07 +00006021 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00006022 return StmtError();
6023
6024 getCurFunction()->setHasBranchProtectedScope();
6025 return OMPTargetParallelForSimdDirective::Create(
6026 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6027}
6028
Kelvin Li986330c2016-07-20 22:57:10 +00006029StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6030 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6031 SourceLocation EndLoc,
6032 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6033 if (!AStmt)
6034 return StmtError();
6035
6036 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6037 // 1.2.2 OpenMP Language Terminology
6038 // Structured block - An executable statement with a single entry at the
6039 // top and a single exit at the bottom.
6040 // The point of exit cannot be a branch out of the structured block.
6041 // longjmp() and throw() must not violate the entry/exit criteria.
6042 CS->getCapturedDecl()->setNothrow();
6043
6044 OMPLoopDirective::HelperExprs B;
6045 // In presence of clause 'collapse' with number of loops, it will define the
6046 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00006047 unsigned NestedLoopCount =
Kelvin Li986330c2016-07-20 22:57:10 +00006048 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
6049 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6050 VarsWithImplicitDSA, B);
6051 if (NestedLoopCount == 0)
6052 return StmtError();
6053
6054 assert((CurContext->isDependentContext() || B.builtAll()) &&
6055 "omp target simd loop exprs were not built");
6056
6057 if (!CurContext->isDependentContext()) {
6058 // Finalize the clauses that need pre-built expressions for CodeGen.
6059 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006060 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00006061 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6062 B.NumIterations, *this, CurScope,
6063 DSAStack))
6064 return StmtError();
6065 }
6066 }
6067
6068 if (checkSimdlenSafelenSpecified(*this, Clauses))
6069 return StmtError();
6070
6071 getCurFunction()->setHasBranchProtectedScope();
6072 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
6073 NestedLoopCount, Clauses, AStmt, B);
6074}
6075
Kelvin Li02532872016-08-05 14:37:37 +00006076StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
6077 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6078 SourceLocation EndLoc,
6079 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6080 if (!AStmt)
6081 return StmtError();
6082
6083 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6084 // 1.2.2 OpenMP Language Terminology
6085 // Structured block - An executable statement with a single entry at the
6086 // top and a single exit at the bottom.
6087 // The point of exit cannot be a branch out of the structured block.
6088 // longjmp() and throw() must not violate the entry/exit criteria.
6089 CS->getCapturedDecl()->setNothrow();
6090
6091 OMPLoopDirective::HelperExprs B;
6092 // In presence of clause 'collapse' with number of loops, it will
6093 // define the nested loops number.
6094 unsigned NestedLoopCount =
6095 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
6096 nullptr /*ordered not a clause on distribute*/, AStmt,
6097 *this, *DSAStack, VarsWithImplicitDSA, B);
6098 if (NestedLoopCount == 0)
6099 return StmtError();
6100
6101 assert((CurContext->isDependentContext() || B.builtAll()) &&
6102 "omp teams distribute loop exprs were not built");
6103
6104 getCurFunction()->setHasBranchProtectedScope();
David Majnemer9d168222016-08-05 17:44:54 +00006105 return OMPTeamsDistributeDirective::Create(
6106 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00006107}
6108
Kelvin Li4e325f72016-10-25 12:50:55 +00006109StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
6110 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6111 SourceLocation EndLoc,
6112 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6113 if (!AStmt)
6114 return StmtError();
6115
6116 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6117 // 1.2.2 OpenMP Language Terminology
6118 // Structured block - An executable statement with a single entry at the
6119 // top and a single exit at the bottom.
6120 // The point of exit cannot be a branch out of the structured block.
6121 // longjmp() and throw() must not violate the entry/exit criteria.
6122 CS->getCapturedDecl()->setNothrow();
6123
6124 OMPLoopDirective::HelperExprs B;
6125 // In presence of clause 'collapse' with number of loops, it will
6126 // define the nested loops number.
Samuel Antao4c8035b2016-12-12 18:00:20 +00006127 unsigned NestedLoopCount = CheckOpenMPLoop(
6128 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6129 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6130 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00006131
6132 if (NestedLoopCount == 0)
6133 return StmtError();
6134
6135 assert((CurContext->isDependentContext() || B.builtAll()) &&
6136 "omp teams distribute simd loop exprs were not built");
6137
6138 if (!CurContext->isDependentContext()) {
6139 // Finalize the clauses that need pre-built expressions for CodeGen.
6140 for (auto C : Clauses) {
6141 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6142 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6143 B.NumIterations, *this, CurScope,
6144 DSAStack))
6145 return StmtError();
6146 }
6147 }
6148
6149 if (checkSimdlenSafelenSpecified(*this, Clauses))
6150 return StmtError();
6151
6152 getCurFunction()->setHasBranchProtectedScope();
6153 return OMPTeamsDistributeSimdDirective::Create(
6154 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6155}
6156
Kelvin Li579e41c2016-11-30 23:51:03 +00006157StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6158 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6159 SourceLocation EndLoc,
6160 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6161 if (!AStmt)
6162 return StmtError();
6163
6164 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6165 // 1.2.2 OpenMP Language Terminology
6166 // Structured block - An executable statement with a single entry at the
6167 // top and a single exit at the bottom.
6168 // The point of exit cannot be a branch out of the structured block.
6169 // longjmp() and throw() must not violate the entry/exit criteria.
6170 CS->getCapturedDecl()->setNothrow();
6171
6172 OMPLoopDirective::HelperExprs B;
6173 // In presence of clause 'collapse' with number of loops, it will
6174 // define the nested loops number.
6175 auto NestedLoopCount = CheckOpenMPLoop(
6176 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6177 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6178 VarsWithImplicitDSA, B);
6179
6180 if (NestedLoopCount == 0)
6181 return StmtError();
6182
6183 assert((CurContext->isDependentContext() || B.builtAll()) &&
6184 "omp for loop exprs were not built");
6185
6186 if (!CurContext->isDependentContext()) {
6187 // Finalize the clauses that need pre-built expressions for CodeGen.
6188 for (auto C : Clauses) {
6189 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6190 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6191 B.NumIterations, *this, CurScope,
6192 DSAStack))
6193 return StmtError();
6194 }
6195 }
6196
6197 if (checkSimdlenSafelenSpecified(*this, Clauses))
6198 return StmtError();
6199
6200 getCurFunction()->setHasBranchProtectedScope();
6201 return OMPTeamsDistributeParallelForSimdDirective::Create(
6202 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6203}
6204
Kelvin Li7ade93f2016-12-09 03:24:30 +00006205StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
6206 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6207 SourceLocation EndLoc,
6208 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6209 if (!AStmt)
6210 return StmtError();
6211
6212 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6213 // 1.2.2 OpenMP Language Terminology
6214 // Structured block - An executable statement with a single entry at the
6215 // top and a single exit at the bottom.
6216 // The point of exit cannot be a branch out of the structured block.
6217 // longjmp() and throw() must not violate the entry/exit criteria.
6218 CS->getCapturedDecl()->setNothrow();
6219
6220 OMPLoopDirective::HelperExprs B;
6221 // In presence of clause 'collapse' with number of loops, it will
6222 // define the nested loops number.
6223 unsigned NestedLoopCount = CheckOpenMPLoop(
6224 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6225 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6226 VarsWithImplicitDSA, B);
6227
6228 if (NestedLoopCount == 0)
6229 return StmtError();
6230
6231 assert((CurContext->isDependentContext() || B.builtAll()) &&
6232 "omp for loop exprs were not built");
6233
6234 if (!CurContext->isDependentContext()) {
6235 // Finalize the clauses that need pre-built expressions for CodeGen.
6236 for (auto C : Clauses) {
6237 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6238 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6239 B.NumIterations, *this, CurScope,
6240 DSAStack))
6241 return StmtError();
6242 }
6243 }
6244
6245 getCurFunction()->setHasBranchProtectedScope();
6246 return OMPTeamsDistributeParallelForDirective::Create(
6247 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6248}
6249
Alexey Bataeved09d242014-05-28 05:53:51 +00006250OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006251 SourceLocation StartLoc,
6252 SourceLocation LParenLoc,
6253 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006254 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006255 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00006256 case OMPC_final:
6257 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
6258 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00006259 case OMPC_num_threads:
6260 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
6261 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006262 case OMPC_safelen:
6263 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
6264 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00006265 case OMPC_simdlen:
6266 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
6267 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00006268 case OMPC_collapse:
6269 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
6270 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006271 case OMPC_ordered:
6272 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
6273 break;
Michael Wonge710d542015-08-07 16:16:36 +00006274 case OMPC_device:
6275 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
6276 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00006277 case OMPC_num_teams:
6278 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
6279 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006280 case OMPC_thread_limit:
6281 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
6282 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00006283 case OMPC_priority:
6284 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
6285 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006286 case OMPC_grainsize:
6287 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
6288 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00006289 case OMPC_num_tasks:
6290 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
6291 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00006292 case OMPC_hint:
6293 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
6294 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006295 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006296 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006297 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006298 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006299 case OMPC_private:
6300 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00006301 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006302 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00006303 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00006304 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006305 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006306 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006307 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00006308 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006309 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006310 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006311 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006312 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006313 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006314 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006315 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006316 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006317 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006318 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00006319 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006320 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006321 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00006322 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00006323 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006324 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006325 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006326 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006327 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006328 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006329 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006330 case OMPC_is_device_ptr:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006331 llvm_unreachable("Clause is not allowed.");
6332 }
6333 return Res;
6334}
6335
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006336OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
6337 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006338 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006339 SourceLocation NameModifierLoc,
6340 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006341 SourceLocation EndLoc) {
6342 Expr *ValExpr = Condition;
6343 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6344 !Condition->isInstantiationDependent() &&
6345 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00006346 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006347 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006348 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006349
Richard Smith03a4aa32016-06-23 19:02:52 +00006350 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006351 }
6352
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006353 return new (Context) OMPIfClause(NameModifier, ValExpr, StartLoc, LParenLoc,
6354 NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006355}
6356
Alexey Bataev3778b602014-07-17 07:32:53 +00006357OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
6358 SourceLocation StartLoc,
6359 SourceLocation LParenLoc,
6360 SourceLocation EndLoc) {
6361 Expr *ValExpr = Condition;
6362 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6363 !Condition->isInstantiationDependent() &&
6364 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00006365 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00006366 if (Val.isInvalid())
6367 return nullptr;
6368
Richard Smith03a4aa32016-06-23 19:02:52 +00006369 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00006370 }
6371
6372 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
6373}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006374ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
6375 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00006376 if (!Op)
6377 return ExprError();
6378
6379 class IntConvertDiagnoser : public ICEConvertDiagnoser {
6380 public:
6381 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00006382 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00006383 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
6384 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006385 return S.Diag(Loc, diag::err_omp_not_integral) << T;
6386 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006387 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
6388 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006389 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
6390 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006391 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
6392 QualType T,
6393 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006394 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
6395 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006396 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
6397 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006398 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00006399 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00006400 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006401 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
6402 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006403 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
6404 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006405 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
6406 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006407 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00006408 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00006409 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006410 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
6411 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006412 llvm_unreachable("conversion functions are permitted");
6413 }
6414 } ConvertDiagnoser;
6415 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
6416}
6417
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006418static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00006419 OpenMPClauseKind CKind,
6420 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006421 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
6422 !ValExpr->isInstantiationDependent()) {
6423 SourceLocation Loc = ValExpr->getExprLoc();
6424 ExprResult Value =
6425 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
6426 if (Value.isInvalid())
6427 return false;
6428
6429 ValExpr = Value.get();
6430 // The expression must evaluate to a non-negative integer value.
6431 llvm::APSInt Result;
6432 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00006433 Result.isSigned() &&
6434 !((!StrictlyPositive && Result.isNonNegative()) ||
6435 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006436 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00006437 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
6438 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006439 return false;
6440 }
6441 }
6442 return true;
6443}
6444
Alexey Bataev568a8332014-03-06 06:15:19 +00006445OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
6446 SourceLocation StartLoc,
6447 SourceLocation LParenLoc,
6448 SourceLocation EndLoc) {
6449 Expr *ValExpr = NumThreads;
Alexey Bataev568a8332014-03-06 06:15:19 +00006450
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006451 // OpenMP [2.5, Restrictions]
6452 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00006453 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
6454 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006455 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00006456
Alexey Bataeved09d242014-05-28 05:53:51 +00006457 return new (Context)
6458 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00006459}
6460
Alexey Bataev62c87d22014-03-21 04:51:18 +00006461ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006462 OpenMPClauseKind CKind,
6463 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00006464 if (!E)
6465 return ExprError();
6466 if (E->isValueDependent() || E->isTypeDependent() ||
6467 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006468 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006469 llvm::APSInt Result;
6470 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
6471 if (ICE.isInvalid())
6472 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006473 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
6474 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00006475 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006476 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
6477 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00006478 return ExprError();
6479 }
Alexander Musman09184fe2014-09-30 05:29:28 +00006480 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
6481 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
6482 << E->getSourceRange();
6483 return ExprError();
6484 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006485 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
6486 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00006487 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006488 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00006489 return ICE;
6490}
6491
6492OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
6493 SourceLocation LParenLoc,
6494 SourceLocation EndLoc) {
6495 // OpenMP [2.8.1, simd construct, Description]
6496 // The parameter of the safelen clause must be a constant
6497 // positive integer expression.
6498 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
6499 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006500 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006501 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006502 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00006503}
6504
Alexey Bataev66b15b52015-08-21 11:14:16 +00006505OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
6506 SourceLocation LParenLoc,
6507 SourceLocation EndLoc) {
6508 // OpenMP [2.8.1, simd construct, Description]
6509 // The parameter of the simdlen clause must be a constant
6510 // positive integer expression.
6511 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
6512 if (Simdlen.isInvalid())
6513 return nullptr;
6514 return new (Context)
6515 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
6516}
6517
Alexander Musman64d33f12014-06-04 07:53:32 +00006518OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
6519 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00006520 SourceLocation LParenLoc,
6521 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00006522 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00006523 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00006524 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00006525 // The parameter of the collapse clause must be a constant
6526 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00006527 ExprResult NumForLoopsResult =
6528 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
6529 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00006530 return nullptr;
6531 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00006532 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00006533}
6534
Alexey Bataev10e775f2015-07-30 11:36:16 +00006535OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
6536 SourceLocation EndLoc,
6537 SourceLocation LParenLoc,
6538 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00006539 // OpenMP [2.7.1, loop construct, Description]
6540 // OpenMP [2.8.1, simd construct, Description]
6541 // OpenMP [2.9.6, distribute construct, Description]
6542 // The parameter of the ordered clause must be a constant
6543 // positive integer expression if any.
6544 if (NumForLoops && LParenLoc.isValid()) {
6545 ExprResult NumForLoopsResult =
6546 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
6547 if (NumForLoopsResult.isInvalid())
6548 return nullptr;
6549 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00006550 } else
6551 NumForLoops = nullptr;
6552 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00006553 return new (Context)
6554 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
6555}
6556
Alexey Bataeved09d242014-05-28 05:53:51 +00006557OMPClause *Sema::ActOnOpenMPSimpleClause(
6558 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
6559 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006560 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006561 switch (Kind) {
6562 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00006563 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00006564 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
6565 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006566 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006567 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00006568 Res = ActOnOpenMPProcBindClause(
6569 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
6570 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006571 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006572 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00006573 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00006574 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00006575 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00006576 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00006577 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006578 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006579 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006580 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00006581 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00006582 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00006583 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00006584 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006585 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006586 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006587 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006588 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00006589 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006590 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006591 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006592 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006593 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006594 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006595 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006596 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006597 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006598 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006599 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00006600 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00006601 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006602 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006603 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00006604 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006605 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00006606 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006607 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00006608 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00006609 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00006610 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00006611 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006612 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006613 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006614 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006615 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006616 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006617 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006618 case OMPC_is_device_ptr:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006619 llvm_unreachable("Clause is not allowed.");
6620 }
6621 return Res;
6622}
6623
Alexey Bataev6402bca2015-12-28 07:25:51 +00006624static std::string
6625getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
6626 ArrayRef<unsigned> Exclude = llvm::None) {
6627 std::string Values;
6628 unsigned Bound = Last >= 2 ? Last - 2 : 0;
6629 unsigned Skipped = Exclude.size();
6630 auto S = Exclude.begin(), E = Exclude.end();
6631 for (unsigned i = First; i < Last; ++i) {
6632 if (std::find(S, E, i) != E) {
6633 --Skipped;
6634 continue;
6635 }
6636 Values += "'";
6637 Values += getOpenMPSimpleClauseTypeName(K, i);
6638 Values += "'";
6639 if (i == Bound - Skipped)
6640 Values += " or ";
6641 else if (i != Bound + 1 - Skipped)
6642 Values += ", ";
6643 }
6644 return Values;
6645}
6646
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006647OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
6648 SourceLocation KindKwLoc,
6649 SourceLocation StartLoc,
6650 SourceLocation LParenLoc,
6651 SourceLocation EndLoc) {
6652 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00006653 static_assert(OMPC_DEFAULT_unknown > 0,
6654 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006655 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00006656 << getListOfPossibleValues(OMPC_default, /*First=*/0,
6657 /*Last=*/OMPC_DEFAULT_unknown)
6658 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006659 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006660 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00006661 switch (Kind) {
6662 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006663 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00006664 break;
6665 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006666 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00006667 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006668 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006669 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00006670 break;
6671 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006672 return new (Context)
6673 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006674}
6675
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006676OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
6677 SourceLocation KindKwLoc,
6678 SourceLocation StartLoc,
6679 SourceLocation LParenLoc,
6680 SourceLocation EndLoc) {
6681 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006682 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00006683 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
6684 /*Last=*/OMPC_PROC_BIND_unknown)
6685 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006686 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006687 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006688 return new (Context)
6689 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006690}
6691
Alexey Bataev56dafe82014-06-20 07:16:17 +00006692OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00006693 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00006694 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00006695 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00006696 SourceLocation EndLoc) {
6697 OMPClause *Res = nullptr;
6698 switch (Kind) {
6699 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00006700 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
6701 assert(Argument.size() == NumberOfElements &&
6702 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00006703 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00006704 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
6705 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
6706 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
6707 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
6708 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00006709 break;
6710 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00006711 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
6712 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
6713 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
6714 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006715 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00006716 case OMPC_dist_schedule:
6717 Res = ActOnOpenMPDistScheduleClause(
6718 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
6719 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
6720 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006721 case OMPC_defaultmap:
6722 enum { Modifier, DefaultmapKind };
6723 Res = ActOnOpenMPDefaultmapClause(
6724 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
6725 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00006726 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
6727 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006728 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00006729 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006730 case OMPC_num_threads:
6731 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00006732 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006733 case OMPC_collapse:
6734 case OMPC_default:
6735 case OMPC_proc_bind:
6736 case OMPC_private:
6737 case OMPC_firstprivate:
6738 case OMPC_lastprivate:
6739 case OMPC_shared:
6740 case OMPC_reduction:
6741 case OMPC_linear:
6742 case OMPC_aligned:
6743 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006744 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006745 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00006746 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006747 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006748 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006749 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006750 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006751 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006752 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006753 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006754 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006755 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006756 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00006757 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00006758 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006759 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006760 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00006761 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006762 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00006763 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006764 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00006765 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00006766 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00006767 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006768 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006769 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006770 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006771 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006772 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006773 case OMPC_is_device_ptr:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006774 llvm_unreachable("Clause is not allowed.");
6775 }
6776 return Res;
6777}
6778
Alexey Bataev6402bca2015-12-28 07:25:51 +00006779static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
6780 OpenMPScheduleClauseModifier M2,
6781 SourceLocation M1Loc, SourceLocation M2Loc) {
6782 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
6783 SmallVector<unsigned, 2> Excluded;
6784 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
6785 Excluded.push_back(M2);
6786 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
6787 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
6788 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
6789 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
6790 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
6791 << getListOfPossibleValues(OMPC_schedule,
6792 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
6793 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
6794 Excluded)
6795 << getOpenMPClauseName(OMPC_schedule);
6796 return true;
6797 }
6798 return false;
6799}
6800
Alexey Bataev56dafe82014-06-20 07:16:17 +00006801OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00006802 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00006803 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00006804 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
6805 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
6806 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
6807 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
6808 return nullptr;
6809 // OpenMP, 2.7.1, Loop Construct, Restrictions
6810 // Either the monotonic modifier or the nonmonotonic modifier can be specified
6811 // but not both.
6812 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
6813 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
6814 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
6815 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
6816 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
6817 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
6818 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
6819 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
6820 return nullptr;
6821 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00006822 if (Kind == OMPC_SCHEDULE_unknown) {
6823 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00006824 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
6825 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
6826 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
6827 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
6828 Exclude);
6829 } else {
6830 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
6831 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00006832 }
6833 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
6834 << Values << getOpenMPClauseName(OMPC_schedule);
6835 return nullptr;
6836 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00006837 // OpenMP, 2.7.1, Loop Construct, Restrictions
6838 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
6839 // schedule(guided).
6840 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
6841 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
6842 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
6843 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
6844 diag::err_omp_schedule_nonmonotonic_static);
6845 return nullptr;
6846 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00006847 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00006848 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00006849 if (ChunkSize) {
6850 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
6851 !ChunkSize->isInstantiationDependent() &&
6852 !ChunkSize->containsUnexpandedParameterPack()) {
6853 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
6854 ExprResult Val =
6855 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
6856 if (Val.isInvalid())
6857 return nullptr;
6858
6859 ValExpr = Val.get();
6860
6861 // OpenMP [2.7.1, Restrictions]
6862 // chunk_size must be a loop invariant integer expression with a positive
6863 // value.
6864 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00006865 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
6866 if (Result.isSigned() && !Result.isStrictlyPositive()) {
6867 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00006868 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00006869 return nullptr;
6870 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +00006871 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
6872 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00006873 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
6874 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
6875 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00006876 }
6877 }
6878 }
6879
Alexey Bataev6402bca2015-12-28 07:25:51 +00006880 return new (Context)
6881 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00006882 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00006883}
6884
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006885OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
6886 SourceLocation StartLoc,
6887 SourceLocation EndLoc) {
6888 OMPClause *Res = nullptr;
6889 switch (Kind) {
6890 case OMPC_ordered:
6891 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
6892 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00006893 case OMPC_nowait:
6894 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
6895 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006896 case OMPC_untied:
6897 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
6898 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006899 case OMPC_mergeable:
6900 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
6901 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006902 case OMPC_read:
6903 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
6904 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00006905 case OMPC_write:
6906 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
6907 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00006908 case OMPC_update:
6909 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
6910 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00006911 case OMPC_capture:
6912 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
6913 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006914 case OMPC_seq_cst:
6915 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
6916 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00006917 case OMPC_threads:
6918 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
6919 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006920 case OMPC_simd:
6921 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
6922 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00006923 case OMPC_nogroup:
6924 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
6925 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006926 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00006927 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006928 case OMPC_num_threads:
6929 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00006930 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006931 case OMPC_collapse:
6932 case OMPC_schedule:
6933 case OMPC_private:
6934 case OMPC_firstprivate:
6935 case OMPC_lastprivate:
6936 case OMPC_shared:
6937 case OMPC_reduction:
6938 case OMPC_linear:
6939 case OMPC_aligned:
6940 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006941 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006942 case OMPC_default:
6943 case OMPC_proc_bind:
6944 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006945 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006946 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00006947 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006948 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00006949 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006950 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00006951 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006952 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00006953 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00006954 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00006955 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006956 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006957 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006958 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006959 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006960 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006961 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006962 case OMPC_is_device_ptr:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006963 llvm_unreachable("Clause is not allowed.");
6964 }
6965 return Res;
6966}
6967
Alexey Bataev236070f2014-06-20 11:19:47 +00006968OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
6969 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006970 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00006971 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
6972}
6973
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006974OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
6975 SourceLocation EndLoc) {
6976 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
6977}
6978
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006979OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
6980 SourceLocation EndLoc) {
6981 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
6982}
6983
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006984OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
6985 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006986 return new (Context) OMPReadClause(StartLoc, EndLoc);
6987}
6988
Alexey Bataevdea47612014-07-23 07:46:59 +00006989OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
6990 SourceLocation EndLoc) {
6991 return new (Context) OMPWriteClause(StartLoc, EndLoc);
6992}
6993
Alexey Bataev67a4f222014-07-23 10:25:33 +00006994OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
6995 SourceLocation EndLoc) {
6996 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
6997}
6998
Alexey Bataev459dec02014-07-24 06:46:57 +00006999OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
7000 SourceLocation EndLoc) {
7001 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
7002}
7003
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007004OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
7005 SourceLocation EndLoc) {
7006 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
7007}
7008
Alexey Bataev346265e2015-09-25 10:37:12 +00007009OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
7010 SourceLocation EndLoc) {
7011 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
7012}
7013
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007014OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
7015 SourceLocation EndLoc) {
7016 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
7017}
7018
Alexey Bataevb825de12015-12-07 10:51:44 +00007019OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
7020 SourceLocation EndLoc) {
7021 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
7022}
7023
Alexey Bataevc5e02582014-06-16 07:08:35 +00007024OMPClause *Sema::ActOnOpenMPVarListClause(
7025 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
7026 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
7027 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007028 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00007029 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
7030 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
7031 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007032 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007033 switch (Kind) {
7034 case OMPC_private:
7035 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7036 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007037 case OMPC_firstprivate:
7038 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7039 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007040 case OMPC_lastprivate:
7041 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7042 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00007043 case OMPC_shared:
7044 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
7045 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00007046 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00007047 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
7048 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00007049 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00007050 case OMPC_linear:
7051 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00007052 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00007053 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007054 case OMPC_aligned:
7055 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
7056 ColonLoc, EndLoc);
7057 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007058 case OMPC_copyin:
7059 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
7060 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00007061 case OMPC_copyprivate:
7062 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7063 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00007064 case OMPC_flush:
7065 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
7066 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007067 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00007068 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00007069 StartLoc, LParenLoc, EndLoc);
7070 break;
7071 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00007072 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
7073 DepLinMapLoc, ColonLoc, VarList, StartLoc,
7074 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007075 break;
Samuel Antao661c0902016-05-26 17:39:58 +00007076 case OMPC_to:
7077 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
7078 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00007079 case OMPC_from:
7080 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
7081 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00007082 case OMPC_use_device_ptr:
7083 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7084 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00007085 case OMPC_is_device_ptr:
7086 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7087 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007088 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007089 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00007090 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00007091 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007092 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00007093 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007094 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007095 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007096 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007097 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007098 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007099 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007100 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007101 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007102 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007103 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007104 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007105 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007106 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00007107 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007108 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007109 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007110 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007111 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007112 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007113 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007114 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007115 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007116 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007117 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007118 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007119 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007120 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007121 llvm_unreachable("Clause is not allowed.");
7122 }
7123 return Res;
7124}
7125
Alexey Bataev90c228f2016-02-08 09:29:13 +00007126ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00007127 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00007128 ExprResult Res = BuildDeclRefExpr(
7129 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
7130 if (!Res.isUsable())
7131 return ExprError();
7132 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
7133 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
7134 if (!Res.isUsable())
7135 return ExprError();
7136 }
7137 if (VK != VK_LValue && Res.get()->isGLValue()) {
7138 Res = DefaultLvalueConversion(Res.get());
7139 if (!Res.isUsable())
7140 return ExprError();
7141 }
7142 return Res;
7143}
7144
Alexey Bataev60da77e2016-02-29 05:54:20 +00007145static std::pair<ValueDecl *, bool>
7146getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
7147 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007148 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
7149 RefExpr->containsUnexpandedParameterPack())
7150 return std::make_pair(nullptr, true);
7151
Alexey Bataevd985eda2016-02-10 11:29:16 +00007152 // OpenMP [3.1, C/C++]
7153 // A list item is a variable name.
7154 // OpenMP [2.9.3.3, Restrictions, p.1]
7155 // A variable that is part of another variable (as an array or
7156 // structure element) cannot appear in a private clause.
7157 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00007158 enum {
7159 NoArrayExpr = -1,
7160 ArraySubscript = 0,
7161 OMPArraySection = 1
7162 } IsArrayExpr = NoArrayExpr;
7163 if (AllowArraySection) {
7164 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
7165 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
7166 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7167 Base = TempASE->getBase()->IgnoreParenImpCasts();
7168 RefExpr = Base;
7169 IsArrayExpr = ArraySubscript;
7170 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
7171 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
7172 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
7173 Base = TempOASE->getBase()->IgnoreParenImpCasts();
7174 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7175 Base = TempASE->getBase()->IgnoreParenImpCasts();
7176 RefExpr = Base;
7177 IsArrayExpr = OMPArraySection;
7178 }
7179 }
7180 ELoc = RefExpr->getExprLoc();
7181 ERange = RefExpr->getSourceRange();
7182 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00007183 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
7184 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
7185 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
7186 (S.getCurrentThisType().isNull() || !ME ||
7187 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
7188 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00007189 if (IsArrayExpr != NoArrayExpr)
7190 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
7191 << ERange;
7192 else {
7193 S.Diag(ELoc,
7194 AllowArraySection
7195 ? diag::err_omp_expected_var_name_member_expr_or_array_item
7196 : diag::err_omp_expected_var_name_member_expr)
7197 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
7198 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007199 return std::make_pair(nullptr, false);
7200 }
7201 return std::make_pair(DE ? DE->getDecl() : ME->getMemberDecl(), false);
7202}
7203
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007204OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
7205 SourceLocation StartLoc,
7206 SourceLocation LParenLoc,
7207 SourceLocation EndLoc) {
7208 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00007209 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00007210 for (auto &RefExpr : VarList) {
7211 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007212 SourceLocation ELoc;
7213 SourceRange ERange;
7214 Expr *SimpleRefExpr = RefExpr;
7215 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007216 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007217 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007218 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007219 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007220 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007221 ValueDecl *D = Res.first;
7222 if (!D)
7223 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007224
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007225 QualType Type = D->getType();
7226 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007227
7228 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7229 // A variable that appears in a private clause must not have an incomplete
7230 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007231 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007232 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007233 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007234
Alexey Bataev758e55e2013-09-06 18:03:48 +00007235 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7236 // in a Construct]
7237 // Variables with the predetermined data-sharing attributes may not be
7238 // listed in data-sharing attributes clauses, except for the cases
7239 // listed below. For these exceptions only, listing a predetermined
7240 // variable in a data-sharing attribute clause is allowed and overrides
7241 // the variable's predetermined data-sharing attributes.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007242 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007243 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00007244 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7245 << getOpenMPClauseName(OMPC_private);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007246 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007247 continue;
7248 }
7249
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007250 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00007251 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00007252 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007253 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7254 << getOpenMPClauseName(OMPC_private) << Type
7255 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7256 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007257 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007258 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007259 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007260 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007261 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007262 continue;
7263 }
7264
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007265 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
7266 // A list item cannot appear in both a map clause and a data-sharing
7267 // attribute clause on the same construct
Kelvin Li193ee2d2016-12-16 20:50:46 +00007268 if (DSAStack->getCurrentDirective() == OMPD_target ||
7269 DSAStack->getCurrentDirective() == OMPD_target_parallel) {
Samuel Antao6890b092016-07-28 14:25:09 +00007270 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00007271 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00007272 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00007273 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
7274 OpenMPClauseKind WhereFoundClauseKind) -> bool {
7275 ConflictKind = WhereFoundClauseKind;
7276 return true;
7277 })) {
7278 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007279 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00007280 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007281 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7282 ReportOriginalDSA(*this, DSAStack, D, DVar);
7283 continue;
7284 }
7285 }
7286
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007287 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
7288 // A variable of class type (or array thereof) that appears in a private
7289 // clause requires an accessible, unambiguous default constructor for the
7290 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00007291 // Generate helper private variable and initialize it with the default
7292 // value. The address of the original variable is replaced by the address of
7293 // the new private variable in CodeGen. This new variable is not added to
7294 // IdResolver, so the code in the OpenMP region uses original variable for
7295 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007296 Type = Type.getUnqualifiedType();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007297 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7298 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00007299 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007300 if (VDPrivate->isInvalidDecl())
7301 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007302 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007303 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007304
Alexey Bataev90c228f2016-02-08 09:29:13 +00007305 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007306 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00007307 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00007308 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007309 Vars.push_back((VD || CurContext->isDependentContext())
7310 ? RefExpr->IgnoreParens()
7311 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007312 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007313 }
7314
Alexey Bataeved09d242014-05-28 05:53:51 +00007315 if (Vars.empty())
7316 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007317
Alexey Bataev03b340a2014-10-21 03:16:40 +00007318 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
7319 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007320}
7321
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007322namespace {
7323class DiagsUninitializedSeveretyRAII {
7324private:
7325 DiagnosticsEngine &Diags;
7326 SourceLocation SavedLoc;
7327 bool IsIgnored;
7328
7329public:
7330 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
7331 bool IsIgnored)
7332 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
7333 if (!IsIgnored) {
7334 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
7335 /*Map*/ diag::Severity::Ignored, Loc);
7336 }
7337 }
7338 ~DiagsUninitializedSeveretyRAII() {
7339 if (!IsIgnored)
7340 Diags.popMappings(SavedLoc);
7341 }
7342};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007343}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007344
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007345OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
7346 SourceLocation StartLoc,
7347 SourceLocation LParenLoc,
7348 SourceLocation EndLoc) {
7349 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007350 SmallVector<Expr *, 8> PrivateCopies;
7351 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00007352 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007353 bool IsImplicitClause =
7354 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
7355 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
7356
Alexey Bataeved09d242014-05-28 05:53:51 +00007357 for (auto &RefExpr : VarList) {
7358 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007359 SourceLocation ELoc;
7360 SourceRange ERange;
7361 Expr *SimpleRefExpr = RefExpr;
7362 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007363 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007364 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007365 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007366 PrivateCopies.push_back(nullptr);
7367 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007368 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007369 ValueDecl *D = Res.first;
7370 if (!D)
7371 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007372
Alexey Bataev60da77e2016-02-29 05:54:20 +00007373 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00007374 QualType Type = D->getType();
7375 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007376
7377 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7378 // A variable that appears in a private clause must not have an incomplete
7379 // type or a reference type.
7380 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00007381 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007382 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007383 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007384
7385 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
7386 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00007387 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007388 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007389 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007390
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007391 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00007392 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007393 if (!IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007394 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev005248a2016-02-25 05:25:57 +00007395 TopDVar = DVar;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007396 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007397 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
7398 // A list item that specifies a given variable may not appear in more
7399 // than one clause on the same directive, except that a variable may be
7400 // specified in both firstprivate and lastprivate clauses.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007401 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevf29276e2014-06-18 04:14:57 +00007402 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007403 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00007404 << getOpenMPClauseName(DVar.CKind)
7405 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007406 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007407 continue;
7408 }
7409
7410 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7411 // in a Construct]
7412 // Variables with the predetermined data-sharing attributes may not be
7413 // listed in data-sharing attributes clauses, except for the cases
7414 // listed below. For these exceptions only, listing a predetermined
7415 // variable in a data-sharing attribute clause is allowed and overrides
7416 // the variable's predetermined data-sharing attributes.
7417 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7418 // in a Construct, C/C++, p.2]
7419 // Variables with const-qualified type having no mutable member may be
7420 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00007421 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007422 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
7423 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00007424 << getOpenMPClauseName(DVar.CKind)
7425 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007426 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007427 continue;
7428 }
7429
Alexey Bataevf29276e2014-06-18 04:14:57 +00007430 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007431 // OpenMP [2.9.3.4, Restrictions, p.2]
7432 // A list item that is private within a parallel region must not appear
7433 // in a firstprivate clause on a worksharing construct if any of the
7434 // worksharing regions arising from the worksharing construct ever bind
7435 // to any of the parallel regions arising from the parallel construct.
Alexey Bataev549210e2014-06-24 04:39:47 +00007436 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00007437 !isOpenMPParallelDirective(CurrDir) &&
7438 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007439 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007440 if (DVar.CKind != OMPC_shared &&
7441 (isOpenMPParallelDirective(DVar.DKind) ||
7442 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00007443 Diag(ELoc, diag::err_omp_required_access)
7444 << getOpenMPClauseName(OMPC_firstprivate)
7445 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007446 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00007447 continue;
7448 }
7449 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007450 // OpenMP [2.9.3.4, Restrictions, p.3]
7451 // A list item that appears in a reduction clause of a parallel construct
7452 // must not appear in a firstprivate clause on a worksharing or task
7453 // construct if any of the worksharing or task regions arising from the
7454 // worksharing or task construct ever bind to any of the parallel regions
7455 // arising from the parallel construct.
7456 // OpenMP [2.9.3.4, Restrictions, p.4]
7457 // A list item that appears in a reduction clause in worksharing
7458 // construct must not appear in a firstprivate clause in a task construct
7459 // encountered during execution of any of the worksharing regions arising
7460 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00007461 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007462 DVar = DSAStack->hasInnermostDSA(
7463 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
7464 [](OpenMPDirectiveKind K) -> bool {
7465 return isOpenMPParallelDirective(K) ||
7466 isOpenMPWorksharingDirective(K);
7467 },
7468 false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007469 if (DVar.CKind == OMPC_reduction &&
7470 (isOpenMPParallelDirective(DVar.DKind) ||
7471 isOpenMPWorksharingDirective(DVar.DKind))) {
7472 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
7473 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007474 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007475 continue;
7476 }
7477 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007478
7479 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
7480 // A list item that is private within a teams region must not appear in a
7481 // firstprivate clause on a distribute construct if any of the distribute
7482 // regions arising from the distribute construct ever bind to any of the
7483 // teams regions arising from the teams construct.
7484 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
7485 // A list item that appears in a reduction clause of a teams construct
7486 // must not appear in a firstprivate clause on a distribute construct if
7487 // any of the distribute regions arising from the distribute construct
7488 // ever bind to any of the teams regions arising from the teams construct.
7489 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
7490 // A list item may appear in a firstprivate or lastprivate clause but not
7491 // both.
7492 if (CurrDir == OMPD_distribute) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007493 DVar = DSAStack->hasInnermostDSA(
7494 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_private; },
7495 [](OpenMPDirectiveKind K) -> bool {
7496 return isOpenMPTeamsDirective(K);
7497 },
7498 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007499 if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) {
7500 Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007501 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007502 continue;
7503 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007504 DVar = DSAStack->hasInnermostDSA(
7505 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
7506 [](OpenMPDirectiveKind K) -> bool {
7507 return isOpenMPTeamsDirective(K);
7508 },
7509 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007510 if (DVar.CKind == OMPC_reduction &&
7511 isOpenMPTeamsDirective(DVar.DKind)) {
7512 Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007513 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007514 continue;
7515 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007516 DVar = DSAStack->getTopDSA(D, false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007517 if (DVar.CKind == OMPC_lastprivate) {
7518 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007519 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007520 continue;
7521 }
7522 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007523 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
7524 // A list item cannot appear in both a map clause and a data-sharing
7525 // attribute clause on the same construct
Kelvin Li193ee2d2016-12-16 20:50:46 +00007526 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel) {
Samuel Antao6890b092016-07-28 14:25:09 +00007527 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00007528 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00007529 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00007530 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
7531 OpenMPClauseKind WhereFoundClauseKind) -> bool {
7532 ConflictKind = WhereFoundClauseKind;
7533 return true;
7534 })) {
7535 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007536 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +00007537 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007538 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7539 ReportOriginalDSA(*this, DSAStack, D, DVar);
7540 continue;
7541 }
7542 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007543 }
7544
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007545 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00007546 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00007547 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007548 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7549 << getOpenMPClauseName(OMPC_firstprivate) << Type
7550 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7551 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00007552 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007553 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00007554 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007555 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00007556 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007557 continue;
7558 }
7559
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007560 Type = Type.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00007561 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7562 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007563 // Generate helper private variable and initialize it with the value of the
7564 // original variable. The address of the original variable is replaced by
7565 // the address of the new private variable in the CodeGen. This new variable
7566 // is not added to IdResolver, so the code in the OpenMP region uses
7567 // original variable for proper diagnostics and variable capturing.
7568 Expr *VDInitRefExpr = nullptr;
7569 // For arrays generate initializer for single element and replace it by the
7570 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007571 if (Type->isArrayType()) {
7572 auto VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00007573 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007574 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007575 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007576 ElemType = ElemType.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00007577 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007578 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00007579 InitializedEntity Entity =
7580 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007581 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
7582
7583 InitializationSequence InitSeq(*this, Entity, Kind, Init);
7584 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
7585 if (Result.isInvalid())
7586 VDPrivate->setInvalidDecl();
7587 else
7588 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00007589 // Remove temp variable declaration.
7590 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007591 } else {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007592 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
7593 ".firstprivate.temp");
7594 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
7595 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00007596 AddInitializerToDecl(VDPrivate,
7597 DefaultLvalueConversion(VDInitRefExpr).get(),
7598 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007599 }
7600 if (VDPrivate->isInvalidDecl()) {
7601 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007602 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007603 diag::note_omp_task_predetermined_firstprivate_here);
7604 }
7605 continue;
7606 }
7607 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00007608 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00007609 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
7610 RefExpr->getExprLoc());
7611 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007612 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00007613 if (TopDVar.CKind == OMPC_lastprivate)
7614 Ref = TopDVar.PrivateCopy;
7615 else {
Alexey Bataev61205072016-03-02 04:57:40 +00007616 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataev005248a2016-02-25 05:25:57 +00007617 if (!IsOpenMPCapturedDecl(D))
7618 ExprCaptures.push_back(Ref->getDecl());
7619 }
Alexey Bataev417089f2016-02-17 13:19:37 +00007620 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007621 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007622 Vars.push_back((VD || CurContext->isDependentContext())
7623 ? RefExpr->IgnoreParens()
7624 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007625 PrivateCopies.push_back(VDPrivateRefExpr);
7626 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007627 }
7628
Alexey Bataeved09d242014-05-28 05:53:51 +00007629 if (Vars.empty())
7630 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007631
7632 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00007633 Vars, PrivateCopies, Inits,
7634 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007635}
7636
Alexander Musman1bb328c2014-06-04 13:06:39 +00007637OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
7638 SourceLocation StartLoc,
7639 SourceLocation LParenLoc,
7640 SourceLocation EndLoc) {
7641 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00007642 SmallVector<Expr *, 8> SrcExprs;
7643 SmallVector<Expr *, 8> DstExprs;
7644 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00007645 SmallVector<Decl *, 4> ExprCaptures;
7646 SmallVector<Expr *, 4> ExprPostUpdates;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007647 for (auto &RefExpr : VarList) {
7648 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007649 SourceLocation ELoc;
7650 SourceRange ERange;
7651 Expr *SimpleRefExpr = RefExpr;
7652 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00007653 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00007654 // It will be analyzed later.
7655 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00007656 SrcExprs.push_back(nullptr);
7657 DstExprs.push_back(nullptr);
7658 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007659 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00007660 ValueDecl *D = Res.first;
7661 if (!D)
7662 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007663
Alexey Bataev74caaf22016-02-20 04:09:36 +00007664 QualType Type = D->getType();
7665 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007666
7667 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
7668 // A variable that appears in a lastprivate clause must not have an
7669 // incomplete type or a reference type.
7670 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00007671 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00007672 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007673 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00007674
7675 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
7676 // in a Construct]
7677 // Variables with the predetermined data-sharing attributes may not be
7678 // listed in data-sharing attributes clauses, except for the cases
7679 // listed below.
Alexey Bataev74caaf22016-02-20 04:09:36 +00007680 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007681 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
7682 DVar.CKind != OMPC_firstprivate &&
7683 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
7684 Diag(ELoc, diag::err_omp_wrong_dsa)
7685 << getOpenMPClauseName(DVar.CKind)
7686 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev74caaf22016-02-20 04:09:36 +00007687 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007688 continue;
7689 }
7690
Alexey Bataevf29276e2014-06-18 04:14:57 +00007691 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
7692 // OpenMP [2.14.3.5, Restrictions, p.2]
7693 // A list item that is private within a parallel region, or that appears in
7694 // the reduction clause of a parallel construct, must not appear in a
7695 // lastprivate clause on a worksharing construct if any of the corresponding
7696 // worksharing regions ever binds to any of the corresponding parallel
7697 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00007698 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00007699 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00007700 !isOpenMPParallelDirective(CurrDir) &&
7701 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00007702 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00007703 if (DVar.CKind != OMPC_shared) {
7704 Diag(ELoc, diag::err_omp_required_access)
7705 << getOpenMPClauseName(OMPC_lastprivate)
7706 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev74caaf22016-02-20 04:09:36 +00007707 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00007708 continue;
7709 }
7710 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00007711
7712 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
7713 // A list item may appear in a firstprivate or lastprivate clause but not
7714 // both.
7715 if (CurrDir == OMPD_distribute) {
7716 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
7717 if (DVar.CKind == OMPC_firstprivate) {
7718 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
7719 ReportOriginalDSA(*this, DSAStack, D, DVar);
7720 continue;
7721 }
7722 }
7723
Alexander Musman1bb328c2014-06-04 13:06:39 +00007724 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00007725 // A variable of class type (or array thereof) that appears in a
7726 // lastprivate clause requires an accessible, unambiguous default
7727 // constructor for the class type, unless the list item is also specified
7728 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00007729 // A variable of class type (or array thereof) that appears in a
7730 // lastprivate clause requires an accessible, unambiguous copy assignment
7731 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00007732 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00007733 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00007734 Type.getUnqualifiedType(), ".lastprivate.src",
Alexey Bataev74caaf22016-02-20 04:09:36 +00007735 D->hasAttrs() ? &D->getAttrs() : nullptr);
7736 auto *PseudoSrcExpr =
7737 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00007738 auto *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00007739 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00007740 D->hasAttrs() ? &D->getAttrs() : nullptr);
7741 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00007742 // For arrays generate assignment operation for single element and replace
7743 // it by the original array element in CodeGen.
Alexey Bataev74caaf22016-02-20 04:09:36 +00007744 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
Alexey Bataev38e89532015-04-16 04:54:05 +00007745 PseudoDstExpr, PseudoSrcExpr);
7746 if (AssignmentOp.isInvalid())
7747 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00007748 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00007749 /*DiscardedValue=*/true);
7750 if (AssignmentOp.isInvalid())
7751 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007752
Alexey Bataev74caaf22016-02-20 04:09:36 +00007753 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007754 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00007755 if (TopDVar.CKind == OMPC_firstprivate)
7756 Ref = TopDVar.PrivateCopy;
7757 else {
Alexey Bataev61205072016-03-02 04:57:40 +00007758 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00007759 if (!IsOpenMPCapturedDecl(D))
7760 ExprCaptures.push_back(Ref->getDecl());
7761 }
7762 if (TopDVar.CKind == OMPC_firstprivate ||
7763 (!IsOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00007764 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00007765 ExprResult RefRes = DefaultLvalueConversion(Ref);
7766 if (!RefRes.isUsable())
7767 continue;
7768 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00007769 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
7770 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00007771 if (!PostUpdateRes.isUsable())
7772 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00007773 ExprPostUpdates.push_back(
7774 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00007775 }
7776 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007777 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007778 Vars.push_back((VD || CurContext->isDependentContext())
7779 ? RefExpr->IgnoreParens()
7780 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00007781 SrcExprs.push_back(PseudoSrcExpr);
7782 DstExprs.push_back(PseudoDstExpr);
7783 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00007784 }
7785
7786 if (Vars.empty())
7787 return nullptr;
7788
7789 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00007790 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00007791 buildPreInits(Context, ExprCaptures),
7792 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00007793}
7794
Alexey Bataev758e55e2013-09-06 18:03:48 +00007795OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
7796 SourceLocation StartLoc,
7797 SourceLocation LParenLoc,
7798 SourceLocation EndLoc) {
7799 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00007800 for (auto &RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007801 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007802 SourceLocation ELoc;
7803 SourceRange ERange;
7804 Expr *SimpleRefExpr = RefExpr;
7805 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007806 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00007807 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007808 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007809 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007810 ValueDecl *D = Res.first;
7811 if (!D)
7812 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00007813
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007814 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007815 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7816 // in a Construct]
7817 // Variables with the predetermined data-sharing attributes may not be
7818 // listed in data-sharing attributes clauses, except for the cases
7819 // listed below. For these exceptions only, listing a predetermined
7820 // variable in a data-sharing attribute clause is allowed and overrides
7821 // the variable's predetermined data-sharing attributes.
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007822 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00007823 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
7824 DVar.RefExpr) {
7825 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7826 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007827 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007828 continue;
7829 }
7830
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007831 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007832 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00007833 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007834 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007835 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
7836 ? RefExpr->IgnoreParens()
7837 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007838 }
7839
Alexey Bataeved09d242014-05-28 05:53:51 +00007840 if (Vars.empty())
7841 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00007842
7843 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
7844}
7845
Alexey Bataevc5e02582014-06-16 07:08:35 +00007846namespace {
7847class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
7848 DSAStackTy *Stack;
7849
7850public:
7851 bool VisitDeclRefExpr(DeclRefExpr *E) {
7852 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007853 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00007854 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
7855 return false;
7856 if (DVar.CKind != OMPC_unknown)
7857 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007858 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
7859 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
7860 false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00007861 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00007862 return true;
7863 return false;
7864 }
7865 return false;
7866 }
7867 bool VisitStmt(Stmt *S) {
7868 for (auto Child : S->children()) {
7869 if (Child && Visit(Child))
7870 return true;
7871 }
7872 return false;
7873 }
Alexey Bataev23b69422014-06-18 07:08:49 +00007874 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00007875};
Alexey Bataev23b69422014-06-18 07:08:49 +00007876} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00007877
Alexey Bataev60da77e2016-02-29 05:54:20 +00007878namespace {
7879// Transform MemberExpression for specified FieldDecl of current class to
7880// DeclRefExpr to specified OMPCapturedExprDecl.
7881class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
7882 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
7883 ValueDecl *Field;
7884 DeclRefExpr *CapturedExpr;
7885
7886public:
7887 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
7888 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
7889
7890 ExprResult TransformMemberExpr(MemberExpr *E) {
7891 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
7892 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00007893 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00007894 return CapturedExpr;
7895 }
7896 return BaseTransform::TransformMemberExpr(E);
7897 }
7898 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
7899};
7900} // namespace
7901
Alexey Bataeva839ddd2016-03-17 10:19:46 +00007902template <typename T>
7903static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
7904 const llvm::function_ref<T(ValueDecl *)> &Gen) {
7905 for (auto &Set : Lookups) {
7906 for (auto *D : Set) {
7907 if (auto Res = Gen(cast<ValueDecl>(D)))
7908 return Res;
7909 }
7910 }
7911 return T();
7912}
7913
7914static ExprResult
7915buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
7916 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
7917 const DeclarationNameInfo &ReductionId, QualType Ty,
7918 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
7919 if (ReductionIdScopeSpec.isInvalid())
7920 return ExprError();
7921 SmallVector<UnresolvedSet<8>, 4> Lookups;
7922 if (S) {
7923 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
7924 Lookup.suppressDiagnostics();
7925 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
7926 auto *D = Lookup.getRepresentativeDecl();
7927 do {
7928 S = S->getParent();
7929 } while (S && !S->isDeclScope(D));
7930 if (S)
7931 S = S->getParent();
7932 Lookups.push_back(UnresolvedSet<8>());
7933 Lookups.back().append(Lookup.begin(), Lookup.end());
7934 Lookup.clear();
7935 }
7936 } else if (auto *ULE =
7937 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
7938 Lookups.push_back(UnresolvedSet<8>());
7939 Decl *PrevD = nullptr;
David Majnemer9d168222016-08-05 17:44:54 +00007940 for (auto *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00007941 if (D == PrevD)
7942 Lookups.push_back(UnresolvedSet<8>());
7943 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
7944 Lookups.back().addDecl(DRD);
7945 PrevD = D;
7946 }
7947 }
7948 if (Ty->isDependentType() || Ty->isInstantiationDependentType() ||
7949 Ty->containsUnexpandedParameterPack() ||
7950 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
7951 return !D->isInvalidDecl() &&
7952 (D->getType()->isDependentType() ||
7953 D->getType()->isInstantiationDependentType() ||
7954 D->getType()->containsUnexpandedParameterPack());
7955 })) {
7956 UnresolvedSet<8> ResSet;
7957 for (auto &Set : Lookups) {
7958 ResSet.append(Set.begin(), Set.end());
7959 // The last item marks the end of all declarations at the specified scope.
7960 ResSet.addDecl(Set[Set.size() - 1]);
7961 }
7962 return UnresolvedLookupExpr::Create(
7963 SemaRef.Context, /*NamingClass=*/nullptr,
7964 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
7965 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
7966 }
7967 if (auto *VD = filterLookupForUDR<ValueDecl *>(
7968 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
7969 if (!D->isInvalidDecl() &&
7970 SemaRef.Context.hasSameType(D->getType(), Ty))
7971 return D;
7972 return nullptr;
7973 }))
7974 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
7975 if (auto *VD = filterLookupForUDR<ValueDecl *>(
7976 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
7977 if (!D->isInvalidDecl() &&
7978 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
7979 !Ty.isMoreQualifiedThan(D->getType()))
7980 return D;
7981 return nullptr;
7982 })) {
7983 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
7984 /*DetectVirtual=*/false);
7985 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
7986 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
7987 VD->getType().getUnqualifiedType()))) {
7988 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
7989 /*DiagID=*/0) !=
7990 Sema::AR_inaccessible) {
7991 SemaRef.BuildBasePathArray(Paths, BasePath);
7992 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
7993 }
7994 }
7995 }
7996 }
7997 if (ReductionIdScopeSpec.isSet()) {
7998 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
7999 return ExprError();
8000 }
8001 return ExprEmpty();
8002}
8003
Alexey Bataevc5e02582014-06-16 07:08:35 +00008004OMPClause *Sema::ActOnOpenMPReductionClause(
8005 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
8006 SourceLocation ColonLoc, SourceLocation EndLoc,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008007 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
8008 ArrayRef<Expr *> UnresolvedReductions) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00008009 auto DN = ReductionId.getName();
8010 auto OOK = DN.getCXXOverloadedOperator();
8011 BinaryOperatorKind BOK = BO_Comma;
8012
8013 // OpenMP [2.14.3.6, reduction clause]
8014 // C
8015 // reduction-identifier is either an identifier or one of the following
8016 // operators: +, -, *, &, |, ^, && and ||
8017 // C++
8018 // reduction-identifier is either an id-expression or one of the following
8019 // operators: +, -, *, &, |, ^, && and ||
8020 // FIXME: Only 'min' and 'max' identifiers are supported for now.
8021 switch (OOK) {
8022 case OO_Plus:
8023 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008024 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008025 break;
8026 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008027 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008028 break;
8029 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008030 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008031 break;
8032 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008033 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008034 break;
8035 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008036 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008037 break;
8038 case OO_AmpAmp:
8039 BOK = BO_LAnd;
8040 break;
8041 case OO_PipePipe:
8042 BOK = BO_LOr;
8043 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008044 case OO_New:
8045 case OO_Delete:
8046 case OO_Array_New:
8047 case OO_Array_Delete:
8048 case OO_Slash:
8049 case OO_Percent:
8050 case OO_Tilde:
8051 case OO_Exclaim:
8052 case OO_Equal:
8053 case OO_Less:
8054 case OO_Greater:
8055 case OO_LessEqual:
8056 case OO_GreaterEqual:
8057 case OO_PlusEqual:
8058 case OO_MinusEqual:
8059 case OO_StarEqual:
8060 case OO_SlashEqual:
8061 case OO_PercentEqual:
8062 case OO_CaretEqual:
8063 case OO_AmpEqual:
8064 case OO_PipeEqual:
8065 case OO_LessLess:
8066 case OO_GreaterGreater:
8067 case OO_LessLessEqual:
8068 case OO_GreaterGreaterEqual:
8069 case OO_EqualEqual:
8070 case OO_ExclaimEqual:
8071 case OO_PlusPlus:
8072 case OO_MinusMinus:
8073 case OO_Comma:
8074 case OO_ArrowStar:
8075 case OO_Arrow:
8076 case OO_Call:
8077 case OO_Subscript:
8078 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +00008079 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008080 case NUM_OVERLOADED_OPERATORS:
8081 llvm_unreachable("Unexpected reduction identifier");
8082 case OO_None:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008083 if (auto II = DN.getAsIdentifierInfo()) {
8084 if (II->isStr("max"))
8085 BOK = BO_GT;
8086 else if (II->isStr("min"))
8087 BOK = BO_LT;
8088 }
8089 break;
8090 }
8091 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008092 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +00008093 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008094 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008095
8096 SmallVector<Expr *, 8> Vars;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008097 SmallVector<Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008098 SmallVector<Expr *, 8> LHSs;
8099 SmallVector<Expr *, 8> RHSs;
8100 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev61205072016-03-02 04:57:40 +00008101 SmallVector<Decl *, 4> ExprCaptures;
8102 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008103 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
8104 bool FirstIter = true;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008105 for (auto RefExpr : VarList) {
8106 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +00008107 // OpenMP [2.1, C/C++]
8108 // A list item is a variable or array section, subject to the restrictions
8109 // specified in Section 2.4 on page 42 and in each of the sections
8110 // describing clauses and directives for which a list appears.
8111 // OpenMP [2.14.3.3, Restrictions, p.1]
8112 // A variable that is part of another variable (as an array or
8113 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008114 if (!FirstIter && IR != ER)
8115 ++IR;
8116 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008117 SourceLocation ELoc;
8118 SourceRange ERange;
8119 Expr *SimpleRefExpr = RefExpr;
8120 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8121 /*AllowArraySection=*/true);
8122 if (Res.second) {
8123 // It will be analyzed later.
8124 Vars.push_back(RefExpr);
8125 Privates.push_back(nullptr);
8126 LHSs.push_back(nullptr);
8127 RHSs.push_back(nullptr);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008128 // Try to find 'declare reduction' corresponding construct before using
8129 // builtin/overloaded operators.
8130 QualType Type = Context.DependentTy;
8131 CXXCastPath BasePath;
8132 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8133 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8134 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8135 if (CurContext->isDependentContext() &&
8136 (DeclareReductionRef.isUnset() ||
8137 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
8138 ReductionOps.push_back(DeclareReductionRef.get());
8139 else
8140 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008141 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00008142 ValueDecl *D = Res.first;
8143 if (!D)
8144 continue;
8145
Alexey Bataeva1764212015-09-30 09:22:36 +00008146 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008147 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
8148 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
8149 if (ASE)
Alexey Bataev31300ed2016-02-04 11:27:03 +00008150 Type = ASE->getType().getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008151 else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008152 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
8153 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
8154 Type = ATy->getElementType();
8155 else
8156 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00008157 Type = Type.getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008158 } else
8159 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
8160 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +00008161
Alexey Bataevc5e02582014-06-16 07:08:35 +00008162 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8163 // A variable that appears in a private clause must not have an incomplete
8164 // type or a reference type.
8165 if (RequireCompleteType(ELoc, Type,
8166 diag::err_omp_reduction_incomplete_type))
8167 continue;
8168 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +00008169 // A list item that appears in a reduction clause must not be
8170 // const-qualified.
8171 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008172 Diag(ELoc, diag::err_omp_const_reduction_list_item)
Alexey Bataevc5e02582014-06-16 07:08:35 +00008173 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008174 if (!ASE && !OASE) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008175 bool IsDecl = !VD ||
8176 VD->isThisDeclarationADefinition(Context) ==
8177 VarDecl::DeclarationOnly;
8178 Diag(D->getLocation(),
Alexey Bataeva1764212015-09-30 09:22:36 +00008179 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +00008180 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +00008181 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00008182 continue;
8183 }
8184 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
8185 // If a list-item is a reference type then it must bind to the same object
8186 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +00008187 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008188 VarDecl *VDDef = VD->getDefinition();
David Sheinkman92589992016-10-04 14:41:36 +00008189 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008190 DSARefChecker Check(DSAStack);
8191 if (Check.Visit(VDDef->getInit())) {
8192 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
8193 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
8194 continue;
8195 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00008196 }
8197 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008198
Alexey Bataevc5e02582014-06-16 07:08:35 +00008199 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8200 // in a Construct]
8201 // Variables with the predetermined data-sharing attributes may not be
8202 // listed in data-sharing attributes clauses, except for the cases
8203 // listed below. For these exceptions only, listing a predetermined
8204 // variable in a data-sharing attribute clause is allowed and overrides
8205 // the variable's predetermined data-sharing attributes.
8206 // OpenMP [2.14.3.6, Restrictions, p.3]
8207 // Any number of reduction clauses can be specified on the directive,
8208 // but a list item can appear only once in the reduction clauses for that
8209 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +00008210 DSAStackTy::DSAVarData DVar;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008211 DVar = DSAStack->getTopDSA(D, false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008212 if (DVar.CKind == OMPC_reduction) {
8213 Diag(ELoc, diag::err_omp_once_referenced)
8214 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008215 if (DVar.RefExpr)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008216 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008217 } else if (DVar.CKind != OMPC_unknown) {
8218 Diag(ELoc, diag::err_omp_wrong_dsa)
8219 << getOpenMPClauseName(DVar.CKind)
8220 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008221 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008222 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008223 }
8224
8225 // OpenMP [2.14.3.6, Restrictions, p.1]
8226 // A list item that appears in a reduction clause of a worksharing
8227 // construct must be shared in the parallel regions to which any of the
8228 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008229 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8230 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008231 !isOpenMPParallelDirective(CurrDir) &&
8232 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008233 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008234 if (DVar.CKind != OMPC_shared) {
8235 Diag(ELoc, diag::err_omp_required_access)
8236 << getOpenMPClauseName(OMPC_reduction)
8237 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008238 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008239 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +00008240 }
8241 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008242
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008243 // Try to find 'declare reduction' corresponding construct before using
8244 // builtin/overloaded operators.
8245 CXXCastPath BasePath;
8246 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8247 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8248 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8249 if (DeclareReductionRef.isInvalid())
8250 continue;
8251 if (CurContext->isDependentContext() &&
8252 (DeclareReductionRef.isUnset() ||
8253 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
8254 Vars.push_back(RefExpr);
8255 Privates.push_back(nullptr);
8256 LHSs.push_back(nullptr);
8257 RHSs.push_back(nullptr);
8258 ReductionOps.push_back(DeclareReductionRef.get());
8259 continue;
8260 }
8261 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
8262 // Not allowed reduction identifier is found.
8263 Diag(ReductionId.getLocStart(),
8264 diag::err_omp_unknown_reduction_identifier)
8265 << Type << ReductionIdRange;
8266 continue;
8267 }
8268
8269 // OpenMP [2.14.3.6, reduction clause, Restrictions]
8270 // The type of a list item that appears in a reduction clause must be valid
8271 // for the reduction-identifier. For a max or min reduction in C, the type
8272 // of the list item must be an allowed arithmetic data type: char, int,
8273 // float, double, or _Bool, possibly modified with long, short, signed, or
8274 // unsigned. For a max or min reduction in C++, the type of the list item
8275 // must be an allowed arithmetic data type: char, wchar_t, int, float,
8276 // double, or bool, possibly modified with long, short, signed, or unsigned.
8277 if (DeclareReductionRef.isUnset()) {
8278 if ((BOK == BO_GT || BOK == BO_LT) &&
8279 !(Type->isScalarType() ||
8280 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
8281 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
8282 << getLangOpts().CPlusPlus;
8283 if (!ASE && !OASE) {
8284 bool IsDecl = !VD ||
8285 VD->isThisDeclarationADefinition(Context) ==
8286 VarDecl::DeclarationOnly;
8287 Diag(D->getLocation(),
8288 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8289 << D;
8290 }
8291 continue;
8292 }
8293 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
8294 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
8295 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
8296 if (!ASE && !OASE) {
8297 bool IsDecl = !VD ||
8298 VD->isThisDeclarationADefinition(Context) ==
8299 VarDecl::DeclarationOnly;
8300 Diag(D->getLocation(),
8301 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8302 << D;
8303 }
8304 continue;
8305 }
8306 }
8307
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008308 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008309 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
Alexey Bataev60da77e2016-02-29 05:54:20 +00008310 D->hasAttrs() ? &D->getAttrs() : nullptr);
8311 auto *RHSVD = buildVarDecl(*this, ELoc, Type, D->getName(),
8312 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008313 auto PrivateTy = Type;
Alexey Bataev1189bd02016-01-26 12:20:39 +00008314 if (OASE ||
Alexey Bataev60da77e2016-02-29 05:54:20 +00008315 (!ASE &&
8316 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
David Majnemer9d168222016-08-05 17:44:54 +00008317 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008318 // Create pseudo array type for private copy. The size for this array will
8319 // be generated during codegen.
8320 // For array subscripts or single variables Private Ty is the same as Type
8321 // (type of the variable or single array element).
8322 PrivateTy = Context.getVariableArrayType(
8323 Type, new (Context) OpaqueValueExpr(SourceLocation(),
8324 Context.getSizeType(), VK_RValue),
8325 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +00008326 } else if (!ASE && !OASE &&
8327 Context.getAsArrayType(D->getType().getNonReferenceType()))
8328 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008329 // Private copy.
Alexey Bataev60da77e2016-02-29 05:54:20 +00008330 auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, D->getName(),
8331 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008332 // Add initializer for private variable.
8333 Expr *Init = nullptr;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008334 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
8335 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
8336 if (DeclareReductionRef.isUsable()) {
8337 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
8338 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
8339 if (DRD->getInitializer()) {
8340 Init = DRDRef;
8341 RHSVD->setInit(DRDRef);
8342 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008343 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008344 } else {
8345 switch (BOK) {
8346 case BO_Add:
8347 case BO_Xor:
8348 case BO_Or:
8349 case BO_LOr:
8350 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
8351 if (Type->isScalarType() || Type->isAnyComplexType())
8352 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
8353 break;
8354 case BO_Mul:
8355 case BO_LAnd:
8356 if (Type->isScalarType() || Type->isAnyComplexType()) {
8357 // '*' and '&&' reduction ops - initializer is '1'.
8358 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00008359 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008360 break;
8361 case BO_And: {
8362 // '&' reduction op - initializer is '~0'.
8363 QualType OrigType = Type;
8364 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
8365 Type = ComplexTy->getElementType();
8366 if (Type->isRealFloatingType()) {
8367 llvm::APFloat InitValue =
8368 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
8369 /*isIEEE=*/true);
8370 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
8371 Type, ELoc);
8372 } else if (Type->isScalarType()) {
8373 auto Size = Context.getTypeSize(Type);
8374 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
8375 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
8376 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
8377 }
8378 if (Init && OrigType->isAnyComplexType()) {
8379 // Init = 0xFFFF + 0xFFFFi;
8380 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
8381 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
8382 }
8383 Type = OrigType;
8384 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008385 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008386 case BO_LT:
8387 case BO_GT: {
8388 // 'min' reduction op - initializer is 'Largest representable number in
8389 // the reduction list item type'.
8390 // 'max' reduction op - initializer is 'Least representable number in
8391 // the reduction list item type'.
8392 if (Type->isIntegerType() || Type->isPointerType()) {
8393 bool IsSigned = Type->hasSignedIntegerRepresentation();
8394 auto Size = Context.getTypeSize(Type);
8395 QualType IntTy =
8396 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
8397 llvm::APInt InitValue =
8398 (BOK != BO_LT)
8399 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
8400 : llvm::APInt::getMinValue(Size)
8401 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
8402 : llvm::APInt::getMaxValue(Size);
8403 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
8404 if (Type->isPointerType()) {
8405 // Cast to pointer type.
8406 auto CastExpr = BuildCStyleCastExpr(
8407 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
8408 SourceLocation(), Init);
8409 if (CastExpr.isInvalid())
8410 continue;
8411 Init = CastExpr.get();
8412 }
8413 } else if (Type->isRealFloatingType()) {
8414 llvm::APFloat InitValue = llvm::APFloat::getLargest(
8415 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
8416 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
8417 Type, ELoc);
8418 }
8419 break;
8420 }
8421 case BO_PtrMemD:
8422 case BO_PtrMemI:
8423 case BO_MulAssign:
8424 case BO_Div:
8425 case BO_Rem:
8426 case BO_Sub:
8427 case BO_Shl:
8428 case BO_Shr:
8429 case BO_LE:
8430 case BO_GE:
8431 case BO_EQ:
8432 case BO_NE:
8433 case BO_AndAssign:
8434 case BO_XorAssign:
8435 case BO_OrAssign:
8436 case BO_Assign:
8437 case BO_AddAssign:
8438 case BO_SubAssign:
8439 case BO_DivAssign:
8440 case BO_RemAssign:
8441 case BO_ShlAssign:
8442 case BO_ShrAssign:
8443 case BO_Comma:
8444 llvm_unreachable("Unexpected reduction operation");
8445 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008446 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008447 if (Init && DeclareReductionRef.isUnset()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008448 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
8449 /*TypeMayContainAuto=*/false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008450 } else if (!Init)
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008451 ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008452 if (RHSVD->isInvalidDecl())
8453 continue;
8454 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008455 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
8456 << ReductionIdRange;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008457 bool IsDecl =
8458 !VD ||
8459 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8460 Diag(D->getLocation(),
8461 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8462 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008463 continue;
8464 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008465 // Store initializer for single element in private copy. Will be used during
8466 // codegen.
8467 PrivateVD->setInit(RHSVD->getInit());
8468 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008469 auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008470 ExprResult ReductionOp;
8471 if (DeclareReductionRef.isUsable()) {
8472 QualType RedTy = DeclareReductionRef.get()->getType();
8473 QualType PtrRedTy = Context.getPointerType(RedTy);
8474 ExprResult LHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
8475 ExprResult RHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
8476 if (!BasePath.empty()) {
8477 LHS = DefaultLvalueConversion(LHS.get());
8478 RHS = DefaultLvalueConversion(RHS.get());
8479 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
8480 CK_UncheckedDerivedToBase, LHS.get(),
8481 &BasePath, LHS.get()->getValueKind());
8482 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
8483 CK_UncheckedDerivedToBase, RHS.get(),
8484 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008485 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008486 FunctionProtoType::ExtProtoInfo EPI;
8487 QualType Params[] = {PtrRedTy, PtrRedTy};
8488 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
8489 auto *OVE = new (Context) OpaqueValueExpr(
8490 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
8491 DefaultLvalueConversion(DeclareReductionRef.get()).get());
8492 Expr *Args[] = {LHS.get(), RHS.get()};
8493 ReductionOp = new (Context)
8494 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
8495 } else {
8496 ReductionOp = BuildBinOp(DSAStack->getCurScope(),
8497 ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
8498 if (ReductionOp.isUsable()) {
8499 if (BOK != BO_LT && BOK != BO_GT) {
8500 ReductionOp =
8501 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
8502 BO_Assign, LHSDRE, ReductionOp.get());
8503 } else {
8504 auto *ConditionalOp = new (Context) ConditionalOperator(
8505 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
8506 RHSDRE, Type, VK_LValue, OK_Ordinary);
8507 ReductionOp =
8508 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
8509 BO_Assign, LHSDRE, ConditionalOp);
8510 }
8511 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
8512 }
8513 if (ReductionOp.isInvalid())
8514 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008515 }
8516
Alexey Bataev60da77e2016-02-29 05:54:20 +00008517 DeclRefExpr *Ref = nullptr;
8518 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008519 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008520 if (ASE || OASE) {
8521 TransformExprToCaptures RebuildToCapture(*this, D);
8522 VarsExpr =
8523 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
8524 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +00008525 } else {
8526 VarsExpr = Ref =
8527 buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +00008528 }
8529 if (!IsOpenMPCapturedDecl(D)) {
8530 ExprCaptures.push_back(Ref->getDecl());
8531 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
8532 ExprResult RefRes = DefaultLvalueConversion(Ref);
8533 if (!RefRes.isUsable())
8534 continue;
8535 ExprResult PostUpdateRes =
8536 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
8537 SimpleRefExpr, RefRes.get());
8538 if (!PostUpdateRes.isUsable())
8539 continue;
8540 ExprPostUpdates.push_back(
8541 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +00008542 }
8543 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00008544 }
8545 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
8546 Vars.push_back(VarsExpr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008547 Privates.push_back(PrivateDRE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008548 LHSs.push_back(LHSDRE);
8549 RHSs.push_back(RHSDRE);
8550 ReductionOps.push_back(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008551 }
8552
8553 if (Vars.empty())
8554 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +00008555
Alexey Bataevc5e02582014-06-16 07:08:35 +00008556 return OMPReductionClause::Create(
8557 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008558 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008559 LHSs, RHSs, ReductionOps, buildPreInits(Context, ExprCaptures),
8560 buildPostUpdate(*this, ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +00008561}
8562
Alexey Bataevecba70f2016-04-12 11:02:11 +00008563bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
8564 SourceLocation LinLoc) {
8565 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
8566 LinKind == OMPC_LINEAR_unknown) {
8567 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
8568 return true;
8569 }
8570 return false;
8571}
8572
8573bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
8574 OpenMPLinearClauseKind LinKind,
8575 QualType Type) {
8576 auto *VD = dyn_cast_or_null<VarDecl>(D);
8577 // A variable must not have an incomplete type or a reference type.
8578 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
8579 return true;
8580 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
8581 !Type->isReferenceType()) {
8582 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
8583 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
8584 return true;
8585 }
8586 Type = Type.getNonReferenceType();
8587
8588 // A list item must not be const-qualified.
8589 if (Type.isConstant(Context)) {
8590 Diag(ELoc, diag::err_omp_const_variable)
8591 << getOpenMPClauseName(OMPC_linear);
8592 if (D) {
8593 bool IsDecl =
8594 !VD ||
8595 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8596 Diag(D->getLocation(),
8597 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8598 << D;
8599 }
8600 return true;
8601 }
8602
8603 // A list item must be of integral or pointer type.
8604 Type = Type.getUnqualifiedType().getCanonicalType();
8605 const auto *Ty = Type.getTypePtrOrNull();
8606 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
8607 !Ty->isPointerType())) {
8608 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
8609 if (D) {
8610 bool IsDecl =
8611 !VD ||
8612 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8613 Diag(D->getLocation(),
8614 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8615 << D;
8616 }
8617 return true;
8618 }
8619 return false;
8620}
8621
Alexey Bataev182227b2015-08-20 10:54:39 +00008622OMPClause *Sema::ActOnOpenMPLinearClause(
8623 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
8624 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
8625 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +00008626 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008627 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +00008628 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +00008629 SmallVector<Decl *, 4> ExprCaptures;
8630 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +00008631 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +00008632 LinKind = OMPC_LINEAR_val;
Alexey Bataeved09d242014-05-28 05:53:51 +00008633 for (auto &RefExpr : VarList) {
8634 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008635 SourceLocation ELoc;
8636 SourceRange ERange;
8637 Expr *SimpleRefExpr = RefExpr;
8638 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8639 /*AllowArraySection=*/false);
8640 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +00008641 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008642 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008643 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +00008644 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00008645 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008646 ValueDecl *D = Res.first;
8647 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +00008648 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +00008649
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008650 QualType Type = D->getType();
8651 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +00008652
8653 // OpenMP [2.14.3.7, linear clause]
8654 // A list-item cannot appear in more than one linear clause.
8655 // A list-item that appears in a linear clause cannot appear in any
8656 // other data-sharing attribute clause.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008657 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00008658 if (DVar.RefExpr) {
8659 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8660 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008661 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00008662 continue;
8663 }
8664
Alexey Bataevecba70f2016-04-12 11:02:11 +00008665 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +00008666 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00008667 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +00008668
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008669 // Build private copy of original var.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008670 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
8671 D->hasAttrs() ? &D->getAttrs() : nullptr);
8672 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +00008673 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008674 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008675 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008676 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008677 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +00008678 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
8679 if (!IsOpenMPCapturedDecl(D)) {
8680 ExprCaptures.push_back(Ref->getDecl());
8681 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
8682 ExprResult RefRes = DefaultLvalueConversion(Ref);
8683 if (!RefRes.isUsable())
8684 continue;
8685 ExprResult PostUpdateRes =
8686 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
8687 SimpleRefExpr, RefRes.get());
8688 if (!PostUpdateRes.isUsable())
8689 continue;
8690 ExprPostUpdates.push_back(
8691 IgnoredValueConversions(PostUpdateRes.get()).get());
8692 }
8693 }
8694 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008695 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008696 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008697 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008698 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008699 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008700 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
8701 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
8702
8703 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008704 Vars.push_back((VD || CurContext->isDependentContext())
8705 ? RefExpr->IgnoreParens()
8706 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008707 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +00008708 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00008709 }
8710
8711 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008712 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00008713
8714 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00008715 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00008716 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
8717 !Step->isInstantiationDependent() &&
8718 !Step->containsUnexpandedParameterPack()) {
8719 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00008720 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00008721 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008722 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008723 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00008724
Alexander Musman3276a272015-03-21 10:12:56 +00008725 // Build var to save the step value.
8726 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00008727 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +00008728 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +00008729 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +00008730 ExprResult CalcStep =
8731 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008732 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +00008733
Alexander Musman8dba6642014-04-22 13:09:42 +00008734 // Warn about zero linear step (it would be probably better specified as
8735 // making corresponding variables 'const').
8736 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00008737 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
8738 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00008739 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
8740 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00008741 if (!IsConstant && CalcStep.isUsable()) {
8742 // Calculate the step beforehand instead of doing this on each iteration.
8743 // (This is not used if the number of iterations may be kfold-ed).
8744 CalcStepExpr = CalcStep.get();
8745 }
Alexander Musman8dba6642014-04-22 13:09:42 +00008746 }
8747
Alexey Bataev182227b2015-08-20 10:54:39 +00008748 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
8749 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008750 StepExpr, CalcStepExpr,
8751 buildPreInits(Context, ExprCaptures),
8752 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +00008753}
8754
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008755static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
8756 Expr *NumIterations, Sema &SemaRef,
8757 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +00008758 // Walk the vars and build update/final expressions for the CodeGen.
8759 SmallVector<Expr *, 8> Updates;
8760 SmallVector<Expr *, 8> Finals;
8761 Expr *Step = Clause.getStep();
8762 Expr *CalcStep = Clause.getCalcStep();
8763 // OpenMP [2.14.3.7, linear clause]
8764 // If linear-step is not specified it is assumed to be 1.
8765 if (Step == nullptr)
8766 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00008767 else if (CalcStep) {
Alexander Musman3276a272015-03-21 10:12:56 +00008768 Step = cast<BinaryOperator>(CalcStep)->getLHS();
Alexey Bataev5a3af132016-03-29 08:58:54 +00008769 }
Alexander Musman3276a272015-03-21 10:12:56 +00008770 bool HasErrors = false;
8771 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008772 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008773 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +00008774 for (auto &RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008775 SourceLocation ELoc;
8776 SourceRange ERange;
8777 Expr *SimpleRefExpr = RefExpr;
8778 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
8779 /*AllowArraySection=*/false);
8780 ValueDecl *D = Res.first;
8781 if (Res.second || !D) {
8782 Updates.push_back(nullptr);
8783 Finals.push_back(nullptr);
8784 HasErrors = true;
8785 continue;
8786 }
8787 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) {
8788 D = cast<MemberExpr>(CED->getInit()->IgnoreParenImpCasts())
8789 ->getMemberDecl();
8790 }
8791 auto &&Info = Stack->isLoopControlVariable(D);
Alexander Musman3276a272015-03-21 10:12:56 +00008792 Expr *InitExpr = *CurInit;
8793
8794 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +00008795 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008796 Expr *CapturedRef;
8797 if (LinKind == OMPC_LINEAR_uval)
8798 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
8799 else
8800 CapturedRef =
8801 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
8802 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
8803 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00008804
8805 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008806 ExprResult Update;
8807 if (!Info.first) {
8808 Update =
8809 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
8810 InitExpr, IV, Step, /* Subtract */ false);
8811 } else
8812 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008813 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
8814 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00008815
8816 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008817 ExprResult Final;
8818 if (!Info.first) {
8819 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
8820 InitExpr, NumIterations, Step,
8821 /* Subtract */ false);
8822 } else
8823 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008824 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
8825 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008826
Alexander Musman3276a272015-03-21 10:12:56 +00008827 if (!Update.isUsable() || !Final.isUsable()) {
8828 Updates.push_back(nullptr);
8829 Finals.push_back(nullptr);
8830 HasErrors = true;
8831 } else {
8832 Updates.push_back(Update.get());
8833 Finals.push_back(Final.get());
8834 }
Richard Trieucc3949d2016-02-18 22:34:54 +00008835 ++CurInit;
8836 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00008837 }
8838 Clause.setUpdates(Updates);
8839 Clause.setFinals(Finals);
8840 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00008841}
8842
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008843OMPClause *Sema::ActOnOpenMPAlignedClause(
8844 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
8845 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
8846
8847 SmallVector<Expr *, 8> Vars;
8848 for (auto &RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +00008849 assert(RefExpr && "NULL expr in OpenMP linear clause.");
8850 SourceLocation ELoc;
8851 SourceRange ERange;
8852 Expr *SimpleRefExpr = RefExpr;
8853 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8854 /*AllowArraySection=*/false);
8855 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008856 // It will be analyzed later.
8857 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008858 }
Alexey Bataev1efd1662016-03-29 10:59:56 +00008859 ValueDecl *D = Res.first;
8860 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008861 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008862
Alexey Bataev1efd1662016-03-29 10:59:56 +00008863 QualType QType = D->getType();
8864 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008865
8866 // OpenMP [2.8.1, simd construct, Restrictions]
8867 // The type of list items appearing in the aligned clause must be
8868 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008869 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008870 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +00008871 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008872 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +00008873 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008874 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +00008875 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008876 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +00008877 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008878 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +00008879 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008880 continue;
8881 }
8882
8883 // OpenMP [2.8.1, simd construct, Restrictions]
8884 // A list-item cannot appear in more than one aligned clause.
Alexey Bataev1efd1662016-03-29 10:59:56 +00008885 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00008886 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008887 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
8888 << getOpenMPClauseName(OMPC_aligned);
8889 continue;
8890 }
8891
Alexey Bataev1efd1662016-03-29 10:59:56 +00008892 DeclRefExpr *Ref = nullptr;
8893 if (!VD && IsOpenMPCapturedDecl(D))
8894 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
8895 Vars.push_back(DefaultFunctionArrayConversion(
8896 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
8897 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008898 }
8899
8900 // OpenMP [2.8.1, simd construct, Description]
8901 // The parameter of the aligned clause, alignment, must be a constant
8902 // positive integer expression.
8903 // If no optional parameter is specified, implementation-defined default
8904 // alignments for SIMD instructions on the target platforms are assumed.
8905 if (Alignment != nullptr) {
8906 ExprResult AlignResult =
8907 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
8908 if (AlignResult.isInvalid())
8909 return nullptr;
8910 Alignment = AlignResult.get();
8911 }
8912 if (Vars.empty())
8913 return nullptr;
8914
8915 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
8916 EndLoc, Vars, Alignment);
8917}
8918
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008919OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
8920 SourceLocation StartLoc,
8921 SourceLocation LParenLoc,
8922 SourceLocation EndLoc) {
8923 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +00008924 SmallVector<Expr *, 8> SrcExprs;
8925 SmallVector<Expr *, 8> DstExprs;
8926 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +00008927 for (auto &RefExpr : VarList) {
8928 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
8929 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008930 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008931 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00008932 SrcExprs.push_back(nullptr);
8933 DstExprs.push_back(nullptr);
8934 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008935 continue;
8936 }
8937
Alexey Bataeved09d242014-05-28 05:53:51 +00008938 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008939 // OpenMP [2.1, C/C++]
8940 // A list item is a variable name.
8941 // OpenMP [2.14.4.1, Restrictions, p.1]
8942 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +00008943 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008944 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008945 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
8946 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008947 continue;
8948 }
8949
8950 Decl *D = DE->getDecl();
8951 VarDecl *VD = cast<VarDecl>(D);
8952
8953 QualType Type = VD->getType();
8954 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
8955 // It will be analyzed later.
8956 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00008957 SrcExprs.push_back(nullptr);
8958 DstExprs.push_back(nullptr);
8959 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008960 continue;
8961 }
8962
8963 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
8964 // A list item that appears in a copyin clause must be threadprivate.
8965 if (!DSAStack->isThreadPrivate(VD)) {
8966 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +00008967 << getOpenMPClauseName(OMPC_copyin)
8968 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008969 continue;
8970 }
8971
8972 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
8973 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +00008974 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008975 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008976 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00008977 auto *SrcVD =
8978 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
8979 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00008980 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008981 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
8982 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00008983 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
8984 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00008985 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008986 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +00008987 // For arrays generate assignment operation for single element and replace
8988 // it by the original array element in CodeGen.
8989 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
8990 PseudoDstExpr, PseudoSrcExpr);
8991 if (AssignmentOp.isInvalid())
8992 continue;
8993 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
8994 /*DiscardedValue=*/true);
8995 if (AssignmentOp.isInvalid())
8996 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008997
8998 DSAStack->addDSA(VD, DE, OMPC_copyin);
8999 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009000 SrcExprs.push_back(PseudoSrcExpr);
9001 DstExprs.push_back(PseudoDstExpr);
9002 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009003 }
9004
Alexey Bataeved09d242014-05-28 05:53:51 +00009005 if (Vars.empty())
9006 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009007
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009008 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9009 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009010}
9011
Alexey Bataevbae9a792014-06-27 10:37:06 +00009012OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
9013 SourceLocation StartLoc,
9014 SourceLocation LParenLoc,
9015 SourceLocation EndLoc) {
9016 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +00009017 SmallVector<Expr *, 8> SrcExprs;
9018 SmallVector<Expr *, 8> DstExprs;
9019 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009020 for (auto &RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +00009021 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9022 SourceLocation ELoc;
9023 SourceRange ERange;
9024 Expr *SimpleRefExpr = RefExpr;
9025 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9026 /*AllowArraySection=*/false);
9027 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00009028 // It will be analyzed later.
9029 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +00009030 SrcExprs.push_back(nullptr);
9031 DstExprs.push_back(nullptr);
9032 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009033 }
Alexey Bataeve122da12016-03-17 10:50:17 +00009034 ValueDecl *D = Res.first;
9035 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +00009036 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009037
Alexey Bataeve122da12016-03-17 10:50:17 +00009038 QualType Type = D->getType();
9039 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009040
9041 // OpenMP [2.14.4.2, Restrictions, p.2]
9042 // A list item that appears in a copyprivate clause may not appear in a
9043 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +00009044 if (!VD || !DSAStack->isThreadPrivate(VD)) {
9045 auto DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +00009046 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
9047 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00009048 Diag(ELoc, diag::err_omp_wrong_dsa)
9049 << getOpenMPClauseName(DVar.CKind)
9050 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve122da12016-03-17 10:50:17 +00009051 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009052 continue;
9053 }
9054
9055 // OpenMP [2.11.4.2, Restrictions, p.1]
9056 // All list items that appear in a copyprivate clause must be either
9057 // threadprivate or private in the enclosing context.
9058 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +00009059 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009060 if (DVar.CKind == OMPC_shared) {
9061 Diag(ELoc, diag::err_omp_required_access)
9062 << getOpenMPClauseName(OMPC_copyprivate)
9063 << "threadprivate or private in the enclosing context";
Alexey Bataeve122da12016-03-17 10:50:17 +00009064 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009065 continue;
9066 }
9067 }
9068 }
9069
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009070 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009071 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009072 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009073 << getOpenMPClauseName(OMPC_copyprivate) << Type
9074 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009075 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +00009076 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009077 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +00009078 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009079 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +00009080 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009081 continue;
9082 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009083
Alexey Bataevbae9a792014-06-27 10:37:06 +00009084 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9085 // A variable of class type (or array thereof) that appears in a
9086 // copyin clause requires an accessible, unambiguous copy assignment
9087 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009088 Type = Context.getBaseElementType(Type.getNonReferenceType())
9089 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +00009090 auto *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +00009091 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
9092 D->hasAttrs() ? &D->getAttrs() : nullptr);
9093 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
Alexey Bataev420d45b2015-04-14 05:11:24 +00009094 auto *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +00009095 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
9096 D->hasAttrs() ? &D->getAttrs() : nullptr);
David Majnemer9d168222016-08-05 17:44:54 +00009097 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataeve122da12016-03-17 10:50:17 +00009098 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
Alexey Bataeva63048e2015-03-23 06:18:07 +00009099 PseudoDstExpr, PseudoSrcExpr);
9100 if (AssignmentOp.isInvalid())
9101 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +00009102 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +00009103 /*DiscardedValue=*/true);
9104 if (AssignmentOp.isInvalid())
9105 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009106
9107 // No need to mark vars as copyprivate, they are already threadprivate or
9108 // implicitly private.
Alexey Bataeve122da12016-03-17 10:50:17 +00009109 assert(VD || IsOpenMPCapturedDecl(D));
9110 Vars.push_back(
9111 VD ? RefExpr->IgnoreParens()
9112 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +00009113 SrcExprs.push_back(PseudoSrcExpr);
9114 DstExprs.push_back(PseudoDstExpr);
9115 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +00009116 }
9117
9118 if (Vars.empty())
9119 return nullptr;
9120
Alexey Bataeva63048e2015-03-23 06:18:07 +00009121 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9122 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009123}
9124
Alexey Bataev6125da92014-07-21 11:26:11 +00009125OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
9126 SourceLocation StartLoc,
9127 SourceLocation LParenLoc,
9128 SourceLocation EndLoc) {
9129 if (VarList.empty())
9130 return nullptr;
9131
9132 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
9133}
Alexey Bataevdea47612014-07-23 07:46:59 +00009134
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009135OMPClause *
9136Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
9137 SourceLocation DepLoc, SourceLocation ColonLoc,
9138 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9139 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00009140 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009141 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +00009142 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009143 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +00009144 return nullptr;
9145 }
9146 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009147 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
9148 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +00009149 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009150 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009151 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
9152 /*Last=*/OMPC_DEPEND_unknown, Except)
9153 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009154 return nullptr;
9155 }
9156 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +00009157 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009158 llvm::APSInt DepCounter(/*BitWidth=*/32);
9159 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
9160 if (DepKind == OMPC_DEPEND_sink) {
9161 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
9162 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
9163 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009164 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009165 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009166 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
9167 DSAStack->getParentOrderedRegionParam()) {
9168 for (auto &RefExpr : VarList) {
9169 assert(RefExpr && "NULL expr in OpenMP shared clause.");
Alexey Bataev8b427062016-05-25 12:36:08 +00009170 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009171 // It will be analyzed later.
9172 Vars.push_back(RefExpr);
9173 continue;
9174 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009175
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009176 SourceLocation ELoc = RefExpr->getExprLoc();
9177 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
9178 if (DepKind == OMPC_DEPEND_sink) {
9179 if (DepCounter >= TotalDepCount) {
9180 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
9181 continue;
9182 }
9183 ++DepCounter;
9184 // OpenMP [2.13.9, Summary]
9185 // depend(dependence-type : vec), where dependence-type is:
9186 // 'sink' and where vec is the iteration vector, which has the form:
9187 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
9188 // where n is the value specified by the ordered clause in the loop
9189 // directive, xi denotes the loop iteration variable of the i-th nested
9190 // loop associated with the loop directive, and di is a constant
9191 // non-negative integer.
Alexey Bataev8b427062016-05-25 12:36:08 +00009192 if (CurContext->isDependentContext()) {
9193 // It will be analyzed later.
9194 Vars.push_back(RefExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009195 continue;
9196 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009197 SimpleExpr = SimpleExpr->IgnoreImplicit();
9198 OverloadedOperatorKind OOK = OO_None;
9199 SourceLocation OOLoc;
9200 Expr *LHS = SimpleExpr;
9201 Expr *RHS = nullptr;
9202 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
9203 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
9204 OOLoc = BO->getOperatorLoc();
9205 LHS = BO->getLHS()->IgnoreParenImpCasts();
9206 RHS = BO->getRHS()->IgnoreParenImpCasts();
9207 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
9208 OOK = OCE->getOperator();
9209 OOLoc = OCE->getOperatorLoc();
9210 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9211 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
9212 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
9213 OOK = MCE->getMethodDecl()
9214 ->getNameInfo()
9215 .getName()
9216 .getCXXOverloadedOperator();
9217 OOLoc = MCE->getCallee()->getExprLoc();
9218 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
9219 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9220 }
9221 SourceLocation ELoc;
9222 SourceRange ERange;
9223 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
9224 /*AllowArraySection=*/false);
9225 if (Res.second) {
9226 // It will be analyzed later.
9227 Vars.push_back(RefExpr);
9228 }
9229 ValueDecl *D = Res.first;
9230 if (!D)
9231 continue;
9232
9233 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
9234 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
9235 continue;
9236 }
9237 if (RHS) {
9238 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
9239 RHS, OMPC_depend, /*StrictlyPositive=*/false);
9240 if (RHSRes.isInvalid())
9241 continue;
9242 }
9243 if (!CurContext->isDependentContext() &&
9244 DSAStack->getParentOrderedRegionParam() &&
9245 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
9246 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
9247 << DSAStack->getParentLoopControlVariable(
9248 DepCounter.getZExtValue());
9249 continue;
9250 }
9251 OpsOffs.push_back({RHS, OOK});
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009252 } else {
9253 // OpenMP [2.11.1.1, Restrictions, p.3]
9254 // A variable that is part of another variable (such as a field of a
9255 // structure) but is not an array element or an array section cannot
9256 // appear in a depend clause.
9257 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
9258 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
9259 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
9260 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
9261 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
Alexey Bataev31300ed2016-02-04 11:27:03 +00009262 (ASE &&
9263 !ASE->getBase()
9264 ->getType()
9265 .getNonReferenceType()
9266 ->isPointerType() &&
9267 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009268 Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item)
9269 << 0 << RefExpr->getSourceRange();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009270 continue;
9271 }
9272 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009273 Vars.push_back(RefExpr->IgnoreParenImpCasts());
9274 }
9275
9276 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
9277 TotalDepCount > VarList.size() &&
9278 DSAStack->getParentOrderedRegionParam()) {
9279 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
9280 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
9281 }
9282 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
9283 Vars.empty())
9284 return nullptr;
9285 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009286 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9287 DepKind, DepLoc, ColonLoc, Vars);
9288 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
9289 DSAStack->addDoacrossDependClause(C, OpsOffs);
9290 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009291}
Michael Wonge710d542015-08-07 16:16:36 +00009292
9293OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
9294 SourceLocation LParenLoc,
9295 SourceLocation EndLoc) {
9296 Expr *ValExpr = Device;
Michael Wonge710d542015-08-07 16:16:36 +00009297
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009298 // OpenMP [2.9.1, Restrictions]
9299 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00009300 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
9301 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009302 return nullptr;
9303
Michael Wonge710d542015-08-07 16:16:36 +00009304 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9305}
Kelvin Li0bff7af2015-11-23 05:32:03 +00009306
9307static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
9308 DSAStackTy *Stack, CXXRecordDecl *RD) {
9309 if (!RD || RD->isInvalidDecl())
9310 return true;
9311
9312 auto QTy = SemaRef.Context.getRecordType(RD);
9313 if (RD->isDynamicClass()) {
9314 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9315 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
9316 return false;
9317 }
9318 auto *DC = RD;
9319 bool IsCorrect = true;
9320 for (auto *I : DC->decls()) {
9321 if (I) {
9322 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
9323 if (MD->isStatic()) {
9324 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9325 SemaRef.Diag(MD->getLocation(),
9326 diag::note_omp_static_member_in_target);
9327 IsCorrect = false;
9328 }
9329 } else if (auto *VD = dyn_cast<VarDecl>(I)) {
9330 if (VD->isStaticDataMember()) {
9331 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9332 SemaRef.Diag(VD->getLocation(),
9333 diag::note_omp_static_member_in_target);
9334 IsCorrect = false;
9335 }
9336 }
9337 }
9338 }
9339
9340 for (auto &I : RD->bases()) {
9341 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
9342 I.getType()->getAsCXXRecordDecl()))
9343 IsCorrect = false;
9344 }
9345 return IsCorrect;
9346}
9347
9348static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
9349 DSAStackTy *Stack, QualType QTy) {
9350 NamedDecl *ND;
9351 if (QTy->isIncompleteType(&ND)) {
9352 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
9353 return false;
9354 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
David Majnemer9d168222016-08-05 17:44:54 +00009355 if (!RD->isInvalidDecl() && !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
Kelvin Li0bff7af2015-11-23 05:32:03 +00009356 return false;
9357 }
9358 return true;
9359}
9360
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009361/// \brief Return true if it can be proven that the provided array expression
9362/// (array section or array subscript) does NOT specify the whole size of the
9363/// array whose base type is \a BaseQTy.
9364static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
9365 const Expr *E,
9366 QualType BaseQTy) {
9367 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
9368
9369 // If this is an array subscript, it refers to the whole size if the size of
9370 // the dimension is constant and equals 1. Also, an array section assumes the
9371 // format of an array subscript if no colon is used.
9372 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
9373 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
9374 return ATy->getSize().getSExtValue() != 1;
9375 // Size can't be evaluated statically.
9376 return false;
9377 }
9378
9379 assert(OASE && "Expecting array section if not an array subscript.");
9380 auto *LowerBound = OASE->getLowerBound();
9381 auto *Length = OASE->getLength();
9382
9383 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +00009384 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009385 if (LowerBound) {
9386 llvm::APSInt ConstLowerBound;
9387 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
9388 return false; // Can't get the integer value as a constant.
9389 if (ConstLowerBound.getSExtValue())
9390 return true;
9391 }
9392
9393 // If we don't have a length we covering the whole dimension.
9394 if (!Length)
9395 return false;
9396
9397 // If the base is a pointer, we don't have a way to get the size of the
9398 // pointee.
9399 if (BaseQTy->isPointerType())
9400 return false;
9401
9402 // We can only check if the length is the same as the size of the dimension
9403 // if we have a constant array.
9404 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
9405 if (!CATy)
9406 return false;
9407
9408 llvm::APSInt ConstLength;
9409 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
9410 return false; // Can't get the integer value as a constant.
9411
9412 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
9413}
9414
9415// Return true if it can be proven that the provided array expression (array
9416// section or array subscript) does NOT specify a single element of the array
9417// whose base type is \a BaseQTy.
9418static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +00009419 const Expr *E,
9420 QualType BaseQTy) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009421 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
9422
9423 // An array subscript always refer to a single element. Also, an array section
9424 // assumes the format of an array subscript if no colon is used.
9425 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
9426 return false;
9427
9428 assert(OASE && "Expecting array section if not an array subscript.");
9429 auto *Length = OASE->getLength();
9430
9431 // If we don't have a length we have to check if the array has unitary size
9432 // for this dimension. Also, we should always expect a length if the base type
9433 // is pointer.
9434 if (!Length) {
9435 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
9436 return ATy->getSize().getSExtValue() != 1;
9437 // We cannot assume anything.
9438 return false;
9439 }
9440
9441 // Check if the length evaluates to 1.
9442 llvm::APSInt ConstLength;
9443 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
9444 return false; // Can't get the integer value as a constant.
9445
9446 return ConstLength.getSExtValue() != 1;
9447}
9448
Samuel Antao661c0902016-05-26 17:39:58 +00009449// Return the expression of the base of the mappable expression or null if it
9450// cannot be determined and do all the necessary checks to see if the expression
9451// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +00009452// components of the expression.
9453static Expr *CheckMapClauseExpressionBase(
9454 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +00009455 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
9456 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009457 SourceLocation ELoc = E->getExprLoc();
9458 SourceRange ERange = E->getSourceRange();
9459
9460 // The base of elements of list in a map clause have to be either:
9461 // - a reference to variable or field.
9462 // - a member expression.
9463 // - an array expression.
9464 //
9465 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
9466 // reference to 'r'.
9467 //
9468 // If we have:
9469 //
9470 // struct SS {
9471 // Bla S;
9472 // foo() {
9473 // #pragma omp target map (S.Arr[:12]);
9474 // }
9475 // }
9476 //
9477 // We want to retrieve the member expression 'this->S';
9478
9479 Expr *RelevantExpr = nullptr;
9480
Samuel Antao5de996e2016-01-22 20:21:36 +00009481 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
9482 // If a list item is an array section, it must specify contiguous storage.
9483 //
9484 // For this restriction it is sufficient that we make sure only references
9485 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009486 // exist except in the rightmost expression (unless they cover the whole
9487 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +00009488 //
9489 // r.ArrS[3:5].Arr[6:7]
9490 //
9491 // r.ArrS[3:5].x
9492 //
9493 // but these would be valid:
9494 // r.ArrS[3].Arr[6:7]
9495 //
9496 // r.ArrS[3].x
9497
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009498 bool AllowUnitySizeArraySection = true;
9499 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +00009500
Dmitry Polukhin644a9252016-03-11 07:58:34 +00009501 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009502 E = E->IgnoreParenImpCasts();
9503
9504 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
9505 if (!isa<VarDecl>(CurE->getDecl()))
9506 break;
9507
9508 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009509
9510 // If we got a reference to a declaration, we should not expect any array
9511 // section before that.
9512 AllowUnitySizeArraySection = false;
9513 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +00009514
9515 // Record the component.
9516 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
9517 CurE, CurE->getDecl()));
Samuel Antao5de996e2016-01-22 20:21:36 +00009518 continue;
9519 }
9520
9521 if (auto *CurE = dyn_cast<MemberExpr>(E)) {
9522 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
9523
9524 if (isa<CXXThisExpr>(BaseE))
9525 // We found a base expression: this->Val.
9526 RelevantExpr = CurE;
9527 else
9528 E = BaseE;
9529
9530 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
9531 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
9532 << CurE->getSourceRange();
9533 break;
9534 }
9535
9536 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
9537
9538 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
9539 // A bit-field cannot appear in a map clause.
9540 //
9541 if (FD->isBitField()) {
Samuel Antao661c0902016-05-26 17:39:58 +00009542 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
9543 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +00009544 break;
9545 }
9546
9547 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9548 // If the type of a list item is a reference to a type T then the type
9549 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009550 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +00009551
9552 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
9553 // A list item cannot be a variable that is a member of a structure with
9554 // a union type.
9555 //
9556 if (auto *RT = CurType->getAs<RecordType>())
9557 if (RT->isUnionType()) {
9558 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
9559 << CurE->getSourceRange();
9560 break;
9561 }
9562
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009563 // If we got a member expression, we should not expect any array section
9564 // before that:
9565 //
9566 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
9567 // If a list item is an element of a structure, only the rightmost symbol
9568 // of the variable reference can be an array section.
9569 //
9570 AllowUnitySizeArraySection = false;
9571 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +00009572
9573 // Record the component.
9574 CurComponents.push_back(
9575 OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
Samuel Antao5de996e2016-01-22 20:21:36 +00009576 continue;
9577 }
9578
9579 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
9580 E = CurE->getBase()->IgnoreParenImpCasts();
9581
9582 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
9583 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
9584 << 0 << CurE->getSourceRange();
9585 break;
9586 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009587
9588 // If we got an array subscript that express the whole dimension we
9589 // can have any array expressions before. If it only expressing part of
9590 // the dimension, we can only have unitary-size array expressions.
9591 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
9592 E->getType()))
9593 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +00009594
9595 // Record the component - we don't have any declaration associated.
9596 CurComponents.push_back(
9597 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +00009598 continue;
9599 }
9600
9601 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009602 E = CurE->getBase()->IgnoreParenImpCasts();
9603
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009604 auto CurType =
9605 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
9606
Samuel Antao5de996e2016-01-22 20:21:36 +00009607 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9608 // If the type of a list item is a reference to a type T then the type
9609 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +00009610 if (CurType->isReferenceType())
9611 CurType = CurType->getPointeeType();
9612
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009613 bool IsPointer = CurType->isAnyPointerType();
9614
9615 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009616 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
9617 << 0 << CurE->getSourceRange();
9618 break;
9619 }
9620
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009621 bool NotWhole =
9622 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
9623 bool NotUnity =
9624 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
9625
Samuel Antaodab51bb2016-07-18 23:22:11 +00009626 if (AllowWholeSizeArraySection) {
9627 // Any array section is currently allowed. Allowing a whole size array
9628 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009629 //
9630 // If this array section refers to the whole dimension we can still
9631 // accept other array sections before this one, except if the base is a
9632 // pointer. Otherwise, only unitary sections are accepted.
9633 if (NotWhole || IsPointer)
9634 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +00009635 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009636 // A unity or whole array section is not allowed and that is not
9637 // compatible with the properties of the current array section.
9638 SemaRef.Diag(
9639 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
9640 << CurE->getSourceRange();
9641 break;
9642 }
Samuel Antao90927002016-04-26 14:54:23 +00009643
9644 // Record the component - we don't have any declaration associated.
9645 CurComponents.push_back(
9646 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +00009647 continue;
9648 }
9649
9650 // If nothing else worked, this is not a valid map clause expression.
9651 SemaRef.Diag(ELoc,
9652 diag::err_omp_expected_named_var_member_or_array_expression)
9653 << ERange;
9654 break;
9655 }
9656
9657 return RelevantExpr;
9658}
9659
9660// Return true if expression E associated with value VD has conflicts with other
9661// map information.
Samuel Antao90927002016-04-26 14:54:23 +00009662static bool CheckMapConflicts(
9663 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
9664 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +00009665 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
9666 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009667 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +00009668 SourceLocation ELoc = E->getExprLoc();
9669 SourceRange ERange = E->getSourceRange();
9670
9671 // In order to easily check the conflicts we need to match each component of
9672 // the expression under test with the components of the expressions that are
9673 // already in the stack.
9674
Samuel Antao5de996e2016-01-22 20:21:36 +00009675 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +00009676 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +00009677 "Map clause expression with unexpected base!");
9678
9679 // Variables to help detecting enclosing problems in data environment nests.
9680 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +00009681 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +00009682
Samuel Antao90927002016-04-26 14:54:23 +00009683 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
9684 VD, CurrentRegionOnly,
9685 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00009686 StackComponents,
9687 OpenMPClauseKind) -> bool {
Samuel Antao90927002016-04-26 14:54:23 +00009688
Samuel Antao5de996e2016-01-22 20:21:36 +00009689 assert(!StackComponents.empty() &&
9690 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +00009691 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +00009692 "Map clause expression with unexpected base!");
9693
Samuel Antao90927002016-04-26 14:54:23 +00009694 // The whole expression in the stack.
9695 auto *RE = StackComponents.front().getAssociatedExpression();
9696
Samuel Antao5de996e2016-01-22 20:21:36 +00009697 // Expressions must start from the same base. Here we detect at which
9698 // point both expressions diverge from each other and see if we can
9699 // detect if the memory referred to both expressions is contiguous and
9700 // do not overlap.
9701 auto CI = CurComponents.rbegin();
9702 auto CE = CurComponents.rend();
9703 auto SI = StackComponents.rbegin();
9704 auto SE = StackComponents.rend();
9705 for (; CI != CE && SI != SE; ++CI, ++SI) {
9706
9707 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
9708 // At most one list item can be an array item derived from a given
9709 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +00009710 if (CurrentRegionOnly &&
9711 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
9712 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
9713 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
9714 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
9715 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +00009716 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +00009717 << CI->getAssociatedExpression()->getSourceRange();
9718 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
9719 diag::note_used_here)
9720 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +00009721 return true;
9722 }
9723
9724 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +00009725 if (CI->getAssociatedExpression()->getStmtClass() !=
9726 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +00009727 break;
9728
9729 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +00009730 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +00009731 break;
9732 }
Kelvin Li9f645ae2016-07-18 22:49:16 +00009733 // Check if the extra components of the expressions in the enclosing
9734 // data environment are redundant for the current base declaration.
9735 // If they are, the maps completely overlap, which is legal.
9736 for (; SI != SE; ++SI) {
9737 QualType Type;
9738 if (auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +00009739 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +00009740 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
David Majnemer9d168222016-08-05 17:44:54 +00009741 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
9742 SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +00009743 auto *E = OASE->getBase()->IgnoreParenImpCasts();
9744 Type =
9745 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
9746 }
9747 if (Type.isNull() || Type->isAnyPointerType() ||
9748 CheckArrayExpressionDoesNotReferToWholeSize(
9749 SemaRef, SI->getAssociatedExpression(), Type))
9750 break;
9751 }
Samuel Antao5de996e2016-01-22 20:21:36 +00009752
9753 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
9754 // List items of map clauses in the same construct must not share
9755 // original storage.
9756 //
9757 // If the expressions are exactly the same or one is a subset of the
9758 // other, it means they are sharing storage.
9759 if (CI == CE && SI == SE) {
9760 if (CurrentRegionOnly) {
Samuel Antao661c0902016-05-26 17:39:58 +00009761 if (CKind == OMPC_map)
9762 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
9763 else {
Samuel Antaoec172c62016-05-26 17:49:04 +00009764 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +00009765 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
9766 << ERange;
9767 }
Samuel Antao5de996e2016-01-22 20:21:36 +00009768 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
9769 << RE->getSourceRange();
9770 return true;
9771 } else {
9772 // If we find the same expression in the enclosing data environment,
9773 // that is legal.
9774 IsEnclosedByDataEnvironmentExpr = true;
9775 return false;
9776 }
9777 }
9778
Samuel Antao90927002016-04-26 14:54:23 +00009779 QualType DerivedType =
9780 std::prev(CI)->getAssociatedDeclaration()->getType();
9781 SourceLocation DerivedLoc =
9782 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +00009783
9784 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9785 // If the type of a list item is a reference to a type T then the type
9786 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +00009787 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +00009788
9789 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
9790 // A variable for which the type is pointer and an array section
9791 // derived from that variable must not appear as list items of map
9792 // clauses of the same construct.
9793 //
9794 // Also, cover one of the cases in:
9795 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
9796 // If any part of the original storage of a list item has corresponding
9797 // storage in the device data environment, all of the original storage
9798 // must have corresponding storage in the device data environment.
9799 //
9800 if (DerivedType->isAnyPointerType()) {
9801 if (CI == CE || SI == SE) {
9802 SemaRef.Diag(
9803 DerivedLoc,
9804 diag::err_omp_pointer_mapped_along_with_derived_section)
9805 << DerivedLoc;
9806 } else {
9807 assert(CI != CE && SI != SE);
9808 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
9809 << DerivedLoc;
9810 }
9811 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
9812 << RE->getSourceRange();
9813 return true;
9814 }
9815
9816 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
9817 // List items of map clauses in the same construct must not share
9818 // original storage.
9819 //
9820 // An expression is a subset of the other.
9821 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Samuel Antao661c0902016-05-26 17:39:58 +00009822 if (CKind == OMPC_map)
9823 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
9824 else {
Samuel Antaoec172c62016-05-26 17:49:04 +00009825 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +00009826 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
9827 << ERange;
9828 }
Samuel Antao5de996e2016-01-22 20:21:36 +00009829 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
9830 << RE->getSourceRange();
9831 return true;
9832 }
9833
9834 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +00009835 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +00009836 if (!CurrentRegionOnly && SI != SE)
9837 EnclosingExpr = RE;
9838
9839 // The current expression is a subset of the expression in the data
9840 // environment.
9841 IsEnclosedByDataEnvironmentExpr |=
9842 (!CurrentRegionOnly && CI != CE && SI == SE);
9843
9844 return false;
9845 });
9846
9847 if (CurrentRegionOnly)
9848 return FoundError;
9849
9850 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
9851 // If any part of the original storage of a list item has corresponding
9852 // storage in the device data environment, all of the original storage must
9853 // have corresponding storage in the device data environment.
9854 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
9855 // If a list item is an element of a structure, and a different element of
9856 // the structure has a corresponding list item in the device data environment
9857 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +00009858 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +00009859 // data environment prior to the task encountering the construct.
9860 //
9861 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
9862 SemaRef.Diag(ELoc,
9863 diag::err_omp_original_storage_is_shared_and_does_not_contain)
9864 << ERange;
9865 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
9866 << EnclosingExpr->getSourceRange();
9867 return true;
9868 }
9869
9870 return FoundError;
9871}
9872
Samuel Antao661c0902016-05-26 17:39:58 +00009873namespace {
9874// Utility struct that gathers all the related lists associated with a mappable
9875// expression.
9876struct MappableVarListInfo final {
9877 // The list of expressions.
9878 ArrayRef<Expr *> VarList;
9879 // The list of processed expressions.
9880 SmallVector<Expr *, 16> ProcessedVarList;
9881 // The mappble components for each expression.
9882 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
9883 // The base declaration of the variable.
9884 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
9885
9886 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
9887 // We have a list of components and base declarations for each entry in the
9888 // variable list.
9889 VarComponents.reserve(VarList.size());
9890 VarBaseDeclarations.reserve(VarList.size());
9891 }
9892};
9893}
9894
9895// Check the validity of the provided variable list for the provided clause kind
9896// \a CKind. In the check process the valid expressions, and mappable expression
9897// components and variables are extracted and used to fill \a Vars,
9898// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
9899// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
9900static void
9901checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
9902 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
9903 SourceLocation StartLoc,
9904 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
9905 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +00009906 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
9907 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +00009908 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +00009909
Samuel Antao90927002016-04-26 14:54:23 +00009910 // Keep track of the mappable components and base declarations in this clause.
9911 // Each entry in the list is going to have a list of components associated. We
9912 // record each set of the components so that we can build the clause later on.
9913 // In the end we should have the same amount of declarations and component
9914 // lists.
Samuel Antao90927002016-04-26 14:54:23 +00009915
Samuel Antao661c0902016-05-26 17:39:58 +00009916 for (auto &RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +00009917 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +00009918 SourceLocation ELoc = RE->getExprLoc();
9919
Kelvin Li0bff7af2015-11-23 05:32:03 +00009920 auto *VE = RE->IgnoreParenLValueCasts();
9921
9922 if (VE->isValueDependent() || VE->isTypeDependent() ||
9923 VE->isInstantiationDependent() ||
9924 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009925 // We can only analyze this information once the missing information is
9926 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +00009927 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +00009928 continue;
9929 }
9930
9931 auto *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +00009932
Samuel Antao5de996e2016-01-22 20:21:36 +00009933 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +00009934 SemaRef.Diag(ELoc,
9935 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +00009936 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +00009937 continue;
9938 }
9939
Samuel Antao90927002016-04-26 14:54:23 +00009940 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
9941 ValueDecl *CurDeclaration = nullptr;
9942
9943 // Obtain the array or member expression bases if required. Also, fill the
9944 // components array with all the components identified in the process.
Samuel Antao661c0902016-05-26 17:39:58 +00009945 auto *BE =
9946 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +00009947 if (!BE)
9948 continue;
9949
Samuel Antao90927002016-04-26 14:54:23 +00009950 assert(!CurComponents.empty() &&
9951 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +00009952
Samuel Antao90927002016-04-26 14:54:23 +00009953 // For the following checks, we rely on the base declaration which is
9954 // expected to be associated with the last component. The declaration is
9955 // expected to be a variable or a field (if 'this' is being mapped).
9956 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
9957 assert(CurDeclaration && "Null decl on map clause.");
9958 assert(
9959 CurDeclaration->isCanonicalDecl() &&
9960 "Expecting components to have associated only canonical declarations.");
9961
9962 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
9963 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +00009964
9965 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +00009966 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +00009967
9968 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +00009969 // threadprivate variables cannot appear in a map clause.
9970 // OpenMP 4.5 [2.10.5, target update Construct]
9971 // threadprivate variables cannot appear in a from clause.
9972 if (VD && DSAS->isThreadPrivate(VD)) {
9973 auto DVar = DSAS->getTopDSA(VD, false);
9974 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
9975 << getOpenMPClauseName(CKind);
9976 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +00009977 continue;
9978 }
9979
Samuel Antao5de996e2016-01-22 20:21:36 +00009980 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
9981 // A list item cannot appear in both a map clause and a data-sharing
9982 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +00009983
Samuel Antao5de996e2016-01-22 20:21:36 +00009984 // Check conflicts with other map clause expressions. We check the conflicts
9985 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +00009986 // environment, because the restrictions are different. We only have to
9987 // check conflicts across regions for the map clauses.
9988 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
9989 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +00009990 break;
Samuel Antao661c0902016-05-26 17:39:58 +00009991 if (CKind == OMPC_map &&
9992 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
9993 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +00009994 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +00009995
Samuel Antao661c0902016-05-26 17:39:58 +00009996 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +00009997 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9998 // If the type of a list item is a reference to a type T then the type will
9999 // be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000010000 QualType Type = CurDeclaration->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010001
Samuel Antao661c0902016-05-26 17:39:58 +000010002 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
10003 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000010004 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000010005 // A list item must have a mappable type.
Samuel Antao661c0902016-05-26 17:39:58 +000010006 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
10007 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000010008 continue;
10009
Samuel Antao661c0902016-05-26 17:39:58 +000010010 if (CKind == OMPC_map) {
10011 // target enter data
10012 // OpenMP [2.10.2, Restrictions, p. 99]
10013 // A map-type must be specified in all map clauses and must be either
10014 // to or alloc.
10015 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
10016 if (DKind == OMPD_target_enter_data &&
10017 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
10018 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10019 << (IsMapTypeImplicit ? 1 : 0)
10020 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10021 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010022 continue;
10023 }
Samuel Antao661c0902016-05-26 17:39:58 +000010024
10025 // target exit_data
10026 // OpenMP [2.10.3, Restrictions, p. 102]
10027 // A map-type must be specified in all map clauses and must be either
10028 // from, release, or delete.
10029 if (DKind == OMPD_target_exit_data &&
10030 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
10031 MapType == OMPC_MAP_delete)) {
10032 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10033 << (IsMapTypeImplicit ? 1 : 0)
10034 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10035 << getOpenMPDirectiveName(DKind);
10036 continue;
10037 }
10038
10039 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10040 // A list item cannot appear in both a map clause and a data-sharing
10041 // attribute clause on the same construct
10042 if (DKind == OMPD_target && VD) {
10043 auto DVar = DSAS->getTopDSA(VD, false);
10044 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010045 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000010046 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000010047 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000010048 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
10049 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
10050 continue;
10051 }
10052 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010053 }
10054
Samuel Antao90927002016-04-26 14:54:23 +000010055 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000010056 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000010057
10058 // Store the components in the stack so that they can be used to check
10059 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000010060 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
10061 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000010062
10063 // Save the components and declaration to create the clause. For purposes of
10064 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000010065 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000010066 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
10067 MVLI.VarComponents.back().append(CurComponents.begin(),
10068 CurComponents.end());
10069 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
10070 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010071 }
Samuel Antao661c0902016-05-26 17:39:58 +000010072}
10073
10074OMPClause *
10075Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
10076 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
10077 SourceLocation MapLoc, SourceLocation ColonLoc,
10078 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10079 SourceLocation LParenLoc, SourceLocation EndLoc) {
10080 MappableVarListInfo MVLI(VarList);
10081 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
10082 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010083
Samuel Antao5de996e2016-01-22 20:21:36 +000010084 // We need to produce a map clause even if we don't have variables so that
10085 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +000010086 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10087 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10088 MVLI.VarComponents, MapTypeModifier, MapType,
10089 IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010090}
Kelvin Li099bb8c2015-11-24 20:50:12 +000010091
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010092QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
10093 TypeResult ParsedType) {
10094 assert(ParsedType.isUsable());
10095
10096 QualType ReductionType = GetTypeFromParser(ParsedType.get());
10097 if (ReductionType.isNull())
10098 return QualType();
10099
10100 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
10101 // A type name in a declare reduction directive cannot be a function type, an
10102 // array type, a reference type, or a type qualified with const, volatile or
10103 // restrict.
10104 if (ReductionType.hasQualifiers()) {
10105 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
10106 return QualType();
10107 }
10108
10109 if (ReductionType->isFunctionType()) {
10110 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
10111 return QualType();
10112 }
10113 if (ReductionType->isReferenceType()) {
10114 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
10115 return QualType();
10116 }
10117 if (ReductionType->isArrayType()) {
10118 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
10119 return QualType();
10120 }
10121 return ReductionType;
10122}
10123
10124Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
10125 Scope *S, DeclContext *DC, DeclarationName Name,
10126 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
10127 AccessSpecifier AS, Decl *PrevDeclInScope) {
10128 SmallVector<Decl *, 8> Decls;
10129 Decls.reserve(ReductionTypes.size());
10130
10131 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
10132 ForRedeclaration);
10133 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
10134 // A reduction-identifier may not be re-declared in the current scope for the
10135 // same type or for a type that is compatible according to the base language
10136 // rules.
10137 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
10138 OMPDeclareReductionDecl *PrevDRD = nullptr;
10139 bool InCompoundScope = true;
10140 if (S != nullptr) {
10141 // Find previous declaration with the same name not referenced in other
10142 // declarations.
10143 FunctionScopeInfo *ParentFn = getEnclosingFunction();
10144 InCompoundScope =
10145 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
10146 LookupName(Lookup, S);
10147 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
10148 /*AllowInlineNamespace=*/false);
10149 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
10150 auto Filter = Lookup.makeFilter();
10151 while (Filter.hasNext()) {
10152 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
10153 if (InCompoundScope) {
10154 auto I = UsedAsPrevious.find(PrevDecl);
10155 if (I == UsedAsPrevious.end())
10156 UsedAsPrevious[PrevDecl] = false;
10157 if (auto *D = PrevDecl->getPrevDeclInScope())
10158 UsedAsPrevious[D] = true;
10159 }
10160 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
10161 PrevDecl->getLocation();
10162 }
10163 Filter.done();
10164 if (InCompoundScope) {
10165 for (auto &PrevData : UsedAsPrevious) {
10166 if (!PrevData.second) {
10167 PrevDRD = PrevData.first;
10168 break;
10169 }
10170 }
10171 }
10172 } else if (PrevDeclInScope != nullptr) {
10173 auto *PrevDRDInScope = PrevDRD =
10174 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
10175 do {
10176 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
10177 PrevDRDInScope->getLocation();
10178 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
10179 } while (PrevDRDInScope != nullptr);
10180 }
10181 for (auto &TyData : ReductionTypes) {
10182 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
10183 bool Invalid = false;
10184 if (I != PreviousRedeclTypes.end()) {
10185 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
10186 << TyData.first;
10187 Diag(I->second, diag::note_previous_definition);
10188 Invalid = true;
10189 }
10190 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
10191 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
10192 Name, TyData.first, PrevDRD);
10193 DC->addDecl(DRD);
10194 DRD->setAccess(AS);
10195 Decls.push_back(DRD);
10196 if (Invalid)
10197 DRD->setInvalidDecl();
10198 else
10199 PrevDRD = DRD;
10200 }
10201
10202 return DeclGroupPtrTy::make(
10203 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
10204}
10205
10206void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
10207 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10208
10209 // Enter new function scope.
10210 PushFunctionScope();
10211 getCurFunction()->setHasBranchProtectedScope();
10212 getCurFunction()->setHasOMPDeclareReductionCombiner();
10213
10214 if (S != nullptr)
10215 PushDeclContext(S, DRD);
10216 else
10217 CurContext = DRD;
10218
10219 PushExpressionEvaluationContext(PotentiallyEvaluated);
10220
10221 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010222 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
10223 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
10224 // uses semantics of argument handles by value, but it should be passed by
10225 // reference. C lang does not support references, so pass all parameters as
10226 // pointers.
10227 // Create 'T omp_in;' variable.
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010228 auto *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010229 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010230 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
10231 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
10232 // uses semantics of argument handles by value, but it should be passed by
10233 // reference. C lang does not support references, so pass all parameters as
10234 // pointers.
10235 // Create 'T omp_out;' variable.
10236 auto *OmpOutParm =
10237 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
10238 if (S != nullptr) {
10239 PushOnScopeChains(OmpInParm, S);
10240 PushOnScopeChains(OmpOutParm, S);
10241 } else {
10242 DRD->addDecl(OmpInParm);
10243 DRD->addDecl(OmpOutParm);
10244 }
10245}
10246
10247void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
10248 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10249 DiscardCleanupsInEvaluationContext();
10250 PopExpressionEvaluationContext();
10251
10252 PopDeclContext();
10253 PopFunctionScopeInfo();
10254
10255 if (Combiner != nullptr)
10256 DRD->setCombiner(Combiner);
10257 else
10258 DRD->setInvalidDecl();
10259}
10260
10261void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
10262 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10263
10264 // Enter new function scope.
10265 PushFunctionScope();
10266 getCurFunction()->setHasBranchProtectedScope();
10267
10268 if (S != nullptr)
10269 PushDeclContext(S, DRD);
10270 else
10271 CurContext = DRD;
10272
10273 PushExpressionEvaluationContext(PotentiallyEvaluated);
10274
10275 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010276 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
10277 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
10278 // uses semantics of argument handles by value, but it should be passed by
10279 // reference. C lang does not support references, so pass all parameters as
10280 // pointers.
10281 // Create 'T omp_priv;' variable.
10282 auto *OmpPrivParm =
10283 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010284 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
10285 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
10286 // uses semantics of argument handles by value, but it should be passed by
10287 // reference. C lang does not support references, so pass all parameters as
10288 // pointers.
10289 // Create 'T omp_orig;' variable.
10290 auto *OmpOrigParm =
10291 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010292 if (S != nullptr) {
10293 PushOnScopeChains(OmpPrivParm, S);
10294 PushOnScopeChains(OmpOrigParm, S);
10295 } else {
10296 DRD->addDecl(OmpPrivParm);
10297 DRD->addDecl(OmpOrigParm);
10298 }
10299}
10300
10301void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D,
10302 Expr *Initializer) {
10303 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10304 DiscardCleanupsInEvaluationContext();
10305 PopExpressionEvaluationContext();
10306
10307 PopDeclContext();
10308 PopFunctionScopeInfo();
10309
10310 if (Initializer != nullptr)
10311 DRD->setInitializer(Initializer);
10312 else
10313 DRD->setInvalidDecl();
10314}
10315
10316Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
10317 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
10318 for (auto *D : DeclReductions.get()) {
10319 if (IsValid) {
10320 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10321 if (S != nullptr)
10322 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
10323 } else
10324 D->setInvalidDecl();
10325 }
10326 return DeclReductions;
10327}
10328
David Majnemer9d168222016-08-05 17:44:54 +000010329OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000010330 SourceLocation StartLoc,
10331 SourceLocation LParenLoc,
10332 SourceLocation EndLoc) {
10333 Expr *ValExpr = NumTeams;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010334
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010335 // OpenMP [teams Constrcut, Restrictions]
10336 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000010337 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
10338 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010339 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010340
10341 return new (Context) OMPNumTeamsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10342}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010343
10344OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
10345 SourceLocation StartLoc,
10346 SourceLocation LParenLoc,
10347 SourceLocation EndLoc) {
10348 Expr *ValExpr = ThreadLimit;
10349
10350 // OpenMP [teams Constrcut, Restrictions]
10351 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000010352 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
10353 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010354 return nullptr;
10355
David Majnemer9d168222016-08-05 17:44:54 +000010356 return new (Context)
10357 OMPThreadLimitClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010358}
Alexey Bataeva0569352015-12-01 10:17:31 +000010359
10360OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
10361 SourceLocation StartLoc,
10362 SourceLocation LParenLoc,
10363 SourceLocation EndLoc) {
10364 Expr *ValExpr = Priority;
10365
10366 // OpenMP [2.9.1, task Constrcut]
10367 // The priority-value is a non-negative numerical scalar expression.
10368 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
10369 /*StrictlyPositive=*/false))
10370 return nullptr;
10371
10372 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10373}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010374
10375OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
10376 SourceLocation StartLoc,
10377 SourceLocation LParenLoc,
10378 SourceLocation EndLoc) {
10379 Expr *ValExpr = Grainsize;
10380
10381 // OpenMP [2.9.2, taskloop Constrcut]
10382 // The parameter of the grainsize clause must be a positive integer
10383 // expression.
10384 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
10385 /*StrictlyPositive=*/true))
10386 return nullptr;
10387
10388 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10389}
Alexey Bataev382967a2015-12-08 12:06:20 +000010390
10391OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
10392 SourceLocation StartLoc,
10393 SourceLocation LParenLoc,
10394 SourceLocation EndLoc) {
10395 Expr *ValExpr = NumTasks;
10396
10397 // OpenMP [2.9.2, taskloop Constrcut]
10398 // The parameter of the num_tasks clause must be a positive integer
10399 // expression.
10400 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
10401 /*StrictlyPositive=*/true))
10402 return nullptr;
10403
10404 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10405}
10406
Alexey Bataev28c75412015-12-15 08:19:24 +000010407OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
10408 SourceLocation LParenLoc,
10409 SourceLocation EndLoc) {
10410 // OpenMP [2.13.2, critical construct, Description]
10411 // ... where hint-expression is an integer constant expression that evaluates
10412 // to a valid lock hint.
10413 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
10414 if (HintExpr.isInvalid())
10415 return nullptr;
10416 return new (Context)
10417 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
10418}
10419
Carlo Bertollib4adf552016-01-15 18:50:31 +000010420OMPClause *Sema::ActOnOpenMPDistScheduleClause(
10421 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
10422 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
10423 SourceLocation EndLoc) {
10424 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
10425 std::string Values;
10426 Values += "'";
10427 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
10428 Values += "'";
10429 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
10430 << Values << getOpenMPClauseName(OMPC_dist_schedule);
10431 return nullptr;
10432 }
10433 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000010434 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000010435 if (ChunkSize) {
10436 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
10437 !ChunkSize->isInstantiationDependent() &&
10438 !ChunkSize->containsUnexpandedParameterPack()) {
10439 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
10440 ExprResult Val =
10441 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
10442 if (Val.isInvalid())
10443 return nullptr;
10444
10445 ValExpr = Val.get();
10446
10447 // OpenMP [2.7.1, Restrictions]
10448 // chunk_size must be a loop invariant integer expression with a positive
10449 // value.
10450 llvm::APSInt Result;
10451 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
10452 if (Result.isSigned() && !Result.isStrictlyPositive()) {
10453 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
10454 << "dist_schedule" << ChunkSize->getSourceRange();
10455 return nullptr;
10456 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +000010457 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
10458 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +000010459 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
10460 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
10461 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000010462 }
10463 }
10464 }
10465
10466 return new (Context)
10467 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000010468 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000010469}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010470
10471OMPClause *Sema::ActOnOpenMPDefaultmapClause(
10472 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
10473 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
10474 SourceLocation KindLoc, SourceLocation EndLoc) {
10475 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000010476 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010477 std::string Value;
10478 SourceLocation Loc;
10479 Value += "'";
10480 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
10481 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000010482 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010483 Loc = MLoc;
10484 } else {
10485 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000010486 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010487 Loc = KindLoc;
10488 }
10489 Value += "'";
10490 Diag(Loc, diag::err_omp_unexpected_clause_value)
10491 << Value << getOpenMPClauseName(OMPC_defaultmap);
10492 return nullptr;
10493 }
10494
10495 return new (Context)
10496 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
10497}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010498
10499bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
10500 DeclContext *CurLexicalContext = getCurLexicalContext();
10501 if (!CurLexicalContext->isFileContext() &&
10502 !CurLexicalContext->isExternCContext() &&
10503 !CurLexicalContext->isExternCXXContext()) {
10504 Diag(Loc, diag::err_omp_region_not_file_context);
10505 return false;
10506 }
10507 if (IsInOpenMPDeclareTargetContext) {
10508 Diag(Loc, diag::err_omp_enclosed_declare_target);
10509 return false;
10510 }
10511
10512 IsInOpenMPDeclareTargetContext = true;
10513 return true;
10514}
10515
10516void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
10517 assert(IsInOpenMPDeclareTargetContext &&
10518 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
10519
10520 IsInOpenMPDeclareTargetContext = false;
10521}
10522
David Majnemer9d168222016-08-05 17:44:54 +000010523void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
10524 CXXScopeSpec &ScopeSpec,
10525 const DeclarationNameInfo &Id,
10526 OMPDeclareTargetDeclAttr::MapTypeTy MT,
10527 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010528 LookupResult Lookup(*this, Id, LookupOrdinaryName);
10529 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
10530
10531 if (Lookup.isAmbiguous())
10532 return;
10533 Lookup.suppressDiagnostics();
10534
10535 if (!Lookup.isSingleResult()) {
10536 if (TypoCorrection Corrected =
10537 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
10538 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
10539 CTK_ErrorRecovery)) {
10540 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
10541 << Id.getName());
10542 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
10543 return;
10544 }
10545
10546 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
10547 return;
10548 }
10549
10550 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
10551 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
10552 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
10553 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
10554
10555 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
10556 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
10557 ND->addAttr(A);
10558 if (ASTMutationListener *ML = Context.getASTMutationListener())
10559 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
10560 checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
10561 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
10562 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
10563 << Id.getName();
10564 }
10565 } else
10566 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
10567}
10568
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010569static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
10570 Sema &SemaRef, Decl *D) {
10571 if (!D)
10572 return;
10573 Decl *LD = nullptr;
10574 if (isa<TagDecl>(D)) {
10575 LD = cast<TagDecl>(D)->getDefinition();
10576 } else if (isa<VarDecl>(D)) {
10577 LD = cast<VarDecl>(D)->getDefinition();
10578
10579 // If this is an implicit variable that is legal and we do not need to do
10580 // anything.
10581 if (cast<VarDecl>(D)->isImplicit()) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010582 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10583 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10584 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010585 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010586 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010587 return;
10588 }
10589
10590 } else if (isa<FunctionDecl>(D)) {
10591 const FunctionDecl *FD = nullptr;
10592 if (cast<FunctionDecl>(D)->hasBody(FD))
10593 LD = const_cast<FunctionDecl *>(FD);
10594
10595 // If the definition is associated with the current declaration in the
10596 // target region (it can be e.g. a lambda) that is legal and we do not need
10597 // to do anything else.
10598 if (LD == D) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010599 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10600 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10601 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010602 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010603 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010604 return;
10605 }
10606 }
10607 if (!LD)
10608 LD = D;
10609 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
10610 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
10611 // Outlined declaration is not declared target.
10612 if (LD->isOutOfLine()) {
10613 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
10614 SemaRef.Diag(SL, diag::note_used_here) << SR;
10615 } else {
10616 DeclContext *DC = LD->getDeclContext();
10617 while (DC) {
10618 if (isa<FunctionDecl>(DC) &&
10619 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
10620 break;
10621 DC = DC->getParent();
10622 }
10623 if (DC)
10624 return;
10625
10626 // Is not declared in target context.
10627 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
10628 SemaRef.Diag(SL, diag::note_used_here) << SR;
10629 }
10630 // Mark decl as declared target to prevent further diagnostic.
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010631 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10632 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10633 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010634 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010635 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010636 }
10637}
10638
10639static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
10640 Sema &SemaRef, DSAStackTy *Stack,
10641 ValueDecl *VD) {
10642 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
10643 return true;
10644 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
10645 return false;
10646 return true;
10647}
10648
10649void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
10650 if (!D || D->isInvalidDecl())
10651 return;
10652 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
10653 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
10654 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
10655 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10656 if (DSAStack->isThreadPrivate(VD)) {
10657 Diag(SL, diag::err_omp_threadprivate_in_target);
10658 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
10659 return;
10660 }
10661 }
10662 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
10663 // Problem if any with var declared with incomplete type will be reported
10664 // as normal, so no need to check it here.
10665 if ((E || !VD->getType()->isIncompleteType()) &&
10666 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
10667 // Mark decl as declared target to prevent further diagnostic.
10668 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010669 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10670 Context, OMPDeclareTargetDeclAttr::MT_To);
10671 VD->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010672 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010673 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010674 }
10675 return;
10676 }
10677 }
10678 if (!E) {
10679 // Checking declaration inside declare target region.
10680 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
10681 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010682 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10683 Context, OMPDeclareTargetDeclAttr::MT_To);
10684 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010685 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010686 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010687 }
10688 return;
10689 }
10690 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
10691}
Samuel Antao661c0902016-05-26 17:39:58 +000010692
10693OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
10694 SourceLocation StartLoc,
10695 SourceLocation LParenLoc,
10696 SourceLocation EndLoc) {
10697 MappableVarListInfo MVLI(VarList);
10698 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
10699 if (MVLI.ProcessedVarList.empty())
10700 return nullptr;
10701
10702 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10703 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10704 MVLI.VarComponents);
10705}
Samuel Antaoec172c62016-05-26 17:49:04 +000010706
10707OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
10708 SourceLocation StartLoc,
10709 SourceLocation LParenLoc,
10710 SourceLocation EndLoc) {
10711 MappableVarListInfo MVLI(VarList);
10712 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
10713 if (MVLI.ProcessedVarList.empty())
10714 return nullptr;
10715
10716 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10717 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10718 MVLI.VarComponents);
10719}
Carlo Bertolli2404b172016-07-13 15:37:16 +000010720
10721OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
10722 SourceLocation StartLoc,
10723 SourceLocation LParenLoc,
10724 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000010725 MappableVarListInfo MVLI(VarList);
10726 SmallVector<Expr *, 8> PrivateCopies;
10727 SmallVector<Expr *, 8> Inits;
10728
Carlo Bertolli2404b172016-07-13 15:37:16 +000010729 for (auto &RefExpr : VarList) {
10730 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
10731 SourceLocation ELoc;
10732 SourceRange ERange;
10733 Expr *SimpleRefExpr = RefExpr;
10734 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10735 if (Res.second) {
10736 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000010737 MVLI.ProcessedVarList.push_back(RefExpr);
10738 PrivateCopies.push_back(nullptr);
10739 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000010740 }
10741 ValueDecl *D = Res.first;
10742 if (!D)
10743 continue;
10744
10745 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000010746 Type = Type.getNonReferenceType().getUnqualifiedType();
10747
10748 auto *VD = dyn_cast<VarDecl>(D);
10749
10750 // Item should be a pointer or reference to pointer.
10751 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000010752 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
10753 << 0 << RefExpr->getSourceRange();
10754 continue;
10755 }
Samuel Antaocc10b852016-07-28 14:23:26 +000010756
10757 // Build the private variable and the expression that refers to it.
10758 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
10759 D->hasAttrs() ? &D->getAttrs() : nullptr);
10760 if (VDPrivate->isInvalidDecl())
10761 continue;
10762
10763 CurContext->addDecl(VDPrivate);
10764 auto VDPrivateRefExpr = buildDeclRefExpr(
10765 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
10766
10767 // Add temporary variable to initialize the private copy of the pointer.
10768 auto *VDInit =
10769 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
10770 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
10771 RefExpr->getExprLoc());
10772 AddInitializerToDecl(VDPrivate,
10773 DefaultLvalueConversion(VDInitRefExpr).get(),
10774 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
10775
10776 // If required, build a capture to implement the privatization initialized
10777 // with the current list item value.
10778 DeclRefExpr *Ref = nullptr;
10779 if (!VD)
10780 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
10781 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
10782 PrivateCopies.push_back(VDPrivateRefExpr);
10783 Inits.push_back(VDInitRefExpr);
10784
10785 // We need to add a data sharing attribute for this variable to make sure it
10786 // is correctly captured. A variable that shows up in a use_device_ptr has
10787 // similar properties of a first private variable.
10788 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
10789
10790 // Create a mappable component for the list item. List items in this clause
10791 // only need a component.
10792 MVLI.VarBaseDeclarations.push_back(D);
10793 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
10794 MVLI.VarComponents.back().push_back(
10795 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000010796 }
10797
Samuel Antaocc10b852016-07-28 14:23:26 +000010798 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000010799 return nullptr;
10800
Samuel Antaocc10b852016-07-28 14:23:26 +000010801 return OMPUseDevicePtrClause::Create(
10802 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
10803 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000010804}
Carlo Bertolli70594e92016-07-13 17:16:49 +000010805
10806OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
10807 SourceLocation StartLoc,
10808 SourceLocation LParenLoc,
10809 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000010810 MappableVarListInfo MVLI(VarList);
Carlo Bertolli70594e92016-07-13 17:16:49 +000010811 for (auto &RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000010812 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000010813 SourceLocation ELoc;
10814 SourceRange ERange;
10815 Expr *SimpleRefExpr = RefExpr;
10816 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10817 if (Res.second) {
10818 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000010819 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000010820 }
10821 ValueDecl *D = Res.first;
10822 if (!D)
10823 continue;
10824
10825 QualType Type = D->getType();
10826 // item should be a pointer or array or reference to pointer or array
10827 if (!Type.getNonReferenceType()->isPointerType() &&
10828 !Type.getNonReferenceType()->isArrayType()) {
10829 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
10830 << 0 << RefExpr->getSourceRange();
10831 continue;
10832 }
Samuel Antao6890b092016-07-28 14:25:09 +000010833
10834 // Check if the declaration in the clause does not show up in any data
10835 // sharing attribute.
10836 auto DVar = DSAStack->getTopDSA(D, false);
10837 if (isOpenMPPrivate(DVar.CKind)) {
10838 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
10839 << getOpenMPClauseName(DVar.CKind)
10840 << getOpenMPClauseName(OMPC_is_device_ptr)
10841 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
10842 ReportOriginalDSA(*this, DSAStack, D, DVar);
10843 continue;
10844 }
10845
10846 Expr *ConflictExpr;
10847 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000010848 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000010849 [&ConflictExpr](
10850 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
10851 OpenMPClauseKind) -> bool {
10852 ConflictExpr = R.front().getAssociatedExpression();
10853 return true;
10854 })) {
10855 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
10856 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
10857 << ConflictExpr->getSourceRange();
10858 continue;
10859 }
10860
10861 // Store the components in the stack so that they can be used to check
10862 // against other clauses later on.
10863 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
10864 DSAStack->addMappableExpressionComponents(
10865 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
10866
10867 // Record the expression we've just processed.
10868 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
10869
10870 // Create a mappable component for the list item. List items in this clause
10871 // only need a component. We use a null declaration to signal fields in
10872 // 'this'.
10873 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
10874 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
10875 "Unexpected device pointer expression!");
10876 MVLI.VarBaseDeclarations.push_back(
10877 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
10878 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
10879 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000010880 }
10881
Samuel Antao6890b092016-07-28 14:25:09 +000010882 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000010883 return nullptr;
10884
Samuel Antao6890b092016-07-28 14:25:09 +000010885 return OMPIsDevicePtrClause::Create(
10886 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
10887 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000010888}