blob: 5cae7e300253cabb6d82f0e927f8d6c1375c2508 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
Alexey Bataeva769e072013-03-22 06:34:35 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// \brief This file implements semantic analysis for OpenMP directives and
Alexey Bataev6f6f3b42013-05-13 04:18:18 +000011/// clauses.
Alexey Bataeva769e072013-03-22 06:34:35 +000012///
13//===----------------------------------------------------------------------===//
14
Alexey Bataevb08f89f2015-08-14 12:25:37 +000015#include "TreeTransform.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000016#include "clang/AST/ASTContext.h"
Alexey Bataev97720002014-11-11 04:05:39 +000017#include "clang/AST/ASTMutationListener.h"
Alexey Bataeva839ddd2016-03-17 10:19:46 +000018#include "clang/AST/CXXInheritance.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000019#include "clang/AST/Decl.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000020#include "clang/AST/DeclCXX.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000021#include "clang/AST/DeclOpenMP.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000022#include "clang/AST/StmtCXX.h"
23#include "clang/AST/StmtOpenMP.h"
24#include "clang/AST/StmtVisitor.h"
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000025#include "clang/AST/TypeOrdering.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000026#include "clang/Basic/OpenMPKinds.h"
Samuel Antaof8b50122015-07-13 22:54:53 +000027#include "clang/Basic/TargetInfo.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000028#include "clang/Lex/Preprocessor.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000029#include "clang/Sema/Initialization.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000030#include "clang/Sema/Lookup.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000031#include "clang/Sema/Scope.h"
32#include "clang/Sema/ScopeInfo.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000033#include "clang/Sema/SemaInternal.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000034using namespace clang;
35
Alexey Bataev758e55e2013-09-06 18:03:48 +000036//===----------------------------------------------------------------------===//
37// Stack of data-sharing attributes for variables
38//===----------------------------------------------------------------------===//
39
40namespace {
41/// \brief Default data sharing attributes, which can be applied to directive.
42enum DefaultDataSharingAttributes {
Alexey Bataeved09d242014-05-28 05:53:51 +000043 DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
44 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
45 DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'.
Alexey Bataev758e55e2013-09-06 18:03:48 +000046};
Alexey Bataev7ff55242014-06-19 09:13:45 +000047
Alexey Bataev758e55e2013-09-06 18:03:48 +000048/// \brief Stack for tracking declarations used in OpenMP directives and
49/// clauses and their data-sharing attributes.
Alexey Bataev7ace49d2016-05-17 08:55:33 +000050class DSAStackTy final {
Alexey Bataev758e55e2013-09-06 18:03:48 +000051public:
Alexey Bataev7ace49d2016-05-17 08:55:33 +000052 struct DSAVarData final {
53 OpenMPDirectiveKind DKind = OMPD_unknown;
54 OpenMPClauseKind CKind = OMPC_unknown;
55 Expr *RefExpr = nullptr;
56 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000057 SourceLocation ImplicitDSALoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000058 DSAVarData() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +000059 };
Alexey Bataev8b427062016-05-25 12:36:08 +000060 typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>
61 OperatorOffsetTy;
Alexey Bataeved09d242014-05-28 05:53:51 +000062
Alexey Bataev758e55e2013-09-06 18:03:48 +000063private:
Alexey Bataev7ace49d2016-05-17 08:55:33 +000064 struct DSAInfo final {
65 OpenMPClauseKind Attributes = OMPC_unknown;
66 /// Pointer to a reference expression and a flag which shows that the
67 /// variable is marked as lastprivate(true) or not (false).
68 llvm::PointerIntPair<Expr *, 1, bool> RefExpr;
69 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000070 };
Alexey Bataev90c228f2016-02-08 09:29:13 +000071 typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy;
72 typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +000073 typedef std::pair<unsigned, VarDecl *> LCDeclInfo;
74 typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy;
Samuel Antao6890b092016-07-28 14:25:09 +000075 /// Struct that associates a component with the clause kind where they are
76 /// found.
77 struct MappedExprComponentTy {
78 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
79 OpenMPClauseKind Kind = OMPC_unknown;
80 };
81 typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy>
Samuel Antao90927002016-04-26 14:54:23 +000082 MappedExprComponentsTy;
Alexey Bataev28c75412015-12-15 08:19:24 +000083 typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
84 CriticalsWithHintsTy;
Alexey Bataev8b427062016-05-25 12:36:08 +000085 typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>
86 DoacrossDependMapTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +000087
Alexey Bataev7ace49d2016-05-17 08:55:33 +000088 struct SharingMapTy final {
Alexey Bataev758e55e2013-09-06 18:03:48 +000089 DeclSAMapTy SharingMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000090 AlignedMapTy AlignedMap;
Samuel Antao90927002016-04-26 14:54:23 +000091 MappedExprComponentsTy MappedExprComponents;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000092 LoopControlVariablesMapTy LCVMap;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000093 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
Alexey Bataevbae9a792014-06-27 10:37:06 +000094 SourceLocation DefaultAttrLoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000095 OpenMPDirectiveKind Directive = OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +000096 DeclarationNameInfo DirectiveName;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000097 Scope *CurScope = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000098 SourceLocation ConstructLoc;
Alexey Bataev8b427062016-05-25 12:36:08 +000099 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
100 /// get the data (loop counters etc.) about enclosing loop-based construct.
101 /// This data is required during codegen.
102 DoacrossDependMapTy DoacrossDepends;
Alexey Bataev346265e2015-09-25 10:37:12 +0000103 /// \brief first argument (Expr *) contains optional argument of the
104 /// 'ordered' clause, the second one is true if the regions has 'ordered'
105 /// clause, false otherwise.
106 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000107 bool NowaitRegion = false;
108 bool CancelRegion = false;
109 unsigned AssociatedLoops = 1;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000110 SourceLocation InnerTeamsRegionLoc;
Alexey Bataeved09d242014-05-28 05:53:51 +0000111 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000112 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000113 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
114 ConstructLoc(Loc) {}
115 SharingMapTy() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +0000116 };
117
Axel Naumann323862e2016-02-03 10:45:22 +0000118 typedef SmallVector<SharingMapTy, 4> StackTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000119
120 /// \brief Stack of used declaration and their data-sharing attributes.
121 StackTy Stack;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000122 /// \brief true, if check for DSA must be from parent directive, false, if
123 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000124 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000125 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000126 bool ForceCapturing = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000127 CriticalsWithHintsTy Criticals;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000128
129 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
130
David Majnemer9d168222016-08-05 17:44:54 +0000131 DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D);
Alexey Bataevec3da872014-01-31 05:15:34 +0000132
133 /// \brief Checks if the variable is a local for OpenMP region.
134 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
Alexey Bataeved09d242014-05-28 05:53:51 +0000135
Alexey Bataev758e55e2013-09-06 18:03:48 +0000136public:
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000137 explicit DSAStackTy(Sema &S) : Stack(1), SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000138
Alexey Bataevaac108a2015-06-23 04:51:00 +0000139 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
140 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000141
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000142 bool isForceVarCapturing() const { return ForceCapturing; }
143 void setForceVarCapturing(bool V) { ForceCapturing = V; }
144
Alexey Bataev758e55e2013-09-06 18:03:48 +0000145 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000146 Scope *CurScope, SourceLocation Loc) {
147 Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
148 Stack.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000149 }
150
151 void pop() {
152 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
153 Stack.pop_back();
154 }
155
Alexey Bataev28c75412015-12-15 08:19:24 +0000156 void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
157 Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
158 }
159 const std::pair<OMPCriticalDirective *, llvm::APSInt>
160 getCriticalWithHint(const DeclarationNameInfo &Name) const {
161 auto I = Criticals.find(Name.getAsString());
162 if (I != Criticals.end())
163 return I->second;
164 return std::make_pair(nullptr, llvm::APSInt());
165 }
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000166 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000167 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000168 /// for diagnostics.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000169 Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000170
Alexey Bataev9c821032015-04-30 04:23:23 +0000171 /// \brief Register specified variable as loop control variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000172 void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
Alexey Bataev9c821032015-04-30 04:23:23 +0000173 /// \brief Check if the specified variable is a loop control variable for
174 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000175 /// \return The index of the loop control variable in the list of associated
176 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000177 LCDeclInfo isLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000178 /// \brief Check if the specified variable is a loop control variable for
179 /// parent region.
180 /// \return The index of the loop control variable in the list of associated
181 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000182 LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000183 /// \brief Get the loop control variable for the I-th loop (or nullptr) in
184 /// parent directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000185 ValueDecl *getParentLoopControlVariable(unsigned I);
Alexey Bataev9c821032015-04-30 04:23:23 +0000186
Alexey Bataev758e55e2013-09-06 18:03:48 +0000187 /// \brief Adds explicit data sharing attribute to the specified declaration.
Alexey Bataev90c228f2016-02-08 09:29:13 +0000188 void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
189 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000190
Alexey Bataev758e55e2013-09-06 18:03:48 +0000191 /// \brief Returns data sharing attributes from top of the stack for the
192 /// specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000193 DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000194 /// \brief Returns data-sharing attributes for the specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000195 DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000196 /// \brief Checks if the specified variables has data-sharing attributes which
197 /// match specified \a CPred predicate in any directive which matches \a DPred
198 /// predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000199 DSAVarData hasDSA(ValueDecl *D,
200 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
201 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
202 bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000203 /// \brief Checks if the specified variables has data-sharing attributes which
204 /// match specified \a CPred predicate in any innermost directive which
205 /// matches \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000206 DSAVarData
207 hasInnermostDSA(ValueDecl *D,
208 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
209 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
210 bool FromParent);
Alexey Bataevaac108a2015-06-23 04:51:00 +0000211 /// \brief Checks if the specified variables has explicit data-sharing
212 /// attributes which match specified \a CPred predicate at the specified
213 /// OpenMP region.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000214 bool hasExplicitDSA(ValueDecl *D,
Alexey Bataevaac108a2015-06-23 04:51:00 +0000215 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000216 unsigned Level, bool NotLastprivate = false);
Samuel Antao4be30e92015-10-02 17:14:03 +0000217
218 /// \brief Returns true if the directive at level \Level matches in the
219 /// specified \a DPred predicate.
220 bool hasExplicitDirective(
221 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
222 unsigned Level);
223
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000224 /// \brief Finds a directive which matches specified \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000225 bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind,
226 const DeclarationNameInfo &,
227 SourceLocation)> &DPred,
228 bool FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000229
Alexey Bataev758e55e2013-09-06 18:03:48 +0000230 /// \brief Returns currently analyzed directive.
231 OpenMPDirectiveKind getCurrentDirective() const {
232 return Stack.back().Directive;
233 }
Alexey Bataev549210e2014-06-24 04:39:47 +0000234 /// \brief Returns parent directive.
235 OpenMPDirectiveKind getParentDirective() const {
236 if (Stack.size() > 2)
237 return Stack[Stack.size() - 2].Directive;
238 return OMPD_unknown;
239 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000240
241 /// \brief Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000242 void setDefaultDSANone(SourceLocation Loc) {
243 Stack.back().DefaultAttr = DSA_none;
244 Stack.back().DefaultAttrLoc = Loc;
245 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000246 /// \brief Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000247 void setDefaultDSAShared(SourceLocation Loc) {
248 Stack.back().DefaultAttr = DSA_shared;
249 Stack.back().DefaultAttrLoc = Loc;
250 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000251
252 DefaultDataSharingAttributes getDefaultDSA() const {
253 return Stack.back().DefaultAttr;
254 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000255 SourceLocation getDefaultDSALocation() const {
256 return Stack.back().DefaultAttrLoc;
257 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000258
Alexey Bataevf29276e2014-06-18 04:14:57 +0000259 /// \brief Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000260 bool isThreadPrivate(VarDecl *D) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000261 DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000262 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000263 }
264
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000265 /// \brief Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataev346265e2015-09-25 10:37:12 +0000266 void setOrderedRegion(bool IsOrdered, Expr *Param) {
267 Stack.back().OrderedRegion.setInt(IsOrdered);
268 Stack.back().OrderedRegion.setPointer(Param);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000269 }
270 /// \brief Returns true, if parent region is ordered (has associated
271 /// 'ordered' clause), false - otherwise.
272 bool isParentOrderedRegion() const {
273 if (Stack.size() > 2)
Alexey Bataev346265e2015-09-25 10:37:12 +0000274 return Stack[Stack.size() - 2].OrderedRegion.getInt();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000275 return false;
276 }
Alexey Bataev346265e2015-09-25 10:37:12 +0000277 /// \brief Returns optional parameter for the ordered region.
278 Expr *getParentOrderedRegionParam() const {
279 if (Stack.size() > 2)
280 return Stack[Stack.size() - 2].OrderedRegion.getPointer();
281 return nullptr;
282 }
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000283 /// \brief Marks current region as nowait (it has a 'nowait' clause).
284 void setNowaitRegion(bool IsNowait = true) {
285 Stack.back().NowaitRegion = IsNowait;
286 }
287 /// \brief Returns true, if parent region is nowait (has associated
288 /// 'nowait' clause), false - otherwise.
289 bool isParentNowaitRegion() const {
290 if (Stack.size() > 2)
291 return Stack[Stack.size() - 2].NowaitRegion;
292 return false;
293 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000294 /// \brief Marks parent region as cancel region.
295 void setParentCancelRegion(bool Cancel = true) {
296 if (Stack.size() > 2)
297 Stack[Stack.size() - 2].CancelRegion =
298 Stack[Stack.size() - 2].CancelRegion || Cancel;
299 }
300 /// \brief Return true if current region has inner cancel construct.
David Majnemer9d168222016-08-05 17:44:54 +0000301 bool isCancelRegion() const { return Stack.back().CancelRegion; }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000302
Alexey Bataev9c821032015-04-30 04:23:23 +0000303 /// \brief Set collapse value for the region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000304 void setAssociatedLoops(unsigned Val) { Stack.back().AssociatedLoops = Val; }
Alexey Bataev9c821032015-04-30 04:23:23 +0000305 /// \brief Return collapse value for region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000306 unsigned getAssociatedLoops() const { return Stack.back().AssociatedLoops; }
Alexey Bataev9c821032015-04-30 04:23:23 +0000307
Alexey Bataev13314bf2014-10-09 04:18:56 +0000308 /// \brief Marks current target region as one with closely nested teams
309 /// region.
310 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
311 if (Stack.size() > 2)
312 Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
313 }
314 /// \brief Returns true, if current region has closely nested teams region.
315 bool hasInnerTeamsRegion() const {
316 return getInnerTeamsRegionLoc().isValid();
317 }
318 /// \brief Returns location of the nested teams region (if any).
319 SourceLocation getInnerTeamsRegionLoc() const {
320 if (Stack.size() > 1)
321 return Stack.back().InnerTeamsRegionLoc;
322 return SourceLocation();
323 }
324
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000325 Scope *getCurScope() const { return Stack.back().CurScope; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000326 Scope *getCurScope() { return Stack.back().CurScope; }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000327 SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000328
Samuel Antao90927002016-04-26 14:54:23 +0000329 // Do the check specified in \a Check to all component lists and return true
330 // if any issue is found.
331 bool checkMappableExprComponentListsForDecl(
332 ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000333 const llvm::function_ref<
334 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
335 OpenMPClauseKind)> &Check) {
Samuel Antao5de996e2016-01-22 20:21:36 +0000336 auto SI = Stack.rbegin();
337 auto SE = Stack.rend();
338
339 if (SI == SE)
340 return false;
341
342 if (CurrentRegionOnly) {
343 SE = std::next(SI);
344 } else {
345 ++SI;
346 }
347
348 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000349 auto MI = SI->MappedExprComponents.find(VD);
350 if (MI != SI->MappedExprComponents.end())
Samuel Antao6890b092016-07-28 14:25:09 +0000351 for (auto &L : MI->second.Components)
352 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000353 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000354 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000355 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000356 }
357
Samuel Antao90927002016-04-26 14:54:23 +0000358 // Create a new mappable expression component list associated with a given
359 // declaration and initialize it with the provided list of components.
360 void addMappableExpressionComponents(
361 ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000362 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
363 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao90927002016-04-26 14:54:23 +0000364 assert(Stack.size() > 1 &&
365 "Not expecting to retrieve components from a empty stack!");
366 auto &MEC = Stack.back().MappedExprComponents[VD];
367 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000368 MEC.Components.resize(MEC.Components.size() + 1);
369 MEC.Components.back().append(Components.begin(), Components.end());
370 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000371 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000372
373 unsigned getNestingLevel() const {
374 assert(Stack.size() > 1);
375 return Stack.size() - 2;
376 }
Alexey Bataev8b427062016-05-25 12:36:08 +0000377 void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) {
378 assert(Stack.size() > 2);
379 assert(isOpenMPWorksharingDirective(Stack[Stack.size() - 2].Directive));
380 Stack[Stack.size() - 2].DoacrossDepends.insert({C, OpsOffs});
381 }
382 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
383 getDoacrossDependClauses() const {
384 assert(Stack.size() > 1);
385 if (isOpenMPWorksharingDirective(Stack[Stack.size() - 1].Directive)) {
386 auto &Ref = Stack[Stack.size() - 1].DoacrossDepends;
387 return llvm::make_range(Ref.begin(), Ref.end());
388 }
389 return llvm::make_range(Stack[0].DoacrossDepends.end(),
390 Stack[0].DoacrossDepends.end());
391 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000392};
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000393bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
Alexey Bataev35aaee62016-04-13 13:36:48 +0000394 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
395 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000396}
Alexey Bataeved09d242014-05-28 05:53:51 +0000397} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000398
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000399static ValueDecl *getCanonicalDecl(ValueDecl *D) {
400 auto *VD = dyn_cast<VarDecl>(D);
401 auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000402 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000403 VD = VD->getCanonicalDecl();
404 D = VD;
405 } else {
406 assert(FD);
407 FD = FD->getCanonicalDecl();
408 D = FD;
409 }
410 return D;
411}
412
David Majnemer9d168222016-08-05 17:44:54 +0000413DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000414 ValueDecl *D) {
415 D = getCanonicalDecl(D);
416 auto *VD = dyn_cast<VarDecl>(D);
417 auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000418 DSAVarData DVar;
Alexey Bataevdf9b1592014-06-25 04:09:13 +0000419 if (Iter == std::prev(Stack.rend())) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000420 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
421 // in a region but not in construct]
422 // File-scope or namespace-scope variables referenced in called routines
423 // in the region are shared unless they appear in a threadprivate
424 // directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000425 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000426 DVar.CKind = OMPC_shared;
427
428 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
429 // in a region but not in construct]
430 // Variables with static storage duration that are declared in called
431 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000432 if (VD && VD->hasGlobalStorage())
433 DVar.CKind = OMPC_shared;
434
435 // Non-static data members are shared by default.
436 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000437 DVar.CKind = OMPC_shared;
438
Alexey Bataev758e55e2013-09-06 18:03:48 +0000439 return DVar;
440 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000441
Alexey Bataev758e55e2013-09-06 18:03:48 +0000442 DVar.DKind = Iter->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +0000443 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
444 // in a Construct, C/C++, predetermined, p.1]
445 // Variables with automatic storage duration that are declared in a scope
446 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000447 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
448 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000449 DVar.CKind = OMPC_private;
450 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000451 }
452
Alexey Bataev758e55e2013-09-06 18:03:48 +0000453 // Explicitly specified attributes and local variables with predetermined
454 // attributes.
455 if (Iter->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000456 DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000457 DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000458 DVar.CKind = Iter->SharingMap[D].Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000459 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000460 return DVar;
461 }
462
463 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
464 // in a Construct, C/C++, implicitly determined, p.1]
465 // In a parallel or task construct, the data-sharing attributes of these
466 // variables are determined by the default clause, if present.
467 switch (Iter->DefaultAttr) {
468 case DSA_shared:
469 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000470 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000471 return DVar;
472 case DSA_none:
473 return DVar;
474 case DSA_unspecified:
475 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
476 // in a Construct, implicitly determined, p.2]
477 // In a parallel construct, if no default clause is present, these
478 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000479 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000480 if (isOpenMPParallelDirective(DVar.DKind) ||
481 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000482 DVar.CKind = OMPC_shared;
483 return DVar;
484 }
485
486 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
487 // in a Construct, implicitly determined, p.4]
488 // In a task construct, if no default clause is present, a variable that in
489 // the enclosing context is determined to be shared by all implicit tasks
490 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000491 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000492 DSAVarData DVarTemp;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000493 for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000494 I != EE; ++I) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000495 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000496 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000497 // In a task construct, if no default clause is present, a variable
498 // whose data-sharing attribute is not determined by the rules above is
499 // firstprivate.
500 DVarTemp = getDSA(I, D);
501 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000502 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000503 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000504 return DVar;
505 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000506 if (isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000507 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000508 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000509 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000510 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000511 return DVar;
512 }
513 }
514 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
515 // in a Construct, implicitly determined, p.3]
516 // For constructs other than task, if no default clause is present, these
517 // variables inherit their data-sharing attributes from the enclosing
518 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000519 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000520}
521
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000522Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000523 assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000524 D = getCanonicalDecl(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000525 auto It = Stack.back().AlignedMap.find(D);
526 if (It == Stack.back().AlignedMap.end()) {
527 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
528 Stack.back().AlignedMap[D] = NewDE;
529 return nullptr;
530 } else {
531 assert(It->second && "Unexpected nullptr expr in the aligned map");
532 return It->second;
533 }
534 return nullptr;
535}
536
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000537void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
Alexey Bataev9c821032015-04-30 04:23:23 +0000538 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000539 D = getCanonicalDecl(D);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000540 Stack.back().LCVMap.insert(
541 std::make_pair(D, LCDeclInfo(Stack.back().LCVMap.size() + 1, Capture)));
Alexey Bataev9c821032015-04-30 04:23:23 +0000542}
543
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000544DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
Alexey Bataev9c821032015-04-30 04:23:23 +0000545 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000546 D = getCanonicalDecl(D);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000547 return Stack.back().LCVMap.count(D) > 0 ? Stack.back().LCVMap[D]
548 : LCDeclInfo(0, nullptr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000549}
550
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000551DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000552 assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000553 D = getCanonicalDecl(D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000554 return Stack[Stack.size() - 2].LCVMap.count(D) > 0
555 ? Stack[Stack.size() - 2].LCVMap[D]
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000556 : LCDeclInfo(0, nullptr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000557}
558
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000559ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000560 assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
561 if (Stack[Stack.size() - 2].LCVMap.size() < I)
562 return nullptr;
563 for (auto &Pair : Stack[Stack.size() - 2].LCVMap) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000564 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000565 return Pair.first;
566 }
567 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +0000568}
569
Alexey Bataev90c228f2016-02-08 09:29:13 +0000570void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
571 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000572 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000573 if (A == OMPC_threadprivate) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000574 auto &Data = Stack[0].SharingMap[D];
575 Data.Attributes = A;
576 Data.RefExpr.setPointer(E);
577 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000578 } else {
579 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000580 auto &Data = Stack.back().SharingMap[D];
581 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
582 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
583 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
584 (isLoopControlVariable(D).first && A == OMPC_private));
585 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
586 Data.RefExpr.setInt(/*IntVal=*/true);
587 return;
588 }
589 const bool IsLastprivate =
590 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
591 Data.Attributes = A;
592 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
593 Data.PrivateCopy = PrivateCopy;
594 if (PrivateCopy) {
595 auto &Data = Stack.back().SharingMap[PrivateCopy->getDecl()];
596 Data.Attributes = A;
597 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
598 Data.PrivateCopy = nullptr;
599 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000600 }
601}
602
Alexey Bataeved09d242014-05-28 05:53:51 +0000603bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000604 D = D->getCanonicalDecl();
Alexey Bataevec3da872014-01-31 05:15:34 +0000605 if (Stack.size() > 2) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000606 reverse_iterator I = Iter, E = std::prev(Stack.rend());
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000607 Scope *TopScope = nullptr;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000608 while (I != E && !isParallelOrTaskRegion(I->Directive)) {
Alexey Bataevec3da872014-01-31 05:15:34 +0000609 ++I;
610 }
Alexey Bataeved09d242014-05-28 05:53:51 +0000611 if (I == E)
612 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000613 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000614 Scope *CurScope = getCurScope();
615 while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000616 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000617 }
618 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000619 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000620 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000621}
622
Alexey Bataev39f915b82015-05-08 10:41:21 +0000623/// \brief Build a variable declaration for OpenMP loop iteration variable.
624static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000625 StringRef Name, const AttrVec *Attrs = nullptr) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000626 DeclContext *DC = SemaRef.CurContext;
627 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
628 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
629 VarDecl *Decl =
630 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000631 if (Attrs) {
632 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
633 I != E; ++I)
634 Decl->addAttr(*I);
635 }
Alexey Bataev39f915b82015-05-08 10:41:21 +0000636 Decl->setImplicit();
637 return Decl;
638}
639
640static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
641 SourceLocation Loc,
642 bool RefersToCapture = false) {
643 D->setReferenced();
644 D->markUsed(S.Context);
645 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
646 SourceLocation(), D, RefersToCapture, Loc, Ty,
647 VK_LValue);
648}
649
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000650DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
651 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000652 DSAVarData DVar;
653
654 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
655 // in a Construct, C/C++, predetermined, p.1]
656 // Variables appearing in threadprivate directives are threadprivate.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000657 auto *VD = dyn_cast<VarDecl>(D);
658 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
659 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
Samuel Antaof8b50122015-07-13 22:54:53 +0000660 SemaRef.getLangOpts().OpenMPUseTLS &&
661 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000662 (VD && VD->getStorageClass() == SC_Register &&
663 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
664 addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
Alexey Bataev39f915b82015-05-08 10:41:21 +0000665 D->getLocation()),
Alexey Bataevf2453a02015-05-06 07:25:08 +0000666 OMPC_threadprivate);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000667 }
668 if (Stack[0].SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000669 DVar.RefExpr = Stack[0].SharingMap[D].RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000670 DVar.CKind = OMPC_threadprivate;
671 return DVar;
672 }
673
Dmitry Polukhin0b0da292016-04-06 11:38:59 +0000674 if (Stack.size() == 1) {
675 // Not in OpenMP execution region and top scope was already checked.
676 return DVar;
677 }
678
Alexey Bataev758e55e2013-09-06 18:03:48 +0000679 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000680 // in a Construct, C/C++, predetermined, p.4]
681 // Static data members are shared.
682 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
683 // in a Construct, C/C++, predetermined, p.7]
684 // Variables with static storage duration that are declared in a scope
685 // inside the construct are shared.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000686 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000687 if (VD && VD->isStaticDataMember()) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000688 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000689 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
Alexey Bataevec3da872014-01-31 05:15:34 +0000690 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000691
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000692 DVar.CKind = OMPC_shared;
693 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000694 }
695
696 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000697 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
698 Type = SemaRef.getASTContext().getBaseElementType(Type);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000699 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
700 // in a Construct, C/C++, predetermined, p.6]
701 // Variables with const qualified type having no mutable member are
702 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000703 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +0000704 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataevc9bd03d2015-12-17 06:55:08 +0000705 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
706 if (auto *CTD = CTSD->getSpecializedTemplate())
707 RD = CTD->getTemplatedDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000708 if (IsConstant &&
Alexey Bataev4bcad7f2016-02-10 10:50:12 +0000709 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
710 RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000711 // Variables with const-qualified type having no mutable member may be
712 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000713 DSAVarData DVarTemp = hasDSA(
714 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
715 MatchesAlways, FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000716 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
717 return DVar;
718
Alexey Bataev758e55e2013-09-06 18:03:48 +0000719 DVar.CKind = OMPC_shared;
720 return DVar;
721 }
722
Alexey Bataev758e55e2013-09-06 18:03:48 +0000723 // Explicitly specified attributes and local variables with predetermined
724 // attributes.
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000725 auto StartI = std::next(Stack.rbegin());
726 auto EndI = std::prev(Stack.rend());
727 if (FromParent && StartI != EndI) {
728 StartI = std::next(StartI);
729 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000730 auto I = std::prev(StartI);
731 if (I->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000732 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000733 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000734 DVar.CKind = I->SharingMap[D].Attributes;
735 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000736 }
737
738 return DVar;
739}
740
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000741DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
742 bool FromParent) {
743 D = getCanonicalDecl(D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000744 auto StartI = Stack.rbegin();
745 auto EndI = std::prev(Stack.rend());
746 if (FromParent && StartI != EndI) {
747 StartI = std::next(StartI);
748 }
749 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000750}
751
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000752DSAStackTy::DSAVarData
753DSAStackTy::hasDSA(ValueDecl *D,
754 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
755 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
756 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000757 D = getCanonicalDecl(D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000758 auto StartI = std::next(Stack.rbegin());
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000759 auto EndI = Stack.rend();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000760 if (FromParent && StartI != EndI) {
761 StartI = std::next(StartI);
762 }
763 for (auto I = StartI, EE = EndI; I != EE; ++I) {
764 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000765 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000766 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000767 if (CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000768 return DVar;
769 }
770 return DSAVarData();
771}
772
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000773DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
774 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
775 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
776 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000777 D = getCanonicalDecl(D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000778 auto StartI = std::next(Stack.rbegin());
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000779 auto EndI = Stack.rend();
Alexey Bataeve3978122016-07-19 05:06:39 +0000780 if (FromParent && StartI != EndI)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000781 StartI = std::next(StartI);
Alexey Bataeve3978122016-07-19 05:06:39 +0000782 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataevc5e02582014-06-16 07:08:35 +0000783 return DSAVarData();
Alexey Bataeve3978122016-07-19 05:06:39 +0000784 DSAVarData DVar = getDSA(StartI, D);
785 return CPred(DVar.CKind) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +0000786}
787
Alexey Bataevaac108a2015-06-23 04:51:00 +0000788bool DSAStackTy::hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000789 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000790 unsigned Level, bool NotLastprivate) {
Alexey Bataevaac108a2015-06-23 04:51:00 +0000791 if (CPred(ClauseKindMode))
792 return true;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000793 D = getCanonicalDecl(D);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000794 auto StartI = std::next(Stack.begin());
795 auto EndI = Stack.end();
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +0000796 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +0000797 return false;
798 std::advance(StartI, Level);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000799 return (StartI->SharingMap.count(D) > 0) &&
800 StartI->SharingMap[D].RefExpr.getPointer() &&
801 CPred(StartI->SharingMap[D].Attributes) &&
802 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
Alexey Bataevaac108a2015-06-23 04:51:00 +0000803}
804
Samuel Antao4be30e92015-10-02 17:14:03 +0000805bool DSAStackTy::hasExplicitDirective(
806 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
807 unsigned Level) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000808 auto StartI = std::next(Stack.begin());
809 auto EndI = Stack.end();
Samuel Antao4be30e92015-10-02 17:14:03 +0000810 if (std::distance(StartI, EndI) <= (int)Level)
811 return false;
812 std::advance(StartI, Level);
813 return DPred(StartI->Directive);
814}
815
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000816bool DSAStackTy::hasDirective(
817 const llvm::function_ref<bool(OpenMPDirectiveKind,
818 const DeclarationNameInfo &, SourceLocation)>
819 &DPred,
820 bool FromParent) {
Samuel Antaof0d79752016-05-27 15:21:27 +0000821 // We look only in the enclosing region.
822 if (Stack.size() < 2)
823 return false;
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000824 auto StartI = std::next(Stack.rbegin());
825 auto EndI = std::prev(Stack.rend());
826 if (FromParent && StartI != EndI) {
827 StartI = std::next(StartI);
828 }
829 for (auto I = StartI, EE = EndI; I != EE; ++I) {
830 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
831 return true;
832 }
833 return false;
834}
835
Alexey Bataev758e55e2013-09-06 18:03:48 +0000836void Sema::InitDataSharingAttributesStack() {
837 VarDataSharingAttributesStack = new DSAStackTy(*this);
838}
839
840#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
841
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000842bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000843 assert(LangOpts.OpenMP && "OpenMP is not allowed");
844
845 auto &Ctx = getASTContext();
846 bool IsByRef = true;
847
848 // Find the directive that is associated with the provided scope.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000849 auto Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000850
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000851 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000852 // This table summarizes how a given variable should be passed to the device
853 // given its type and the clauses where it appears. This table is based on
854 // the description in OpenMP 4.5 [2.10.4, target Construct] and
855 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
856 //
857 // =========================================================================
858 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
859 // | |(tofrom:scalar)| | pvt | | | |
860 // =========================================================================
861 // | scl | | | | - | | bycopy|
862 // | scl | | - | x | - | - | bycopy|
863 // | scl | | x | - | - | - | null |
864 // | scl | x | | | - | | byref |
865 // | scl | x | - | x | - | - | bycopy|
866 // | scl | x | x | - | - | - | null |
867 // | scl | | - | - | - | x | byref |
868 // | scl | x | - | - | - | x | byref |
869 //
870 // | agg | n.a. | | | - | | byref |
871 // | agg | n.a. | - | x | - | - | byref |
872 // | agg | n.a. | x | - | - | - | null |
873 // | agg | n.a. | - | - | - | x | byref |
874 // | agg | n.a. | - | - | - | x[] | byref |
875 //
876 // | ptr | n.a. | | | - | | bycopy|
877 // | ptr | n.a. | - | x | - | - | bycopy|
878 // | ptr | n.a. | x | - | - | - | null |
879 // | ptr | n.a. | - | - | - | x | byref |
880 // | ptr | n.a. | - | - | - | x[] | bycopy|
881 // | ptr | n.a. | - | - | x | | bycopy|
882 // | ptr | n.a. | - | - | x | x | bycopy|
883 // | ptr | n.a. | - | - | x | x[] | bycopy|
884 // =========================================================================
885 // Legend:
886 // scl - scalar
887 // ptr - pointer
888 // agg - aggregate
889 // x - applies
890 // - - invalid in this combination
891 // [] - mapped with an array section
892 // byref - should be mapped by reference
893 // byval - should be mapped by value
894 // null - initialize a local variable to null on the device
895 //
896 // Observations:
897 // - All scalar declarations that show up in a map clause have to be passed
898 // by reference, because they may have been mapped in the enclosing data
899 // environment.
900 // - If the scalar value does not fit the size of uintptr, it has to be
901 // passed by reference, regardless the result in the table above.
902 // - For pointers mapped by value that have either an implicit map or an
903 // array section, the runtime library may pass the NULL value to the
904 // device instead of the value passed to it by the compiler.
905
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000906 if (Ty->isReferenceType())
907 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +0000908
909 // Locate map clauses and see if the variable being captured is referred to
910 // in any of those clauses. Here we only care about variables, not fields,
911 // because fields are part of aggregates.
912 bool IsVariableUsedInMapClause = false;
913 bool IsVariableAssociatedWithSection = false;
914
915 DSAStack->checkMappableExprComponentListsForDecl(
916 D, /*CurrentRegionOnly=*/true,
917 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +0000918 MapExprComponents,
919 OpenMPClauseKind WhereFoundClauseKind) {
920 // Only the map clause information influences how a variable is
921 // captured. E.g. is_device_ptr does not require changing the default
922 // behaviour.
923 if (WhereFoundClauseKind != OMPC_map)
924 return false;
Samuel Antao86ace552016-04-27 22:40:57 +0000925
926 auto EI = MapExprComponents.rbegin();
927 auto EE = MapExprComponents.rend();
928
929 assert(EI != EE && "Invalid map expression!");
930
931 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
932 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
933
934 ++EI;
935 if (EI == EE)
936 return false;
937
938 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
939 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
940 isa<MemberExpr>(EI->getAssociatedExpression())) {
941 IsVariableAssociatedWithSection = true;
942 // There is nothing more we need to know about this variable.
943 return true;
944 }
945
946 // Keep looking for more map info.
947 return false;
948 });
949
950 if (IsVariableUsedInMapClause) {
951 // If variable is identified in a map clause it is always captured by
952 // reference except if it is a pointer that is dereferenced somehow.
953 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
954 } else {
955 // By default, all the data that has a scalar type is mapped by copy.
956 IsByRef = !Ty->isScalarType();
957 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000958 }
959
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000960 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
961 IsByRef = !DSAStack->hasExplicitDSA(
962 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
963 Level, /*NotLastprivate=*/true);
964 }
965
Samuel Antao86ace552016-04-27 22:40:57 +0000966 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000967 // and alignment, because the runtime library only deals with uintptr types.
968 // If it does not fit the uintptr size, we need to pass the data by reference
969 // instead.
970 if (!IsByRef &&
971 (Ctx.getTypeSizeInChars(Ty) >
972 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000973 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000974 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000975 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000976
977 return IsByRef;
978}
979
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000980unsigned Sema::getOpenMPNestingLevel() const {
981 assert(getLangOpts().OpenMP);
982 return DSAStack->getNestingLevel();
983}
984
Alexey Bataev90c228f2016-02-08 09:29:13 +0000985VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
Alexey Bataevf841bd92014-12-16 07:00:22 +0000986 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000987 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +0000988
989 // If we are attempting to capture a global variable in a directive with
990 // 'target' we return true so that this global is also mapped to the device.
991 //
992 // FIXME: If the declaration is enclosed in a 'declare target' directive,
993 // then it should not be captured. Therefore, an extra check has to be
994 // inserted here once support for 'declare target' is added.
995 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000996 auto *VD = dyn_cast<VarDecl>(D);
997 if (VD && !VD->hasLocalStorage()) {
Samuel Antao4be30e92015-10-02 17:14:03 +0000998 if (DSAStack->getCurrentDirective() == OMPD_target &&
Alexey Bataev90c228f2016-02-08 09:29:13 +0000999 !DSAStack->isClauseParsingMode())
1000 return VD;
Samuel Antaof0d79752016-05-27 15:21:27 +00001001 if (DSAStack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001002 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1003 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001004 return isOpenMPTargetExecutionDirective(K);
Samuel Antao4be30e92015-10-02 17:14:03 +00001005 },
Alexey Bataev90c228f2016-02-08 09:29:13 +00001006 false))
1007 return VD;
Samuel Antao4be30e92015-10-02 17:14:03 +00001008 }
1009
Alexey Bataev48977c32015-08-04 08:10:48 +00001010 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1011 (!DSAStack->isClauseParsingMode() ||
1012 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001013 auto &&Info = DSAStack->isLoopControlVariable(D);
1014 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001015 (VD && VD->hasLocalStorage() &&
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001016 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001017 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001018 return VD ? VD : Info.second;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001019 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001020 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001021 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001022 DVarPrivate = DSAStack->hasDSA(
1023 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1024 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +00001025 if (DVarPrivate.CKind != OMPC_unknown)
1026 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001027 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001028 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001029}
1030
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001031bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001032 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1033 return DSAStack->hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001034 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
Alexey Bataevaac108a2015-06-23 04:51:00 +00001035}
1036
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001037bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
Samuel Antao4be30e92015-10-02 17:14:03 +00001038 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1039 // Return true if the current level is no longer enclosed in a target region.
1040
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001041 auto *VD = dyn_cast<VarDecl>(D);
1042 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001043 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1044 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001045}
1046
Alexey Bataeved09d242014-05-28 05:53:51 +00001047void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001048
1049void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1050 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001051 Scope *CurScope, SourceLocation Loc) {
1052 DSAStack->push(DKind, DirName, CurScope, Loc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001053 PushExpressionEvaluationContext(PotentiallyEvaluated);
1054}
1055
Alexey Bataevaac108a2015-06-23 04:51:00 +00001056void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1057 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001058}
1059
Alexey Bataevaac108a2015-06-23 04:51:00 +00001060void Sema::EndOpenMPClause() {
1061 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001062}
1063
Alexey Bataev758e55e2013-09-06 18:03:48 +00001064void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001065 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1066 // A variable of class type (or array thereof) that appears in a lastprivate
1067 // clause requires an accessible, unambiguous default constructor for the
1068 // class type, unless the list item is also specified in a firstprivate
1069 // clause.
David Majnemer9d168222016-08-05 17:44:54 +00001070 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001071 for (auto *C : D->clauses()) {
1072 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1073 SmallVector<Expr *, 8> PrivateCopies;
1074 for (auto *DE : Clause->varlists()) {
1075 if (DE->isValueDependent() || DE->isTypeDependent()) {
1076 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001077 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001078 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001079 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataev005248a2016-02-25 05:25:57 +00001080 VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1081 QualType Type = VD->getType().getNonReferenceType();
1082 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001083 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001084 // Generate helper private variable and initialize it with the
1085 // default value. The address of the original variable is replaced
1086 // by the address of the new private variable in CodeGen. This new
1087 // variable is not added to IdResolver, so the code in the OpenMP
1088 // region uses original variable for proper diagnostics.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001089 auto *VDPrivate = buildVarDecl(
1090 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev005248a2016-02-25 05:25:57 +00001091 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev38e89532015-04-16 04:54:05 +00001092 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
1093 if (VDPrivate->isInvalidDecl())
1094 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001095 PrivateCopies.push_back(buildDeclRefExpr(
1096 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001097 } else {
1098 // The variable is also a firstprivate, so initialization sequence
1099 // for private copy is generated already.
1100 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001101 }
1102 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001103 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001104 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001105 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001106 }
1107 }
1108 }
1109
Alexey Bataev758e55e2013-09-06 18:03:48 +00001110 DSAStack->pop();
1111 DiscardCleanupsInEvaluationContext();
1112 PopExpressionEvaluationContext();
1113}
1114
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001115static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1116 Expr *NumIterations, Sema &SemaRef,
1117 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001118
Alexey Bataeva769e072013-03-22 06:34:35 +00001119namespace {
1120
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001121class VarDeclFilterCCC : public CorrectionCandidateCallback {
1122private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001123 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001124
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001125public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001126 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001127 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001128 NamedDecl *ND = Candidate.getCorrectionDecl();
David Majnemer9d168222016-08-05 17:44:54 +00001129 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001130 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001131 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1132 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001133 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001134 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001135 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001136};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001137
1138class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1139private:
1140 Sema &SemaRef;
1141
1142public:
1143 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1144 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1145 NamedDecl *ND = Candidate.getCorrectionDecl();
1146 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
1147 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1148 SemaRef.getCurScope());
1149 }
1150 return false;
1151 }
1152};
1153
Alexey Bataeved09d242014-05-28 05:53:51 +00001154} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001155
1156ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1157 CXXScopeSpec &ScopeSpec,
1158 const DeclarationNameInfo &Id) {
1159 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1160 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1161
1162 if (Lookup.isAmbiguous())
1163 return ExprError();
1164
1165 VarDecl *VD;
1166 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001167 if (TypoCorrection Corrected = CorrectTypo(
1168 Id, LookupOrdinaryName, CurScope, nullptr,
1169 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001170 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001171 PDiag(Lookup.empty()
1172 ? diag::err_undeclared_var_use_suggest
1173 : diag::err_omp_expected_var_arg_suggest)
1174 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001175 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001176 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001177 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1178 : diag::err_omp_expected_var_arg)
1179 << Id.getName();
1180 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001181 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001182 } else {
1183 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00001184 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001185 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1186 return ExprError();
1187 }
1188 }
1189 Lookup.suppressDiagnostics();
1190
1191 // OpenMP [2.9.2, Syntax, C/C++]
1192 // Variables must be file-scope, namespace-scope, or static block-scope.
1193 if (!VD->hasGlobalStorage()) {
1194 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001195 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1196 bool IsDecl =
1197 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001198 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00001199 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1200 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001201 return ExprError();
1202 }
1203
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001204 VarDecl *CanonicalVD = VD->getCanonicalDecl();
1205 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001206 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1207 // A threadprivate directive for file-scope variables must appear outside
1208 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001209 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1210 !getCurLexicalContext()->isTranslationUnit()) {
1211 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001212 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1213 bool IsDecl =
1214 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1215 Diag(VD->getLocation(),
1216 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1217 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001218 return ExprError();
1219 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001220 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1221 // A threadprivate directive for static class member variables must appear
1222 // in the class definition, in the same scope in which the member
1223 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001224 if (CanonicalVD->isStaticDataMember() &&
1225 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1226 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001227 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1228 bool IsDecl =
1229 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1230 Diag(VD->getLocation(),
1231 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1232 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001233 return ExprError();
1234 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001235 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1236 // A threadprivate directive for namespace-scope variables must appear
1237 // outside any definition or declaration other than the namespace
1238 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001239 if (CanonicalVD->getDeclContext()->isNamespace() &&
1240 (!getCurLexicalContext()->isFileContext() ||
1241 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1242 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001243 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1244 bool IsDecl =
1245 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1246 Diag(VD->getLocation(),
1247 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1248 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001249 return ExprError();
1250 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001251 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1252 // A threadprivate directive for static block-scope variables must appear
1253 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001254 if (CanonicalVD->isStaticLocal() && CurScope &&
1255 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001256 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001257 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1258 bool IsDecl =
1259 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1260 Diag(VD->getLocation(),
1261 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1262 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001263 return ExprError();
1264 }
1265
1266 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1267 // A threadprivate directive must lexically precede all references to any
1268 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001269 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001270 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +00001271 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001272 return ExprError();
1273 }
1274
1275 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00001276 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1277 SourceLocation(), VD,
1278 /*RefersToEnclosingVariableOrCapture=*/false,
1279 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001280}
1281
Alexey Bataeved09d242014-05-28 05:53:51 +00001282Sema::DeclGroupPtrTy
1283Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1284 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001285 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001286 CurContext->addDecl(D);
1287 return DeclGroupPtrTy::make(DeclGroupRef(D));
1288 }
David Blaikie0403cb12016-01-15 23:43:25 +00001289 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00001290}
1291
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001292namespace {
1293class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1294 Sema &SemaRef;
1295
1296public:
1297 bool VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer9d168222016-08-05 17:44:54 +00001298 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001299 if (VD->hasLocalStorage()) {
1300 SemaRef.Diag(E->getLocStart(),
1301 diag::err_omp_local_var_in_threadprivate_init)
1302 << E->getSourceRange();
1303 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1304 << VD << VD->getSourceRange();
1305 return true;
1306 }
1307 }
1308 return false;
1309 }
1310 bool VisitStmt(const Stmt *S) {
1311 for (auto Child : S->children()) {
1312 if (Child && Visit(Child))
1313 return true;
1314 }
1315 return false;
1316 }
Alexey Bataev23b69422014-06-18 07:08:49 +00001317 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001318};
1319} // namespace
1320
Alexey Bataeved09d242014-05-28 05:53:51 +00001321OMPThreadPrivateDecl *
1322Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001323 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00001324 for (auto &RefExpr : VarList) {
1325 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001326 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1327 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00001328
Alexey Bataev376b4a42016-02-09 09:41:09 +00001329 // Mark variable as used.
1330 VD->setReferenced();
1331 VD->markUsed(Context);
1332
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001333 QualType QType = VD->getType();
1334 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1335 // It will be analyzed later.
1336 Vars.push_back(DE);
1337 continue;
1338 }
1339
Alexey Bataeva769e072013-03-22 06:34:35 +00001340 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1341 // A threadprivate variable must not have an incomplete type.
1342 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001343 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001344 continue;
1345 }
1346
1347 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1348 // A threadprivate variable must not have a reference type.
1349 if (VD->getType()->isReferenceType()) {
1350 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001351 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1352 bool IsDecl =
1353 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1354 Diag(VD->getLocation(),
1355 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1356 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001357 continue;
1358 }
1359
Samuel Antaof8b50122015-07-13 22:54:53 +00001360 // Check if this is a TLS variable. If TLS is not being supported, produce
1361 // the corresponding diagnostic.
1362 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1363 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1364 getLangOpts().OpenMPUseTLS &&
1365 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00001366 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1367 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00001368 Diag(ILoc, diag::err_omp_var_thread_local)
1369 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00001370 bool IsDecl =
1371 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1372 Diag(VD->getLocation(),
1373 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1374 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001375 continue;
1376 }
1377
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001378 // Check if initial value of threadprivate variable reference variable with
1379 // local storage (it is not supported by runtime).
1380 if (auto Init = VD->getAnyInitializer()) {
1381 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001382 if (Checker.Visit(Init))
1383 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001384 }
1385
Alexey Bataeved09d242014-05-28 05:53:51 +00001386 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00001387 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00001388 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1389 Context, SourceRange(Loc, Loc)));
1390 if (auto *ML = Context.getASTMutationListener())
1391 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00001392 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001393 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001394 if (!Vars.empty()) {
1395 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1396 Vars);
1397 D->setAccess(AS_public);
1398 }
1399 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00001400}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001401
Alexey Bataev7ff55242014-06-19 09:13:45 +00001402static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001403 const ValueDecl *D, DSAStackTy::DSAVarData DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00001404 bool IsLoopIterVar = false) {
1405 if (DVar.RefExpr) {
1406 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1407 << getOpenMPClauseName(DVar.CKind);
1408 return;
1409 }
1410 enum {
1411 PDSA_StaticMemberShared,
1412 PDSA_StaticLocalVarShared,
1413 PDSA_LoopIterVarPrivate,
1414 PDSA_LoopIterVarLinear,
1415 PDSA_LoopIterVarLastprivate,
1416 PDSA_ConstVarShared,
1417 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001418 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001419 PDSA_LocalVarPrivate,
1420 PDSA_Implicit
1421 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001422 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001423 auto ReportLoc = D->getLocation();
1424 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00001425 if (IsLoopIterVar) {
1426 if (DVar.CKind == OMPC_private)
1427 Reason = PDSA_LoopIterVarPrivate;
1428 else if (DVar.CKind == OMPC_lastprivate)
1429 Reason = PDSA_LoopIterVarLastprivate;
1430 else
1431 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00001432 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1433 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001434 Reason = PDSA_TaskVarFirstprivate;
1435 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001436 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001437 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001438 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001439 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001440 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001441 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001442 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00001443 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001444 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001445 ReportHint = true;
1446 Reason = PDSA_LocalVarPrivate;
1447 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001448 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001449 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001450 << Reason << ReportHint
1451 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1452 } else if (DVar.ImplicitDSALoc.isValid()) {
1453 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1454 << getOpenMPClauseName(DVar.CKind);
1455 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001456}
1457
Alexey Bataev758e55e2013-09-06 18:03:48 +00001458namespace {
1459class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1460 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001461 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001462 bool ErrorFound;
1463 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001464 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001465 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataeved09d242014-05-28 05:53:51 +00001466
Alexey Bataev758e55e2013-09-06 18:03:48 +00001467public:
1468 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001469 if (E->isTypeDependent() || E->isValueDependent() ||
1470 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1471 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001472 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001473 // Skip internally declared variables.
Alexey Bataeved09d242014-05-28 05:53:51 +00001474 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1475 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001476
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001477 auto DVar = Stack->getTopDSA(VD, false);
1478 // Check if the variable has explicit DSA set and stop analysis if it so.
David Majnemer9d168222016-08-05 17:44:54 +00001479 if (DVar.RefExpr)
1480 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001481
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001482 auto ELoc = E->getExprLoc();
1483 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001484 // The default(none) clause requires that each variable that is referenced
1485 // in the construct, and does not have a predetermined data-sharing
1486 // attribute, must have its data-sharing attribute explicitly determined
1487 // by being listed in a data-sharing attribute clause.
1488 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001489 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001490 VarsWithInheritedDSA.count(VD) == 0) {
1491 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001492 return;
1493 }
1494
1495 // OpenMP [2.9.3.6, Restrictions, p.2]
1496 // A list item that appears in a reduction clause of the innermost
1497 // enclosing worksharing or parallel construct may not be accessed in an
1498 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001499 DVar = Stack->hasInnermostDSA(
1500 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1501 [](OpenMPDirectiveKind K) -> bool {
1502 return isOpenMPParallelDirective(K) ||
1503 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1504 },
1505 false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001506 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00001507 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001508 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1509 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001510 return;
1511 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001512
1513 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001514 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001515 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1516 !Stack->isLoopControlVariable(VD).first)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001517 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001518 }
1519 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001520 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001521 if (E->isTypeDependent() || E->isValueDependent() ||
1522 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1523 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001524 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
1525 if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
1526 auto DVar = Stack->getTopDSA(FD, false);
1527 // Check if the variable has explicit DSA set and stop analysis if it
1528 // so.
1529 if (DVar.RefExpr)
1530 return;
1531
1532 auto ELoc = E->getExprLoc();
1533 auto DKind = Stack->getCurrentDirective();
1534 // OpenMP [2.9.3.6, Restrictions, p.2]
1535 // A list item that appears in a reduction clause of the innermost
1536 // enclosing worksharing or parallel construct may not be accessed in
Alexey Bataevd985eda2016-02-10 11:29:16 +00001537 // an explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001538 DVar = Stack->hasInnermostDSA(
1539 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1540 [](OpenMPDirectiveKind K) -> bool {
1541 return isOpenMPParallelDirective(K) ||
1542 isOpenMPWorksharingDirective(K) ||
1543 isOpenMPTeamsDirective(K);
1544 },
1545 false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001546 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001547 ErrorFound = true;
1548 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1549 ReportOriginalDSA(SemaRef, Stack, FD, DVar);
1550 return;
1551 }
1552
1553 // Define implicit data-sharing attributes for task.
1554 DVar = Stack->getImplicitDSA(FD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001555 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1556 !Stack->isLoopControlVariable(FD).first)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001557 ImplicitFirstprivate.push_back(E);
1558 }
1559 }
1560 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001561 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001562 for (auto *C : S->clauses()) {
1563 // Skip analysis of arguments of implicitly defined firstprivate clause
1564 // for task directives.
1565 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1566 for (auto *CC : C->children()) {
1567 if (CC)
1568 Visit(CC);
1569 }
1570 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001571 }
1572 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001573 for (auto *C : S->children()) {
1574 if (C && !isa<OMPExecutableDirective>(C))
1575 Visit(C);
1576 }
Alexey Bataeved09d242014-05-28 05:53:51 +00001577 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001578
1579 bool isErrorFound() { return ErrorFound; }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001580 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001581 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
Alexey Bataev4acb8592014-07-07 13:01:15 +00001582 return VarsWithInheritedDSA;
1583 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001584
Alexey Bataev7ff55242014-06-19 09:13:45 +00001585 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1586 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00001587};
Alexey Bataeved09d242014-05-28 05:53:51 +00001588} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00001589
Alexey Bataevbae9a792014-06-27 10:37:06 +00001590void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001591 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00001592 case OMPD_parallel:
1593 case OMPD_parallel_for:
1594 case OMPD_parallel_for_simd:
1595 case OMPD_parallel_sections:
1596 case OMPD_teams: {
Alexey Bataev9959db52014-05-06 10:08:46 +00001597 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001598 QualType KmpInt32PtrTy =
1599 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001600 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001601 std::make_pair(".global_tid.", KmpInt32PtrTy),
1602 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1603 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001604 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001605 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1606 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001607 break;
1608 }
Kelvin Li70a12c52016-07-13 21:51:49 +00001609 case OMPD_simd:
1610 case OMPD_for:
1611 case OMPD_for_simd:
1612 case OMPD_sections:
1613 case OMPD_section:
1614 case OMPD_single:
1615 case OMPD_master:
1616 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00001617 case OMPD_taskgroup:
1618 case OMPD_distribute:
Kelvin Li70a12c52016-07-13 21:51:49 +00001619 case OMPD_ordered:
1620 case OMPD_atomic:
1621 case OMPD_target_data:
1622 case OMPD_target:
1623 case OMPD_target_parallel:
1624 case OMPD_target_parallel_for:
Kelvin Li986330c2016-07-20 22:57:10 +00001625 case OMPD_target_parallel_for_simd:
1626 case OMPD_target_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001627 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001628 std::make_pair(StringRef(), QualType()) // __context with shared vars
1629 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001630 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1631 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001632 break;
1633 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001634 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001635 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001636 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1637 FunctionProtoType::ExtProtoInfo EPI;
1638 EPI.Variadic = true;
1639 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001640 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001641 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataev48591dd2016-04-20 04:01:36 +00001642 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1643 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
1644 std::make_pair(".copy_fn.",
1645 Context.getPointerType(CopyFnType).withConst()),
1646 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001647 std::make_pair(StringRef(), QualType()) // __context with shared vars
1648 };
1649 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1650 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001651 // Mark this captured region as inlined, because we don't use outlined
1652 // function directly.
1653 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1654 AlwaysInlineAttr::CreateImplicit(
1655 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001656 break;
1657 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00001658 case OMPD_taskloop:
1659 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00001660 QualType KmpInt32Ty =
1661 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1662 QualType KmpUInt64Ty =
1663 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
1664 QualType KmpInt64Ty =
1665 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
1666 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1667 FunctionProtoType::ExtProtoInfo EPI;
1668 EPI.Variadic = true;
1669 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00001670 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00001671 std::make_pair(".global_tid.", KmpInt32Ty),
1672 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1673 std::make_pair(".privates.",
1674 Context.VoidPtrTy.withConst().withRestrict()),
1675 std::make_pair(
1676 ".copy_fn.",
1677 Context.getPointerType(CopyFnType).withConst().withRestrict()),
1678 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1679 std::make_pair(".lb.", KmpUInt64Ty),
1680 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
1681 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataev49f6e782015-12-01 04:18:41 +00001682 std::make_pair(StringRef(), QualType()) // __context with shared vars
1683 };
1684 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1685 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00001686 // Mark this captured region as inlined, because we don't use outlined
1687 // function directly.
1688 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1689 AlwaysInlineAttr::CreateImplicit(
1690 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev49f6e782015-12-01 04:18:41 +00001691 break;
1692 }
Kelvin Li4a39add2016-07-05 05:00:15 +00001693 case OMPD_distribute_parallel_for_simd:
Kelvin Li787f3fc2016-07-06 04:45:38 +00001694 case OMPD_distribute_simd:
Kelvin Li02532872016-08-05 14:37:37 +00001695 case OMPD_distribute_parallel_for:
Kelvin Li4e325f72016-10-25 12:50:55 +00001696 case OMPD_teams_distribute:
1697 case OMPD_teams_distribute_simd: {
Carlo Bertolli9925f152016-06-27 14:55:37 +00001698 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1699 QualType KmpInt32PtrTy =
1700 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1701 Sema::CapturedParamNameType Params[] = {
1702 std::make_pair(".global_tid.", KmpInt32PtrTy),
1703 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1704 std::make_pair(".previous.lb.", Context.getSizeType()),
1705 std::make_pair(".previous.ub.", Context.getSizeType()),
1706 std::make_pair(StringRef(), QualType()) // __context with shared vars
1707 };
1708 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1709 Params);
1710 break;
1711 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001712 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001713 case OMPD_taskyield:
1714 case OMPD_barrier:
1715 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001716 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00001717 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00001718 case OMPD_flush:
Samuel Antaodf67fc42016-01-19 19:15:56 +00001719 case OMPD_target_enter_data:
Samuel Antao72590762016-01-19 20:04:50 +00001720 case OMPD_target_exit_data:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00001721 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00001722 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001723 case OMPD_declare_target:
1724 case OMPD_end_declare_target:
Samuel Antao686c70c2016-05-26 17:30:50 +00001725 case OMPD_target_update:
Alexey Bataev9959db52014-05-06 10:08:46 +00001726 llvm_unreachable("OpenMP Directive is not allowed");
1727 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001728 llvm_unreachable("Unknown OpenMP directive");
1729 }
1730}
1731
Alexey Bataev3392d762016-02-16 11:18:12 +00001732static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00001733 Expr *CaptureExpr, bool WithInit,
1734 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001735 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00001736 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00001737 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00001738 QualType Ty = Init->getType();
1739 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
1740 if (S.getLangOpts().CPlusPlus)
1741 Ty = C.getLValueReferenceType(Ty);
1742 else {
1743 Ty = C.getPointerType(Ty);
1744 ExprResult Res =
1745 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
1746 if (!Res.isUsable())
1747 return nullptr;
1748 Init = Res.get();
1749 }
Alexey Bataev61205072016-03-02 04:57:40 +00001750 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00001751 }
1752 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001753 if (!WithInit)
1754 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
Alexey Bataev4244be22016-02-11 05:35:55 +00001755 S.CurContext->addHiddenDecl(CED);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001756 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false,
1757 /*TypeMayContainAuto=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00001758 return CED;
1759}
1760
Alexey Bataev61205072016-03-02 04:57:40 +00001761static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
1762 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00001763 OMPCapturedExprDecl *CD;
1764 if (auto *VD = S.IsOpenMPCapturedDecl(D))
1765 CD = cast<OMPCapturedExprDecl>(VD);
1766 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00001767 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
1768 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001769 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00001770 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00001771}
1772
Alexey Bataev5a3af132016-03-29 08:58:54 +00001773static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
1774 if (!Ref) {
1775 auto *CD =
1776 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
1777 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
1778 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
1779 CaptureExpr->getExprLoc());
1780 }
1781 ExprResult Res = Ref;
1782 if (!S.getLangOpts().CPlusPlus &&
1783 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
1784 Ref->getType()->isPointerType())
1785 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
1786 if (!Res.isUsable())
1787 return ExprError();
1788 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00001789}
1790
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001791StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1792 ArrayRef<OMPClause *> Clauses) {
1793 if (!S.isUsable()) {
1794 ActOnCapturedRegionError();
1795 return StmtError();
1796 }
Alexey Bataev993d2802015-12-28 06:23:08 +00001797
1798 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00001799 OMPScheduleClause *SC = nullptr;
Alexey Bataev993d2802015-12-28 06:23:08 +00001800 SmallVector<OMPLinearClause *, 4> LCs;
Alexey Bataev040d5402015-05-12 08:35:28 +00001801 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001802 for (auto *Clause : Clauses) {
Alexey Bataev16dc7b62015-05-20 03:46:04 +00001803 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001804 Clause->getClauseKind() == OMPC_copyprivate ||
1805 (getLangOpts().OpenMPUseTLS &&
1806 getASTContext().getTargetInfo().isTLSSupported() &&
1807 Clause->getClauseKind() == OMPC_copyin)) {
1808 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00001809 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001810 for (auto *VarRef : Clause->children()) {
1811 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00001812 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001813 }
1814 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001815 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001816 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
Alexey Bataev040d5402015-05-12 08:35:28 +00001817 // Mark all variables in private list clauses as used in inner region.
1818 // Required for proper codegen of combined directives.
1819 // TODO: add processing for other clauses.
Alexey Bataev3392d762016-02-16 11:18:12 +00001820 if (auto *C = OMPClauseWithPreInit::get(Clause)) {
Alexey Bataev005248a2016-02-25 05:25:57 +00001821 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
1822 for (auto *D : DS->decls())
Alexey Bataev3392d762016-02-16 11:18:12 +00001823 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
1824 }
Alexey Bataev4244be22016-02-11 05:35:55 +00001825 }
Alexey Bataev005248a2016-02-25 05:25:57 +00001826 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
1827 if (auto *E = C->getPostUpdateExpr())
1828 MarkDeclarationsReferencedInExpr(E);
1829 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001830 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001831 if (Clause->getClauseKind() == OMPC_schedule)
1832 SC = cast<OMPScheduleClause>(Clause);
1833 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00001834 OC = cast<OMPOrderedClause>(Clause);
1835 else if (Clause->getClauseKind() == OMPC_linear)
1836 LCs.push_back(cast<OMPLinearClause>(Clause));
1837 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001838 bool ErrorFound = false;
1839 // OpenMP, 2.7.1 Loop Construct, Restrictions
1840 // The nonmonotonic modifier cannot be specified if an ordered clause is
1841 // specified.
1842 if (SC &&
1843 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
1844 SC->getSecondScheduleModifier() ==
1845 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
1846 OC) {
1847 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
1848 ? SC->getFirstScheduleModifierLoc()
1849 : SC->getSecondScheduleModifierLoc(),
1850 diag::err_omp_schedule_nonmonotonic_ordered)
1851 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1852 ErrorFound = true;
1853 }
Alexey Bataev993d2802015-12-28 06:23:08 +00001854 if (!LCs.empty() && OC && OC->getNumForLoops()) {
1855 for (auto *C : LCs) {
1856 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
1857 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1858 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001859 ErrorFound = true;
1860 }
Alexey Bataev113438c2015-12-30 12:06:23 +00001861 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
1862 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
1863 OC->getNumForLoops()) {
1864 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
1865 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
1866 ErrorFound = true;
1867 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001868 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00001869 ActOnCapturedRegionError();
1870 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001871 }
1872 return ActOnCapturedRegionEnd(S.get());
1873}
1874
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001875static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1876 OpenMPDirectiveKind CurrentRegion,
1877 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001878 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001879 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001880 if (Stack->getCurScope()) {
1881 auto ParentRegion = Stack->getParentDirective();
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001882 auto OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00001883 bool NestingProhibited = false;
1884 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00001885 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001886 enum {
1887 NoRecommend,
1888 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00001889 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00001890 ShouldBeInTargetRegion,
1891 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001892 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00001893 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001894 // OpenMP [2.16, Nesting of Regions]
1895 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00001896 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00001897 // An ordered construct with the simd clause is the only OpenMP
1898 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00001899 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00001900 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
1901 // message.
1902 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
1903 ? diag::err_omp_prohibited_region_simd
1904 : diag::warn_omp_nesting_simd);
1905 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00001906 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001907 if (ParentRegion == OMPD_atomic) {
1908 // OpenMP [2.16, Nesting of Regions]
1909 // OpenMP constructs may not be nested inside an atomic region.
1910 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1911 return true;
1912 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001913 if (CurrentRegion == OMPD_section) {
1914 // OpenMP [2.7.2, sections Construct, Restrictions]
1915 // Orphaned section directives are prohibited. That is, the section
1916 // directives must appear within the sections construct and must not be
1917 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001918 if (ParentRegion != OMPD_sections &&
1919 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001920 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
1921 << (ParentRegion != OMPD_unknown)
1922 << getOpenMPDirectiveName(ParentRegion);
1923 return true;
1924 }
1925 return false;
1926 }
Kelvin Li2b51f722016-07-26 04:32:50 +00001927 // Allow some constructs (except teams) to be orphaned (they could be
David Majnemer9d168222016-08-05 17:44:54 +00001928 // used in functions, called from OpenMP regions with the required
Kelvin Li2b51f722016-07-26 04:32:50 +00001929 // preconditions).
1930 if (ParentRegion == OMPD_unknown && !isOpenMPTeamsDirective(CurrentRegion))
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001931 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00001932 if (CurrentRegion == OMPD_cancellation_point ||
1933 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001934 // OpenMP [2.16, Nesting of Regions]
1935 // A cancellation point construct for which construct-type-clause is
1936 // taskgroup must be nested inside a task construct. A cancellation
1937 // point construct for which construct-type-clause is not taskgroup must
1938 // be closely nested inside an OpenMP construct that matches the type
1939 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00001940 // A cancel construct for which construct-type-clause is taskgroup must be
1941 // nested inside a task construct. A cancel construct for which
1942 // construct-type-clause is not taskgroup must be closely nested inside an
1943 // OpenMP construct that matches the type specified in
1944 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001945 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00001946 !((CancelRegion == OMPD_parallel &&
1947 (ParentRegion == OMPD_parallel ||
1948 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00001949 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00001950 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
1951 ParentRegion == OMPD_target_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001952 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
1953 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00001954 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
1955 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001956 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00001957 // OpenMP [2.16, Nesting of Regions]
1958 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001959 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00001960 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00001961 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001962 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
1963 // OpenMP [2.16, Nesting of Regions]
1964 // A critical region may not be nested (closely or otherwise) inside a
1965 // critical region with the same name. Note that this restriction is not
1966 // sufficient to prevent deadlock.
1967 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00001968 bool DeadLock = Stack->hasDirective(
1969 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
1970 const DeclarationNameInfo &DNI,
1971 SourceLocation Loc) -> bool {
1972 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
1973 PreviousCriticalLoc = Loc;
1974 return true;
1975 } else
1976 return false;
1977 },
1978 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001979 if (DeadLock) {
1980 SemaRef.Diag(StartLoc,
1981 diag::err_omp_prohibited_region_critical_same_name)
1982 << CurrentName.getName();
1983 if (PreviousCriticalLoc.isValid())
1984 SemaRef.Diag(PreviousCriticalLoc,
1985 diag::note_omp_previous_critical_region);
1986 return true;
1987 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001988 } else if (CurrentRegion == OMPD_barrier) {
1989 // OpenMP [2.16, Nesting of Regions]
1990 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001991 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00001992 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
1993 isOpenMPTaskingDirective(ParentRegion) ||
1994 ParentRegion == OMPD_master ||
1995 ParentRegion == OMPD_critical ||
1996 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00001997 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Alexander Musmanf82886e2014-09-18 05:12:34 +00001998 !isOpenMPParallelDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001999 // OpenMP [2.16, Nesting of Regions]
2000 // A worksharing region may not be closely nested inside a worksharing,
2001 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002002 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2003 isOpenMPTaskingDirective(ParentRegion) ||
2004 ParentRegion == OMPD_master ||
2005 ParentRegion == OMPD_critical ||
2006 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002007 Recommend = ShouldBeInParallelRegion;
2008 } else if (CurrentRegion == OMPD_ordered) {
2009 // OpenMP [2.16, Nesting of Regions]
2010 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002011 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002012 // An ordered region must be closely nested inside a loop region (or
2013 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002014 // OpenMP [2.8.1,simd Construct, Restrictions]
2015 // An ordered construct with the simd clause is the only OpenMP construct
2016 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002017 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002018 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002019 !(isOpenMPSimdDirective(ParentRegion) ||
2020 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002021 Recommend = ShouldBeInOrderedRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002022 } else if (isOpenMPTeamsDirective(CurrentRegion)) {
2023 // OpenMP [2.16, Nesting of Regions]
2024 // If specified, a teams construct must be contained within a target
2025 // construct.
2026 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00002027 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002028 Recommend = ShouldBeInTargetRegion;
2029 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2030 }
Kelvin Li02532872016-08-05 14:37:37 +00002031 if (!NestingProhibited && ParentRegion == OMPD_teams) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002032 // OpenMP [2.16, Nesting of Regions]
2033 // distribute, parallel, parallel sections, parallel workshare, and the
2034 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2035 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002036 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2037 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002038 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002039 }
David Majnemer9d168222016-08-05 17:44:54 +00002040 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00002041 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002042 // OpenMP 4.5 [2.17 Nesting of Regions]
2043 // The region associated with the distribute construct must be strictly
2044 // nested inside a teams region
Kelvin Li02532872016-08-05 14:37:37 +00002045 NestingProhibited = ParentRegion != OMPD_teams;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002046 Recommend = ShouldBeInTeamsRegion;
2047 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002048 if (!NestingProhibited &&
2049 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2050 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2051 // OpenMP 4.5 [2.17 Nesting of Regions]
2052 // If a target, target update, target data, target enter data, or
2053 // target exit data construct is encountered during execution of a
2054 // target region, the behavior is unspecified.
2055 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002056 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2057 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002058 if (isOpenMPTargetExecutionDirective(K)) {
2059 OffendingRegion = K;
2060 return true;
2061 } else
2062 return false;
2063 },
2064 false /* don't skip top directive */);
2065 CloseNesting = false;
2066 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002067 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00002068 if (OrphanSeen) {
2069 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2070 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2071 } else {
2072 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2073 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2074 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2075 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002076 return true;
2077 }
2078 }
2079 return false;
2080}
2081
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002082static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2083 ArrayRef<OMPClause *> Clauses,
2084 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2085 bool ErrorFound = false;
2086 unsigned NamedModifiersNumber = 0;
2087 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2088 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002089 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002090 for (const auto *C : Clauses) {
2091 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2092 // At most one if clause without a directive-name-modifier can appear on
2093 // the directive.
2094 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2095 if (FoundNameModifiers[CurNM]) {
2096 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2097 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2098 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2099 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002100 } else if (CurNM != OMPD_unknown) {
2101 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002102 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002103 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002104 FoundNameModifiers[CurNM] = IC;
2105 if (CurNM == OMPD_unknown)
2106 continue;
2107 // Check if the specified name modifier is allowed for the current
2108 // directive.
2109 // At most one if clause with the particular directive-name-modifier can
2110 // appear on the directive.
2111 bool MatchFound = false;
2112 for (auto NM : AllowedNameModifiers) {
2113 if (CurNM == NM) {
2114 MatchFound = true;
2115 break;
2116 }
2117 }
2118 if (!MatchFound) {
2119 S.Diag(IC->getNameModifierLoc(),
2120 diag::err_omp_wrong_if_directive_name_modifier)
2121 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2122 ErrorFound = true;
2123 }
2124 }
2125 }
2126 // If any if clause on the directive includes a directive-name-modifier then
2127 // all if clauses on the directive must include a directive-name-modifier.
2128 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2129 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2130 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2131 diag::err_omp_no_more_if_clause);
2132 } else {
2133 std::string Values;
2134 std::string Sep(", ");
2135 unsigned AllowedCnt = 0;
2136 unsigned TotalAllowedNum =
2137 AllowedNameModifiers.size() - NamedModifiersNumber;
2138 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2139 ++Cnt) {
2140 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2141 if (!FoundNameModifiers[NM]) {
2142 Values += "'";
2143 Values += getOpenMPDirectiveName(NM);
2144 Values += "'";
2145 if (AllowedCnt + 2 == TotalAllowedNum)
2146 Values += " or ";
2147 else if (AllowedCnt + 1 != TotalAllowedNum)
2148 Values += Sep;
2149 ++AllowedCnt;
2150 }
2151 }
2152 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2153 diag::err_omp_unnamed_if_clause)
2154 << (TotalAllowedNum > 1) << Values;
2155 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002156 for (auto Loc : NameModifierLoc) {
2157 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2158 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002159 ErrorFound = true;
2160 }
2161 return ErrorFound;
2162}
2163
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002164StmtResult Sema::ActOnOpenMPExecutableDirective(
2165 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2166 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2167 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002168 StmtResult Res = StmtError();
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002169 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
2170 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002171 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002172
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002173 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002174 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002175 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002176 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00002177 if (AStmt) {
2178 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2179
2180 // Check default data sharing attributes for referenced variables.
2181 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
2182 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
2183 if (DSAChecker.isErrorFound())
2184 return StmtError();
2185 // Generate list of implicitly defined firstprivate variables.
2186 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00002187
2188 if (!DSAChecker.getImplicitFirstprivate().empty()) {
2189 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2190 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
2191 SourceLocation(), SourceLocation())) {
2192 ClausesWithImplicit.push_back(Implicit);
2193 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2194 DSAChecker.getImplicitFirstprivate().size();
2195 } else
2196 ErrorFound = true;
2197 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002198 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002199
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002200 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002201 switch (Kind) {
2202 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00002203 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2204 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002205 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002206 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002207 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002208 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2209 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002210 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002211 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002212 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2213 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002214 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00002215 case OMPD_for_simd:
2216 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2217 EndLoc, VarsWithInheritedDSA);
2218 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002219 case OMPD_sections:
2220 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2221 EndLoc);
2222 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002223 case OMPD_section:
2224 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00002225 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002226 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2227 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002228 case OMPD_single:
2229 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2230 EndLoc);
2231 break;
Alexander Musman80c22892014-07-17 08:54:58 +00002232 case OMPD_master:
2233 assert(ClausesWithImplicit.empty() &&
2234 "No clauses are allowed for 'omp master' directive");
2235 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2236 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002237 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00002238 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2239 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002240 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002241 case OMPD_parallel_for:
2242 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2243 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002244 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002245 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00002246 case OMPD_parallel_for_simd:
2247 Res = ActOnOpenMPParallelForSimdDirective(
2248 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002249 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002250 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002251 case OMPD_parallel_sections:
2252 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2253 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002254 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002255 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002256 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002257 Res =
2258 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002259 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002260 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00002261 case OMPD_taskyield:
2262 assert(ClausesWithImplicit.empty() &&
2263 "No clauses are allowed for 'omp taskyield' directive");
2264 assert(AStmt == nullptr &&
2265 "No associated statement allowed for 'omp taskyield' directive");
2266 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2267 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002268 case OMPD_barrier:
2269 assert(ClausesWithImplicit.empty() &&
2270 "No clauses are allowed for 'omp barrier' directive");
2271 assert(AStmt == nullptr &&
2272 "No associated statement allowed for 'omp barrier' directive");
2273 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2274 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00002275 case OMPD_taskwait:
2276 assert(ClausesWithImplicit.empty() &&
2277 "No clauses are allowed for 'omp taskwait' directive");
2278 assert(AStmt == nullptr &&
2279 "No associated statement allowed for 'omp taskwait' directive");
2280 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2281 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002282 case OMPD_taskgroup:
2283 assert(ClausesWithImplicit.empty() &&
2284 "No clauses are allowed for 'omp taskgroup' directive");
2285 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
2286 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00002287 case OMPD_flush:
2288 assert(AStmt == nullptr &&
2289 "No associated statement allowed for 'omp flush' directive");
2290 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2291 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002292 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00002293 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2294 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002295 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00002296 case OMPD_atomic:
2297 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2298 EndLoc);
2299 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002300 case OMPD_teams:
2301 Res =
2302 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2303 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002304 case OMPD_target:
2305 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2306 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002307 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002308 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002309 case OMPD_target_parallel:
2310 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2311 StartLoc, EndLoc);
2312 AllowedNameModifiers.push_back(OMPD_target);
2313 AllowedNameModifiers.push_back(OMPD_parallel);
2314 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002315 case OMPD_target_parallel_for:
2316 Res = ActOnOpenMPTargetParallelForDirective(
2317 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2318 AllowedNameModifiers.push_back(OMPD_target);
2319 AllowedNameModifiers.push_back(OMPD_parallel);
2320 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002321 case OMPD_cancellation_point:
2322 assert(ClausesWithImplicit.empty() &&
2323 "No clauses are allowed for 'omp cancellation point' directive");
2324 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2325 "cancellation point' directive");
2326 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2327 break;
Alexey Bataev80909872015-07-02 11:25:17 +00002328 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00002329 assert(AStmt == nullptr &&
2330 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00002331 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2332 CancelRegion);
2333 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00002334 break;
Michael Wong65f367f2015-07-21 13:44:28 +00002335 case OMPD_target_data:
2336 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2337 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002338 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00002339 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00002340 case OMPD_target_enter_data:
2341 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
2342 EndLoc);
2343 AllowedNameModifiers.push_back(OMPD_target_enter_data);
2344 break;
Samuel Antao72590762016-01-19 20:04:50 +00002345 case OMPD_target_exit_data:
2346 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
2347 EndLoc);
2348 AllowedNameModifiers.push_back(OMPD_target_exit_data);
2349 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00002350 case OMPD_taskloop:
2351 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
2352 EndLoc, VarsWithInheritedDSA);
2353 AllowedNameModifiers.push_back(OMPD_taskloop);
2354 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002355 case OMPD_taskloop_simd:
2356 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2357 EndLoc, VarsWithInheritedDSA);
2358 AllowedNameModifiers.push_back(OMPD_taskloop);
2359 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002360 case OMPD_distribute:
2361 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
2362 EndLoc, VarsWithInheritedDSA);
2363 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00002364 case OMPD_target_update:
2365 assert(!AStmt && "Statement is not allowed for target update");
2366 Res =
2367 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc);
2368 AllowedNameModifiers.push_back(OMPD_target_update);
2369 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00002370 case OMPD_distribute_parallel_for:
2371 Res = ActOnOpenMPDistributeParallelForDirective(
2372 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2373 AllowedNameModifiers.push_back(OMPD_parallel);
2374 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00002375 case OMPD_distribute_parallel_for_simd:
2376 Res = ActOnOpenMPDistributeParallelForSimdDirective(
2377 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2378 AllowedNameModifiers.push_back(OMPD_parallel);
2379 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00002380 case OMPD_distribute_simd:
2381 Res = ActOnOpenMPDistributeSimdDirective(
2382 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2383 break;
Kelvin Lia579b912016-07-14 02:54:56 +00002384 case OMPD_target_parallel_for_simd:
2385 Res = ActOnOpenMPTargetParallelForSimdDirective(
2386 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2387 AllowedNameModifiers.push_back(OMPD_target);
2388 AllowedNameModifiers.push_back(OMPD_parallel);
2389 break;
Kelvin Li986330c2016-07-20 22:57:10 +00002390 case OMPD_target_simd:
2391 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2392 EndLoc, VarsWithInheritedDSA);
2393 AllowedNameModifiers.push_back(OMPD_target);
2394 break;
Kelvin Li02532872016-08-05 14:37:37 +00002395 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00002396 Res = ActOnOpenMPTeamsDistributeDirective(
2397 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00002398 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00002399 case OMPD_teams_distribute_simd:
2400 Res = ActOnOpenMPTeamsDistributeSimdDirective(
2401 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2402 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002403 case OMPD_declare_target:
2404 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002405 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002406 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002407 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002408 llvm_unreachable("OpenMP Directive is not allowed");
2409 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002410 llvm_unreachable("Unknown OpenMP directive");
2411 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002412
Alexey Bataev4acb8592014-07-07 13:01:15 +00002413 for (auto P : VarsWithInheritedDSA) {
2414 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2415 << P.first << P.second->getSourceRange();
2416 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002417 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
2418
2419 if (!AllowedNameModifiers.empty())
2420 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
2421 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002422
Alexey Bataeved09d242014-05-28 05:53:51 +00002423 if (ErrorFound)
2424 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002425 return Res;
2426}
2427
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002428Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
2429 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00002430 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00002431 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
2432 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00002433 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00002434 assert(Linears.size() == LinModifiers.size());
2435 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00002436 if (!DG || DG.get().isNull())
2437 return DeclGroupPtrTy();
2438
2439 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00002440 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002441 return DG;
2442 }
2443 auto *ADecl = DG.get().getSingleDecl();
2444 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
2445 ADecl = FTD->getTemplatedDecl();
2446
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002447 auto *FD = dyn_cast<FunctionDecl>(ADecl);
2448 if (!FD) {
2449 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002450 return DeclGroupPtrTy();
2451 }
2452
Alexey Bataev2af33e32016-04-07 12:45:37 +00002453 // OpenMP [2.8.2, declare simd construct, Description]
2454 // The parameter of the simdlen clause must be a constant positive integer
2455 // expression.
2456 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002457 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00002458 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002459 // OpenMP [2.8.2, declare simd construct, Description]
2460 // The special this pointer can be used as if was one of the arguments to the
2461 // function in any of the linear, aligned, or uniform clauses.
2462 // The uniform clause declares one or more arguments to have an invariant
2463 // value for all concurrent invocations of the function in the execution of a
2464 // single SIMD loop.
Alexey Bataevecba70f2016-04-12 11:02:11 +00002465 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
2466 Expr *UniformedLinearThis = nullptr;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002467 for (auto *E : Uniforms) {
2468 E = E->IgnoreParenImpCasts();
2469 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2470 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
2471 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2472 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00002473 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
2474 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002475 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002476 }
2477 if (isa<CXXThisExpr>(E)) {
2478 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002479 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002480 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002481 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2482 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00002483 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00002484 // OpenMP [2.8.2, declare simd construct, Description]
2485 // The aligned clause declares that the object to which each list item points
2486 // is aligned to the number of bytes expressed in the optional parameter of
2487 // the aligned clause.
2488 // The special this pointer can be used as if was one of the arguments to the
2489 // function in any of the linear, aligned, or uniform clauses.
2490 // The type of list items appearing in the aligned clause must be array,
2491 // pointer, reference to array, or reference to pointer.
2492 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
2493 Expr *AlignedThis = nullptr;
2494 for (auto *E : Aligneds) {
2495 E = E->IgnoreParenImpCasts();
2496 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2497 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2498 auto *CanonPVD = PVD->getCanonicalDecl();
2499 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2500 FD->getParamDecl(PVD->getFunctionScopeIndex())
2501 ->getCanonicalDecl() == CanonPVD) {
2502 // OpenMP [2.8.1, simd construct, Restrictions]
2503 // A list-item cannot appear in more than one aligned clause.
2504 if (AlignedArgs.count(CanonPVD) > 0) {
2505 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2506 << 1 << E->getSourceRange();
2507 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
2508 diag::note_omp_explicit_dsa)
2509 << getOpenMPClauseName(OMPC_aligned);
2510 continue;
2511 }
2512 AlignedArgs[CanonPVD] = E;
2513 QualType QTy = PVD->getType()
2514 .getNonReferenceType()
2515 .getUnqualifiedType()
2516 .getCanonicalType();
2517 const Type *Ty = QTy.getTypePtrOrNull();
2518 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
2519 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
2520 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
2521 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
2522 }
2523 continue;
2524 }
2525 }
2526 if (isa<CXXThisExpr>(E)) {
2527 if (AlignedThis) {
2528 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2529 << 2 << E->getSourceRange();
2530 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
2531 << getOpenMPClauseName(OMPC_aligned);
2532 }
2533 AlignedThis = E;
2534 continue;
2535 }
2536 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2537 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2538 }
2539 // The optional parameter of the aligned clause, alignment, must be a constant
2540 // positive integer expression. If no optional parameter is specified,
2541 // implementation-defined default alignments for SIMD instructions on the
2542 // target platforms are assumed.
2543 SmallVector<Expr *, 4> NewAligns;
2544 for (auto *E : Alignments) {
2545 ExprResult Align;
2546 if (E)
2547 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
2548 NewAligns.push_back(Align.get());
2549 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00002550 // OpenMP [2.8.2, declare simd construct, Description]
2551 // The linear clause declares one or more list items to be private to a SIMD
2552 // lane and to have a linear relationship with respect to the iteration space
2553 // of a loop.
2554 // The special this pointer can be used as if was one of the arguments to the
2555 // function in any of the linear, aligned, or uniform clauses.
2556 // When a linear-step expression is specified in a linear clause it must be
2557 // either a constant integer expression or an integer-typed parameter that is
2558 // specified in a uniform clause on the directive.
2559 llvm::DenseMap<Decl *, Expr *> LinearArgs;
2560 const bool IsUniformedThis = UniformedLinearThis != nullptr;
2561 auto MI = LinModifiers.begin();
2562 for (auto *E : Linears) {
2563 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
2564 ++MI;
2565 E = E->IgnoreParenImpCasts();
2566 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2567 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2568 auto *CanonPVD = PVD->getCanonicalDecl();
2569 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2570 FD->getParamDecl(PVD->getFunctionScopeIndex())
2571 ->getCanonicalDecl() == CanonPVD) {
2572 // OpenMP [2.15.3.7, linear Clause, Restrictions]
2573 // A list-item cannot appear in more than one linear clause.
2574 if (LinearArgs.count(CanonPVD) > 0) {
2575 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2576 << getOpenMPClauseName(OMPC_linear)
2577 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
2578 Diag(LinearArgs[CanonPVD]->getExprLoc(),
2579 diag::note_omp_explicit_dsa)
2580 << getOpenMPClauseName(OMPC_linear);
2581 continue;
2582 }
2583 // Each argument can appear in at most one uniform or linear clause.
2584 if (UniformedArgs.count(CanonPVD) > 0) {
2585 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2586 << getOpenMPClauseName(OMPC_linear)
2587 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
2588 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
2589 diag::note_omp_explicit_dsa)
2590 << getOpenMPClauseName(OMPC_uniform);
2591 continue;
2592 }
2593 LinearArgs[CanonPVD] = E;
2594 if (E->isValueDependent() || E->isTypeDependent() ||
2595 E->isInstantiationDependent() ||
2596 E->containsUnexpandedParameterPack())
2597 continue;
2598 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
2599 PVD->getOriginalType());
2600 continue;
2601 }
2602 }
2603 if (isa<CXXThisExpr>(E)) {
2604 if (UniformedLinearThis) {
2605 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2606 << getOpenMPClauseName(OMPC_linear)
2607 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
2608 << E->getSourceRange();
2609 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
2610 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
2611 : OMPC_linear);
2612 continue;
2613 }
2614 UniformedLinearThis = E;
2615 if (E->isValueDependent() || E->isTypeDependent() ||
2616 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
2617 continue;
2618 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
2619 E->getType());
2620 continue;
2621 }
2622 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2623 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2624 }
2625 Expr *Step = nullptr;
2626 Expr *NewStep = nullptr;
2627 SmallVector<Expr *, 4> NewSteps;
2628 for (auto *E : Steps) {
2629 // Skip the same step expression, it was checked already.
2630 if (Step == E || !E) {
2631 NewSteps.push_back(E ? NewStep : nullptr);
2632 continue;
2633 }
2634 Step = E;
2635 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
2636 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2637 auto *CanonPVD = PVD->getCanonicalDecl();
2638 if (UniformedArgs.count(CanonPVD) == 0) {
2639 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
2640 << Step->getSourceRange();
2641 } else if (E->isValueDependent() || E->isTypeDependent() ||
2642 E->isInstantiationDependent() ||
2643 E->containsUnexpandedParameterPack() ||
2644 CanonPVD->getType()->hasIntegerRepresentation())
2645 NewSteps.push_back(Step);
2646 else {
2647 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
2648 << Step->getSourceRange();
2649 }
2650 continue;
2651 }
2652 NewStep = Step;
2653 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
2654 !Step->isInstantiationDependent() &&
2655 !Step->containsUnexpandedParameterPack()) {
2656 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
2657 .get();
2658 if (NewStep)
2659 NewStep = VerifyIntegerConstantExpression(NewStep).get();
2660 }
2661 NewSteps.push_back(NewStep);
2662 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002663 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
2664 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00002665 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00002666 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
2667 const_cast<Expr **>(Linears.data()), Linears.size(),
2668 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
2669 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002670 ADecl->addAttr(NewAttr);
2671 return ConvertDeclToDeclGroup(ADecl);
2672}
2673
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002674StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2675 Stmt *AStmt,
2676 SourceLocation StartLoc,
2677 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002678 if (!AStmt)
2679 return StmtError();
2680
Alexey Bataev9959db52014-05-06 10:08:46 +00002681 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2682 // 1.2.2 OpenMP Language Terminology
2683 // Structured block - An executable statement with a single entry at the
2684 // top and a single exit at the bottom.
2685 // The point of exit cannot be a branch out of the structured block.
2686 // longjmp() and throw() must not violate the entry/exit criteria.
2687 CS->getCapturedDecl()->setNothrow();
2688
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002689 getCurFunction()->setHasBranchProtectedScope();
2690
Alexey Bataev25e5b442015-09-15 12:52:43 +00002691 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
2692 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002693}
2694
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002695namespace {
2696/// \brief Helper class for checking canonical form of the OpenMP loops and
2697/// extracting iteration space of each loop in the loop nest, that will be used
2698/// for IR generation.
2699class OpenMPIterationSpaceChecker {
2700 /// \brief Reference to Sema.
2701 Sema &SemaRef;
2702 /// \brief A location for diagnostics (when there is no some better location).
2703 SourceLocation DefaultLoc;
2704 /// \brief A location for diagnostics (when increment is not compatible).
2705 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002706 /// \brief A source location for referring to loop init later.
2707 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002708 /// \brief A source location for referring to condition later.
2709 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002710 /// \brief A source location for referring to increment later.
2711 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002712 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002713 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002714 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002715 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002716 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002717 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002718 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002719 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002720 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002721 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002722 /// \brief This flag is true when condition is one of:
2723 /// Var < UB
2724 /// Var <= UB
2725 /// UB > Var
2726 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002727 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002728 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002729 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002730 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002731 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002732
2733public:
2734 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002735 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002736 /// \brief Check init-expr for canonical loop form and save loop counter
2737 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00002738 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002739 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2740 /// for less/greater and for strict/non-strict comparison.
2741 bool CheckCond(Expr *S);
2742 /// \brief Check incr-expr for canonical loop form and return true if it
2743 /// does not conform, otherwise save loop step (#Step).
2744 bool CheckInc(Expr *S);
2745 /// \brief Return the loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002746 ValueDecl *GetLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002747 /// \brief Return the reference expression to loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002748 Expr *GetLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002749 /// \brief Source range of the loop init.
2750 SourceRange GetInitSrcRange() const { return InitSrcRange; }
2751 /// \brief Source range of the loop condition.
2752 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2753 /// \brief Source range of the loop increment.
2754 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2755 /// \brief True if the step should be subtracted.
2756 bool ShouldSubtractStep() const { return SubtractStep; }
2757 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00002758 Expr *
2759 BuildNumIterations(Scope *S, const bool LimitedType,
2760 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00002761 /// \brief Build the precondition expression for the loops.
Alexey Bataev5a3af132016-03-29 08:58:54 +00002762 Expr *BuildPreCond(Scope *S, Expr *Cond,
2763 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002764 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002765 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
2766 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00002767 /// \brief Build reference expression to the private counter be used for
2768 /// codegen.
2769 Expr *BuildPrivateCounterVar() const;
David Majnemer9d168222016-08-05 17:44:54 +00002770 /// \brief Build initialization of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002771 Expr *BuildCounterInit() const;
2772 /// \brief Build step of the counter be used for codegen.
2773 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002774 /// \brief Return true if any expression is dependent.
2775 bool Dependent() const;
2776
2777private:
2778 /// \brief Check the right-hand side of an assignment in the increment
2779 /// expression.
2780 bool CheckIncRHS(Expr *RHS);
2781 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002782 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002783 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00002784 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00002785 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002786 /// \brief Helper to set loop increment.
2787 bool SetStep(Expr *NewStep, bool Subtract);
2788};
2789
2790bool OpenMPIterationSpaceChecker::Dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002791 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002792 assert(!LB && !UB && !Step);
2793 return false;
2794 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002795 return LCDecl->getType()->isDependentType() ||
2796 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
2797 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002798}
2799
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002800static Expr *getExprAsWritten(Expr *E) {
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002801 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
2802 E = ExprTemp->getSubExpr();
2803
2804 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2805 E = MTE->GetTemporaryExpr();
2806
2807 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
2808 E = Binder->getSubExpr();
2809
2810 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2811 E = ICE->getSubExprAsWritten();
2812 return E->IgnoreParens();
2813}
2814
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002815bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
2816 Expr *NewLCRefExpr,
2817 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002818 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002819 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002820 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002821 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002822 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002823 LCDecl = getCanonicalDecl(NewLCDecl);
2824 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002825 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
2826 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00002827 if ((Ctor->isCopyOrMoveConstructor() ||
2828 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2829 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002830 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002831 LB = NewLB;
2832 return false;
2833}
2834
2835bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00002836 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002837 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002838 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
2839 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002840 if (!NewUB)
2841 return true;
2842 UB = NewUB;
2843 TestIsLessOp = LessOp;
2844 TestIsStrictOp = StrictOp;
2845 ConditionSrcRange = SR;
2846 ConditionLoc = SL;
2847 return false;
2848}
2849
2850bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2851 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002852 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002853 if (!NewStep)
2854 return true;
2855 if (!NewStep->isValueDependent()) {
2856 // Check that the step is integer expression.
2857 SourceLocation StepLoc = NewStep->getLocStart();
2858 ExprResult Val =
2859 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2860 if (Val.isInvalid())
2861 return true;
2862 NewStep = Val.get();
2863
2864 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2865 // If test-expr is of form var relational-op b and relational-op is < or
2866 // <= then incr-expr must cause var to increase on each iteration of the
2867 // loop. If test-expr is of form var relational-op b and relational-op is
2868 // > or >= then incr-expr must cause var to decrease on each iteration of
2869 // the loop.
2870 // If test-expr is of form b relational-op var and relational-op is < or
2871 // <= then incr-expr must cause var to decrease on each iteration of the
2872 // loop. If test-expr is of form b relational-op var and relational-op is
2873 // > or >= then incr-expr must cause var to increase on each iteration of
2874 // the loop.
2875 llvm::APSInt Result;
2876 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
2877 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
2878 bool IsConstNeg =
2879 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002880 bool IsConstPos =
2881 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002882 bool IsConstZero = IsConstant && !Result.getBoolValue();
2883 if (UB && (IsConstZero ||
2884 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00002885 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002886 SemaRef.Diag(NewStep->getExprLoc(),
2887 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002888 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002889 SemaRef.Diag(ConditionLoc,
2890 diag::note_omp_loop_cond_requres_compatible_incr)
2891 << TestIsLessOp << ConditionSrcRange;
2892 return true;
2893 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002894 if (TestIsLessOp == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00002895 NewStep =
2896 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
2897 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00002898 Subtract = !Subtract;
2899 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002900 }
2901
2902 Step = NewStep;
2903 SubtractStep = Subtract;
2904 return false;
2905}
2906
Alexey Bataev9c821032015-04-30 04:23:23 +00002907bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002908 // Check init-expr for canonical loop form and save loop counter
2909 // variable - #Var and its initialization value - #LB.
2910 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
2911 // var = lb
2912 // integer-type var = lb
2913 // random-access-iterator-type var = lb
2914 // pointer-type var = lb
2915 //
2916 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00002917 if (EmitDiags) {
2918 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
2919 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002920 return true;
2921 }
Tim Shen4a05bb82016-06-21 20:29:17 +00002922 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
2923 if (!ExprTemp->cleanupsHaveSideEffects())
2924 S = ExprTemp->getSubExpr();
2925
Alexander Musmana5f070a2014-10-01 06:03:56 +00002926 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002927 if (Expr *E = dyn_cast<Expr>(S))
2928 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00002929 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002930 if (BO->getOpcode() == BO_Assign) {
2931 auto *LHS = BO->getLHS()->IgnoreParens();
2932 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
2933 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
2934 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
2935 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
2936 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
2937 }
2938 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
2939 if (ME->isArrow() &&
2940 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
2941 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
2942 }
2943 }
David Majnemer9d168222016-08-05 17:44:54 +00002944 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002945 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00002946 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00002947 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002948 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00002949 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002950 SemaRef.Diag(S->getLocStart(),
2951 diag::ext_omp_loop_not_canonical_init)
2952 << S->getSourceRange();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002953 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002954 }
2955 }
2956 }
David Majnemer9d168222016-08-05 17:44:54 +00002957 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002958 if (CE->getOperator() == OO_Equal) {
2959 auto *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00002960 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002961 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
2962 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
2963 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
2964 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
2965 }
2966 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
2967 if (ME->isArrow() &&
2968 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
2969 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
2970 }
2971 }
2972 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002973
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002974 if (Dependent() || SemaRef.CurContext->isDependentContext())
2975 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00002976 if (EmitDiags) {
2977 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
2978 << S->getSourceRange();
2979 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002980 return true;
2981}
2982
Alexey Bataev23b69422014-06-18 07:08:49 +00002983/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002984/// variable (which may be the loop variable) if possible.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002985static const ValueDecl *GetInitLCDecl(Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002986 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00002987 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002988 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002989 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
2990 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00002991 if ((Ctor->isCopyOrMoveConstructor() ||
2992 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2993 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002994 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002995 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
2996 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
2997 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
2998 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
2999 return getCanonicalDecl(ME->getMemberDecl());
3000 return getCanonicalDecl(VD);
3001 }
3002 }
3003 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3004 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3005 return getCanonicalDecl(ME->getMemberDecl());
3006 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003007}
3008
3009bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3010 // Check test-expr for canonical form, save upper-bound UB, flags for
3011 // less/greater and for strict/non-strict comparison.
3012 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3013 // var relational-op b
3014 // b relational-op var
3015 //
3016 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003017 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003018 return true;
3019 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003020 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003021 SourceLocation CondLoc = S->getLocStart();
David Majnemer9d168222016-08-05 17:44:54 +00003022 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003023 if (BO->isRelationalOp()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003024 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003025 return SetUB(BO->getRHS(),
3026 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3027 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3028 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003029 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003030 return SetUB(BO->getLHS(),
3031 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3032 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3033 BO->getSourceRange(), BO->getOperatorLoc());
3034 }
David Majnemer9d168222016-08-05 17:44:54 +00003035 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003036 if (CE->getNumArgs() == 2) {
3037 auto Op = CE->getOperator();
3038 switch (Op) {
3039 case OO_Greater:
3040 case OO_GreaterEqual:
3041 case OO_Less:
3042 case OO_LessEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003043 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003044 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3045 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3046 CE->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003047 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003048 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3049 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3050 CE->getOperatorLoc());
3051 break;
3052 default:
3053 break;
3054 }
3055 }
3056 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003057 if (Dependent() || SemaRef.CurContext->isDependentContext())
3058 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003059 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003060 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003061 return true;
3062}
3063
3064bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3065 // RHS of canonical loop form increment can be:
3066 // var + incr
3067 // incr + var
3068 // var - incr
3069 //
3070 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00003071 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003072 if (BO->isAdditiveOp()) {
3073 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003074 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003075 return SetStep(BO->getRHS(), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003076 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003077 return SetStep(BO->getLHS(), false);
3078 }
David Majnemer9d168222016-08-05 17:44:54 +00003079 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003080 bool IsAdd = CE->getOperator() == OO_Plus;
3081 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003082 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003083 return SetStep(CE->getArg(1), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003084 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003085 return SetStep(CE->getArg(0), false);
3086 }
3087 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003088 if (Dependent() || SemaRef.CurContext->isDependentContext())
3089 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003090 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003091 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003092 return true;
3093}
3094
3095bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3096 // Check incr-expr for canonical loop form and return true if it
3097 // does not conform.
3098 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3099 // ++var
3100 // var++
3101 // --var
3102 // var--
3103 // var += incr
3104 // var -= incr
3105 // var = var + incr
3106 // var = incr + var
3107 // var = var - incr
3108 //
3109 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003110 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003111 return true;
3112 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003113 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3114 if (!ExprTemp->cleanupsHaveSideEffects())
3115 S = ExprTemp->getSubExpr();
3116
Alexander Musmana5f070a2014-10-01 06:03:56 +00003117 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003118 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003119 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003120 if (UO->isIncrementDecrementOp() &&
3121 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003122 return SetStep(SemaRef
3123 .ActOnIntegerConstant(UO->getLocStart(),
3124 (UO->isDecrementOp() ? -1 : 1))
3125 .get(),
3126 false);
3127 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003128 switch (BO->getOpcode()) {
3129 case BO_AddAssign:
3130 case BO_SubAssign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003131 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003132 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3133 break;
3134 case BO_Assign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003135 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003136 return CheckIncRHS(BO->getRHS());
3137 break;
3138 default:
3139 break;
3140 }
David Majnemer9d168222016-08-05 17:44:54 +00003141 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003142 switch (CE->getOperator()) {
3143 case OO_PlusPlus:
3144 case OO_MinusMinus:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003145 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003146 return SetStep(SemaRef
3147 .ActOnIntegerConstant(
3148 CE->getLocStart(),
3149 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3150 .get(),
3151 false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003152 break;
3153 case OO_PlusEqual:
3154 case OO_MinusEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003155 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003156 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3157 break;
3158 case OO_Equal:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003159 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003160 return CheckIncRHS(CE->getArg(1));
3161 break;
3162 default:
3163 break;
3164 }
3165 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003166 if (Dependent() || SemaRef.CurContext->isDependentContext())
3167 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003168 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003169 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003170 return true;
3171}
Alexander Musmana5f070a2014-10-01 06:03:56 +00003172
Alexey Bataev5a3af132016-03-29 08:58:54 +00003173static ExprResult
3174tryBuildCapture(Sema &SemaRef, Expr *Capture,
3175 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00003176 if (SemaRef.CurContext->isDependentContext())
3177 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003178 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3179 return SemaRef.PerformImplicitConversion(
3180 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3181 /*AllowExplicit=*/true);
3182 auto I = Captures.find(Capture);
3183 if (I != Captures.end())
3184 return buildCapture(SemaRef, Capture, I->second);
3185 DeclRefExpr *Ref = nullptr;
3186 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3187 Captures[Capture] = Ref;
3188 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003189}
3190
Alexander Musmana5f070a2014-10-01 06:03:56 +00003191/// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003192Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3193 Scope *S, const bool LimitedType,
3194 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003195 ExprResult Diff;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003196 auto VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003197 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003198 SemaRef.getLangOpts().CPlusPlus) {
3199 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003200 auto *UBExpr = TestIsLessOp ? UB : LB;
3201 auto *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00003202 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3203 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003204 if (!Upper || !Lower)
3205 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003206
3207 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3208
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003209 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003210 // BuildBinOp already emitted error, this one is to point user to upper
3211 // and lower bound, and to tell what is passed to 'operator-'.
3212 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3213 << Upper->getSourceRange() << Lower->getSourceRange();
3214 return nullptr;
3215 }
3216 }
3217
3218 if (!Diff.isUsable())
3219 return nullptr;
3220
3221 // Upper - Lower [- 1]
3222 if (TestIsStrictOp)
3223 Diff = SemaRef.BuildBinOp(
3224 S, DefaultLoc, BO_Sub, Diff.get(),
3225 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3226 if (!Diff.isUsable())
3227 return nullptr;
3228
3229 // Upper - Lower [- 1] + Step
Alexey Bataev5a3af132016-03-29 08:58:54 +00003230 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3231 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003232 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003233 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003234 if (!Diff.isUsable())
3235 return nullptr;
3236
3237 // Parentheses (for dumping/debugging purposes only).
3238 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3239 if (!Diff.isUsable())
3240 return nullptr;
3241
3242 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003243 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003244 if (!Diff.isUsable())
3245 return nullptr;
3246
Alexander Musman174b3ca2014-10-06 11:16:29 +00003247 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003248 QualType Type = Diff.get()->getType();
3249 auto &C = SemaRef.Context;
3250 bool UseVarType = VarType->hasIntegerRepresentation() &&
3251 C.getTypeSize(Type) > C.getTypeSize(VarType);
3252 if (!Type->isIntegerType() || UseVarType) {
3253 unsigned NewSize =
3254 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3255 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3256 : Type->hasSignedIntegerRepresentation();
3257 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00003258 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3259 Diff = SemaRef.PerformImplicitConversion(
3260 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3261 if (!Diff.isUsable())
3262 return nullptr;
3263 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003264 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003265 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00003266 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3267 if (NewSize != C.getTypeSize(Type)) {
3268 if (NewSize < C.getTypeSize(Type)) {
3269 assert(NewSize == 64 && "incorrect loop var size");
3270 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3271 << InitSrcRange << ConditionSrcRange;
3272 }
3273 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003274 NewSize, Type->hasSignedIntegerRepresentation() ||
3275 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00003276 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3277 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3278 Sema::AA_Converting, true);
3279 if (!Diff.isUsable())
3280 return nullptr;
3281 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003282 }
3283 }
3284
Alexander Musmana5f070a2014-10-01 06:03:56 +00003285 return Diff.get();
3286}
3287
Alexey Bataev5a3af132016-03-29 08:58:54 +00003288Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3289 Scope *S, Expr *Cond,
3290 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003291 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3292 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3293 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003294
Alexey Bataev5a3af132016-03-29 08:58:54 +00003295 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3296 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3297 if (!NewLB.isUsable() || !NewUB.isUsable())
3298 return nullptr;
3299
Alexey Bataev62dbb972015-04-22 11:59:37 +00003300 auto CondExpr = SemaRef.BuildBinOp(
3301 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3302 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003303 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003304 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003305 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
3306 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00003307 CondExpr = SemaRef.PerformImplicitConversion(
3308 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3309 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003310 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00003311 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3312 // Otherwise use original loop conditon and evaluate it in runtime.
3313 return CondExpr.isUsable() ? CondExpr.get() : Cond;
3314}
3315
Alexander Musmana5f070a2014-10-01 06:03:56 +00003316/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003317DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003318 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003319 auto *VD = dyn_cast<VarDecl>(LCDecl);
3320 if (!VD) {
3321 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
3322 auto *Ref = buildDeclRefExpr(
3323 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003324 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
3325 // If the loop control decl is explicitly marked as private, do not mark it
3326 // as captured again.
3327 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
3328 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003329 return Ref;
3330 }
3331 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00003332 DefaultLoc);
3333}
3334
3335Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003336 if (LCDecl && !LCDecl->isInvalidDecl()) {
3337 auto Type = LCDecl->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00003338 auto *PrivateVar =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003339 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
3340 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00003341 if (PrivateVar->isInvalidDecl())
3342 return nullptr;
3343 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3344 }
3345 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003346}
3347
David Majnemer9d168222016-08-05 17:44:54 +00003348/// \brief Build instillation of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003349Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3350
3351/// \brief Build step of the counter be used for codegen.
3352Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3353
3354/// \brief Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003355struct LoopIterationSpace final {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003356 /// \brief Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003357 Expr *PreCond = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003358 /// \brief This expression calculates the number of iterations in the loop.
3359 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003360 Expr *NumIterations = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003361 /// \brief The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003362 Expr *CounterVar = nullptr;
Alexey Bataeva8899172015-08-06 12:30:57 +00003363 /// \brief Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003364 Expr *PrivateCounterVar = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003365 /// \brief This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00003366 Expr *CounterInit = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003367 /// \brief This is step for the #CounterVar used to generate its update:
3368 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00003369 Expr *CounterStep = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003370 /// \brief Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00003371 bool Subtract = false;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003372 /// \brief Source range of the loop init.
3373 SourceRange InitSrcRange;
3374 /// \brief Source range of the loop condition.
3375 SourceRange CondSrcRange;
3376 /// \brief Source range of the loop increment.
3377 SourceRange IncSrcRange;
3378};
3379
Alexey Bataev23b69422014-06-18 07:08:49 +00003380} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003381
Alexey Bataev9c821032015-04-30 04:23:23 +00003382void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
3383 assert(getLangOpts().OpenMP && "OpenMP is not active.");
3384 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003385 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
3386 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00003387 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
3388 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003389 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
3390 if (auto *D = ISC.GetLoopDecl()) {
3391 auto *VD = dyn_cast<VarDecl>(D);
3392 if (!VD) {
3393 if (auto *Private = IsOpenMPCapturedDecl(D))
3394 VD = Private;
3395 else {
3396 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
3397 /*WithInit=*/false);
3398 VD = cast<VarDecl>(Ref->getDecl());
3399 }
3400 }
3401 DSAStack->addLoopControlVariable(D, VD);
3402 }
3403 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003404 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00003405 }
3406}
3407
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003408/// \brief Called on a for stmt to check and extract its iteration space
3409/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00003410static bool CheckOpenMPIterationSpace(
3411 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3412 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003413 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003414 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003415 LoopIterationSpace &ResultIterSpace,
3416 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003417 // OpenMP [2.6, Canonical Loop Form]
3418 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00003419 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003420 if (!For) {
3421 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003422 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
3423 << getOpenMPDirectiveName(DKind) << NestedLoopCount
3424 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
3425 if (NestedLoopCount > 1) {
3426 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
3427 SemaRef.Diag(DSA.getConstructLoc(),
3428 diag::note_omp_collapse_ordered_expr)
3429 << 2 << CollapseLoopCountExpr->getSourceRange()
3430 << OrderedLoopCountExpr->getSourceRange();
3431 else if (CollapseLoopCountExpr)
3432 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3433 diag::note_omp_collapse_ordered_expr)
3434 << 0 << CollapseLoopCountExpr->getSourceRange();
3435 else
3436 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3437 diag::note_omp_collapse_ordered_expr)
3438 << 1 << OrderedLoopCountExpr->getSourceRange();
3439 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003440 return true;
3441 }
3442 assert(For->getBody());
3443
3444 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3445
3446 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003447 auto Init = For->getInit();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003448 if (ISC.CheckInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003449 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003450
3451 bool HasErrors = false;
3452
3453 // Check loop variable's type.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003454 if (auto *LCDecl = ISC.GetLoopDecl()) {
3455 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003456
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003457 // OpenMP [2.6, Canonical Loop Form]
3458 // Var is one of the following:
3459 // A variable of signed or unsigned integer type.
3460 // For C++, a variable of a random access iterator type.
3461 // For C, a variable of a pointer type.
3462 auto VarType = LCDecl->getType().getNonReferenceType();
3463 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
3464 !VarType->isPointerType() &&
3465 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
3466 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
3467 << SemaRef.getLangOpts().CPlusPlus;
3468 HasErrors = true;
3469 }
3470
3471 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
3472 // a Construct
3473 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3474 // parallel for construct is (are) private.
3475 // The loop iteration variable in the associated for-loop of a simd
3476 // construct with just one associated for-loop is linear with a
3477 // constant-linear-step that is the increment of the associated for-loop.
3478 // Exclude loop var from the list of variables with implicitly defined data
3479 // sharing attributes.
3480 VarsWithImplicitDSA.erase(LCDecl);
3481
3482 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
3483 // in a Construct, C/C++].
3484 // The loop iteration variable in the associated for-loop of a simd
3485 // construct with just one associated for-loop may be listed in a linear
3486 // clause with a constant-linear-step that is the increment of the
3487 // associated for-loop.
3488 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3489 // parallel for construct may be listed in a private or lastprivate clause.
3490 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
3491 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
3492 // declared in the loop and it is predetermined as a private.
3493 auto PredeterminedCKind =
3494 isOpenMPSimdDirective(DKind)
3495 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
3496 : OMPC_private;
3497 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3498 DVar.CKind != PredeterminedCKind) ||
3499 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
3500 isOpenMPDistributeDirective(DKind)) &&
3501 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3502 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
3503 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
3504 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
3505 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
3506 << getOpenMPClauseName(PredeterminedCKind);
3507 if (DVar.RefExpr == nullptr)
3508 DVar.CKind = PredeterminedCKind;
3509 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
3510 HasErrors = true;
3511 } else if (LoopDeclRefExpr != nullptr) {
3512 // Make the loop iteration variable private (for worksharing constructs),
3513 // linear (for simd directives with the only one associated loop) or
3514 // lastprivate (for simd directives with several collapsed or ordered
3515 // loops).
3516 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003517 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
3518 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003519 /*FromParent=*/false);
3520 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
3521 }
3522
3523 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
3524
3525 // Check test-expr.
3526 HasErrors |= ISC.CheckCond(For->getCond());
3527
3528 // Check incr-expr.
3529 HasErrors |= ISC.CheckInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003530 }
3531
Alexander Musmana5f070a2014-10-01 06:03:56 +00003532 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003533 return HasErrors;
3534
Alexander Musmana5f070a2014-10-01 06:03:56 +00003535 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003536 ResultIterSpace.PreCond =
3537 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexander Musman174b3ca2014-10-06 11:16:29 +00003538 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00003539 DSA.getCurScope(),
3540 (isOpenMPWorksharingDirective(DKind) ||
3541 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
3542 Captures);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003543 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
Alexey Bataeva8899172015-08-06 12:30:57 +00003544 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003545 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
3546 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
3547 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
3548 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
3549 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
3550 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
3551
Alexey Bataev62dbb972015-04-22 11:59:37 +00003552 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
3553 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003554 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00003555 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003556 ResultIterSpace.CounterInit == nullptr ||
3557 ResultIterSpace.CounterStep == nullptr);
3558
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003559 return HasErrors;
3560}
3561
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003562/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003563static ExprResult
3564BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
3565 ExprResult Start,
3566 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003567 // Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003568 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
3569 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003570 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00003571 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00003572 VarRef.get()->getType())) {
3573 NewStart = SemaRef.PerformImplicitConversion(
3574 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
3575 /*AllowExplicit=*/true);
3576 if (!NewStart.isUsable())
3577 return ExprError();
3578 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003579
3580 auto Init =
3581 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3582 return Init;
3583}
3584
Alexander Musmana5f070a2014-10-01 06:03:56 +00003585/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003586static ExprResult
3587BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
3588 ExprResult VarRef, ExprResult Start, ExprResult Iter,
3589 ExprResult Step, bool Subtract,
3590 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003591 // Add parentheses (for debugging purposes only).
3592 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
3593 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
3594 !Step.isUsable())
3595 return ExprError();
3596
Alexey Bataev5a3af132016-03-29 08:58:54 +00003597 ExprResult NewStep = Step;
3598 if (Captures)
3599 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003600 if (NewStep.isInvalid())
3601 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003602 ExprResult Update =
3603 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003604 if (!Update.isUsable())
3605 return ExprError();
3606
Alexey Bataevc0214e02016-02-16 12:13:49 +00003607 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
3608 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003609 ExprResult NewStart = Start;
3610 if (Captures)
3611 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003612 if (NewStart.isInvalid())
3613 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003614
Alexey Bataevc0214e02016-02-16 12:13:49 +00003615 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
3616 ExprResult SavedUpdate = Update;
3617 ExprResult UpdateVal;
3618 if (VarRef.get()->getType()->isOverloadableType() ||
3619 NewStart.get()->getType()->isOverloadableType() ||
3620 Update.get()->getType()->isOverloadableType()) {
3621 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3622 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3623 Update =
3624 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3625 if (Update.isUsable()) {
3626 UpdateVal =
3627 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
3628 VarRef.get(), SavedUpdate.get());
3629 if (UpdateVal.isUsable()) {
3630 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
3631 UpdateVal.get());
3632 }
3633 }
3634 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3635 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003636
Alexey Bataevc0214e02016-02-16 12:13:49 +00003637 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
3638 if (!Update.isUsable() || !UpdateVal.isUsable()) {
3639 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
3640 NewStart.get(), SavedUpdate.get());
3641 if (!Update.isUsable())
3642 return ExprError();
3643
Alexey Bataev11481f52016-02-17 10:29:05 +00003644 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
3645 VarRef.get()->getType())) {
3646 Update = SemaRef.PerformImplicitConversion(
3647 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
3648 if (!Update.isUsable())
3649 return ExprError();
3650 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00003651
3652 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
3653 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003654 return Update;
3655}
3656
3657/// \brief Convert integer expression \a E to make it have at least \a Bits
3658/// bits.
David Majnemer9d168222016-08-05 17:44:54 +00003659static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003660 if (E == nullptr)
3661 return ExprError();
3662 auto &C = SemaRef.Context;
3663 QualType OldType = E->getType();
3664 unsigned HasBits = C.getTypeSize(OldType);
3665 if (HasBits >= Bits)
3666 return ExprResult(E);
3667 // OK to convert to signed, because new type has more bits than old.
3668 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
3669 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
3670 true);
3671}
3672
3673/// \brief Check if the given expression \a E is a constant integer that fits
3674/// into \a Bits bits.
3675static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
3676 if (E == nullptr)
3677 return false;
3678 llvm::APSInt Result;
3679 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
3680 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
3681 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003682}
3683
Alexey Bataev5a3af132016-03-29 08:58:54 +00003684/// Build preinits statement for the given declarations.
3685static Stmt *buildPreInits(ASTContext &Context,
3686 SmallVectorImpl<Decl *> &PreInits) {
3687 if (!PreInits.empty()) {
3688 return new (Context) DeclStmt(
3689 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
3690 SourceLocation(), SourceLocation());
3691 }
3692 return nullptr;
3693}
3694
3695/// Build preinits statement for the given declarations.
3696static Stmt *buildPreInits(ASTContext &Context,
3697 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3698 if (!Captures.empty()) {
3699 SmallVector<Decl *, 16> PreInits;
3700 for (auto &Pair : Captures)
3701 PreInits.push_back(Pair.second->getDecl());
3702 return buildPreInits(Context, PreInits);
3703 }
3704 return nullptr;
3705}
3706
3707/// Build postupdate expression for the given list of postupdates expressions.
3708static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
3709 Expr *PostUpdate = nullptr;
3710 if (!PostUpdates.empty()) {
3711 for (auto *E : PostUpdates) {
3712 Expr *ConvE = S.BuildCStyleCastExpr(
3713 E->getExprLoc(),
3714 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
3715 E->getExprLoc(), E)
3716 .get();
3717 PostUpdate = PostUpdate
3718 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
3719 PostUpdate, ConvE)
3720 .get()
3721 : ConvE;
3722 }
3723 }
3724 return PostUpdate;
3725}
3726
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003727/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00003728/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
3729/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003730static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00003731CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
3732 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
3733 DSAStackTy &DSA,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003734 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00003735 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003736 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003737 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003738 // Found 'collapse' clause - calculate collapse number.
3739 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003740 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003741 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00003742 }
3743 if (OrderedLoopCountExpr) {
3744 // Found 'ordered' clause - calculate collapse number.
3745 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003746 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
3747 if (Result.getLimitedValue() < NestedLoopCount) {
3748 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3749 diag::err_omp_wrong_ordered_loop_count)
3750 << OrderedLoopCountExpr->getSourceRange();
3751 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3752 diag::note_collapse_loop_count)
3753 << CollapseLoopCountExpr->getSourceRange();
3754 }
3755 NestedLoopCount = Result.getLimitedValue();
3756 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003757 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003758 // This is helper routine for loop directives (e.g., 'for', 'simd',
3759 // 'for simd', etc.).
Alexey Bataev5a3af132016-03-29 08:58:54 +00003760 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003761 SmallVector<LoopIterationSpace, 4> IterSpaces;
3762 IterSpaces.resize(NestedLoopCount);
3763 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003764 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003765 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003766 NestedLoopCount, CollapseLoopCountExpr,
3767 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003768 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00003769 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003770 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003771 // OpenMP [2.8.1, simd construct, Restrictions]
3772 // All loops associated with the construct must be perfectly nested; that
3773 // is, there must be no intervening code nor any OpenMP directive between
3774 // any two loops.
3775 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003776 }
3777
Alexander Musmana5f070a2014-10-01 06:03:56 +00003778 Built.clear(/* size */ NestedLoopCount);
3779
3780 if (SemaRef.CurContext->isDependentContext())
3781 return NestedLoopCount;
3782
3783 // An example of what is generated for the following code:
3784 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00003785 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00003786 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003787 // for (k = 0; k < NK; ++k)
3788 // for (j = J0; j < NJ; j+=2) {
3789 // <loop body>
3790 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003791 //
3792 // We generate the code below.
3793 // Note: the loop body may be outlined in CodeGen.
3794 // Note: some counters may be C++ classes, operator- is used to find number of
3795 // iterations and operator+= to calculate counter value.
3796 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
3797 // or i64 is currently supported).
3798 //
3799 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
3800 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
3801 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
3802 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
3803 // // similar updates for vars in clauses (e.g. 'linear')
3804 // <loop body (using local i and j)>
3805 // }
3806 // i = NI; // assign final values of counters
3807 // j = NJ;
3808 //
3809
3810 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
3811 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00003812 // Precondition tests if there is at least one iteration (all conditions are
3813 // true).
3814 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003815 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003816 ExprResult LastIteration32 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00003817 32 /* Bits */, SemaRef
3818 .PerformImplicitConversion(
3819 N0->IgnoreImpCasts(), N0->getType(),
3820 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003821 .get(),
3822 SemaRef);
3823 ExprResult LastIteration64 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00003824 64 /* Bits */, SemaRef
3825 .PerformImplicitConversion(
3826 N0->IgnoreImpCasts(), N0->getType(),
3827 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003828 .get(),
3829 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003830
3831 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
3832 return NestedLoopCount;
3833
3834 auto &C = SemaRef.Context;
3835 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
3836
3837 Scope *CurScope = DSA.getCurScope();
3838 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003839 if (PreCond.isUsable()) {
3840 PreCond = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_LAnd,
3841 PreCond.get(), IterSpaces[Cnt].PreCond);
3842 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003843 auto N = IterSpaces[Cnt].NumIterations;
3844 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
3845 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003846 LastIteration32 = SemaRef.BuildBinOp(
3847 CurScope, SourceLocation(), BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00003848 SemaRef
3849 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3850 Sema::AA_Converting,
3851 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003852 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003853 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003854 LastIteration64 = SemaRef.BuildBinOp(
3855 CurScope, SourceLocation(), BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00003856 SemaRef
3857 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3858 Sema::AA_Converting,
3859 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003860 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003861 }
3862
3863 // Choose either the 32-bit or 64-bit version.
3864 ExprResult LastIteration = LastIteration64;
3865 if (LastIteration32.isUsable() &&
3866 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
3867 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
3868 FitsInto(
3869 32 /* Bits */,
3870 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
3871 LastIteration64.get(), SemaRef)))
3872 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00003873 QualType VType = LastIteration.get()->getType();
3874 QualType RealVType = VType;
3875 QualType StrideVType = VType;
3876 if (isOpenMPTaskLoopDirective(DKind)) {
3877 VType =
3878 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3879 StrideVType =
3880 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3881 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003882
3883 if (!LastIteration.isUsable())
3884 return 0;
3885
3886 // Save the number of iterations.
3887 ExprResult NumIterations = LastIteration;
3888 {
3889 LastIteration = SemaRef.BuildBinOp(
3890 CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
3891 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3892 if (!LastIteration.isUsable())
3893 return 0;
3894 }
3895
3896 // Calculate the last iteration number beforehand instead of doing this on
3897 // each iteration. Do not do this if the number of iterations may be kfold-ed.
3898 llvm::APSInt Result;
3899 bool IsConstant =
3900 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
3901 ExprResult CalcLastIteration;
3902 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003903 ExprResult SaveRef =
3904 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003905 LastIteration = SaveRef;
3906
3907 // Prepare SaveRef + 1.
3908 NumIterations = SemaRef.BuildBinOp(
Alexey Bataev5a3af132016-03-29 08:58:54 +00003909 CurScope, SourceLocation(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00003910 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3911 if (!NumIterations.isUsable())
3912 return 0;
3913 }
3914
3915 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
3916
David Majnemer9d168222016-08-05 17:44:54 +00003917 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolli9925f152016-06-27 14:55:37 +00003918 ExprResult LB, UB, IL, ST, EUB, PrevLB, PrevUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003919 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
3920 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003921 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00003922 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
3923 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003924 SemaRef.AddInitializerToDecl(
3925 LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3926 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3927
3928 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00003929 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
3930 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003931 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
3932 /*DirectInit*/ false,
3933 /*TypeMayContainAuto*/ false);
3934
3935 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
3936 // This will be used to implement clause 'lastprivate'.
3937 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00003938 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
3939 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003940 SemaRef.AddInitializerToDecl(
3941 ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3942 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3943
3944 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00003945 VarDecl *STDecl =
3946 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
3947 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003948 SemaRef.AddInitializerToDecl(
3949 STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
3950 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3951
3952 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00003953 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00003954 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
3955 UB.get(), LastIteration.get());
3956 ExprResult CondOp = SemaRef.ActOnConditionalOp(
3957 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
3958 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
3959 CondOp.get());
3960 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
Carlo Bertolli9925f152016-06-27 14:55:37 +00003961
3962 // If we have a combined directive that combines 'distribute', 'for' or
3963 // 'simd' we need to be able to access the bounds of the schedule of the
3964 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
3965 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
3966 if (isOpenMPLoopBoundSharingDirective(DKind)) {
3967 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
3968
3969 // We expect to have at least 2 more parameters than the 'parallel'
3970 // directive does - the lower and upper bounds of the previous schedule.
3971 assert(CD->getNumParams() >= 4 &&
3972 "Unexpected number of parameters in loop combined directive");
3973
3974 // Set the proper type for the bounds given what we learned from the
3975 // enclosed loops.
3976 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
3977 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
3978
3979 // Previous lower and upper bounds are obtained from the region
3980 // parameters.
3981 PrevLB =
3982 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
3983 PrevUB =
3984 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
3985 }
Alexander Musmanc6388682014-12-15 07:07:06 +00003986 }
3987
3988 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003989 ExprResult IV;
3990 ExprResult Init;
3991 {
Alexey Bataev7292c292016-04-25 12:22:29 +00003992 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
3993 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00003994 Expr *RHS =
3995 (isOpenMPWorksharingDirective(DKind) ||
3996 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
3997 ? LB.get()
3998 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00003999 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4000 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004001 }
4002
Alexander Musmanc6388682014-12-15 07:07:06 +00004003 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004004 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00004005 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004006 (isOpenMPWorksharingDirective(DKind) ||
4007 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004008 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4009 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4010 NumIterations.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004011
4012 // Loop increment (IV = IV + 1)
4013 SourceLocation IncLoc;
4014 ExprResult Inc =
4015 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4016 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4017 if (!Inc.isUsable())
4018 return 0;
4019 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00004020 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4021 if (!Inc.isUsable())
4022 return 0;
4023
4024 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4025 // Used for directives with static scheduling.
4026 ExprResult NextLB, NextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004027 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4028 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004029 // LB + ST
4030 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4031 if (!NextLB.isUsable())
4032 return 0;
4033 // LB = LB + ST
4034 NextLB =
4035 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4036 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4037 if (!NextLB.isUsable())
4038 return 0;
4039 // UB + ST
4040 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4041 if (!NextUB.isUsable())
4042 return 0;
4043 // UB = UB + ST
4044 NextUB =
4045 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4046 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4047 if (!NextUB.isUsable())
4048 return 0;
4049 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004050
4051 // Build updates and final values of the loop counters.
4052 bool HasErrors = false;
4053 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004054 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004055 Built.Updates.resize(NestedLoopCount);
4056 Built.Finals.resize(NestedLoopCount);
Alexey Bataev8b427062016-05-25 12:36:08 +00004057 SmallVector<Expr *, 4> LoopMultipliers;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004058 {
4059 ExprResult Div;
4060 // Go from inner nested loop to outer.
4061 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4062 LoopIterationSpace &IS = IterSpaces[Cnt];
4063 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4064 // Build: Iter = (IV / Div) % IS.NumIters
4065 // where Div is product of previous iterations' IS.NumIters.
4066 ExprResult Iter;
4067 if (Div.isUsable()) {
4068 Iter =
4069 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4070 } else {
4071 Iter = IV;
4072 assert((Cnt == (int)NestedLoopCount - 1) &&
4073 "unusable div expected on first iteration only");
4074 }
4075
4076 if (Cnt != 0 && Iter.isUsable())
4077 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4078 IS.NumIterations);
4079 if (!Iter.isUsable()) {
4080 HasErrors = true;
4081 break;
4082 }
4083
Alexey Bataev39f915b82015-05-08 10:41:21 +00004084 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004085 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4086 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4087 IS.CounterVar->getExprLoc(),
4088 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004089 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004090 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004091 if (!Init.isUsable()) {
4092 HasErrors = true;
4093 break;
4094 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00004095 ExprResult Update = BuildCounterUpdate(
4096 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4097 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004098 if (!Update.isUsable()) {
4099 HasErrors = true;
4100 break;
4101 }
4102
4103 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4104 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00004105 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004106 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004107 if (!Final.isUsable()) {
4108 HasErrors = true;
4109 break;
4110 }
4111
4112 // Build Div for the next iteration: Div <- Div * IS.NumIters
4113 if (Cnt != 0) {
4114 if (Div.isUnset())
4115 Div = IS.NumIterations;
4116 else
4117 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4118 IS.NumIterations);
4119
4120 // Add parentheses (for debugging purposes only).
4121 if (Div.isUsable())
Alexey Bataev8b427062016-05-25 12:36:08 +00004122 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004123 if (!Div.isUsable()) {
4124 HasErrors = true;
4125 break;
4126 }
Alexey Bataev8b427062016-05-25 12:36:08 +00004127 LoopMultipliers.push_back(Div.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004128 }
4129 if (!Update.isUsable() || !Final.isUsable()) {
4130 HasErrors = true;
4131 break;
4132 }
4133 // Save results
4134 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00004135 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004136 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004137 Built.Updates[Cnt] = Update.get();
4138 Built.Finals[Cnt] = Final.get();
4139 }
4140 }
4141
4142 if (HasErrors)
4143 return 0;
4144
4145 // Save results
4146 Built.IterationVarRef = IV.get();
4147 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00004148 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004149 Built.CalcLastIteration =
4150 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004151 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00004152 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004153 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004154 Built.Init = Init.get();
4155 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004156 Built.LB = LB.get();
4157 Built.UB = UB.get();
4158 Built.IL = IL.get();
4159 Built.ST = ST.get();
4160 Built.EUB = EUB.get();
4161 Built.NLB = NextLB.get();
4162 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004163 Built.PrevLB = PrevLB.get();
4164 Built.PrevUB = PrevUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004165
Alexey Bataev8b427062016-05-25 12:36:08 +00004166 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4167 // Fill data for doacross depend clauses.
4168 for (auto Pair : DSA.getDoacrossDependClauses()) {
4169 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4170 Pair.first->setCounterValue(CounterVal);
4171 else {
4172 if (NestedLoopCount != Pair.second.size() ||
4173 NestedLoopCount != LoopMultipliers.size() + 1) {
4174 // Erroneous case - clause has some problems.
4175 Pair.first->setCounterValue(CounterVal);
4176 continue;
4177 }
4178 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4179 auto I = Pair.second.rbegin();
4180 auto IS = IterSpaces.rbegin();
4181 auto ILM = LoopMultipliers.rbegin();
4182 Expr *UpCounterVal = CounterVal;
4183 Expr *Multiplier = nullptr;
4184 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4185 if (I->first) {
4186 assert(IS->CounterStep);
4187 Expr *NormalizedOffset =
4188 SemaRef
4189 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4190 I->first, IS->CounterStep)
4191 .get();
4192 if (Multiplier) {
4193 NormalizedOffset =
4194 SemaRef
4195 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
4196 NormalizedOffset, Multiplier)
4197 .get();
4198 }
4199 assert(I->second == OO_Plus || I->second == OO_Minus);
4200 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
David Majnemer9d168222016-08-05 17:44:54 +00004201 UpCounterVal = SemaRef
4202 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
4203 UpCounterVal, NormalizedOffset)
4204 .get();
Alexey Bataev8b427062016-05-25 12:36:08 +00004205 }
4206 Multiplier = *ILM;
4207 ++I;
4208 ++IS;
4209 ++ILM;
4210 }
4211 Pair.first->setCounterValue(UpCounterVal);
4212 }
4213 }
4214
Alexey Bataevabfc0692014-06-25 06:52:00 +00004215 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004216}
4217
Alexey Bataev10e775f2015-07-30 11:36:16 +00004218static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004219 auto CollapseClauses =
4220 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4221 if (CollapseClauses.begin() != CollapseClauses.end())
4222 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004223 return nullptr;
4224}
4225
Alexey Bataev10e775f2015-07-30 11:36:16 +00004226static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004227 auto OrderedClauses =
4228 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4229 if (OrderedClauses.begin() != OrderedClauses.end())
4230 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004231 return nullptr;
4232}
4233
Kelvin Lic5609492016-07-15 04:39:07 +00004234static bool checkSimdlenSafelenSpecified(Sema &S,
4235 const ArrayRef<OMPClause *> Clauses) {
4236 OMPSafelenClause *Safelen = nullptr;
4237 OMPSimdlenClause *Simdlen = nullptr;
4238
4239 for (auto *Clause : Clauses) {
4240 if (Clause->getClauseKind() == OMPC_safelen)
4241 Safelen = cast<OMPSafelenClause>(Clause);
4242 else if (Clause->getClauseKind() == OMPC_simdlen)
4243 Simdlen = cast<OMPSimdlenClause>(Clause);
4244 if (Safelen && Simdlen)
4245 break;
4246 }
4247
4248 if (Simdlen && Safelen) {
4249 llvm::APSInt SimdlenRes, SafelenRes;
4250 auto SimdlenLength = Simdlen->getSimdlen();
4251 auto SafelenLength = Safelen->getSafelen();
4252 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
4253 SimdlenLength->isInstantiationDependent() ||
4254 SimdlenLength->containsUnexpandedParameterPack())
4255 return false;
4256 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
4257 SafelenLength->isInstantiationDependent() ||
4258 SafelenLength->containsUnexpandedParameterPack())
4259 return false;
4260 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
4261 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
4262 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
4263 // If both simdlen and safelen clauses are specified, the value of the
4264 // simdlen parameter must be less than or equal to the value of the safelen
4265 // parameter.
4266 if (SimdlenRes > SafelenRes) {
4267 S.Diag(SimdlenLength->getExprLoc(),
4268 diag::err_omp_wrong_simdlen_safelen_values)
4269 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
4270 return true;
4271 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00004272 }
4273 return false;
4274}
4275
Alexey Bataev4acb8592014-07-07 13:01:15 +00004276StmtResult Sema::ActOnOpenMPSimdDirective(
4277 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4278 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004279 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004280 if (!AStmt)
4281 return StmtError();
4282
4283 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004284 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004285 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4286 // define the nested loops number.
4287 unsigned NestedLoopCount = CheckOpenMPLoop(
4288 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4289 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004290 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004291 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004292
Alexander Musmana5f070a2014-10-01 06:03:56 +00004293 assert((CurContext->isDependentContext() || B.builtAll()) &&
4294 "omp simd loop exprs were not built");
4295
Alexander Musman3276a272015-03-21 10:12:56 +00004296 if (!CurContext->isDependentContext()) {
4297 // Finalize the clauses that need pre-built expressions for CodeGen.
4298 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004299 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00004300 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004301 B.NumIterations, *this, CurScope,
4302 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00004303 return StmtError();
4304 }
4305 }
4306
Kelvin Lic5609492016-07-15 04:39:07 +00004307 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004308 return StmtError();
4309
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004310 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004311 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4312 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004313}
4314
Alexey Bataev4acb8592014-07-07 13:01:15 +00004315StmtResult Sema::ActOnOpenMPForDirective(
4316 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4317 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004318 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004319 if (!AStmt)
4320 return StmtError();
4321
4322 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004323 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004324 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4325 // define the nested loops number.
4326 unsigned NestedLoopCount = CheckOpenMPLoop(
4327 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4328 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004329 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00004330 return StmtError();
4331
Alexander Musmana5f070a2014-10-01 06:03:56 +00004332 assert((CurContext->isDependentContext() || B.builtAll()) &&
4333 "omp for loop exprs were not built");
4334
Alexey Bataev54acd402015-08-04 11:18:19 +00004335 if (!CurContext->isDependentContext()) {
4336 // Finalize the clauses that need pre-built expressions for CodeGen.
4337 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004338 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004339 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004340 B.NumIterations, *this, CurScope,
4341 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004342 return StmtError();
4343 }
4344 }
4345
Alexey Bataevf29276e2014-06-18 04:14:57 +00004346 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004347 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004348 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00004349}
4350
Alexander Musmanf82886e2014-09-18 05:12:34 +00004351StmtResult Sema::ActOnOpenMPForSimdDirective(
4352 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4353 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004354 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004355 if (!AStmt)
4356 return StmtError();
4357
4358 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004359 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004360 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4361 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00004362 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004363 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
4364 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4365 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004366 if (NestedLoopCount == 0)
4367 return StmtError();
4368
Alexander Musmanc6388682014-12-15 07:07:06 +00004369 assert((CurContext->isDependentContext() || B.builtAll()) &&
4370 "omp for simd loop exprs were not built");
4371
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004372 if (!CurContext->isDependentContext()) {
4373 // Finalize the clauses that need pre-built expressions for CodeGen.
4374 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004375 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004376 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004377 B.NumIterations, *this, CurScope,
4378 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004379 return StmtError();
4380 }
4381 }
4382
Kelvin Lic5609492016-07-15 04:39:07 +00004383 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004384 return StmtError();
4385
Alexander Musmanf82886e2014-09-18 05:12:34 +00004386 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004387 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4388 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004389}
4390
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004391StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
4392 Stmt *AStmt,
4393 SourceLocation StartLoc,
4394 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004395 if (!AStmt)
4396 return StmtError();
4397
4398 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004399 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004400 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004401 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004402 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004403 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004404 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004405 return StmtError();
4406 // All associated statements must be '#pragma omp section' except for
4407 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004408 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004409 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4410 if (SectionStmt)
4411 Diag(SectionStmt->getLocStart(),
4412 diag::err_omp_sections_substmt_not_section);
4413 return StmtError();
4414 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004415 cast<OMPSectionDirective>(SectionStmt)
4416 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004417 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004418 } else {
4419 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
4420 return StmtError();
4421 }
4422
4423 getCurFunction()->setHasBranchProtectedScope();
4424
Alexey Bataev25e5b442015-09-15 12:52:43 +00004425 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4426 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004427}
4428
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004429StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
4430 SourceLocation StartLoc,
4431 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004432 if (!AStmt)
4433 return StmtError();
4434
4435 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004436
4437 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00004438 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004439
Alexey Bataev25e5b442015-09-15 12:52:43 +00004440 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
4441 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004442}
4443
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004444StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
4445 Stmt *AStmt,
4446 SourceLocation StartLoc,
4447 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004448 if (!AStmt)
4449 return StmtError();
4450
4451 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00004452
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004453 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00004454
Alexey Bataev3255bf32015-01-19 05:20:46 +00004455 // OpenMP [2.7.3, single Construct, Restrictions]
4456 // The copyprivate clause must not be used with the nowait clause.
4457 OMPClause *Nowait = nullptr;
4458 OMPClause *Copyprivate = nullptr;
4459 for (auto *Clause : Clauses) {
4460 if (Clause->getClauseKind() == OMPC_nowait)
4461 Nowait = Clause;
4462 else if (Clause->getClauseKind() == OMPC_copyprivate)
4463 Copyprivate = Clause;
4464 if (Copyprivate && Nowait) {
4465 Diag(Copyprivate->getLocStart(),
4466 diag::err_omp_single_copyprivate_with_nowait);
4467 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
4468 return StmtError();
4469 }
4470 }
4471
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004472 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4473}
4474
Alexander Musman80c22892014-07-17 08:54:58 +00004475StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
4476 SourceLocation StartLoc,
4477 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004478 if (!AStmt)
4479 return StmtError();
4480
4481 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00004482
4483 getCurFunction()->setHasBranchProtectedScope();
4484
4485 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
4486}
4487
Alexey Bataev28c75412015-12-15 08:19:24 +00004488StmtResult Sema::ActOnOpenMPCriticalDirective(
4489 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
4490 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004491 if (!AStmt)
4492 return StmtError();
4493
4494 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004495
Alexey Bataev28c75412015-12-15 08:19:24 +00004496 bool ErrorFound = false;
4497 llvm::APSInt Hint;
4498 SourceLocation HintLoc;
4499 bool DependentHint = false;
4500 for (auto *C : Clauses) {
4501 if (C->getClauseKind() == OMPC_hint) {
4502 if (!DirName.getName()) {
4503 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
4504 ErrorFound = true;
4505 }
4506 Expr *E = cast<OMPHintClause>(C)->getHint();
4507 if (E->isTypeDependent() || E->isValueDependent() ||
4508 E->isInstantiationDependent())
4509 DependentHint = true;
4510 else {
4511 Hint = E->EvaluateKnownConstInt(Context);
4512 HintLoc = C->getLocStart();
4513 }
4514 }
4515 }
4516 if (ErrorFound)
4517 return StmtError();
4518 auto Pair = DSAStack->getCriticalWithHint(DirName);
4519 if (Pair.first && DirName.getName() && !DependentHint) {
4520 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
4521 Diag(StartLoc, diag::err_omp_critical_with_hint);
4522 if (HintLoc.isValid()) {
4523 Diag(HintLoc, diag::note_omp_critical_hint_here)
4524 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
4525 } else
4526 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
4527 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
4528 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
4529 << 1
4530 << C->getHint()->EvaluateKnownConstInt(Context).toString(
4531 /*Radix=*/10, /*Signed=*/false);
4532 } else
4533 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
4534 }
4535 }
4536
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004537 getCurFunction()->setHasBranchProtectedScope();
4538
Alexey Bataev28c75412015-12-15 08:19:24 +00004539 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
4540 Clauses, AStmt);
4541 if (!Pair.first && DirName.getName() && !DependentHint)
4542 DSAStack->addCriticalWithHint(Dir, Hint);
4543 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004544}
4545
Alexey Bataev4acb8592014-07-07 13:01:15 +00004546StmtResult Sema::ActOnOpenMPParallelForDirective(
4547 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4548 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004549 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004550 if (!AStmt)
4551 return StmtError();
4552
Alexey Bataev4acb8592014-07-07 13:01:15 +00004553 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4554 // 1.2.2 OpenMP Language Terminology
4555 // Structured block - An executable statement with a single entry at the
4556 // top and a single exit at the bottom.
4557 // The point of exit cannot be a branch out of the structured block.
4558 // longjmp() and throw() must not violate the entry/exit criteria.
4559 CS->getCapturedDecl()->setNothrow();
4560
Alexander Musmanc6388682014-12-15 07:07:06 +00004561 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004562 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4563 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004564 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004565 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
4566 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4567 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004568 if (NestedLoopCount == 0)
4569 return StmtError();
4570
Alexander Musmana5f070a2014-10-01 06:03:56 +00004571 assert((CurContext->isDependentContext() || B.builtAll()) &&
4572 "omp parallel for loop exprs were not built");
4573
Alexey Bataev54acd402015-08-04 11:18:19 +00004574 if (!CurContext->isDependentContext()) {
4575 // Finalize the clauses that need pre-built expressions for CodeGen.
4576 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004577 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004578 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004579 B.NumIterations, *this, CurScope,
4580 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004581 return StmtError();
4582 }
4583 }
4584
Alexey Bataev4acb8592014-07-07 13:01:15 +00004585 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004586 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004587 NestedLoopCount, Clauses, AStmt, B,
4588 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00004589}
4590
Alexander Musmane4e893b2014-09-23 09:33:00 +00004591StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
4592 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4593 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004594 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004595 if (!AStmt)
4596 return StmtError();
4597
Alexander Musmane4e893b2014-09-23 09:33:00 +00004598 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4599 // 1.2.2 OpenMP Language Terminology
4600 // Structured block - An executable statement with a single entry at the
4601 // top and a single exit at the bottom.
4602 // The point of exit cannot be a branch out of the structured block.
4603 // longjmp() and throw() must not violate the entry/exit criteria.
4604 CS->getCapturedDecl()->setNothrow();
4605
Alexander Musmanc6388682014-12-15 07:07:06 +00004606 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004607 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4608 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00004609 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004610 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
4611 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4612 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004613 if (NestedLoopCount == 0)
4614 return StmtError();
4615
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004616 if (!CurContext->isDependentContext()) {
4617 // Finalize the clauses that need pre-built expressions for CodeGen.
4618 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004619 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004620 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004621 B.NumIterations, *this, CurScope,
4622 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004623 return StmtError();
4624 }
4625 }
4626
Kelvin Lic5609492016-07-15 04:39:07 +00004627 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004628 return StmtError();
4629
Alexander Musmane4e893b2014-09-23 09:33:00 +00004630 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004631 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00004632 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004633}
4634
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004635StmtResult
4636Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
4637 Stmt *AStmt, SourceLocation StartLoc,
4638 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004639 if (!AStmt)
4640 return StmtError();
4641
4642 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004643 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004644 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004645 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004646 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004647 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004648 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004649 return StmtError();
4650 // All associated statements must be '#pragma omp section' except for
4651 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004652 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004653 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4654 if (SectionStmt)
4655 Diag(SectionStmt->getLocStart(),
4656 diag::err_omp_parallel_sections_substmt_not_section);
4657 return StmtError();
4658 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004659 cast<OMPSectionDirective>(SectionStmt)
4660 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004661 }
4662 } else {
4663 Diag(AStmt->getLocStart(),
4664 diag::err_omp_parallel_sections_not_compound_stmt);
4665 return StmtError();
4666 }
4667
4668 getCurFunction()->setHasBranchProtectedScope();
4669
Alexey Bataev25e5b442015-09-15 12:52:43 +00004670 return OMPParallelSectionsDirective::Create(
4671 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004672}
4673
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004674StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
4675 Stmt *AStmt, SourceLocation StartLoc,
4676 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004677 if (!AStmt)
4678 return StmtError();
4679
David Majnemer9d168222016-08-05 17:44:54 +00004680 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004681 // 1.2.2 OpenMP Language Terminology
4682 // Structured block - An executable statement with a single entry at the
4683 // top and a single exit at the bottom.
4684 // The point of exit cannot be a branch out of the structured block.
4685 // longjmp() and throw() must not violate the entry/exit criteria.
4686 CS->getCapturedDecl()->setNothrow();
4687
4688 getCurFunction()->setHasBranchProtectedScope();
4689
Alexey Bataev25e5b442015-09-15 12:52:43 +00004690 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4691 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004692}
4693
Alexey Bataev68446b72014-07-18 07:47:19 +00004694StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
4695 SourceLocation EndLoc) {
4696 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
4697}
4698
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004699StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
4700 SourceLocation EndLoc) {
4701 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
4702}
4703
Alexey Bataev2df347a2014-07-18 10:17:07 +00004704StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
4705 SourceLocation EndLoc) {
4706 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
4707}
4708
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004709StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
4710 SourceLocation StartLoc,
4711 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004712 if (!AStmt)
4713 return StmtError();
4714
4715 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004716
4717 getCurFunction()->setHasBranchProtectedScope();
4718
4719 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
4720}
4721
Alexey Bataev6125da92014-07-21 11:26:11 +00004722StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
4723 SourceLocation StartLoc,
4724 SourceLocation EndLoc) {
4725 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
4726 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
4727}
4728
Alexey Bataev346265e2015-09-25 10:37:12 +00004729StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
4730 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004731 SourceLocation StartLoc,
4732 SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00004733 OMPClause *DependFound = nullptr;
4734 OMPClause *DependSourceClause = nullptr;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004735 OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00004736 bool ErrorFound = false;
Alexey Bataev346265e2015-09-25 10:37:12 +00004737 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004738 OMPSIMDClause *SC = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00004739 for (auto *C : Clauses) {
4740 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
4741 DependFound = C;
4742 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
4743 if (DependSourceClause) {
4744 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
4745 << getOpenMPDirectiveName(OMPD_ordered)
4746 << getOpenMPClauseName(OMPC_depend) << 2;
4747 ErrorFound = true;
4748 } else
4749 DependSourceClause = C;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004750 if (DependSinkClause) {
4751 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4752 << 0;
4753 ErrorFound = true;
4754 }
4755 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
4756 if (DependSourceClause) {
4757 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4758 << 1;
4759 ErrorFound = true;
4760 }
4761 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00004762 }
4763 } else if (C->getClauseKind() == OMPC_threads)
Alexey Bataev346265e2015-09-25 10:37:12 +00004764 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004765 else if (C->getClauseKind() == OMPC_simd)
4766 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00004767 }
Alexey Bataeveb482352015-12-18 05:05:56 +00004768 if (!ErrorFound && !SC &&
4769 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004770 // OpenMP [2.8.1,simd Construct, Restrictions]
4771 // An ordered construct with the simd clause is the only OpenMP construct
4772 // that can appear in the simd region.
4773 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00004774 ErrorFound = true;
4775 } else if (DependFound && (TC || SC)) {
4776 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
4777 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
4778 ErrorFound = true;
4779 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
4780 Diag(DependFound->getLocStart(),
4781 diag::err_omp_ordered_directive_without_param);
4782 ErrorFound = true;
4783 } else if (TC || Clauses.empty()) {
4784 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
4785 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
4786 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
4787 << (TC != nullptr);
4788 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
4789 ErrorFound = true;
4790 }
4791 }
4792 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004793 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00004794
4795 if (AStmt) {
4796 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4797
4798 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004799 }
Alexey Bataev346265e2015-09-25 10:37:12 +00004800
4801 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004802}
4803
Alexey Bataev1d160b12015-03-13 12:27:31 +00004804namespace {
4805/// \brief Helper class for checking expression in 'omp atomic [update]'
4806/// construct.
4807class OpenMPAtomicUpdateChecker {
4808 /// \brief Error results for atomic update expressions.
4809 enum ExprAnalysisErrorCode {
4810 /// \brief A statement is not an expression statement.
4811 NotAnExpression,
4812 /// \brief Expression is not builtin binary or unary operation.
4813 NotABinaryOrUnaryExpression,
4814 /// \brief Unary operation is not post-/pre- increment/decrement operation.
4815 NotAnUnaryIncDecExpression,
4816 /// \brief An expression is not of scalar type.
4817 NotAScalarType,
4818 /// \brief A binary operation is not an assignment operation.
4819 NotAnAssignmentOp,
4820 /// \brief RHS part of the binary operation is not a binary expression.
4821 NotABinaryExpression,
4822 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
4823 /// expression.
4824 NotABinaryOperator,
4825 /// \brief RHS binary operation does not have reference to the updated LHS
4826 /// part.
4827 NotAnUpdateExpression,
4828 /// \brief No errors is found.
4829 NoError
4830 };
4831 /// \brief Reference to Sema.
4832 Sema &SemaRef;
4833 /// \brief A location for note diagnostics (when error is found).
4834 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004835 /// \brief 'x' lvalue part of the source atomic expression.
4836 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004837 /// \brief 'expr' rvalue part of the source atomic expression.
4838 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004839 /// \brief Helper expression of the form
4840 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4841 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4842 Expr *UpdateExpr;
4843 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
4844 /// important for non-associative operations.
4845 bool IsXLHSInRHSPart;
4846 BinaryOperatorKind Op;
4847 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00004848 /// \brief true if the source expression is a postfix unary operation, false
4849 /// if it is a prefix unary operation.
4850 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004851
4852public:
4853 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00004854 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00004855 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00004856 /// \brief Check specified statement that it is suitable for 'atomic update'
4857 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00004858 /// expression. If DiagId and NoteId == 0, then only check is performed
4859 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00004860 /// \param DiagId Diagnostic which should be emitted if error is found.
4861 /// \param NoteId Diagnostic note for the main error message.
4862 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00004863 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00004864 /// \brief Return the 'x' lvalue part of the source atomic expression.
4865 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00004866 /// \brief Return the 'expr' rvalue part of the source atomic expression.
4867 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00004868 /// \brief Return the update expression used in calculation of the updated
4869 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4870 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4871 Expr *getUpdateExpr() const { return UpdateExpr; }
4872 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
4873 /// false otherwise.
4874 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
4875
Alexey Bataevb78ca832015-04-01 03:33:17 +00004876 /// \brief true if the source expression is a postfix unary operation, false
4877 /// if it is a prefix unary operation.
4878 bool isPostfixUpdate() const { return IsPostfixUpdate; }
4879
Alexey Bataev1d160b12015-03-13 12:27:31 +00004880private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00004881 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
4882 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00004883};
4884} // namespace
4885
4886bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
4887 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
4888 ExprAnalysisErrorCode ErrorFound = NoError;
4889 SourceLocation ErrorLoc, NoteLoc;
4890 SourceRange ErrorRange, NoteRange;
4891 // Allowed constructs are:
4892 // x = x binop expr;
4893 // x = expr binop x;
4894 if (AtomicBinOp->getOpcode() == BO_Assign) {
4895 X = AtomicBinOp->getLHS();
4896 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
4897 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
4898 if (AtomicInnerBinOp->isMultiplicativeOp() ||
4899 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
4900 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00004901 Op = AtomicInnerBinOp->getOpcode();
4902 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00004903 auto *LHS = AtomicInnerBinOp->getLHS();
4904 auto *RHS = AtomicInnerBinOp->getRHS();
4905 llvm::FoldingSetNodeID XId, LHSId, RHSId;
4906 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
4907 /*Canonical=*/true);
4908 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
4909 /*Canonical=*/true);
4910 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
4911 /*Canonical=*/true);
4912 if (XId == LHSId) {
4913 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004914 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004915 } else if (XId == RHSId) {
4916 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004917 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004918 } else {
4919 ErrorLoc = AtomicInnerBinOp->getExprLoc();
4920 ErrorRange = AtomicInnerBinOp->getSourceRange();
4921 NoteLoc = X->getExprLoc();
4922 NoteRange = X->getSourceRange();
4923 ErrorFound = NotAnUpdateExpression;
4924 }
4925 } else {
4926 ErrorLoc = AtomicInnerBinOp->getExprLoc();
4927 ErrorRange = AtomicInnerBinOp->getSourceRange();
4928 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
4929 NoteRange = SourceRange(NoteLoc, NoteLoc);
4930 ErrorFound = NotABinaryOperator;
4931 }
4932 } else {
4933 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
4934 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
4935 ErrorFound = NotABinaryExpression;
4936 }
4937 } else {
4938 ErrorLoc = AtomicBinOp->getExprLoc();
4939 ErrorRange = AtomicBinOp->getSourceRange();
4940 NoteLoc = AtomicBinOp->getOperatorLoc();
4941 NoteRange = SourceRange(NoteLoc, NoteLoc);
4942 ErrorFound = NotAnAssignmentOp;
4943 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00004944 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00004945 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
4946 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
4947 return true;
4948 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00004949 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00004950 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004951}
4952
4953bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
4954 unsigned NoteId) {
4955 ExprAnalysisErrorCode ErrorFound = NoError;
4956 SourceLocation ErrorLoc, NoteLoc;
4957 SourceRange ErrorRange, NoteRange;
4958 // Allowed constructs are:
4959 // x++;
4960 // x--;
4961 // ++x;
4962 // --x;
4963 // x binop= expr;
4964 // x = x binop expr;
4965 // x = expr binop x;
4966 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
4967 AtomicBody = AtomicBody->IgnoreParenImpCasts();
4968 if (AtomicBody->getType()->isScalarType() ||
4969 AtomicBody->isInstantiationDependent()) {
4970 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
4971 AtomicBody->IgnoreParenImpCasts())) {
4972 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00004973 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00004974 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00004975 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00004976 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00004977 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00004978 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004979 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
4980 AtomicBody->IgnoreParenImpCasts())) {
4981 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00004982 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00004983 return true;
David Majnemer9d168222016-08-05 17:44:54 +00004984 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
4985 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00004986 // Check for Unary Operation
4987 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00004988 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00004989 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
4990 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00004991 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00004992 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
4993 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004994 } else {
4995 ErrorFound = NotAnUnaryIncDecExpression;
4996 ErrorLoc = AtomicUnaryOp->getExprLoc();
4997 ErrorRange = AtomicUnaryOp->getSourceRange();
4998 NoteLoc = AtomicUnaryOp->getOperatorLoc();
4999 NoteRange = SourceRange(NoteLoc, NoteLoc);
5000 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005001 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005002 ErrorFound = NotABinaryOrUnaryExpression;
5003 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5004 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5005 }
5006 } else {
5007 ErrorFound = NotAScalarType;
5008 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5009 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5010 }
5011 } else {
5012 ErrorFound = NotAnExpression;
5013 NoteLoc = ErrorLoc = S->getLocStart();
5014 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5015 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005016 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005017 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5018 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5019 return true;
5020 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005021 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005022 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005023 // Build an update expression of form 'OpaqueValueExpr(x) binop
5024 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5025 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5026 auto *OVEX = new (SemaRef.getASTContext())
5027 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5028 auto *OVEExpr = new (SemaRef.getASTContext())
5029 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5030 auto Update =
5031 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5032 IsXLHSInRHSPart ? OVEExpr : OVEX);
5033 if (Update.isInvalid())
5034 return true;
5035 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5036 Sema::AA_Casting);
5037 if (Update.isInvalid())
5038 return true;
5039 UpdateExpr = Update.get();
5040 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00005041 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005042}
5043
Alexey Bataev0162e452014-07-22 10:10:35 +00005044StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5045 Stmt *AStmt,
5046 SourceLocation StartLoc,
5047 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005048 if (!AStmt)
5049 return StmtError();
5050
David Majnemer9d168222016-08-05 17:44:54 +00005051 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00005052 // 1.2.2 OpenMP Language Terminology
5053 // Structured block - An executable statement with a single entry at the
5054 // top and a single exit at the bottom.
5055 // The point of exit cannot be a branch out of the structured block.
5056 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00005057 OpenMPClauseKind AtomicKind = OMPC_unknown;
5058 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005059 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00005060 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00005061 C->getClauseKind() == OMPC_update ||
5062 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00005063 if (AtomicKind != OMPC_unknown) {
5064 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5065 << SourceRange(C->getLocStart(), C->getLocEnd());
5066 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5067 << getOpenMPClauseName(AtomicKind);
5068 } else {
5069 AtomicKind = C->getClauseKind();
5070 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005071 }
5072 }
5073 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005074
Alexey Bataev459dec02014-07-24 06:46:57 +00005075 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00005076 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5077 Body = EWC->getSubExpr();
5078
Alexey Bataev62cec442014-11-18 10:14:22 +00005079 Expr *X = nullptr;
5080 Expr *V = nullptr;
5081 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005082 Expr *UE = nullptr;
5083 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005084 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00005085 // OpenMP [2.12.6, atomic Construct]
5086 // In the next expressions:
5087 // * x and v (as applicable) are both l-value expressions with scalar type.
5088 // * During the execution of an atomic region, multiple syntactic
5089 // occurrences of x must designate the same storage location.
5090 // * Neither of v and expr (as applicable) may access the storage location
5091 // designated by x.
5092 // * Neither of x and expr (as applicable) may access the storage location
5093 // designated by v.
5094 // * expr is an expression with scalar type.
5095 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5096 // * binop, binop=, ++, and -- are not overloaded operators.
5097 // * The expression x binop expr must be numerically equivalent to x binop
5098 // (expr). This requirement is satisfied if the operators in expr have
5099 // precedence greater than binop, or by using parentheses around expr or
5100 // subexpressions of expr.
5101 // * The expression expr binop x must be numerically equivalent to (expr)
5102 // binop x. This requirement is satisfied if the operators in expr have
5103 // precedence equal to or greater than binop, or by using parentheses around
5104 // expr or subexpressions of expr.
5105 // * For forms that allow multiple occurrences of x, the number of times
5106 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00005107 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005108 enum {
5109 NotAnExpression,
5110 NotAnAssignmentOp,
5111 NotAScalarType,
5112 NotAnLValue,
5113 NoError
5114 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00005115 SourceLocation ErrorLoc, NoteLoc;
5116 SourceRange ErrorRange, NoteRange;
5117 // If clause is read:
5118 // v = x;
David Majnemer9d168222016-08-05 17:44:54 +00005119 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5120 auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00005121 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5122 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5123 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5124 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5125 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5126 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5127 if (!X->isLValue() || !V->isLValue()) {
5128 auto NotLValueExpr = X->isLValue() ? V : X;
5129 ErrorFound = NotAnLValue;
5130 ErrorLoc = AtomicBinOp->getExprLoc();
5131 ErrorRange = AtomicBinOp->getSourceRange();
5132 NoteLoc = NotLValueExpr->getExprLoc();
5133 NoteRange = NotLValueExpr->getSourceRange();
5134 }
5135 } else if (!X->isInstantiationDependent() ||
5136 !V->isInstantiationDependent()) {
5137 auto NotScalarExpr =
5138 (X->isInstantiationDependent() || X->getType()->isScalarType())
5139 ? V
5140 : X;
5141 ErrorFound = NotAScalarType;
5142 ErrorLoc = AtomicBinOp->getExprLoc();
5143 ErrorRange = AtomicBinOp->getSourceRange();
5144 NoteLoc = NotScalarExpr->getExprLoc();
5145 NoteRange = NotScalarExpr->getSourceRange();
5146 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005147 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00005148 ErrorFound = NotAnAssignmentOp;
5149 ErrorLoc = AtomicBody->getExprLoc();
5150 ErrorRange = AtomicBody->getSourceRange();
5151 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5152 : AtomicBody->getExprLoc();
5153 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5154 : AtomicBody->getSourceRange();
5155 }
5156 } else {
5157 ErrorFound = NotAnExpression;
5158 NoteLoc = ErrorLoc = Body->getLocStart();
5159 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005160 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005161 if (ErrorFound != NoError) {
5162 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5163 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005164 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5165 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00005166 return StmtError();
5167 } else if (CurContext->isDependentContext())
5168 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00005169 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005170 enum {
5171 NotAnExpression,
5172 NotAnAssignmentOp,
5173 NotAScalarType,
5174 NotAnLValue,
5175 NoError
5176 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005177 SourceLocation ErrorLoc, NoteLoc;
5178 SourceRange ErrorRange, NoteRange;
5179 // If clause is write:
5180 // x = expr;
David Majnemer9d168222016-08-05 17:44:54 +00005181 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5182 auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00005183 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5184 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00005185 X = AtomicBinOp->getLHS();
5186 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00005187 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5188 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5189 if (!X->isLValue()) {
5190 ErrorFound = NotAnLValue;
5191 ErrorLoc = AtomicBinOp->getExprLoc();
5192 ErrorRange = AtomicBinOp->getSourceRange();
5193 NoteLoc = X->getExprLoc();
5194 NoteRange = X->getSourceRange();
5195 }
5196 } else if (!X->isInstantiationDependent() ||
5197 !E->isInstantiationDependent()) {
5198 auto NotScalarExpr =
5199 (X->isInstantiationDependent() || X->getType()->isScalarType())
5200 ? E
5201 : X;
5202 ErrorFound = NotAScalarType;
5203 ErrorLoc = AtomicBinOp->getExprLoc();
5204 ErrorRange = AtomicBinOp->getSourceRange();
5205 NoteLoc = NotScalarExpr->getExprLoc();
5206 NoteRange = NotScalarExpr->getSourceRange();
5207 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005208 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00005209 ErrorFound = NotAnAssignmentOp;
5210 ErrorLoc = AtomicBody->getExprLoc();
5211 ErrorRange = AtomicBody->getSourceRange();
5212 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5213 : AtomicBody->getExprLoc();
5214 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5215 : AtomicBody->getSourceRange();
5216 }
5217 } else {
5218 ErrorFound = NotAnExpression;
5219 NoteLoc = ErrorLoc = Body->getLocStart();
5220 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005221 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00005222 if (ErrorFound != NoError) {
5223 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
5224 << ErrorRange;
5225 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5226 << NoteRange;
5227 return StmtError();
5228 } else if (CurContext->isDependentContext())
5229 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00005230 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005231 // If clause is update:
5232 // x++;
5233 // x--;
5234 // ++x;
5235 // --x;
5236 // x binop= expr;
5237 // x = x binop expr;
5238 // x = expr binop x;
5239 OpenMPAtomicUpdateChecker Checker(*this);
5240 if (Checker.checkStatement(
5241 Body, (AtomicKind == OMPC_update)
5242 ? diag::err_omp_atomic_update_not_expression_statement
5243 : diag::err_omp_atomic_not_expression_statement,
5244 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00005245 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005246 if (!CurContext->isDependentContext()) {
5247 E = Checker.getExpr();
5248 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005249 UE = Checker.getUpdateExpr();
5250 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00005251 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005252 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005253 enum {
5254 NotAnAssignmentOp,
5255 NotACompoundStatement,
5256 NotTwoSubstatements,
5257 NotASpecificExpression,
5258 NoError
5259 } ErrorFound = NoError;
5260 SourceLocation ErrorLoc, NoteLoc;
5261 SourceRange ErrorRange, NoteRange;
5262 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5263 // If clause is a capture:
5264 // v = x++;
5265 // v = x--;
5266 // v = ++x;
5267 // v = --x;
5268 // v = x binop= expr;
5269 // v = x = x binop expr;
5270 // v = x = expr binop x;
5271 auto *AtomicBinOp =
5272 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5273 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5274 V = AtomicBinOp->getLHS();
5275 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5276 OpenMPAtomicUpdateChecker Checker(*this);
5277 if (Checker.checkStatement(
5278 Body, diag::err_omp_atomic_capture_not_expression_statement,
5279 diag::note_omp_atomic_update))
5280 return StmtError();
5281 E = Checker.getExpr();
5282 X = Checker.getX();
5283 UE = Checker.getUpdateExpr();
5284 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5285 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00005286 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005287 ErrorLoc = AtomicBody->getExprLoc();
5288 ErrorRange = AtomicBody->getSourceRange();
5289 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5290 : AtomicBody->getExprLoc();
5291 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5292 : AtomicBody->getSourceRange();
5293 ErrorFound = NotAnAssignmentOp;
5294 }
5295 if (ErrorFound != NoError) {
5296 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
5297 << ErrorRange;
5298 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5299 return StmtError();
5300 } else if (CurContext->isDependentContext()) {
5301 UE = V = E = X = nullptr;
5302 }
5303 } else {
5304 // If clause is a capture:
5305 // { v = x; x = expr; }
5306 // { v = x; x++; }
5307 // { v = x; x--; }
5308 // { v = x; ++x; }
5309 // { v = x; --x; }
5310 // { v = x; x binop= expr; }
5311 // { v = x; x = x binop expr; }
5312 // { v = x; x = expr binop x; }
5313 // { x++; v = x; }
5314 // { x--; v = x; }
5315 // { ++x; v = x; }
5316 // { --x; v = x; }
5317 // { x binop= expr; v = x; }
5318 // { x = x binop expr; v = x; }
5319 // { x = expr binop x; v = x; }
5320 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
5321 // Check that this is { expr1; expr2; }
5322 if (CS->size() == 2) {
5323 auto *First = CS->body_front();
5324 auto *Second = CS->body_back();
5325 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
5326 First = EWC->getSubExpr()->IgnoreParenImpCasts();
5327 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
5328 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
5329 // Need to find what subexpression is 'v' and what is 'x'.
5330 OpenMPAtomicUpdateChecker Checker(*this);
5331 bool IsUpdateExprFound = !Checker.checkStatement(Second);
5332 BinaryOperator *BinOp = nullptr;
5333 if (IsUpdateExprFound) {
5334 BinOp = dyn_cast<BinaryOperator>(First);
5335 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5336 }
5337 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5338 // { v = x; x++; }
5339 // { v = x; x--; }
5340 // { v = x; ++x; }
5341 // { v = x; --x; }
5342 // { v = x; x binop= expr; }
5343 // { v = x; x = x binop expr; }
5344 // { v = x; x = expr binop x; }
5345 // Check that the first expression has form v = x.
5346 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5347 llvm::FoldingSetNodeID XId, PossibleXId;
5348 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5349 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5350 IsUpdateExprFound = XId == PossibleXId;
5351 if (IsUpdateExprFound) {
5352 V = BinOp->getLHS();
5353 X = Checker.getX();
5354 E = Checker.getExpr();
5355 UE = Checker.getUpdateExpr();
5356 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005357 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005358 }
5359 }
5360 if (!IsUpdateExprFound) {
5361 IsUpdateExprFound = !Checker.checkStatement(First);
5362 BinOp = nullptr;
5363 if (IsUpdateExprFound) {
5364 BinOp = dyn_cast<BinaryOperator>(Second);
5365 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5366 }
5367 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5368 // { x++; v = x; }
5369 // { x--; v = x; }
5370 // { ++x; v = x; }
5371 // { --x; v = x; }
5372 // { x binop= expr; v = x; }
5373 // { x = x binop expr; v = x; }
5374 // { x = expr binop x; v = x; }
5375 // Check that the second expression has form v = x.
5376 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5377 llvm::FoldingSetNodeID XId, PossibleXId;
5378 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5379 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5380 IsUpdateExprFound = XId == PossibleXId;
5381 if (IsUpdateExprFound) {
5382 V = BinOp->getLHS();
5383 X = Checker.getX();
5384 E = Checker.getExpr();
5385 UE = Checker.getUpdateExpr();
5386 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005387 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005388 }
5389 }
5390 }
5391 if (!IsUpdateExprFound) {
5392 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00005393 auto *FirstExpr = dyn_cast<Expr>(First);
5394 auto *SecondExpr = dyn_cast<Expr>(Second);
5395 if (!FirstExpr || !SecondExpr ||
5396 !(FirstExpr->isInstantiationDependent() ||
5397 SecondExpr->isInstantiationDependent())) {
5398 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
5399 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005400 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00005401 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
5402 : First->getLocStart();
5403 NoteRange = ErrorRange = FirstBinOp
5404 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00005405 : SourceRange(ErrorLoc, ErrorLoc);
5406 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005407 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
5408 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
5409 ErrorFound = NotAnAssignmentOp;
5410 NoteLoc = ErrorLoc = SecondBinOp
5411 ? SecondBinOp->getOperatorLoc()
5412 : Second->getLocStart();
5413 NoteRange = ErrorRange =
5414 SecondBinOp ? SecondBinOp->getSourceRange()
5415 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00005416 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005417 auto *PossibleXRHSInFirst =
5418 FirstBinOp->getRHS()->IgnoreParenImpCasts();
5419 auto *PossibleXLHSInSecond =
5420 SecondBinOp->getLHS()->IgnoreParenImpCasts();
5421 llvm::FoldingSetNodeID X1Id, X2Id;
5422 PossibleXRHSInFirst->Profile(X1Id, Context,
5423 /*Canonical=*/true);
5424 PossibleXLHSInSecond->Profile(X2Id, Context,
5425 /*Canonical=*/true);
5426 IsUpdateExprFound = X1Id == X2Id;
5427 if (IsUpdateExprFound) {
5428 V = FirstBinOp->getLHS();
5429 X = SecondBinOp->getLHS();
5430 E = SecondBinOp->getRHS();
5431 UE = nullptr;
5432 IsXLHSInRHSPart = false;
5433 IsPostfixUpdate = true;
5434 } else {
5435 ErrorFound = NotASpecificExpression;
5436 ErrorLoc = FirstBinOp->getExprLoc();
5437 ErrorRange = FirstBinOp->getSourceRange();
5438 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
5439 NoteRange = SecondBinOp->getRHS()->getSourceRange();
5440 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005441 }
5442 }
5443 }
5444 }
5445 } else {
5446 NoteLoc = ErrorLoc = Body->getLocStart();
5447 NoteRange = ErrorRange =
5448 SourceRange(Body->getLocStart(), Body->getLocStart());
5449 ErrorFound = NotTwoSubstatements;
5450 }
5451 } else {
5452 NoteLoc = ErrorLoc = Body->getLocStart();
5453 NoteRange = ErrorRange =
5454 SourceRange(Body->getLocStart(), Body->getLocStart());
5455 ErrorFound = NotACompoundStatement;
5456 }
5457 if (ErrorFound != NoError) {
5458 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
5459 << ErrorRange;
5460 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5461 return StmtError();
5462 } else if (CurContext->isDependentContext()) {
5463 UE = V = E = X = nullptr;
5464 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005465 }
Alexey Bataevdea47612014-07-23 07:46:59 +00005466 }
Alexey Bataev0162e452014-07-22 10:10:35 +00005467
5468 getCurFunction()->setHasBranchProtectedScope();
5469
Alexey Bataev62cec442014-11-18 10:14:22 +00005470 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00005471 X, V, E, UE, IsXLHSInRHSPart,
5472 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00005473}
5474
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005475StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
5476 Stmt *AStmt,
5477 SourceLocation StartLoc,
5478 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005479 if (!AStmt)
5480 return StmtError();
5481
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005482 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5483 // 1.2.2 OpenMP Language Terminology
5484 // Structured block - An executable statement with a single entry at the
5485 // top and a single exit at the bottom.
5486 // The point of exit cannot be a branch out of the structured block.
5487 // longjmp() and throw() must not violate the entry/exit criteria.
5488 CS->getCapturedDecl()->setNothrow();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005489
Alexey Bataev13314bf2014-10-09 04:18:56 +00005490 // OpenMP [2.16, Nesting of Regions]
5491 // If specified, a teams construct must be contained within a target
5492 // construct. That target construct must contain no statements or directives
5493 // outside of the teams construct.
5494 if (DSAStack->hasInnerTeamsRegion()) {
5495 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
5496 bool OMPTeamsFound = true;
5497 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
5498 auto I = CS->body_begin();
5499 while (I != CS->body_end()) {
David Majnemer9d168222016-08-05 17:44:54 +00005500 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00005501 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
5502 OMPTeamsFound = false;
5503 break;
5504 }
5505 ++I;
5506 }
5507 assert(I != CS->body_end() && "Not found statement");
5508 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00005509 } else {
5510 auto *OED = dyn_cast<OMPExecutableDirective>(S);
5511 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00005512 }
5513 if (!OMPTeamsFound) {
5514 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
5515 Diag(DSAStack->getInnerTeamsRegionLoc(),
5516 diag::note_omp_nested_teams_construct_here);
5517 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
5518 << isa<OMPExecutableDirective>(S);
5519 return StmtError();
5520 }
5521 }
5522
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005523 getCurFunction()->setHasBranchProtectedScope();
5524
5525 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5526}
5527
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005528StmtResult
5529Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
5530 Stmt *AStmt, SourceLocation StartLoc,
5531 SourceLocation EndLoc) {
5532 if (!AStmt)
5533 return StmtError();
5534
5535 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5536 // 1.2.2 OpenMP Language Terminology
5537 // Structured block - An executable statement with a single entry at the
5538 // top and a single exit at the bottom.
5539 // The point of exit cannot be a branch out of the structured block.
5540 // longjmp() and throw() must not violate the entry/exit criteria.
5541 CS->getCapturedDecl()->setNothrow();
5542
5543 getCurFunction()->setHasBranchProtectedScope();
5544
5545 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5546 AStmt);
5547}
5548
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005549StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
5550 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5551 SourceLocation EndLoc,
5552 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5553 if (!AStmt)
5554 return StmtError();
5555
5556 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5557 // 1.2.2 OpenMP Language Terminology
5558 // Structured block - An executable statement with a single entry at the
5559 // top and a single exit at the bottom.
5560 // The point of exit cannot be a branch out of the structured block.
5561 // longjmp() and throw() must not violate the entry/exit criteria.
5562 CS->getCapturedDecl()->setNothrow();
5563
5564 OMPLoopDirective::HelperExprs B;
5565 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5566 // define the nested loops number.
5567 unsigned NestedLoopCount =
5568 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
5569 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5570 VarsWithImplicitDSA, B);
5571 if (NestedLoopCount == 0)
5572 return StmtError();
5573
5574 assert((CurContext->isDependentContext() || B.builtAll()) &&
5575 "omp target parallel for loop exprs were not built");
5576
5577 if (!CurContext->isDependentContext()) {
5578 // Finalize the clauses that need pre-built expressions for CodeGen.
5579 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005580 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005581 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005582 B.NumIterations, *this, CurScope,
5583 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005584 return StmtError();
5585 }
5586 }
5587
5588 getCurFunction()->setHasBranchProtectedScope();
5589 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
5590 NestedLoopCount, Clauses, AStmt,
5591 B, DSAStack->isCancelRegion());
5592}
5593
Samuel Antaodf67fc42016-01-19 19:15:56 +00005594/// \brief Check for existence of a map clause in the list of clauses.
5595static bool HasMapClause(ArrayRef<OMPClause *> Clauses) {
5596 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
5597 I != E; ++I) {
5598 if (*I != nullptr && (*I)->getClauseKind() == OMPC_map) {
5599 return true;
5600 }
5601 }
5602
5603 return false;
5604}
5605
Michael Wong65f367f2015-07-21 13:44:28 +00005606StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
5607 Stmt *AStmt,
5608 SourceLocation StartLoc,
5609 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005610 if (!AStmt)
5611 return StmtError();
5612
5613 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5614
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005615 // OpenMP [2.10.1, Restrictions, p. 97]
5616 // At least one map clause must appear on the directive.
5617 if (!HasMapClause(Clauses)) {
David Majnemer9d168222016-08-05 17:44:54 +00005618 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5619 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005620 return StmtError();
5621 }
5622
Michael Wong65f367f2015-07-21 13:44:28 +00005623 getCurFunction()->setHasBranchProtectedScope();
5624
5625 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
5626 AStmt);
5627}
5628
Samuel Antaodf67fc42016-01-19 19:15:56 +00005629StmtResult
5630Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
5631 SourceLocation StartLoc,
5632 SourceLocation EndLoc) {
5633 // OpenMP [2.10.2, Restrictions, p. 99]
5634 // At least one map clause must appear on the directive.
5635 if (!HasMapClause(Clauses)) {
5636 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5637 << getOpenMPDirectiveName(OMPD_target_enter_data);
5638 return StmtError();
5639 }
5640
5641 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
5642 Clauses);
5643}
5644
Samuel Antao72590762016-01-19 20:04:50 +00005645StmtResult
5646Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
5647 SourceLocation StartLoc,
5648 SourceLocation EndLoc) {
5649 // OpenMP [2.10.3, Restrictions, p. 102]
5650 // At least one map clause must appear on the directive.
5651 if (!HasMapClause(Clauses)) {
5652 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5653 << getOpenMPDirectiveName(OMPD_target_exit_data);
5654 return StmtError();
5655 }
5656
5657 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
5658}
5659
Samuel Antao686c70c2016-05-26 17:30:50 +00005660StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
5661 SourceLocation StartLoc,
5662 SourceLocation EndLoc) {
Samuel Antao686c70c2016-05-26 17:30:50 +00005663 bool seenMotionClause = false;
Samuel Antao661c0902016-05-26 17:39:58 +00005664 for (auto *C : Clauses) {
Samuel Antaoec172c62016-05-26 17:49:04 +00005665 if (C->getClauseKind() == OMPC_to || C->getClauseKind() == OMPC_from)
Samuel Antao661c0902016-05-26 17:39:58 +00005666 seenMotionClause = true;
5667 }
Samuel Antao686c70c2016-05-26 17:30:50 +00005668 if (!seenMotionClause) {
5669 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
5670 return StmtError();
5671 }
5672 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses);
5673}
5674
Alexey Bataev13314bf2014-10-09 04:18:56 +00005675StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
5676 Stmt *AStmt, SourceLocation StartLoc,
5677 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005678 if (!AStmt)
5679 return StmtError();
5680
Alexey Bataev13314bf2014-10-09 04:18:56 +00005681 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5682 // 1.2.2 OpenMP Language Terminology
5683 // Structured block - An executable statement with a single entry at the
5684 // top and a single exit at the bottom.
5685 // The point of exit cannot be a branch out of the structured block.
5686 // longjmp() and throw() must not violate the entry/exit criteria.
5687 CS->getCapturedDecl()->setNothrow();
5688
5689 getCurFunction()->setHasBranchProtectedScope();
5690
5691 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5692}
5693
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005694StmtResult
5695Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
5696 SourceLocation EndLoc,
5697 OpenMPDirectiveKind CancelRegion) {
5698 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5699 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5700 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5701 << getOpenMPDirectiveName(CancelRegion);
5702 return StmtError();
5703 }
5704 if (DSAStack->isParentNowaitRegion()) {
5705 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
5706 return StmtError();
5707 }
5708 if (DSAStack->isParentOrderedRegion()) {
5709 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
5710 return StmtError();
5711 }
5712 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
5713 CancelRegion);
5714}
5715
Alexey Bataev87933c72015-09-18 08:07:34 +00005716StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
5717 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00005718 SourceLocation EndLoc,
5719 OpenMPDirectiveKind CancelRegion) {
5720 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5721 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5722 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5723 << getOpenMPDirectiveName(CancelRegion);
5724 return StmtError();
5725 }
5726 if (DSAStack->isParentNowaitRegion()) {
5727 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
5728 return StmtError();
5729 }
5730 if (DSAStack->isParentOrderedRegion()) {
5731 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
5732 return StmtError();
5733 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005734 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00005735 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5736 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00005737}
5738
Alexey Bataev382967a2015-12-08 12:06:20 +00005739static bool checkGrainsizeNumTasksClauses(Sema &S,
5740 ArrayRef<OMPClause *> Clauses) {
5741 OMPClause *PrevClause = nullptr;
5742 bool ErrorFound = false;
5743 for (auto *C : Clauses) {
5744 if (C->getClauseKind() == OMPC_grainsize ||
5745 C->getClauseKind() == OMPC_num_tasks) {
5746 if (!PrevClause)
5747 PrevClause = C;
5748 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
5749 S.Diag(C->getLocStart(),
5750 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
5751 << getOpenMPClauseName(C->getClauseKind())
5752 << getOpenMPClauseName(PrevClause->getClauseKind());
5753 S.Diag(PrevClause->getLocStart(),
5754 diag::note_omp_previous_grainsize_num_tasks)
5755 << getOpenMPClauseName(PrevClause->getClauseKind());
5756 ErrorFound = true;
5757 }
5758 }
5759 }
5760 return ErrorFound;
5761}
5762
Alexey Bataev49f6e782015-12-01 04:18:41 +00005763StmtResult Sema::ActOnOpenMPTaskLoopDirective(
5764 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5765 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005766 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00005767 if (!AStmt)
5768 return StmtError();
5769
5770 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5771 OMPLoopDirective::HelperExprs B;
5772 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5773 // define the nested loops number.
5774 unsigned NestedLoopCount =
5775 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005776 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00005777 VarsWithImplicitDSA, B);
5778 if (NestedLoopCount == 0)
5779 return StmtError();
5780
5781 assert((CurContext->isDependentContext() || B.builtAll()) &&
5782 "omp for loop exprs were not built");
5783
Alexey Bataev382967a2015-12-08 12:06:20 +00005784 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5785 // The grainsize clause and num_tasks clause are mutually exclusive and may
5786 // not appear on the same taskloop directive.
5787 if (checkGrainsizeNumTasksClauses(*this, Clauses))
5788 return StmtError();
5789
Alexey Bataev49f6e782015-12-01 04:18:41 +00005790 getCurFunction()->setHasBranchProtectedScope();
5791 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
5792 NestedLoopCount, Clauses, AStmt, B);
5793}
5794
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005795StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
5796 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5797 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005798 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005799 if (!AStmt)
5800 return StmtError();
5801
5802 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5803 OMPLoopDirective::HelperExprs B;
5804 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5805 // define the nested loops number.
5806 unsigned NestedLoopCount =
5807 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
5808 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
5809 VarsWithImplicitDSA, B);
5810 if (NestedLoopCount == 0)
5811 return StmtError();
5812
5813 assert((CurContext->isDependentContext() || B.builtAll()) &&
5814 "omp for loop exprs were not built");
5815
Alexey Bataev5a3af132016-03-29 08:58:54 +00005816 if (!CurContext->isDependentContext()) {
5817 // Finalize the clauses that need pre-built expressions for CodeGen.
5818 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005819 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00005820 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005821 B.NumIterations, *this, CurScope,
5822 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00005823 return StmtError();
5824 }
5825 }
5826
Alexey Bataev382967a2015-12-08 12:06:20 +00005827 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5828 // The grainsize clause and num_tasks clause are mutually exclusive and may
5829 // not appear on the same taskloop directive.
5830 if (checkGrainsizeNumTasksClauses(*this, Clauses))
5831 return StmtError();
5832
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005833 getCurFunction()->setHasBranchProtectedScope();
5834 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
5835 NestedLoopCount, Clauses, AStmt, B);
5836}
5837
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005838StmtResult Sema::ActOnOpenMPDistributeDirective(
5839 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5840 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005841 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005842 if (!AStmt)
5843 return StmtError();
5844
5845 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5846 OMPLoopDirective::HelperExprs B;
5847 // In presence of clause 'collapse' with number of loops, it will
5848 // define the nested loops number.
5849 unsigned NestedLoopCount =
5850 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
5851 nullptr /*ordered not a clause on distribute*/, AStmt,
5852 *this, *DSAStack, VarsWithImplicitDSA, B);
5853 if (NestedLoopCount == 0)
5854 return StmtError();
5855
5856 assert((CurContext->isDependentContext() || B.builtAll()) &&
5857 "omp for loop exprs were not built");
5858
5859 getCurFunction()->setHasBranchProtectedScope();
5860 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
5861 NestedLoopCount, Clauses, AStmt, B);
5862}
5863
Carlo Bertolli9925f152016-06-27 14:55:37 +00005864StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
5865 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5866 SourceLocation EndLoc,
5867 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5868 if (!AStmt)
5869 return StmtError();
5870
5871 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5872 // 1.2.2 OpenMP Language Terminology
5873 // Structured block - An executable statement with a single entry at the
5874 // top and a single exit at the bottom.
5875 // The point of exit cannot be a branch out of the structured block.
5876 // longjmp() and throw() must not violate the entry/exit criteria.
5877 CS->getCapturedDecl()->setNothrow();
5878
5879 OMPLoopDirective::HelperExprs B;
5880 // In presence of clause 'collapse' with number of loops, it will
5881 // define the nested loops number.
5882 unsigned NestedLoopCount = CheckOpenMPLoop(
5883 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
5884 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
5885 VarsWithImplicitDSA, B);
5886 if (NestedLoopCount == 0)
5887 return StmtError();
5888
5889 assert((CurContext->isDependentContext() || B.builtAll()) &&
5890 "omp for loop exprs were not built");
5891
5892 getCurFunction()->setHasBranchProtectedScope();
5893 return OMPDistributeParallelForDirective::Create(
5894 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
5895}
5896
Kelvin Li4a39add2016-07-05 05:00:15 +00005897StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
5898 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5899 SourceLocation EndLoc,
5900 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5901 if (!AStmt)
5902 return StmtError();
5903
5904 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5905 // 1.2.2 OpenMP Language Terminology
5906 // Structured block - An executable statement with a single entry at the
5907 // top and a single exit at the bottom.
5908 // The point of exit cannot be a branch out of the structured block.
5909 // longjmp() and throw() must not violate the entry/exit criteria.
5910 CS->getCapturedDecl()->setNothrow();
5911
5912 OMPLoopDirective::HelperExprs B;
5913 // In presence of clause 'collapse' with number of loops, it will
5914 // define the nested loops number.
5915 unsigned NestedLoopCount = CheckOpenMPLoop(
5916 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
5917 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
5918 VarsWithImplicitDSA, B);
5919 if (NestedLoopCount == 0)
5920 return StmtError();
5921
5922 assert((CurContext->isDependentContext() || B.builtAll()) &&
5923 "omp for loop exprs were not built");
5924
Kelvin Lic5609492016-07-15 04:39:07 +00005925 if (checkSimdlenSafelenSpecified(*this, Clauses))
5926 return StmtError();
5927
Kelvin Li4a39add2016-07-05 05:00:15 +00005928 getCurFunction()->setHasBranchProtectedScope();
5929 return OMPDistributeParallelForSimdDirective::Create(
5930 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
5931}
5932
Kelvin Li787f3fc2016-07-06 04:45:38 +00005933StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
5934 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5935 SourceLocation EndLoc,
5936 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5937 if (!AStmt)
5938 return StmtError();
5939
5940 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5941 // 1.2.2 OpenMP Language Terminology
5942 // Structured block - An executable statement with a single entry at the
5943 // top and a single exit at the bottom.
5944 // The point of exit cannot be a branch out of the structured block.
5945 // longjmp() and throw() must not violate the entry/exit criteria.
5946 CS->getCapturedDecl()->setNothrow();
5947
5948 OMPLoopDirective::HelperExprs B;
5949 // In presence of clause 'collapse' with number of loops, it will
5950 // define the nested loops number.
5951 unsigned NestedLoopCount =
5952 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
5953 nullptr /*ordered not a clause on distribute*/, AStmt,
5954 *this, *DSAStack, VarsWithImplicitDSA, B);
5955 if (NestedLoopCount == 0)
5956 return StmtError();
5957
5958 assert((CurContext->isDependentContext() || B.builtAll()) &&
5959 "omp for loop exprs were not built");
5960
Kelvin Lic5609492016-07-15 04:39:07 +00005961 if (checkSimdlenSafelenSpecified(*this, Clauses))
5962 return StmtError();
5963
Kelvin Li787f3fc2016-07-06 04:45:38 +00005964 getCurFunction()->setHasBranchProtectedScope();
5965 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
5966 NestedLoopCount, Clauses, AStmt, B);
5967}
5968
Kelvin Lia579b912016-07-14 02:54:56 +00005969StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
5970 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5971 SourceLocation EndLoc,
5972 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5973 if (!AStmt)
5974 return StmtError();
5975
5976 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5977 // 1.2.2 OpenMP Language Terminology
5978 // Structured block - An executable statement with a single entry at the
5979 // top and a single exit at the bottom.
5980 // The point of exit cannot be a branch out of the structured block.
5981 // longjmp() and throw() must not violate the entry/exit criteria.
5982 CS->getCapturedDecl()->setNothrow();
5983
5984 OMPLoopDirective::HelperExprs B;
5985 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5986 // define the nested loops number.
5987 unsigned NestedLoopCount = CheckOpenMPLoop(
5988 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
5989 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5990 VarsWithImplicitDSA, B);
5991 if (NestedLoopCount == 0)
5992 return StmtError();
5993
5994 assert((CurContext->isDependentContext() || B.builtAll()) &&
5995 "omp target parallel for simd loop exprs were not built");
5996
5997 if (!CurContext->isDependentContext()) {
5998 // Finalize the clauses that need pre-built expressions for CodeGen.
5999 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006000 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00006001 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6002 B.NumIterations, *this, CurScope,
6003 DSAStack))
6004 return StmtError();
6005 }
6006 }
Kelvin Lic5609492016-07-15 04:39:07 +00006007 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00006008 return StmtError();
6009
6010 getCurFunction()->setHasBranchProtectedScope();
6011 return OMPTargetParallelForSimdDirective::Create(
6012 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6013}
6014
Kelvin Li986330c2016-07-20 22:57:10 +00006015StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6016 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6017 SourceLocation EndLoc,
6018 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6019 if (!AStmt)
6020 return StmtError();
6021
6022 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6023 // 1.2.2 OpenMP Language Terminology
6024 // Structured block - An executable statement with a single entry at the
6025 // top and a single exit at the bottom.
6026 // The point of exit cannot be a branch out of the structured block.
6027 // longjmp() and throw() must not violate the entry/exit criteria.
6028 CS->getCapturedDecl()->setNothrow();
6029
6030 OMPLoopDirective::HelperExprs B;
6031 // In presence of clause 'collapse' with number of loops, it will define the
6032 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00006033 unsigned NestedLoopCount =
Kelvin Li986330c2016-07-20 22:57:10 +00006034 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
6035 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6036 VarsWithImplicitDSA, B);
6037 if (NestedLoopCount == 0)
6038 return StmtError();
6039
6040 assert((CurContext->isDependentContext() || B.builtAll()) &&
6041 "omp target simd loop exprs were not built");
6042
6043 if (!CurContext->isDependentContext()) {
6044 // Finalize the clauses that need pre-built expressions for CodeGen.
6045 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006046 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00006047 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6048 B.NumIterations, *this, CurScope,
6049 DSAStack))
6050 return StmtError();
6051 }
6052 }
6053
6054 if (checkSimdlenSafelenSpecified(*this, Clauses))
6055 return StmtError();
6056
6057 getCurFunction()->setHasBranchProtectedScope();
6058 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
6059 NestedLoopCount, Clauses, AStmt, B);
6060}
6061
Kelvin Li02532872016-08-05 14:37:37 +00006062StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
6063 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6064 SourceLocation EndLoc,
6065 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6066 if (!AStmt)
6067 return StmtError();
6068
6069 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6070 // 1.2.2 OpenMP Language Terminology
6071 // Structured block - An executable statement with a single entry at the
6072 // top and a single exit at the bottom.
6073 // The point of exit cannot be a branch out of the structured block.
6074 // longjmp() and throw() must not violate the entry/exit criteria.
6075 CS->getCapturedDecl()->setNothrow();
6076
6077 OMPLoopDirective::HelperExprs B;
6078 // In presence of clause 'collapse' with number of loops, it will
6079 // define the nested loops number.
6080 unsigned NestedLoopCount =
6081 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
6082 nullptr /*ordered not a clause on distribute*/, AStmt,
6083 *this, *DSAStack, VarsWithImplicitDSA, B);
6084 if (NestedLoopCount == 0)
6085 return StmtError();
6086
6087 assert((CurContext->isDependentContext() || B.builtAll()) &&
6088 "omp teams distribute loop exprs were not built");
6089
6090 getCurFunction()->setHasBranchProtectedScope();
David Majnemer9d168222016-08-05 17:44:54 +00006091 return OMPTeamsDistributeDirective::Create(
6092 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00006093}
6094
Kelvin Li4e325f72016-10-25 12:50:55 +00006095StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
6096 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6097 SourceLocation EndLoc,
6098 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6099 if (!AStmt)
6100 return StmtError();
6101
6102 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6103 // 1.2.2 OpenMP Language Terminology
6104 // Structured block - An executable statement with a single entry at the
6105 // top and a single exit at the bottom.
6106 // The point of exit cannot be a branch out of the structured block.
6107 // longjmp() and throw() must not violate the entry/exit criteria.
6108 CS->getCapturedDecl()->setNothrow();
6109
6110 OMPLoopDirective::HelperExprs B;
6111 // In presence of clause 'collapse' with number of loops, it will
6112 // define the nested loops number.
6113 unsigned NestedLoopCount =
6114 CheckOpenMPLoop(OMPD_teams_distribute_simd,
6115 getCollapseNumberExpr(Clauses),
6116 nullptr /*ordered not a clause on distribute*/, AStmt,
6117 *this, *DSAStack, VarsWithImplicitDSA, B);
6118
6119 if (NestedLoopCount == 0)
6120 return StmtError();
6121
6122 assert((CurContext->isDependentContext() || B.builtAll()) &&
6123 "omp teams distribute simd loop exprs were not built");
6124
6125 if (!CurContext->isDependentContext()) {
6126 // Finalize the clauses that need pre-built expressions for CodeGen.
6127 for (auto C : Clauses) {
6128 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6129 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6130 B.NumIterations, *this, CurScope,
6131 DSAStack))
6132 return StmtError();
6133 }
6134 }
6135
6136 if (checkSimdlenSafelenSpecified(*this, Clauses))
6137 return StmtError();
6138
6139 getCurFunction()->setHasBranchProtectedScope();
6140 return OMPTeamsDistributeSimdDirective::Create(
6141 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6142}
6143
Alexey Bataeved09d242014-05-28 05:53:51 +00006144OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006145 SourceLocation StartLoc,
6146 SourceLocation LParenLoc,
6147 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006148 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006149 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00006150 case OMPC_final:
6151 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
6152 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00006153 case OMPC_num_threads:
6154 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
6155 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006156 case OMPC_safelen:
6157 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
6158 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00006159 case OMPC_simdlen:
6160 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
6161 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00006162 case OMPC_collapse:
6163 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
6164 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006165 case OMPC_ordered:
6166 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
6167 break;
Michael Wonge710d542015-08-07 16:16:36 +00006168 case OMPC_device:
6169 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
6170 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00006171 case OMPC_num_teams:
6172 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
6173 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006174 case OMPC_thread_limit:
6175 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
6176 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00006177 case OMPC_priority:
6178 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
6179 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006180 case OMPC_grainsize:
6181 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
6182 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00006183 case OMPC_num_tasks:
6184 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
6185 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00006186 case OMPC_hint:
6187 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
6188 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006189 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006190 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006191 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006192 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006193 case OMPC_private:
6194 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00006195 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006196 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00006197 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00006198 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006199 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006200 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006201 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00006202 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006203 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006204 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006205 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006206 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006207 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006208 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006209 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006210 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006211 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006212 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00006213 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006214 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006215 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00006216 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00006217 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006218 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006219 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006220 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006221 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006222 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006223 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006224 case OMPC_is_device_ptr:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006225 llvm_unreachable("Clause is not allowed.");
6226 }
6227 return Res;
6228}
6229
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006230OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
6231 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006232 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006233 SourceLocation NameModifierLoc,
6234 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006235 SourceLocation EndLoc) {
6236 Expr *ValExpr = Condition;
6237 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6238 !Condition->isInstantiationDependent() &&
6239 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00006240 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006241 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006242 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006243
Richard Smith03a4aa32016-06-23 19:02:52 +00006244 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006245 }
6246
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006247 return new (Context) OMPIfClause(NameModifier, ValExpr, StartLoc, LParenLoc,
6248 NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006249}
6250
Alexey Bataev3778b602014-07-17 07:32:53 +00006251OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
6252 SourceLocation StartLoc,
6253 SourceLocation LParenLoc,
6254 SourceLocation EndLoc) {
6255 Expr *ValExpr = Condition;
6256 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6257 !Condition->isInstantiationDependent() &&
6258 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00006259 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00006260 if (Val.isInvalid())
6261 return nullptr;
6262
Richard Smith03a4aa32016-06-23 19:02:52 +00006263 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00006264 }
6265
6266 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
6267}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006268ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
6269 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00006270 if (!Op)
6271 return ExprError();
6272
6273 class IntConvertDiagnoser : public ICEConvertDiagnoser {
6274 public:
6275 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00006276 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00006277 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
6278 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006279 return S.Diag(Loc, diag::err_omp_not_integral) << T;
6280 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006281 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
6282 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006283 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
6284 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006285 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
6286 QualType T,
6287 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006288 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
6289 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006290 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
6291 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006292 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00006293 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00006294 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006295 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
6296 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006297 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
6298 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006299 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
6300 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006301 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00006302 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00006303 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006304 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
6305 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006306 llvm_unreachable("conversion functions are permitted");
6307 }
6308 } ConvertDiagnoser;
6309 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
6310}
6311
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006312static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00006313 OpenMPClauseKind CKind,
6314 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006315 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
6316 !ValExpr->isInstantiationDependent()) {
6317 SourceLocation Loc = ValExpr->getExprLoc();
6318 ExprResult Value =
6319 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
6320 if (Value.isInvalid())
6321 return false;
6322
6323 ValExpr = Value.get();
6324 // The expression must evaluate to a non-negative integer value.
6325 llvm::APSInt Result;
6326 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00006327 Result.isSigned() &&
6328 !((!StrictlyPositive && Result.isNonNegative()) ||
6329 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006330 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00006331 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
6332 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006333 return false;
6334 }
6335 }
6336 return true;
6337}
6338
Alexey Bataev568a8332014-03-06 06:15:19 +00006339OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
6340 SourceLocation StartLoc,
6341 SourceLocation LParenLoc,
6342 SourceLocation EndLoc) {
6343 Expr *ValExpr = NumThreads;
Alexey Bataev568a8332014-03-06 06:15:19 +00006344
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006345 // OpenMP [2.5, Restrictions]
6346 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00006347 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
6348 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006349 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00006350
Alexey Bataeved09d242014-05-28 05:53:51 +00006351 return new (Context)
6352 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00006353}
6354
Alexey Bataev62c87d22014-03-21 04:51:18 +00006355ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006356 OpenMPClauseKind CKind,
6357 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00006358 if (!E)
6359 return ExprError();
6360 if (E->isValueDependent() || E->isTypeDependent() ||
6361 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006362 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006363 llvm::APSInt Result;
6364 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
6365 if (ICE.isInvalid())
6366 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006367 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
6368 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00006369 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006370 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
6371 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00006372 return ExprError();
6373 }
Alexander Musman09184fe2014-09-30 05:29:28 +00006374 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
6375 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
6376 << E->getSourceRange();
6377 return ExprError();
6378 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006379 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
6380 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00006381 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006382 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00006383 return ICE;
6384}
6385
6386OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
6387 SourceLocation LParenLoc,
6388 SourceLocation EndLoc) {
6389 // OpenMP [2.8.1, simd construct, Description]
6390 // The parameter of the safelen clause must be a constant
6391 // positive integer expression.
6392 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
6393 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006394 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006395 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006396 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00006397}
6398
Alexey Bataev66b15b52015-08-21 11:14:16 +00006399OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
6400 SourceLocation LParenLoc,
6401 SourceLocation EndLoc) {
6402 // OpenMP [2.8.1, simd construct, Description]
6403 // The parameter of the simdlen clause must be a constant
6404 // positive integer expression.
6405 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
6406 if (Simdlen.isInvalid())
6407 return nullptr;
6408 return new (Context)
6409 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
6410}
6411
Alexander Musman64d33f12014-06-04 07:53:32 +00006412OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
6413 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00006414 SourceLocation LParenLoc,
6415 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00006416 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00006417 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00006418 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00006419 // The parameter of the collapse clause must be a constant
6420 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00006421 ExprResult NumForLoopsResult =
6422 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
6423 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00006424 return nullptr;
6425 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00006426 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00006427}
6428
Alexey Bataev10e775f2015-07-30 11:36:16 +00006429OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
6430 SourceLocation EndLoc,
6431 SourceLocation LParenLoc,
6432 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00006433 // OpenMP [2.7.1, loop construct, Description]
6434 // OpenMP [2.8.1, simd construct, Description]
6435 // OpenMP [2.9.6, distribute construct, Description]
6436 // The parameter of the ordered clause must be a constant
6437 // positive integer expression if any.
6438 if (NumForLoops && LParenLoc.isValid()) {
6439 ExprResult NumForLoopsResult =
6440 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
6441 if (NumForLoopsResult.isInvalid())
6442 return nullptr;
6443 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00006444 } else
6445 NumForLoops = nullptr;
6446 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00006447 return new (Context)
6448 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
6449}
6450
Alexey Bataeved09d242014-05-28 05:53:51 +00006451OMPClause *Sema::ActOnOpenMPSimpleClause(
6452 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
6453 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006454 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006455 switch (Kind) {
6456 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00006457 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00006458 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
6459 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006460 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006461 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00006462 Res = ActOnOpenMPProcBindClause(
6463 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
6464 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006465 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006466 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00006467 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00006468 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00006469 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00006470 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00006471 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006472 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006473 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006474 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00006475 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00006476 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00006477 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00006478 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006479 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006480 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006481 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006482 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00006483 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006484 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006485 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006486 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006487 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006488 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006489 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006490 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006491 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006492 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006493 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00006494 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00006495 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006496 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006497 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00006498 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006499 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00006500 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006501 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00006502 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00006503 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00006504 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00006505 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006506 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006507 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006508 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006509 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006510 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006511 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006512 case OMPC_is_device_ptr:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006513 llvm_unreachable("Clause is not allowed.");
6514 }
6515 return Res;
6516}
6517
Alexey Bataev6402bca2015-12-28 07:25:51 +00006518static std::string
6519getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
6520 ArrayRef<unsigned> Exclude = llvm::None) {
6521 std::string Values;
6522 unsigned Bound = Last >= 2 ? Last - 2 : 0;
6523 unsigned Skipped = Exclude.size();
6524 auto S = Exclude.begin(), E = Exclude.end();
6525 for (unsigned i = First; i < Last; ++i) {
6526 if (std::find(S, E, i) != E) {
6527 --Skipped;
6528 continue;
6529 }
6530 Values += "'";
6531 Values += getOpenMPSimpleClauseTypeName(K, i);
6532 Values += "'";
6533 if (i == Bound - Skipped)
6534 Values += " or ";
6535 else if (i != Bound + 1 - Skipped)
6536 Values += ", ";
6537 }
6538 return Values;
6539}
6540
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006541OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
6542 SourceLocation KindKwLoc,
6543 SourceLocation StartLoc,
6544 SourceLocation LParenLoc,
6545 SourceLocation EndLoc) {
6546 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00006547 static_assert(OMPC_DEFAULT_unknown > 0,
6548 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006549 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00006550 << getListOfPossibleValues(OMPC_default, /*First=*/0,
6551 /*Last=*/OMPC_DEFAULT_unknown)
6552 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006553 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006554 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00006555 switch (Kind) {
6556 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006557 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00006558 break;
6559 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006560 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00006561 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006562 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006563 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00006564 break;
6565 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006566 return new (Context)
6567 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006568}
6569
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006570OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
6571 SourceLocation KindKwLoc,
6572 SourceLocation StartLoc,
6573 SourceLocation LParenLoc,
6574 SourceLocation EndLoc) {
6575 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006576 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00006577 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
6578 /*Last=*/OMPC_PROC_BIND_unknown)
6579 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006580 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006581 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006582 return new (Context)
6583 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006584}
6585
Alexey Bataev56dafe82014-06-20 07:16:17 +00006586OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00006587 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00006588 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00006589 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00006590 SourceLocation EndLoc) {
6591 OMPClause *Res = nullptr;
6592 switch (Kind) {
6593 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00006594 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
6595 assert(Argument.size() == NumberOfElements &&
6596 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00006597 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00006598 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
6599 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
6600 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
6601 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
6602 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00006603 break;
6604 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00006605 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
6606 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
6607 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
6608 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006609 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00006610 case OMPC_dist_schedule:
6611 Res = ActOnOpenMPDistScheduleClause(
6612 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
6613 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
6614 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006615 case OMPC_defaultmap:
6616 enum { Modifier, DefaultmapKind };
6617 Res = ActOnOpenMPDefaultmapClause(
6618 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
6619 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00006620 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
6621 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006622 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00006623 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006624 case OMPC_num_threads:
6625 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00006626 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006627 case OMPC_collapse:
6628 case OMPC_default:
6629 case OMPC_proc_bind:
6630 case OMPC_private:
6631 case OMPC_firstprivate:
6632 case OMPC_lastprivate:
6633 case OMPC_shared:
6634 case OMPC_reduction:
6635 case OMPC_linear:
6636 case OMPC_aligned:
6637 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006638 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006639 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00006640 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006641 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006642 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006643 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006644 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006645 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006646 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006647 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006648 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006649 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006650 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00006651 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00006652 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006653 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006654 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00006655 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006656 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00006657 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006658 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00006659 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00006660 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00006661 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006662 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006663 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006664 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006665 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006666 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006667 case OMPC_is_device_ptr:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006668 llvm_unreachable("Clause is not allowed.");
6669 }
6670 return Res;
6671}
6672
Alexey Bataev6402bca2015-12-28 07:25:51 +00006673static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
6674 OpenMPScheduleClauseModifier M2,
6675 SourceLocation M1Loc, SourceLocation M2Loc) {
6676 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
6677 SmallVector<unsigned, 2> Excluded;
6678 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
6679 Excluded.push_back(M2);
6680 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
6681 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
6682 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
6683 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
6684 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
6685 << getListOfPossibleValues(OMPC_schedule,
6686 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
6687 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
6688 Excluded)
6689 << getOpenMPClauseName(OMPC_schedule);
6690 return true;
6691 }
6692 return false;
6693}
6694
Alexey Bataev56dafe82014-06-20 07:16:17 +00006695OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00006696 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00006697 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00006698 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
6699 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
6700 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
6701 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
6702 return nullptr;
6703 // OpenMP, 2.7.1, Loop Construct, Restrictions
6704 // Either the monotonic modifier or the nonmonotonic modifier can be specified
6705 // but not both.
6706 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
6707 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
6708 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
6709 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
6710 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
6711 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
6712 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
6713 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
6714 return nullptr;
6715 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00006716 if (Kind == OMPC_SCHEDULE_unknown) {
6717 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00006718 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
6719 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
6720 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
6721 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
6722 Exclude);
6723 } else {
6724 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
6725 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00006726 }
6727 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
6728 << Values << getOpenMPClauseName(OMPC_schedule);
6729 return nullptr;
6730 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00006731 // OpenMP, 2.7.1, Loop Construct, Restrictions
6732 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
6733 // schedule(guided).
6734 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
6735 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
6736 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
6737 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
6738 diag::err_omp_schedule_nonmonotonic_static);
6739 return nullptr;
6740 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00006741 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00006742 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00006743 if (ChunkSize) {
6744 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
6745 !ChunkSize->isInstantiationDependent() &&
6746 !ChunkSize->containsUnexpandedParameterPack()) {
6747 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
6748 ExprResult Val =
6749 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
6750 if (Val.isInvalid())
6751 return nullptr;
6752
6753 ValExpr = Val.get();
6754
6755 // OpenMP [2.7.1, Restrictions]
6756 // chunk_size must be a loop invariant integer expression with a positive
6757 // value.
6758 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00006759 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
6760 if (Result.isSigned() && !Result.isStrictlyPositive()) {
6761 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00006762 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00006763 return nullptr;
6764 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +00006765 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
6766 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00006767 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
6768 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
6769 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00006770 }
6771 }
6772 }
6773
Alexey Bataev6402bca2015-12-28 07:25:51 +00006774 return new (Context)
6775 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00006776 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00006777}
6778
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006779OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
6780 SourceLocation StartLoc,
6781 SourceLocation EndLoc) {
6782 OMPClause *Res = nullptr;
6783 switch (Kind) {
6784 case OMPC_ordered:
6785 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
6786 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00006787 case OMPC_nowait:
6788 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
6789 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006790 case OMPC_untied:
6791 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
6792 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006793 case OMPC_mergeable:
6794 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
6795 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006796 case OMPC_read:
6797 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
6798 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00006799 case OMPC_write:
6800 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
6801 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00006802 case OMPC_update:
6803 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
6804 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00006805 case OMPC_capture:
6806 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
6807 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006808 case OMPC_seq_cst:
6809 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
6810 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00006811 case OMPC_threads:
6812 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
6813 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006814 case OMPC_simd:
6815 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
6816 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00006817 case OMPC_nogroup:
6818 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
6819 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006820 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00006821 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006822 case OMPC_num_threads:
6823 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00006824 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006825 case OMPC_collapse:
6826 case OMPC_schedule:
6827 case OMPC_private:
6828 case OMPC_firstprivate:
6829 case OMPC_lastprivate:
6830 case OMPC_shared:
6831 case OMPC_reduction:
6832 case OMPC_linear:
6833 case OMPC_aligned:
6834 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006835 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006836 case OMPC_default:
6837 case OMPC_proc_bind:
6838 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006839 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006840 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00006841 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006842 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00006843 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006844 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00006845 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006846 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00006847 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00006848 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00006849 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006850 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006851 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006852 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006853 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006854 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006855 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006856 case OMPC_is_device_ptr:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006857 llvm_unreachable("Clause is not allowed.");
6858 }
6859 return Res;
6860}
6861
Alexey Bataev236070f2014-06-20 11:19:47 +00006862OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
6863 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006864 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00006865 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
6866}
6867
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006868OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
6869 SourceLocation EndLoc) {
6870 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
6871}
6872
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006873OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
6874 SourceLocation EndLoc) {
6875 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
6876}
6877
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006878OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
6879 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006880 return new (Context) OMPReadClause(StartLoc, EndLoc);
6881}
6882
Alexey Bataevdea47612014-07-23 07:46:59 +00006883OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
6884 SourceLocation EndLoc) {
6885 return new (Context) OMPWriteClause(StartLoc, EndLoc);
6886}
6887
Alexey Bataev67a4f222014-07-23 10:25:33 +00006888OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
6889 SourceLocation EndLoc) {
6890 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
6891}
6892
Alexey Bataev459dec02014-07-24 06:46:57 +00006893OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
6894 SourceLocation EndLoc) {
6895 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
6896}
6897
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006898OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
6899 SourceLocation EndLoc) {
6900 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
6901}
6902
Alexey Bataev346265e2015-09-25 10:37:12 +00006903OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
6904 SourceLocation EndLoc) {
6905 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
6906}
6907
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006908OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
6909 SourceLocation EndLoc) {
6910 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
6911}
6912
Alexey Bataevb825de12015-12-07 10:51:44 +00006913OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
6914 SourceLocation EndLoc) {
6915 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
6916}
6917
Alexey Bataevc5e02582014-06-16 07:08:35 +00006918OMPClause *Sema::ActOnOpenMPVarListClause(
6919 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
6920 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
6921 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006922 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00006923 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
6924 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
6925 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006926 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006927 switch (Kind) {
6928 case OMPC_private:
6929 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
6930 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006931 case OMPC_firstprivate:
6932 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
6933 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00006934 case OMPC_lastprivate:
6935 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
6936 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00006937 case OMPC_shared:
6938 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
6939 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006940 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00006941 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
6942 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00006943 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00006944 case OMPC_linear:
6945 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00006946 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00006947 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006948 case OMPC_aligned:
6949 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
6950 ColonLoc, EndLoc);
6951 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006952 case OMPC_copyin:
6953 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
6954 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00006955 case OMPC_copyprivate:
6956 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
6957 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00006958 case OMPC_flush:
6959 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
6960 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006961 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00006962 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00006963 StartLoc, LParenLoc, EndLoc);
6964 break;
6965 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00006966 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
6967 DepLinMapLoc, ColonLoc, VarList, StartLoc,
6968 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006969 break;
Samuel Antao661c0902016-05-26 17:39:58 +00006970 case OMPC_to:
6971 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
6972 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00006973 case OMPC_from:
6974 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
6975 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00006976 case OMPC_use_device_ptr:
6977 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
6978 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00006979 case OMPC_is_device_ptr:
6980 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
6981 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006982 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00006983 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00006984 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00006985 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00006986 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00006987 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006988 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006989 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006990 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006991 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00006992 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006993 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006994 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006995 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006996 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006997 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006998 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006999 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007000 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00007001 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007002 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007003 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007004 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007005 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007006 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007007 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007008 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007009 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007010 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007011 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007012 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007013 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007014 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007015 llvm_unreachable("Clause is not allowed.");
7016 }
7017 return Res;
7018}
7019
Alexey Bataev90c228f2016-02-08 09:29:13 +00007020ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00007021 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00007022 ExprResult Res = BuildDeclRefExpr(
7023 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
7024 if (!Res.isUsable())
7025 return ExprError();
7026 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
7027 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
7028 if (!Res.isUsable())
7029 return ExprError();
7030 }
7031 if (VK != VK_LValue && Res.get()->isGLValue()) {
7032 Res = DefaultLvalueConversion(Res.get());
7033 if (!Res.isUsable())
7034 return ExprError();
7035 }
7036 return Res;
7037}
7038
Alexey Bataev60da77e2016-02-29 05:54:20 +00007039static std::pair<ValueDecl *, bool>
7040getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
7041 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007042 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
7043 RefExpr->containsUnexpandedParameterPack())
7044 return std::make_pair(nullptr, true);
7045
Alexey Bataevd985eda2016-02-10 11:29:16 +00007046 // OpenMP [3.1, C/C++]
7047 // A list item is a variable name.
7048 // OpenMP [2.9.3.3, Restrictions, p.1]
7049 // A variable that is part of another variable (as an array or
7050 // structure element) cannot appear in a private clause.
7051 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00007052 enum {
7053 NoArrayExpr = -1,
7054 ArraySubscript = 0,
7055 OMPArraySection = 1
7056 } IsArrayExpr = NoArrayExpr;
7057 if (AllowArraySection) {
7058 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
7059 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
7060 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7061 Base = TempASE->getBase()->IgnoreParenImpCasts();
7062 RefExpr = Base;
7063 IsArrayExpr = ArraySubscript;
7064 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
7065 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
7066 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
7067 Base = TempOASE->getBase()->IgnoreParenImpCasts();
7068 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7069 Base = TempASE->getBase()->IgnoreParenImpCasts();
7070 RefExpr = Base;
7071 IsArrayExpr = OMPArraySection;
7072 }
7073 }
7074 ELoc = RefExpr->getExprLoc();
7075 ERange = RefExpr->getSourceRange();
7076 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00007077 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
7078 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
7079 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
7080 (S.getCurrentThisType().isNull() || !ME ||
7081 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
7082 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00007083 if (IsArrayExpr != NoArrayExpr)
7084 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
7085 << ERange;
7086 else {
7087 S.Diag(ELoc,
7088 AllowArraySection
7089 ? diag::err_omp_expected_var_name_member_expr_or_array_item
7090 : diag::err_omp_expected_var_name_member_expr)
7091 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
7092 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007093 return std::make_pair(nullptr, false);
7094 }
7095 return std::make_pair(DE ? DE->getDecl() : ME->getMemberDecl(), false);
7096}
7097
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007098OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
7099 SourceLocation StartLoc,
7100 SourceLocation LParenLoc,
7101 SourceLocation EndLoc) {
7102 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00007103 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00007104 for (auto &RefExpr : VarList) {
7105 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007106 SourceLocation ELoc;
7107 SourceRange ERange;
7108 Expr *SimpleRefExpr = RefExpr;
7109 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007110 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007111 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007112 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007113 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007114 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007115 ValueDecl *D = Res.first;
7116 if (!D)
7117 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007118
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007119 QualType Type = D->getType();
7120 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007121
7122 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7123 // A variable that appears in a private clause must not have an incomplete
7124 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007125 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007126 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007127 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007128
Alexey Bataev758e55e2013-09-06 18:03:48 +00007129 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7130 // in a Construct]
7131 // Variables with the predetermined data-sharing attributes may not be
7132 // listed in data-sharing attributes clauses, except for the cases
7133 // listed below. For these exceptions only, listing a predetermined
7134 // variable in a data-sharing attribute clause is allowed and overrides
7135 // the variable's predetermined data-sharing attributes.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007136 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007137 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00007138 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7139 << getOpenMPClauseName(OMPC_private);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007140 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007141 continue;
7142 }
7143
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007144 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00007145 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00007146 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007147 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7148 << getOpenMPClauseName(OMPC_private) << Type
7149 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7150 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007151 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007152 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007153 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007154 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007155 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007156 continue;
7157 }
7158
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007159 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
7160 // A list item cannot appear in both a map clause and a data-sharing
7161 // attribute clause on the same construct
7162 if (DSAStack->getCurrentDirective() == OMPD_target) {
Samuel Antao6890b092016-07-28 14:25:09 +00007163 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00007164 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00007165 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00007166 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
7167 OpenMPClauseKind WhereFoundClauseKind) -> bool {
7168 ConflictKind = WhereFoundClauseKind;
7169 return true;
7170 })) {
7171 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007172 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00007173 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007174 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7175 ReportOriginalDSA(*this, DSAStack, D, DVar);
7176 continue;
7177 }
7178 }
7179
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007180 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
7181 // A variable of class type (or array thereof) that appears in a private
7182 // clause requires an accessible, unambiguous default constructor for the
7183 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00007184 // Generate helper private variable and initialize it with the default
7185 // value. The address of the original variable is replaced by the address of
7186 // the new private variable in CodeGen. This new variable is not added to
7187 // IdResolver, so the code in the OpenMP region uses original variable for
7188 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007189 Type = Type.getUnqualifiedType();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007190 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7191 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00007192 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007193 if (VDPrivate->isInvalidDecl())
7194 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007195 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007196 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007197
Alexey Bataev90c228f2016-02-08 09:29:13 +00007198 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007199 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00007200 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00007201 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007202 Vars.push_back((VD || CurContext->isDependentContext())
7203 ? RefExpr->IgnoreParens()
7204 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007205 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007206 }
7207
Alexey Bataeved09d242014-05-28 05:53:51 +00007208 if (Vars.empty())
7209 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007210
Alexey Bataev03b340a2014-10-21 03:16:40 +00007211 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
7212 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007213}
7214
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007215namespace {
7216class DiagsUninitializedSeveretyRAII {
7217private:
7218 DiagnosticsEngine &Diags;
7219 SourceLocation SavedLoc;
7220 bool IsIgnored;
7221
7222public:
7223 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
7224 bool IsIgnored)
7225 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
7226 if (!IsIgnored) {
7227 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
7228 /*Map*/ diag::Severity::Ignored, Loc);
7229 }
7230 }
7231 ~DiagsUninitializedSeveretyRAII() {
7232 if (!IsIgnored)
7233 Diags.popMappings(SavedLoc);
7234 }
7235};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007236}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007237
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007238OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
7239 SourceLocation StartLoc,
7240 SourceLocation LParenLoc,
7241 SourceLocation EndLoc) {
7242 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007243 SmallVector<Expr *, 8> PrivateCopies;
7244 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00007245 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007246 bool IsImplicitClause =
7247 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
7248 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
7249
Alexey Bataeved09d242014-05-28 05:53:51 +00007250 for (auto &RefExpr : VarList) {
7251 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007252 SourceLocation ELoc;
7253 SourceRange ERange;
7254 Expr *SimpleRefExpr = RefExpr;
7255 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007256 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007257 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007258 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007259 PrivateCopies.push_back(nullptr);
7260 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007261 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007262 ValueDecl *D = Res.first;
7263 if (!D)
7264 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007265
Alexey Bataev60da77e2016-02-29 05:54:20 +00007266 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00007267 QualType Type = D->getType();
7268 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007269
7270 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7271 // A variable that appears in a private clause must not have an incomplete
7272 // type or a reference type.
7273 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00007274 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007275 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007276 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007277
7278 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
7279 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00007280 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007281 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007282 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007283
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007284 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00007285 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007286 if (!IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007287 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev005248a2016-02-25 05:25:57 +00007288 TopDVar = DVar;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007289 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007290 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
7291 // A list item that specifies a given variable may not appear in more
7292 // than one clause on the same directive, except that a variable may be
7293 // specified in both firstprivate and lastprivate clauses.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007294 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevf29276e2014-06-18 04:14:57 +00007295 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007296 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00007297 << getOpenMPClauseName(DVar.CKind)
7298 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007299 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007300 continue;
7301 }
7302
7303 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7304 // in a Construct]
7305 // Variables with the predetermined data-sharing attributes may not be
7306 // listed in data-sharing attributes clauses, except for the cases
7307 // listed below. For these exceptions only, listing a predetermined
7308 // variable in a data-sharing attribute clause is allowed and overrides
7309 // the variable's predetermined data-sharing attributes.
7310 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7311 // in a Construct, C/C++, p.2]
7312 // Variables with const-qualified type having no mutable member may be
7313 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00007314 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007315 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
7316 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00007317 << getOpenMPClauseName(DVar.CKind)
7318 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007319 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007320 continue;
7321 }
7322
Alexey Bataevf29276e2014-06-18 04:14:57 +00007323 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007324 // OpenMP [2.9.3.4, Restrictions, p.2]
7325 // A list item that is private within a parallel region must not appear
7326 // in a firstprivate clause on a worksharing construct if any of the
7327 // worksharing regions arising from the worksharing construct ever bind
7328 // to any of the parallel regions arising from the parallel construct.
Alexey Bataev549210e2014-06-24 04:39:47 +00007329 if (isOpenMPWorksharingDirective(CurrDir) &&
7330 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007331 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007332 if (DVar.CKind != OMPC_shared &&
7333 (isOpenMPParallelDirective(DVar.DKind) ||
7334 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00007335 Diag(ELoc, diag::err_omp_required_access)
7336 << getOpenMPClauseName(OMPC_firstprivate)
7337 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007338 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00007339 continue;
7340 }
7341 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007342 // OpenMP [2.9.3.4, Restrictions, p.3]
7343 // A list item that appears in a reduction clause of a parallel construct
7344 // must not appear in a firstprivate clause on a worksharing or task
7345 // construct if any of the worksharing or task regions arising from the
7346 // worksharing or task construct ever bind to any of the parallel regions
7347 // arising from the parallel construct.
7348 // OpenMP [2.9.3.4, Restrictions, p.4]
7349 // A list item that appears in a reduction clause in worksharing
7350 // construct must not appear in a firstprivate clause in a task construct
7351 // encountered during execution of any of the worksharing regions arising
7352 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00007353 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007354 DVar = DSAStack->hasInnermostDSA(
7355 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
7356 [](OpenMPDirectiveKind K) -> bool {
7357 return isOpenMPParallelDirective(K) ||
7358 isOpenMPWorksharingDirective(K);
7359 },
7360 false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007361 if (DVar.CKind == OMPC_reduction &&
7362 (isOpenMPParallelDirective(DVar.DKind) ||
7363 isOpenMPWorksharingDirective(DVar.DKind))) {
7364 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
7365 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007366 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007367 continue;
7368 }
7369 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007370
7371 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
7372 // A list item that is private within a teams region must not appear in a
7373 // firstprivate clause on a distribute construct if any of the distribute
7374 // regions arising from the distribute construct ever bind to any of the
7375 // teams regions arising from the teams construct.
7376 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
7377 // A list item that appears in a reduction clause of a teams construct
7378 // must not appear in a firstprivate clause on a distribute construct if
7379 // any of the distribute regions arising from the distribute construct
7380 // ever bind to any of the teams regions arising from the teams construct.
7381 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
7382 // A list item may appear in a firstprivate or lastprivate clause but not
7383 // both.
7384 if (CurrDir == OMPD_distribute) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007385 DVar = DSAStack->hasInnermostDSA(
7386 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_private; },
7387 [](OpenMPDirectiveKind K) -> bool {
7388 return isOpenMPTeamsDirective(K);
7389 },
7390 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007391 if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) {
7392 Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007393 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007394 continue;
7395 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007396 DVar = DSAStack->hasInnermostDSA(
7397 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
7398 [](OpenMPDirectiveKind K) -> bool {
7399 return isOpenMPTeamsDirective(K);
7400 },
7401 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007402 if (DVar.CKind == OMPC_reduction &&
7403 isOpenMPTeamsDirective(DVar.DKind)) {
7404 Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007405 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007406 continue;
7407 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007408 DVar = DSAStack->getTopDSA(D, false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007409 if (DVar.CKind == OMPC_lastprivate) {
7410 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007411 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007412 continue;
7413 }
7414 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007415 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
7416 // A list item cannot appear in both a map clause and a data-sharing
7417 // attribute clause on the same construct
7418 if (CurrDir == OMPD_target) {
Samuel Antao6890b092016-07-28 14:25:09 +00007419 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00007420 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00007421 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00007422 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
7423 OpenMPClauseKind WhereFoundClauseKind) -> bool {
7424 ConflictKind = WhereFoundClauseKind;
7425 return true;
7426 })) {
7427 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007428 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +00007429 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007430 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7431 ReportOriginalDSA(*this, DSAStack, D, DVar);
7432 continue;
7433 }
7434 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007435 }
7436
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007437 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00007438 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00007439 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007440 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7441 << getOpenMPClauseName(OMPC_firstprivate) << Type
7442 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7443 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00007444 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007445 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00007446 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007447 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00007448 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007449 continue;
7450 }
7451
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007452 Type = Type.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00007453 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7454 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007455 // Generate helper private variable and initialize it with the value of the
7456 // original variable. The address of the original variable is replaced by
7457 // the address of the new private variable in the CodeGen. This new variable
7458 // is not added to IdResolver, so the code in the OpenMP region uses
7459 // original variable for proper diagnostics and variable capturing.
7460 Expr *VDInitRefExpr = nullptr;
7461 // For arrays generate initializer for single element and replace it by the
7462 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007463 if (Type->isArrayType()) {
7464 auto VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00007465 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007466 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007467 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007468 ElemType = ElemType.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00007469 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007470 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00007471 InitializedEntity Entity =
7472 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007473 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
7474
7475 InitializationSequence InitSeq(*this, Entity, Kind, Init);
7476 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
7477 if (Result.isInvalid())
7478 VDPrivate->setInvalidDecl();
7479 else
7480 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00007481 // Remove temp variable declaration.
7482 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007483 } else {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007484 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
7485 ".firstprivate.temp");
7486 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
7487 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00007488 AddInitializerToDecl(VDPrivate,
7489 DefaultLvalueConversion(VDInitRefExpr).get(),
7490 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007491 }
7492 if (VDPrivate->isInvalidDecl()) {
7493 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007494 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007495 diag::note_omp_task_predetermined_firstprivate_here);
7496 }
7497 continue;
7498 }
7499 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00007500 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00007501 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
7502 RefExpr->getExprLoc());
7503 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007504 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00007505 if (TopDVar.CKind == OMPC_lastprivate)
7506 Ref = TopDVar.PrivateCopy;
7507 else {
Alexey Bataev61205072016-03-02 04:57:40 +00007508 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataev005248a2016-02-25 05:25:57 +00007509 if (!IsOpenMPCapturedDecl(D))
7510 ExprCaptures.push_back(Ref->getDecl());
7511 }
Alexey Bataev417089f2016-02-17 13:19:37 +00007512 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007513 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007514 Vars.push_back((VD || CurContext->isDependentContext())
7515 ? RefExpr->IgnoreParens()
7516 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007517 PrivateCopies.push_back(VDPrivateRefExpr);
7518 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007519 }
7520
Alexey Bataeved09d242014-05-28 05:53:51 +00007521 if (Vars.empty())
7522 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007523
7524 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00007525 Vars, PrivateCopies, Inits,
7526 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007527}
7528
Alexander Musman1bb328c2014-06-04 13:06:39 +00007529OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
7530 SourceLocation StartLoc,
7531 SourceLocation LParenLoc,
7532 SourceLocation EndLoc) {
7533 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00007534 SmallVector<Expr *, 8> SrcExprs;
7535 SmallVector<Expr *, 8> DstExprs;
7536 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00007537 SmallVector<Decl *, 4> ExprCaptures;
7538 SmallVector<Expr *, 4> ExprPostUpdates;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007539 for (auto &RefExpr : VarList) {
7540 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007541 SourceLocation ELoc;
7542 SourceRange ERange;
7543 Expr *SimpleRefExpr = RefExpr;
7544 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00007545 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00007546 // It will be analyzed later.
7547 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00007548 SrcExprs.push_back(nullptr);
7549 DstExprs.push_back(nullptr);
7550 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007551 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00007552 ValueDecl *D = Res.first;
7553 if (!D)
7554 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007555
Alexey Bataev74caaf22016-02-20 04:09:36 +00007556 QualType Type = D->getType();
7557 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007558
7559 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
7560 // A variable that appears in a lastprivate clause must not have an
7561 // incomplete type or a reference type.
7562 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00007563 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00007564 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007565 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00007566
7567 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
7568 // in a Construct]
7569 // Variables with the predetermined data-sharing attributes may not be
7570 // listed in data-sharing attributes clauses, except for the cases
7571 // listed below.
Alexey Bataev74caaf22016-02-20 04:09:36 +00007572 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007573 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
7574 DVar.CKind != OMPC_firstprivate &&
7575 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
7576 Diag(ELoc, diag::err_omp_wrong_dsa)
7577 << getOpenMPClauseName(DVar.CKind)
7578 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev74caaf22016-02-20 04:09:36 +00007579 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007580 continue;
7581 }
7582
Alexey Bataevf29276e2014-06-18 04:14:57 +00007583 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
7584 // OpenMP [2.14.3.5, Restrictions, p.2]
7585 // A list item that is private within a parallel region, or that appears in
7586 // the reduction clause of a parallel construct, must not appear in a
7587 // lastprivate clause on a worksharing construct if any of the corresponding
7588 // worksharing regions ever binds to any of the corresponding parallel
7589 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00007590 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00007591 if (isOpenMPWorksharingDirective(CurrDir) &&
7592 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00007593 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00007594 if (DVar.CKind != OMPC_shared) {
7595 Diag(ELoc, diag::err_omp_required_access)
7596 << getOpenMPClauseName(OMPC_lastprivate)
7597 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev74caaf22016-02-20 04:09:36 +00007598 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00007599 continue;
7600 }
7601 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00007602
7603 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
7604 // A list item may appear in a firstprivate or lastprivate clause but not
7605 // both.
7606 if (CurrDir == OMPD_distribute) {
7607 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
7608 if (DVar.CKind == OMPC_firstprivate) {
7609 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
7610 ReportOriginalDSA(*this, DSAStack, D, DVar);
7611 continue;
7612 }
7613 }
7614
Alexander Musman1bb328c2014-06-04 13:06:39 +00007615 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00007616 // A variable of class type (or array thereof) that appears in a
7617 // lastprivate clause requires an accessible, unambiguous default
7618 // constructor for the class type, unless the list item is also specified
7619 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00007620 // A variable of class type (or array thereof) that appears in a
7621 // lastprivate clause requires an accessible, unambiguous copy assignment
7622 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00007623 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00007624 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00007625 Type.getUnqualifiedType(), ".lastprivate.src",
Alexey Bataev74caaf22016-02-20 04:09:36 +00007626 D->hasAttrs() ? &D->getAttrs() : nullptr);
7627 auto *PseudoSrcExpr =
7628 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00007629 auto *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00007630 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00007631 D->hasAttrs() ? &D->getAttrs() : nullptr);
7632 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00007633 // For arrays generate assignment operation for single element and replace
7634 // it by the original array element in CodeGen.
Alexey Bataev74caaf22016-02-20 04:09:36 +00007635 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
Alexey Bataev38e89532015-04-16 04:54:05 +00007636 PseudoDstExpr, PseudoSrcExpr);
7637 if (AssignmentOp.isInvalid())
7638 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00007639 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00007640 /*DiscardedValue=*/true);
7641 if (AssignmentOp.isInvalid())
7642 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007643
Alexey Bataev74caaf22016-02-20 04:09:36 +00007644 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007645 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00007646 if (TopDVar.CKind == OMPC_firstprivate)
7647 Ref = TopDVar.PrivateCopy;
7648 else {
Alexey Bataev61205072016-03-02 04:57:40 +00007649 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00007650 if (!IsOpenMPCapturedDecl(D))
7651 ExprCaptures.push_back(Ref->getDecl());
7652 }
7653 if (TopDVar.CKind == OMPC_firstprivate ||
7654 (!IsOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00007655 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00007656 ExprResult RefRes = DefaultLvalueConversion(Ref);
7657 if (!RefRes.isUsable())
7658 continue;
7659 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00007660 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
7661 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00007662 if (!PostUpdateRes.isUsable())
7663 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00007664 ExprPostUpdates.push_back(
7665 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00007666 }
7667 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007668 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007669 Vars.push_back((VD || CurContext->isDependentContext())
7670 ? RefExpr->IgnoreParens()
7671 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00007672 SrcExprs.push_back(PseudoSrcExpr);
7673 DstExprs.push_back(PseudoDstExpr);
7674 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00007675 }
7676
7677 if (Vars.empty())
7678 return nullptr;
7679
7680 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00007681 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00007682 buildPreInits(Context, ExprCaptures),
7683 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00007684}
7685
Alexey Bataev758e55e2013-09-06 18:03:48 +00007686OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
7687 SourceLocation StartLoc,
7688 SourceLocation LParenLoc,
7689 SourceLocation EndLoc) {
7690 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00007691 for (auto &RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007692 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007693 SourceLocation ELoc;
7694 SourceRange ERange;
7695 Expr *SimpleRefExpr = RefExpr;
7696 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007697 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00007698 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007699 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007700 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007701 ValueDecl *D = Res.first;
7702 if (!D)
7703 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00007704
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007705 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007706 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7707 // in a Construct]
7708 // Variables with the predetermined data-sharing attributes may not be
7709 // listed in data-sharing attributes clauses, except for the cases
7710 // listed below. For these exceptions only, listing a predetermined
7711 // variable in a data-sharing attribute clause is allowed and overrides
7712 // the variable's predetermined data-sharing attributes.
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007713 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00007714 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
7715 DVar.RefExpr) {
7716 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7717 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007718 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007719 continue;
7720 }
7721
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007722 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007723 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00007724 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007725 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007726 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
7727 ? RefExpr->IgnoreParens()
7728 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007729 }
7730
Alexey Bataeved09d242014-05-28 05:53:51 +00007731 if (Vars.empty())
7732 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00007733
7734 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
7735}
7736
Alexey Bataevc5e02582014-06-16 07:08:35 +00007737namespace {
7738class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
7739 DSAStackTy *Stack;
7740
7741public:
7742 bool VisitDeclRefExpr(DeclRefExpr *E) {
7743 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007744 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00007745 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
7746 return false;
7747 if (DVar.CKind != OMPC_unknown)
7748 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007749 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
7750 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
7751 false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00007752 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00007753 return true;
7754 return false;
7755 }
7756 return false;
7757 }
7758 bool VisitStmt(Stmt *S) {
7759 for (auto Child : S->children()) {
7760 if (Child && Visit(Child))
7761 return true;
7762 }
7763 return false;
7764 }
Alexey Bataev23b69422014-06-18 07:08:49 +00007765 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00007766};
Alexey Bataev23b69422014-06-18 07:08:49 +00007767} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00007768
Alexey Bataev60da77e2016-02-29 05:54:20 +00007769namespace {
7770// Transform MemberExpression for specified FieldDecl of current class to
7771// DeclRefExpr to specified OMPCapturedExprDecl.
7772class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
7773 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
7774 ValueDecl *Field;
7775 DeclRefExpr *CapturedExpr;
7776
7777public:
7778 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
7779 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
7780
7781 ExprResult TransformMemberExpr(MemberExpr *E) {
7782 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
7783 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00007784 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00007785 return CapturedExpr;
7786 }
7787 return BaseTransform::TransformMemberExpr(E);
7788 }
7789 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
7790};
7791} // namespace
7792
Alexey Bataeva839ddd2016-03-17 10:19:46 +00007793template <typename T>
7794static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
7795 const llvm::function_ref<T(ValueDecl *)> &Gen) {
7796 for (auto &Set : Lookups) {
7797 for (auto *D : Set) {
7798 if (auto Res = Gen(cast<ValueDecl>(D)))
7799 return Res;
7800 }
7801 }
7802 return T();
7803}
7804
7805static ExprResult
7806buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
7807 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
7808 const DeclarationNameInfo &ReductionId, QualType Ty,
7809 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
7810 if (ReductionIdScopeSpec.isInvalid())
7811 return ExprError();
7812 SmallVector<UnresolvedSet<8>, 4> Lookups;
7813 if (S) {
7814 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
7815 Lookup.suppressDiagnostics();
7816 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
7817 auto *D = Lookup.getRepresentativeDecl();
7818 do {
7819 S = S->getParent();
7820 } while (S && !S->isDeclScope(D));
7821 if (S)
7822 S = S->getParent();
7823 Lookups.push_back(UnresolvedSet<8>());
7824 Lookups.back().append(Lookup.begin(), Lookup.end());
7825 Lookup.clear();
7826 }
7827 } else if (auto *ULE =
7828 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
7829 Lookups.push_back(UnresolvedSet<8>());
7830 Decl *PrevD = nullptr;
David Majnemer9d168222016-08-05 17:44:54 +00007831 for (auto *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00007832 if (D == PrevD)
7833 Lookups.push_back(UnresolvedSet<8>());
7834 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
7835 Lookups.back().addDecl(DRD);
7836 PrevD = D;
7837 }
7838 }
7839 if (Ty->isDependentType() || Ty->isInstantiationDependentType() ||
7840 Ty->containsUnexpandedParameterPack() ||
7841 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
7842 return !D->isInvalidDecl() &&
7843 (D->getType()->isDependentType() ||
7844 D->getType()->isInstantiationDependentType() ||
7845 D->getType()->containsUnexpandedParameterPack());
7846 })) {
7847 UnresolvedSet<8> ResSet;
7848 for (auto &Set : Lookups) {
7849 ResSet.append(Set.begin(), Set.end());
7850 // The last item marks the end of all declarations at the specified scope.
7851 ResSet.addDecl(Set[Set.size() - 1]);
7852 }
7853 return UnresolvedLookupExpr::Create(
7854 SemaRef.Context, /*NamingClass=*/nullptr,
7855 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
7856 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
7857 }
7858 if (auto *VD = filterLookupForUDR<ValueDecl *>(
7859 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
7860 if (!D->isInvalidDecl() &&
7861 SemaRef.Context.hasSameType(D->getType(), Ty))
7862 return D;
7863 return nullptr;
7864 }))
7865 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
7866 if (auto *VD = filterLookupForUDR<ValueDecl *>(
7867 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
7868 if (!D->isInvalidDecl() &&
7869 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
7870 !Ty.isMoreQualifiedThan(D->getType()))
7871 return D;
7872 return nullptr;
7873 })) {
7874 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
7875 /*DetectVirtual=*/false);
7876 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
7877 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
7878 VD->getType().getUnqualifiedType()))) {
7879 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
7880 /*DiagID=*/0) !=
7881 Sema::AR_inaccessible) {
7882 SemaRef.BuildBasePathArray(Paths, BasePath);
7883 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
7884 }
7885 }
7886 }
7887 }
7888 if (ReductionIdScopeSpec.isSet()) {
7889 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
7890 return ExprError();
7891 }
7892 return ExprEmpty();
7893}
7894
Alexey Bataevc5e02582014-06-16 07:08:35 +00007895OMPClause *Sema::ActOnOpenMPReductionClause(
7896 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
7897 SourceLocation ColonLoc, SourceLocation EndLoc,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00007898 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
7899 ArrayRef<Expr *> UnresolvedReductions) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00007900 auto DN = ReductionId.getName();
7901 auto OOK = DN.getCXXOverloadedOperator();
7902 BinaryOperatorKind BOK = BO_Comma;
7903
7904 // OpenMP [2.14.3.6, reduction clause]
7905 // C
7906 // reduction-identifier is either an identifier or one of the following
7907 // operators: +, -, *, &, |, ^, && and ||
7908 // C++
7909 // reduction-identifier is either an id-expression or one of the following
7910 // operators: +, -, *, &, |, ^, && and ||
7911 // FIXME: Only 'min' and 'max' identifiers are supported for now.
7912 switch (OOK) {
7913 case OO_Plus:
7914 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00007915 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00007916 break;
7917 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00007918 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00007919 break;
7920 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00007921 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00007922 break;
7923 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00007924 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00007925 break;
7926 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00007927 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00007928 break;
7929 case OO_AmpAmp:
7930 BOK = BO_LAnd;
7931 break;
7932 case OO_PipePipe:
7933 BOK = BO_LOr;
7934 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00007935 case OO_New:
7936 case OO_Delete:
7937 case OO_Array_New:
7938 case OO_Array_Delete:
7939 case OO_Slash:
7940 case OO_Percent:
7941 case OO_Tilde:
7942 case OO_Exclaim:
7943 case OO_Equal:
7944 case OO_Less:
7945 case OO_Greater:
7946 case OO_LessEqual:
7947 case OO_GreaterEqual:
7948 case OO_PlusEqual:
7949 case OO_MinusEqual:
7950 case OO_StarEqual:
7951 case OO_SlashEqual:
7952 case OO_PercentEqual:
7953 case OO_CaretEqual:
7954 case OO_AmpEqual:
7955 case OO_PipeEqual:
7956 case OO_LessLess:
7957 case OO_GreaterGreater:
7958 case OO_LessLessEqual:
7959 case OO_GreaterGreaterEqual:
7960 case OO_EqualEqual:
7961 case OO_ExclaimEqual:
7962 case OO_PlusPlus:
7963 case OO_MinusMinus:
7964 case OO_Comma:
7965 case OO_ArrowStar:
7966 case OO_Arrow:
7967 case OO_Call:
7968 case OO_Subscript:
7969 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +00007970 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00007971 case NUM_OVERLOADED_OPERATORS:
7972 llvm_unreachable("Unexpected reduction identifier");
7973 case OO_None:
Alexey Bataevc5e02582014-06-16 07:08:35 +00007974 if (auto II = DN.getAsIdentifierInfo()) {
7975 if (II->isStr("max"))
7976 BOK = BO_GT;
7977 else if (II->isStr("min"))
7978 BOK = BO_LT;
7979 }
7980 break;
7981 }
7982 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00007983 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +00007984 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00007985 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00007986
7987 SmallVector<Expr *, 8> Vars;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00007988 SmallVector<Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00007989 SmallVector<Expr *, 8> LHSs;
7990 SmallVector<Expr *, 8> RHSs;
7991 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev61205072016-03-02 04:57:40 +00007992 SmallVector<Decl *, 4> ExprCaptures;
7993 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00007994 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
7995 bool FirstIter = true;
Alexey Bataevc5e02582014-06-16 07:08:35 +00007996 for (auto RefExpr : VarList) {
7997 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +00007998 // OpenMP [2.1, C/C++]
7999 // A list item is a variable or array section, subject to the restrictions
8000 // specified in Section 2.4 on page 42 and in each of the sections
8001 // describing clauses and directives for which a list appears.
8002 // OpenMP [2.14.3.3, Restrictions, p.1]
8003 // A variable that is part of another variable (as an array or
8004 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008005 if (!FirstIter && IR != ER)
8006 ++IR;
8007 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008008 SourceLocation ELoc;
8009 SourceRange ERange;
8010 Expr *SimpleRefExpr = RefExpr;
8011 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8012 /*AllowArraySection=*/true);
8013 if (Res.second) {
8014 // It will be analyzed later.
8015 Vars.push_back(RefExpr);
8016 Privates.push_back(nullptr);
8017 LHSs.push_back(nullptr);
8018 RHSs.push_back(nullptr);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008019 // Try to find 'declare reduction' corresponding construct before using
8020 // builtin/overloaded operators.
8021 QualType Type = Context.DependentTy;
8022 CXXCastPath BasePath;
8023 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8024 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8025 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8026 if (CurContext->isDependentContext() &&
8027 (DeclareReductionRef.isUnset() ||
8028 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
8029 ReductionOps.push_back(DeclareReductionRef.get());
8030 else
8031 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008032 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00008033 ValueDecl *D = Res.first;
8034 if (!D)
8035 continue;
8036
Alexey Bataeva1764212015-09-30 09:22:36 +00008037 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008038 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
8039 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
8040 if (ASE)
Alexey Bataev31300ed2016-02-04 11:27:03 +00008041 Type = ASE->getType().getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008042 else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008043 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
8044 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
8045 Type = ATy->getElementType();
8046 else
8047 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00008048 Type = Type.getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008049 } else
8050 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
8051 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +00008052
Alexey Bataevc5e02582014-06-16 07:08:35 +00008053 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8054 // A variable that appears in a private clause must not have an incomplete
8055 // type or a reference type.
8056 if (RequireCompleteType(ELoc, Type,
8057 diag::err_omp_reduction_incomplete_type))
8058 continue;
8059 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +00008060 // A list item that appears in a reduction clause must not be
8061 // const-qualified.
8062 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008063 Diag(ELoc, diag::err_omp_const_reduction_list_item)
Alexey Bataevc5e02582014-06-16 07:08:35 +00008064 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008065 if (!ASE && !OASE) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008066 bool IsDecl = !VD ||
8067 VD->isThisDeclarationADefinition(Context) ==
8068 VarDecl::DeclarationOnly;
8069 Diag(D->getLocation(),
Alexey Bataeva1764212015-09-30 09:22:36 +00008070 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +00008071 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +00008072 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00008073 continue;
8074 }
8075 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
8076 // If a list-item is a reference type then it must bind to the same object
8077 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +00008078 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008079 VarDecl *VDDef = VD->getDefinition();
David Sheinkman92589992016-10-04 14:41:36 +00008080 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008081 DSARefChecker Check(DSAStack);
8082 if (Check.Visit(VDDef->getInit())) {
8083 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
8084 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
8085 continue;
8086 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00008087 }
8088 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008089
Alexey Bataevc5e02582014-06-16 07:08:35 +00008090 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8091 // in a Construct]
8092 // Variables with the predetermined data-sharing attributes may not be
8093 // listed in data-sharing attributes clauses, except for the cases
8094 // listed below. For these exceptions only, listing a predetermined
8095 // variable in a data-sharing attribute clause is allowed and overrides
8096 // the variable's predetermined data-sharing attributes.
8097 // OpenMP [2.14.3.6, Restrictions, p.3]
8098 // Any number of reduction clauses can be specified on the directive,
8099 // but a list item can appear only once in the reduction clauses for that
8100 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +00008101 DSAStackTy::DSAVarData DVar;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008102 DVar = DSAStack->getTopDSA(D, false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008103 if (DVar.CKind == OMPC_reduction) {
8104 Diag(ELoc, diag::err_omp_once_referenced)
8105 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008106 if (DVar.RefExpr)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008107 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008108 } else if (DVar.CKind != OMPC_unknown) {
8109 Diag(ELoc, diag::err_omp_wrong_dsa)
8110 << getOpenMPClauseName(DVar.CKind)
8111 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008112 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008113 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008114 }
8115
8116 // OpenMP [2.14.3.6, Restrictions, p.1]
8117 // A list item that appears in a reduction clause of a worksharing
8118 // construct must be shared in the parallel regions to which any of the
8119 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008120 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8121 if (isOpenMPWorksharingDirective(CurrDir) &&
8122 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008123 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008124 if (DVar.CKind != OMPC_shared) {
8125 Diag(ELoc, diag::err_omp_required_access)
8126 << getOpenMPClauseName(OMPC_reduction)
8127 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008128 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008129 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +00008130 }
8131 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008132
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008133 // Try to find 'declare reduction' corresponding construct before using
8134 // builtin/overloaded operators.
8135 CXXCastPath BasePath;
8136 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8137 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8138 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8139 if (DeclareReductionRef.isInvalid())
8140 continue;
8141 if (CurContext->isDependentContext() &&
8142 (DeclareReductionRef.isUnset() ||
8143 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
8144 Vars.push_back(RefExpr);
8145 Privates.push_back(nullptr);
8146 LHSs.push_back(nullptr);
8147 RHSs.push_back(nullptr);
8148 ReductionOps.push_back(DeclareReductionRef.get());
8149 continue;
8150 }
8151 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
8152 // Not allowed reduction identifier is found.
8153 Diag(ReductionId.getLocStart(),
8154 diag::err_omp_unknown_reduction_identifier)
8155 << Type << ReductionIdRange;
8156 continue;
8157 }
8158
8159 // OpenMP [2.14.3.6, reduction clause, Restrictions]
8160 // The type of a list item that appears in a reduction clause must be valid
8161 // for the reduction-identifier. For a max or min reduction in C, the type
8162 // of the list item must be an allowed arithmetic data type: char, int,
8163 // float, double, or _Bool, possibly modified with long, short, signed, or
8164 // unsigned. For a max or min reduction in C++, the type of the list item
8165 // must be an allowed arithmetic data type: char, wchar_t, int, float,
8166 // double, or bool, possibly modified with long, short, signed, or unsigned.
8167 if (DeclareReductionRef.isUnset()) {
8168 if ((BOK == BO_GT || BOK == BO_LT) &&
8169 !(Type->isScalarType() ||
8170 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
8171 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
8172 << getLangOpts().CPlusPlus;
8173 if (!ASE && !OASE) {
8174 bool IsDecl = !VD ||
8175 VD->isThisDeclarationADefinition(Context) ==
8176 VarDecl::DeclarationOnly;
8177 Diag(D->getLocation(),
8178 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8179 << D;
8180 }
8181 continue;
8182 }
8183 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
8184 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
8185 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
8186 if (!ASE && !OASE) {
8187 bool IsDecl = !VD ||
8188 VD->isThisDeclarationADefinition(Context) ==
8189 VarDecl::DeclarationOnly;
8190 Diag(D->getLocation(),
8191 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8192 << D;
8193 }
8194 continue;
8195 }
8196 }
8197
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008198 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008199 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
Alexey Bataev60da77e2016-02-29 05:54:20 +00008200 D->hasAttrs() ? &D->getAttrs() : nullptr);
8201 auto *RHSVD = buildVarDecl(*this, ELoc, Type, D->getName(),
8202 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008203 auto PrivateTy = Type;
Alexey Bataev1189bd02016-01-26 12:20:39 +00008204 if (OASE ||
Alexey Bataev60da77e2016-02-29 05:54:20 +00008205 (!ASE &&
8206 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
David Majnemer9d168222016-08-05 17:44:54 +00008207 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008208 // Create pseudo array type for private copy. The size for this array will
8209 // be generated during codegen.
8210 // For array subscripts or single variables Private Ty is the same as Type
8211 // (type of the variable or single array element).
8212 PrivateTy = Context.getVariableArrayType(
8213 Type, new (Context) OpaqueValueExpr(SourceLocation(),
8214 Context.getSizeType(), VK_RValue),
8215 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +00008216 } else if (!ASE && !OASE &&
8217 Context.getAsArrayType(D->getType().getNonReferenceType()))
8218 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008219 // Private copy.
Alexey Bataev60da77e2016-02-29 05:54:20 +00008220 auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, D->getName(),
8221 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008222 // Add initializer for private variable.
8223 Expr *Init = nullptr;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008224 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
8225 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
8226 if (DeclareReductionRef.isUsable()) {
8227 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
8228 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
8229 if (DRD->getInitializer()) {
8230 Init = DRDRef;
8231 RHSVD->setInit(DRDRef);
8232 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008233 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008234 } else {
8235 switch (BOK) {
8236 case BO_Add:
8237 case BO_Xor:
8238 case BO_Or:
8239 case BO_LOr:
8240 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
8241 if (Type->isScalarType() || Type->isAnyComplexType())
8242 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
8243 break;
8244 case BO_Mul:
8245 case BO_LAnd:
8246 if (Type->isScalarType() || Type->isAnyComplexType()) {
8247 // '*' and '&&' reduction ops - initializer is '1'.
8248 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00008249 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008250 break;
8251 case BO_And: {
8252 // '&' reduction op - initializer is '~0'.
8253 QualType OrigType = Type;
8254 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
8255 Type = ComplexTy->getElementType();
8256 if (Type->isRealFloatingType()) {
8257 llvm::APFloat InitValue =
8258 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
8259 /*isIEEE=*/true);
8260 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
8261 Type, ELoc);
8262 } else if (Type->isScalarType()) {
8263 auto Size = Context.getTypeSize(Type);
8264 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
8265 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
8266 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
8267 }
8268 if (Init && OrigType->isAnyComplexType()) {
8269 // Init = 0xFFFF + 0xFFFFi;
8270 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
8271 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
8272 }
8273 Type = OrigType;
8274 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008275 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008276 case BO_LT:
8277 case BO_GT: {
8278 // 'min' reduction op - initializer is 'Largest representable number in
8279 // the reduction list item type'.
8280 // 'max' reduction op - initializer is 'Least representable number in
8281 // the reduction list item type'.
8282 if (Type->isIntegerType() || Type->isPointerType()) {
8283 bool IsSigned = Type->hasSignedIntegerRepresentation();
8284 auto Size = Context.getTypeSize(Type);
8285 QualType IntTy =
8286 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
8287 llvm::APInt InitValue =
8288 (BOK != BO_LT)
8289 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
8290 : llvm::APInt::getMinValue(Size)
8291 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
8292 : llvm::APInt::getMaxValue(Size);
8293 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
8294 if (Type->isPointerType()) {
8295 // Cast to pointer type.
8296 auto CastExpr = BuildCStyleCastExpr(
8297 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
8298 SourceLocation(), Init);
8299 if (CastExpr.isInvalid())
8300 continue;
8301 Init = CastExpr.get();
8302 }
8303 } else if (Type->isRealFloatingType()) {
8304 llvm::APFloat InitValue = llvm::APFloat::getLargest(
8305 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
8306 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
8307 Type, ELoc);
8308 }
8309 break;
8310 }
8311 case BO_PtrMemD:
8312 case BO_PtrMemI:
8313 case BO_MulAssign:
8314 case BO_Div:
8315 case BO_Rem:
8316 case BO_Sub:
8317 case BO_Shl:
8318 case BO_Shr:
8319 case BO_LE:
8320 case BO_GE:
8321 case BO_EQ:
8322 case BO_NE:
8323 case BO_AndAssign:
8324 case BO_XorAssign:
8325 case BO_OrAssign:
8326 case BO_Assign:
8327 case BO_AddAssign:
8328 case BO_SubAssign:
8329 case BO_DivAssign:
8330 case BO_RemAssign:
8331 case BO_ShlAssign:
8332 case BO_ShrAssign:
8333 case BO_Comma:
8334 llvm_unreachable("Unexpected reduction operation");
8335 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008336 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008337 if (Init && DeclareReductionRef.isUnset()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008338 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
8339 /*TypeMayContainAuto=*/false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008340 } else if (!Init)
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008341 ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008342 if (RHSVD->isInvalidDecl())
8343 continue;
8344 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008345 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
8346 << ReductionIdRange;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008347 bool IsDecl =
8348 !VD ||
8349 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8350 Diag(D->getLocation(),
8351 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8352 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008353 continue;
8354 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008355 // Store initializer for single element in private copy. Will be used during
8356 // codegen.
8357 PrivateVD->setInit(RHSVD->getInit());
8358 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008359 auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008360 ExprResult ReductionOp;
8361 if (DeclareReductionRef.isUsable()) {
8362 QualType RedTy = DeclareReductionRef.get()->getType();
8363 QualType PtrRedTy = Context.getPointerType(RedTy);
8364 ExprResult LHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
8365 ExprResult RHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
8366 if (!BasePath.empty()) {
8367 LHS = DefaultLvalueConversion(LHS.get());
8368 RHS = DefaultLvalueConversion(RHS.get());
8369 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
8370 CK_UncheckedDerivedToBase, LHS.get(),
8371 &BasePath, LHS.get()->getValueKind());
8372 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
8373 CK_UncheckedDerivedToBase, RHS.get(),
8374 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008375 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008376 FunctionProtoType::ExtProtoInfo EPI;
8377 QualType Params[] = {PtrRedTy, PtrRedTy};
8378 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
8379 auto *OVE = new (Context) OpaqueValueExpr(
8380 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
8381 DefaultLvalueConversion(DeclareReductionRef.get()).get());
8382 Expr *Args[] = {LHS.get(), RHS.get()};
8383 ReductionOp = new (Context)
8384 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
8385 } else {
8386 ReductionOp = BuildBinOp(DSAStack->getCurScope(),
8387 ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
8388 if (ReductionOp.isUsable()) {
8389 if (BOK != BO_LT && BOK != BO_GT) {
8390 ReductionOp =
8391 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
8392 BO_Assign, LHSDRE, ReductionOp.get());
8393 } else {
8394 auto *ConditionalOp = new (Context) ConditionalOperator(
8395 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
8396 RHSDRE, Type, VK_LValue, OK_Ordinary);
8397 ReductionOp =
8398 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
8399 BO_Assign, LHSDRE, ConditionalOp);
8400 }
8401 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
8402 }
8403 if (ReductionOp.isInvalid())
8404 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008405 }
8406
Alexey Bataev60da77e2016-02-29 05:54:20 +00008407 DeclRefExpr *Ref = nullptr;
8408 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008409 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008410 if (ASE || OASE) {
8411 TransformExprToCaptures RebuildToCapture(*this, D);
8412 VarsExpr =
8413 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
8414 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +00008415 } else {
8416 VarsExpr = Ref =
8417 buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +00008418 }
8419 if (!IsOpenMPCapturedDecl(D)) {
8420 ExprCaptures.push_back(Ref->getDecl());
8421 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
8422 ExprResult RefRes = DefaultLvalueConversion(Ref);
8423 if (!RefRes.isUsable())
8424 continue;
8425 ExprResult PostUpdateRes =
8426 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
8427 SimpleRefExpr, RefRes.get());
8428 if (!PostUpdateRes.isUsable())
8429 continue;
8430 ExprPostUpdates.push_back(
8431 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +00008432 }
8433 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00008434 }
8435 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
8436 Vars.push_back(VarsExpr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008437 Privates.push_back(PrivateDRE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008438 LHSs.push_back(LHSDRE);
8439 RHSs.push_back(RHSDRE);
8440 ReductionOps.push_back(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008441 }
8442
8443 if (Vars.empty())
8444 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +00008445
Alexey Bataevc5e02582014-06-16 07:08:35 +00008446 return OMPReductionClause::Create(
8447 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008448 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008449 LHSs, RHSs, ReductionOps, buildPreInits(Context, ExprCaptures),
8450 buildPostUpdate(*this, ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +00008451}
8452
Alexey Bataevecba70f2016-04-12 11:02:11 +00008453bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
8454 SourceLocation LinLoc) {
8455 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
8456 LinKind == OMPC_LINEAR_unknown) {
8457 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
8458 return true;
8459 }
8460 return false;
8461}
8462
8463bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
8464 OpenMPLinearClauseKind LinKind,
8465 QualType Type) {
8466 auto *VD = dyn_cast_or_null<VarDecl>(D);
8467 // A variable must not have an incomplete type or a reference type.
8468 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
8469 return true;
8470 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
8471 !Type->isReferenceType()) {
8472 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
8473 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
8474 return true;
8475 }
8476 Type = Type.getNonReferenceType();
8477
8478 // A list item must not be const-qualified.
8479 if (Type.isConstant(Context)) {
8480 Diag(ELoc, diag::err_omp_const_variable)
8481 << getOpenMPClauseName(OMPC_linear);
8482 if (D) {
8483 bool IsDecl =
8484 !VD ||
8485 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8486 Diag(D->getLocation(),
8487 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8488 << D;
8489 }
8490 return true;
8491 }
8492
8493 // A list item must be of integral or pointer type.
8494 Type = Type.getUnqualifiedType().getCanonicalType();
8495 const auto *Ty = Type.getTypePtrOrNull();
8496 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
8497 !Ty->isPointerType())) {
8498 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
8499 if (D) {
8500 bool IsDecl =
8501 !VD ||
8502 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8503 Diag(D->getLocation(),
8504 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8505 << D;
8506 }
8507 return true;
8508 }
8509 return false;
8510}
8511
Alexey Bataev182227b2015-08-20 10:54:39 +00008512OMPClause *Sema::ActOnOpenMPLinearClause(
8513 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
8514 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
8515 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +00008516 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008517 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +00008518 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +00008519 SmallVector<Decl *, 4> ExprCaptures;
8520 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +00008521 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +00008522 LinKind = OMPC_LINEAR_val;
Alexey Bataeved09d242014-05-28 05:53:51 +00008523 for (auto &RefExpr : VarList) {
8524 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008525 SourceLocation ELoc;
8526 SourceRange ERange;
8527 Expr *SimpleRefExpr = RefExpr;
8528 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8529 /*AllowArraySection=*/false);
8530 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +00008531 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008532 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008533 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +00008534 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00008535 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008536 ValueDecl *D = Res.first;
8537 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +00008538 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +00008539
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008540 QualType Type = D->getType();
8541 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +00008542
8543 // OpenMP [2.14.3.7, linear clause]
8544 // A list-item cannot appear in more than one linear clause.
8545 // A list-item that appears in a linear clause cannot appear in any
8546 // other data-sharing attribute clause.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008547 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00008548 if (DVar.RefExpr) {
8549 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8550 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008551 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00008552 continue;
8553 }
8554
Alexey Bataevecba70f2016-04-12 11:02:11 +00008555 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +00008556 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00008557 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +00008558
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008559 // Build private copy of original var.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008560 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
8561 D->hasAttrs() ? &D->getAttrs() : nullptr);
8562 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +00008563 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008564 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008565 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008566 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008567 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +00008568 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
8569 if (!IsOpenMPCapturedDecl(D)) {
8570 ExprCaptures.push_back(Ref->getDecl());
8571 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
8572 ExprResult RefRes = DefaultLvalueConversion(Ref);
8573 if (!RefRes.isUsable())
8574 continue;
8575 ExprResult PostUpdateRes =
8576 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
8577 SimpleRefExpr, RefRes.get());
8578 if (!PostUpdateRes.isUsable())
8579 continue;
8580 ExprPostUpdates.push_back(
8581 IgnoredValueConversions(PostUpdateRes.get()).get());
8582 }
8583 }
8584 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008585 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008586 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008587 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008588 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008589 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008590 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
8591 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
8592
8593 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008594 Vars.push_back((VD || CurContext->isDependentContext())
8595 ? RefExpr->IgnoreParens()
8596 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008597 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +00008598 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00008599 }
8600
8601 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008602 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00008603
8604 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00008605 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00008606 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
8607 !Step->isInstantiationDependent() &&
8608 !Step->containsUnexpandedParameterPack()) {
8609 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00008610 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00008611 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008612 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008613 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00008614
Alexander Musman3276a272015-03-21 10:12:56 +00008615 // Build var to save the step value.
8616 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00008617 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +00008618 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +00008619 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +00008620 ExprResult CalcStep =
8621 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008622 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +00008623
Alexander Musman8dba6642014-04-22 13:09:42 +00008624 // Warn about zero linear step (it would be probably better specified as
8625 // making corresponding variables 'const').
8626 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00008627 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
8628 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00008629 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
8630 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00008631 if (!IsConstant && CalcStep.isUsable()) {
8632 // Calculate the step beforehand instead of doing this on each iteration.
8633 // (This is not used if the number of iterations may be kfold-ed).
8634 CalcStepExpr = CalcStep.get();
8635 }
Alexander Musman8dba6642014-04-22 13:09:42 +00008636 }
8637
Alexey Bataev182227b2015-08-20 10:54:39 +00008638 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
8639 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008640 StepExpr, CalcStepExpr,
8641 buildPreInits(Context, ExprCaptures),
8642 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +00008643}
8644
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008645static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
8646 Expr *NumIterations, Sema &SemaRef,
8647 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +00008648 // Walk the vars and build update/final expressions for the CodeGen.
8649 SmallVector<Expr *, 8> Updates;
8650 SmallVector<Expr *, 8> Finals;
8651 Expr *Step = Clause.getStep();
8652 Expr *CalcStep = Clause.getCalcStep();
8653 // OpenMP [2.14.3.7, linear clause]
8654 // If linear-step is not specified it is assumed to be 1.
8655 if (Step == nullptr)
8656 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00008657 else if (CalcStep) {
Alexander Musman3276a272015-03-21 10:12:56 +00008658 Step = cast<BinaryOperator>(CalcStep)->getLHS();
Alexey Bataev5a3af132016-03-29 08:58:54 +00008659 }
Alexander Musman3276a272015-03-21 10:12:56 +00008660 bool HasErrors = false;
8661 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008662 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008663 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +00008664 for (auto &RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008665 SourceLocation ELoc;
8666 SourceRange ERange;
8667 Expr *SimpleRefExpr = RefExpr;
8668 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
8669 /*AllowArraySection=*/false);
8670 ValueDecl *D = Res.first;
8671 if (Res.second || !D) {
8672 Updates.push_back(nullptr);
8673 Finals.push_back(nullptr);
8674 HasErrors = true;
8675 continue;
8676 }
8677 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) {
8678 D = cast<MemberExpr>(CED->getInit()->IgnoreParenImpCasts())
8679 ->getMemberDecl();
8680 }
8681 auto &&Info = Stack->isLoopControlVariable(D);
Alexander Musman3276a272015-03-21 10:12:56 +00008682 Expr *InitExpr = *CurInit;
8683
8684 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +00008685 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008686 Expr *CapturedRef;
8687 if (LinKind == OMPC_LINEAR_uval)
8688 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
8689 else
8690 CapturedRef =
8691 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
8692 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
8693 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00008694
8695 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008696 ExprResult Update;
8697 if (!Info.first) {
8698 Update =
8699 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
8700 InitExpr, IV, Step, /* Subtract */ false);
8701 } else
8702 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008703 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
8704 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00008705
8706 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008707 ExprResult Final;
8708 if (!Info.first) {
8709 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
8710 InitExpr, NumIterations, Step,
8711 /* Subtract */ false);
8712 } else
8713 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008714 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
8715 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008716
Alexander Musman3276a272015-03-21 10:12:56 +00008717 if (!Update.isUsable() || !Final.isUsable()) {
8718 Updates.push_back(nullptr);
8719 Finals.push_back(nullptr);
8720 HasErrors = true;
8721 } else {
8722 Updates.push_back(Update.get());
8723 Finals.push_back(Final.get());
8724 }
Richard Trieucc3949d2016-02-18 22:34:54 +00008725 ++CurInit;
8726 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00008727 }
8728 Clause.setUpdates(Updates);
8729 Clause.setFinals(Finals);
8730 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00008731}
8732
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008733OMPClause *Sema::ActOnOpenMPAlignedClause(
8734 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
8735 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
8736
8737 SmallVector<Expr *, 8> Vars;
8738 for (auto &RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +00008739 assert(RefExpr && "NULL expr in OpenMP linear clause.");
8740 SourceLocation ELoc;
8741 SourceRange ERange;
8742 Expr *SimpleRefExpr = RefExpr;
8743 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8744 /*AllowArraySection=*/false);
8745 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008746 // It will be analyzed later.
8747 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008748 }
Alexey Bataev1efd1662016-03-29 10:59:56 +00008749 ValueDecl *D = Res.first;
8750 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008751 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008752
Alexey Bataev1efd1662016-03-29 10:59:56 +00008753 QualType QType = D->getType();
8754 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008755
8756 // OpenMP [2.8.1, simd construct, Restrictions]
8757 // The type of list items appearing in the aligned clause must be
8758 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008759 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008760 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +00008761 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008762 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +00008763 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008764 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +00008765 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008766 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +00008767 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008768 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +00008769 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008770 continue;
8771 }
8772
8773 // OpenMP [2.8.1, simd construct, Restrictions]
8774 // A list-item cannot appear in more than one aligned clause.
Alexey Bataev1efd1662016-03-29 10:59:56 +00008775 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00008776 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008777 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
8778 << getOpenMPClauseName(OMPC_aligned);
8779 continue;
8780 }
8781
Alexey Bataev1efd1662016-03-29 10:59:56 +00008782 DeclRefExpr *Ref = nullptr;
8783 if (!VD && IsOpenMPCapturedDecl(D))
8784 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
8785 Vars.push_back(DefaultFunctionArrayConversion(
8786 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
8787 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008788 }
8789
8790 // OpenMP [2.8.1, simd construct, Description]
8791 // The parameter of the aligned clause, alignment, must be a constant
8792 // positive integer expression.
8793 // If no optional parameter is specified, implementation-defined default
8794 // alignments for SIMD instructions on the target platforms are assumed.
8795 if (Alignment != nullptr) {
8796 ExprResult AlignResult =
8797 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
8798 if (AlignResult.isInvalid())
8799 return nullptr;
8800 Alignment = AlignResult.get();
8801 }
8802 if (Vars.empty())
8803 return nullptr;
8804
8805 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
8806 EndLoc, Vars, Alignment);
8807}
8808
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008809OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
8810 SourceLocation StartLoc,
8811 SourceLocation LParenLoc,
8812 SourceLocation EndLoc) {
8813 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +00008814 SmallVector<Expr *, 8> SrcExprs;
8815 SmallVector<Expr *, 8> DstExprs;
8816 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +00008817 for (auto &RefExpr : VarList) {
8818 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
8819 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008820 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008821 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00008822 SrcExprs.push_back(nullptr);
8823 DstExprs.push_back(nullptr);
8824 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008825 continue;
8826 }
8827
Alexey Bataeved09d242014-05-28 05:53:51 +00008828 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008829 // OpenMP [2.1, C/C++]
8830 // A list item is a variable name.
8831 // OpenMP [2.14.4.1, Restrictions, p.1]
8832 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +00008833 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008834 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008835 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
8836 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008837 continue;
8838 }
8839
8840 Decl *D = DE->getDecl();
8841 VarDecl *VD = cast<VarDecl>(D);
8842
8843 QualType Type = VD->getType();
8844 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
8845 // It will be analyzed later.
8846 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00008847 SrcExprs.push_back(nullptr);
8848 DstExprs.push_back(nullptr);
8849 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008850 continue;
8851 }
8852
8853 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
8854 // A list item that appears in a copyin clause must be threadprivate.
8855 if (!DSAStack->isThreadPrivate(VD)) {
8856 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +00008857 << getOpenMPClauseName(OMPC_copyin)
8858 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008859 continue;
8860 }
8861
8862 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
8863 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +00008864 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008865 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008866 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00008867 auto *SrcVD =
8868 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
8869 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00008870 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008871 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
8872 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00008873 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
8874 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00008875 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008876 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +00008877 // For arrays generate assignment operation for single element and replace
8878 // it by the original array element in CodeGen.
8879 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
8880 PseudoDstExpr, PseudoSrcExpr);
8881 if (AssignmentOp.isInvalid())
8882 continue;
8883 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
8884 /*DiscardedValue=*/true);
8885 if (AssignmentOp.isInvalid())
8886 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008887
8888 DSAStack->addDSA(VD, DE, OMPC_copyin);
8889 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00008890 SrcExprs.push_back(PseudoSrcExpr);
8891 DstExprs.push_back(PseudoDstExpr);
8892 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008893 }
8894
Alexey Bataeved09d242014-05-28 05:53:51 +00008895 if (Vars.empty())
8896 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008897
Alexey Bataevf56f98c2015-04-16 05:39:01 +00008898 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
8899 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008900}
8901
Alexey Bataevbae9a792014-06-27 10:37:06 +00008902OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
8903 SourceLocation StartLoc,
8904 SourceLocation LParenLoc,
8905 SourceLocation EndLoc) {
8906 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +00008907 SmallVector<Expr *, 8> SrcExprs;
8908 SmallVector<Expr *, 8> DstExprs;
8909 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +00008910 for (auto &RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +00008911 assert(RefExpr && "NULL expr in OpenMP linear clause.");
8912 SourceLocation ELoc;
8913 SourceRange ERange;
8914 Expr *SimpleRefExpr = RefExpr;
8915 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8916 /*AllowArraySection=*/false);
8917 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00008918 // It will be analyzed later.
8919 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +00008920 SrcExprs.push_back(nullptr);
8921 DstExprs.push_back(nullptr);
8922 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00008923 }
Alexey Bataeve122da12016-03-17 10:50:17 +00008924 ValueDecl *D = Res.first;
8925 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +00008926 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00008927
Alexey Bataeve122da12016-03-17 10:50:17 +00008928 QualType Type = D->getType();
8929 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +00008930
8931 // OpenMP [2.14.4.2, Restrictions, p.2]
8932 // A list item that appears in a copyprivate clause may not appear in a
8933 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +00008934 if (!VD || !DSAStack->isThreadPrivate(VD)) {
8935 auto DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +00008936 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
8937 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00008938 Diag(ELoc, diag::err_omp_wrong_dsa)
8939 << getOpenMPClauseName(DVar.CKind)
8940 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve122da12016-03-17 10:50:17 +00008941 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00008942 continue;
8943 }
8944
8945 // OpenMP [2.11.4.2, Restrictions, p.1]
8946 // All list items that appear in a copyprivate clause must be either
8947 // threadprivate or private in the enclosing context.
8948 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +00008949 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +00008950 if (DVar.CKind == OMPC_shared) {
8951 Diag(ELoc, diag::err_omp_required_access)
8952 << getOpenMPClauseName(OMPC_copyprivate)
8953 << "threadprivate or private in the enclosing context";
Alexey Bataeve122da12016-03-17 10:50:17 +00008954 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00008955 continue;
8956 }
8957 }
8958 }
8959
Alexey Bataev7a3e5852015-05-19 08:19:24 +00008960 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00008961 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +00008962 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008963 << getOpenMPClauseName(OMPC_copyprivate) << Type
8964 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +00008965 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +00008966 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +00008967 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +00008968 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +00008969 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +00008970 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +00008971 continue;
8972 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008973
Alexey Bataevbae9a792014-06-27 10:37:06 +00008974 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
8975 // A variable of class type (or array thereof) that appears in a
8976 // copyin clause requires an accessible, unambiguous copy assignment
8977 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008978 Type = Context.getBaseElementType(Type.getNonReferenceType())
8979 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +00008980 auto *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +00008981 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
8982 D->hasAttrs() ? &D->getAttrs() : nullptr);
8983 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
Alexey Bataev420d45b2015-04-14 05:11:24 +00008984 auto *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +00008985 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
8986 D->hasAttrs() ? &D->getAttrs() : nullptr);
David Majnemer9d168222016-08-05 17:44:54 +00008987 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataeve122da12016-03-17 10:50:17 +00008988 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
Alexey Bataeva63048e2015-03-23 06:18:07 +00008989 PseudoDstExpr, PseudoSrcExpr);
8990 if (AssignmentOp.isInvalid())
8991 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +00008992 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +00008993 /*DiscardedValue=*/true);
8994 if (AssignmentOp.isInvalid())
8995 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00008996
8997 // No need to mark vars as copyprivate, they are already threadprivate or
8998 // implicitly private.
Alexey Bataeve122da12016-03-17 10:50:17 +00008999 assert(VD || IsOpenMPCapturedDecl(D));
9000 Vars.push_back(
9001 VD ? RefExpr->IgnoreParens()
9002 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +00009003 SrcExprs.push_back(PseudoSrcExpr);
9004 DstExprs.push_back(PseudoDstExpr);
9005 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +00009006 }
9007
9008 if (Vars.empty())
9009 return nullptr;
9010
Alexey Bataeva63048e2015-03-23 06:18:07 +00009011 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9012 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009013}
9014
Alexey Bataev6125da92014-07-21 11:26:11 +00009015OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
9016 SourceLocation StartLoc,
9017 SourceLocation LParenLoc,
9018 SourceLocation EndLoc) {
9019 if (VarList.empty())
9020 return nullptr;
9021
9022 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
9023}
Alexey Bataevdea47612014-07-23 07:46:59 +00009024
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009025OMPClause *
9026Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
9027 SourceLocation DepLoc, SourceLocation ColonLoc,
9028 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9029 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00009030 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009031 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +00009032 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009033 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +00009034 return nullptr;
9035 }
9036 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009037 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
9038 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +00009039 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009040 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009041 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
9042 /*Last=*/OMPC_DEPEND_unknown, Except)
9043 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009044 return nullptr;
9045 }
9046 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +00009047 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009048 llvm::APSInt DepCounter(/*BitWidth=*/32);
9049 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
9050 if (DepKind == OMPC_DEPEND_sink) {
9051 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
9052 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
9053 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009054 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009055 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009056 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
9057 DSAStack->getParentOrderedRegionParam()) {
9058 for (auto &RefExpr : VarList) {
9059 assert(RefExpr && "NULL expr in OpenMP shared clause.");
Alexey Bataev8b427062016-05-25 12:36:08 +00009060 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009061 // It will be analyzed later.
9062 Vars.push_back(RefExpr);
9063 continue;
9064 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009065
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009066 SourceLocation ELoc = RefExpr->getExprLoc();
9067 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
9068 if (DepKind == OMPC_DEPEND_sink) {
9069 if (DepCounter >= TotalDepCount) {
9070 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
9071 continue;
9072 }
9073 ++DepCounter;
9074 // OpenMP [2.13.9, Summary]
9075 // depend(dependence-type : vec), where dependence-type is:
9076 // 'sink' and where vec is the iteration vector, which has the form:
9077 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
9078 // where n is the value specified by the ordered clause in the loop
9079 // directive, xi denotes the loop iteration variable of the i-th nested
9080 // loop associated with the loop directive, and di is a constant
9081 // non-negative integer.
Alexey Bataev8b427062016-05-25 12:36:08 +00009082 if (CurContext->isDependentContext()) {
9083 // It will be analyzed later.
9084 Vars.push_back(RefExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009085 continue;
9086 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009087 SimpleExpr = SimpleExpr->IgnoreImplicit();
9088 OverloadedOperatorKind OOK = OO_None;
9089 SourceLocation OOLoc;
9090 Expr *LHS = SimpleExpr;
9091 Expr *RHS = nullptr;
9092 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
9093 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
9094 OOLoc = BO->getOperatorLoc();
9095 LHS = BO->getLHS()->IgnoreParenImpCasts();
9096 RHS = BO->getRHS()->IgnoreParenImpCasts();
9097 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
9098 OOK = OCE->getOperator();
9099 OOLoc = OCE->getOperatorLoc();
9100 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9101 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
9102 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
9103 OOK = MCE->getMethodDecl()
9104 ->getNameInfo()
9105 .getName()
9106 .getCXXOverloadedOperator();
9107 OOLoc = MCE->getCallee()->getExprLoc();
9108 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
9109 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9110 }
9111 SourceLocation ELoc;
9112 SourceRange ERange;
9113 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
9114 /*AllowArraySection=*/false);
9115 if (Res.second) {
9116 // It will be analyzed later.
9117 Vars.push_back(RefExpr);
9118 }
9119 ValueDecl *D = Res.first;
9120 if (!D)
9121 continue;
9122
9123 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
9124 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
9125 continue;
9126 }
9127 if (RHS) {
9128 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
9129 RHS, OMPC_depend, /*StrictlyPositive=*/false);
9130 if (RHSRes.isInvalid())
9131 continue;
9132 }
9133 if (!CurContext->isDependentContext() &&
9134 DSAStack->getParentOrderedRegionParam() &&
9135 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
9136 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
9137 << DSAStack->getParentLoopControlVariable(
9138 DepCounter.getZExtValue());
9139 continue;
9140 }
9141 OpsOffs.push_back({RHS, OOK});
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009142 } else {
9143 // OpenMP [2.11.1.1, Restrictions, p.3]
9144 // A variable that is part of another variable (such as a field of a
9145 // structure) but is not an array element or an array section cannot
9146 // appear in a depend clause.
9147 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
9148 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
9149 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
9150 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
9151 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
Alexey Bataev31300ed2016-02-04 11:27:03 +00009152 (ASE &&
9153 !ASE->getBase()
9154 ->getType()
9155 .getNonReferenceType()
9156 ->isPointerType() &&
9157 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009158 Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item)
9159 << 0 << RefExpr->getSourceRange();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009160 continue;
9161 }
9162 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009163 Vars.push_back(RefExpr->IgnoreParenImpCasts());
9164 }
9165
9166 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
9167 TotalDepCount > VarList.size() &&
9168 DSAStack->getParentOrderedRegionParam()) {
9169 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
9170 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
9171 }
9172 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
9173 Vars.empty())
9174 return nullptr;
9175 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009176 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9177 DepKind, DepLoc, ColonLoc, Vars);
9178 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
9179 DSAStack->addDoacrossDependClause(C, OpsOffs);
9180 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009181}
Michael Wonge710d542015-08-07 16:16:36 +00009182
9183OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
9184 SourceLocation LParenLoc,
9185 SourceLocation EndLoc) {
9186 Expr *ValExpr = Device;
Michael Wonge710d542015-08-07 16:16:36 +00009187
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009188 // OpenMP [2.9.1, Restrictions]
9189 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00009190 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
9191 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009192 return nullptr;
9193
Michael Wonge710d542015-08-07 16:16:36 +00009194 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9195}
Kelvin Li0bff7af2015-11-23 05:32:03 +00009196
9197static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
9198 DSAStackTy *Stack, CXXRecordDecl *RD) {
9199 if (!RD || RD->isInvalidDecl())
9200 return true;
9201
9202 auto QTy = SemaRef.Context.getRecordType(RD);
9203 if (RD->isDynamicClass()) {
9204 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9205 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
9206 return false;
9207 }
9208 auto *DC = RD;
9209 bool IsCorrect = true;
9210 for (auto *I : DC->decls()) {
9211 if (I) {
9212 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
9213 if (MD->isStatic()) {
9214 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9215 SemaRef.Diag(MD->getLocation(),
9216 diag::note_omp_static_member_in_target);
9217 IsCorrect = false;
9218 }
9219 } else if (auto *VD = dyn_cast<VarDecl>(I)) {
9220 if (VD->isStaticDataMember()) {
9221 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9222 SemaRef.Diag(VD->getLocation(),
9223 diag::note_omp_static_member_in_target);
9224 IsCorrect = false;
9225 }
9226 }
9227 }
9228 }
9229
9230 for (auto &I : RD->bases()) {
9231 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
9232 I.getType()->getAsCXXRecordDecl()))
9233 IsCorrect = false;
9234 }
9235 return IsCorrect;
9236}
9237
9238static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
9239 DSAStackTy *Stack, QualType QTy) {
9240 NamedDecl *ND;
9241 if (QTy->isIncompleteType(&ND)) {
9242 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
9243 return false;
9244 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
David Majnemer9d168222016-08-05 17:44:54 +00009245 if (!RD->isInvalidDecl() && !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
Kelvin Li0bff7af2015-11-23 05:32:03 +00009246 return false;
9247 }
9248 return true;
9249}
9250
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009251/// \brief Return true if it can be proven that the provided array expression
9252/// (array section or array subscript) does NOT specify the whole size of the
9253/// array whose base type is \a BaseQTy.
9254static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
9255 const Expr *E,
9256 QualType BaseQTy) {
9257 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
9258
9259 // If this is an array subscript, it refers to the whole size if the size of
9260 // the dimension is constant and equals 1. Also, an array section assumes the
9261 // format of an array subscript if no colon is used.
9262 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
9263 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
9264 return ATy->getSize().getSExtValue() != 1;
9265 // Size can't be evaluated statically.
9266 return false;
9267 }
9268
9269 assert(OASE && "Expecting array section if not an array subscript.");
9270 auto *LowerBound = OASE->getLowerBound();
9271 auto *Length = OASE->getLength();
9272
9273 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +00009274 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009275 if (LowerBound) {
9276 llvm::APSInt ConstLowerBound;
9277 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
9278 return false; // Can't get the integer value as a constant.
9279 if (ConstLowerBound.getSExtValue())
9280 return true;
9281 }
9282
9283 // If we don't have a length we covering the whole dimension.
9284 if (!Length)
9285 return false;
9286
9287 // If the base is a pointer, we don't have a way to get the size of the
9288 // pointee.
9289 if (BaseQTy->isPointerType())
9290 return false;
9291
9292 // We can only check if the length is the same as the size of the dimension
9293 // if we have a constant array.
9294 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
9295 if (!CATy)
9296 return false;
9297
9298 llvm::APSInt ConstLength;
9299 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
9300 return false; // Can't get the integer value as a constant.
9301
9302 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
9303}
9304
9305// Return true if it can be proven that the provided array expression (array
9306// section or array subscript) does NOT specify a single element of the array
9307// whose base type is \a BaseQTy.
9308static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +00009309 const Expr *E,
9310 QualType BaseQTy) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009311 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
9312
9313 // An array subscript always refer to a single element. Also, an array section
9314 // assumes the format of an array subscript if no colon is used.
9315 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
9316 return false;
9317
9318 assert(OASE && "Expecting array section if not an array subscript.");
9319 auto *Length = OASE->getLength();
9320
9321 // If we don't have a length we have to check if the array has unitary size
9322 // for this dimension. Also, we should always expect a length if the base type
9323 // is pointer.
9324 if (!Length) {
9325 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
9326 return ATy->getSize().getSExtValue() != 1;
9327 // We cannot assume anything.
9328 return false;
9329 }
9330
9331 // Check if the length evaluates to 1.
9332 llvm::APSInt ConstLength;
9333 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
9334 return false; // Can't get the integer value as a constant.
9335
9336 return ConstLength.getSExtValue() != 1;
9337}
9338
Samuel Antao661c0902016-05-26 17:39:58 +00009339// Return the expression of the base of the mappable expression or null if it
9340// cannot be determined and do all the necessary checks to see if the expression
9341// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +00009342// components of the expression.
9343static Expr *CheckMapClauseExpressionBase(
9344 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +00009345 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
9346 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009347 SourceLocation ELoc = E->getExprLoc();
9348 SourceRange ERange = E->getSourceRange();
9349
9350 // The base of elements of list in a map clause have to be either:
9351 // - a reference to variable or field.
9352 // - a member expression.
9353 // - an array expression.
9354 //
9355 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
9356 // reference to 'r'.
9357 //
9358 // If we have:
9359 //
9360 // struct SS {
9361 // Bla S;
9362 // foo() {
9363 // #pragma omp target map (S.Arr[:12]);
9364 // }
9365 // }
9366 //
9367 // We want to retrieve the member expression 'this->S';
9368
9369 Expr *RelevantExpr = nullptr;
9370
Samuel Antao5de996e2016-01-22 20:21:36 +00009371 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
9372 // If a list item is an array section, it must specify contiguous storage.
9373 //
9374 // For this restriction it is sufficient that we make sure only references
9375 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009376 // exist except in the rightmost expression (unless they cover the whole
9377 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +00009378 //
9379 // r.ArrS[3:5].Arr[6:7]
9380 //
9381 // r.ArrS[3:5].x
9382 //
9383 // but these would be valid:
9384 // r.ArrS[3].Arr[6:7]
9385 //
9386 // r.ArrS[3].x
9387
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009388 bool AllowUnitySizeArraySection = true;
9389 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +00009390
Dmitry Polukhin644a9252016-03-11 07:58:34 +00009391 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009392 E = E->IgnoreParenImpCasts();
9393
9394 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
9395 if (!isa<VarDecl>(CurE->getDecl()))
9396 break;
9397
9398 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009399
9400 // If we got a reference to a declaration, we should not expect any array
9401 // section before that.
9402 AllowUnitySizeArraySection = false;
9403 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +00009404
9405 // Record the component.
9406 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
9407 CurE, CurE->getDecl()));
Samuel Antao5de996e2016-01-22 20:21:36 +00009408 continue;
9409 }
9410
9411 if (auto *CurE = dyn_cast<MemberExpr>(E)) {
9412 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
9413
9414 if (isa<CXXThisExpr>(BaseE))
9415 // We found a base expression: this->Val.
9416 RelevantExpr = CurE;
9417 else
9418 E = BaseE;
9419
9420 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
9421 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
9422 << CurE->getSourceRange();
9423 break;
9424 }
9425
9426 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
9427
9428 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
9429 // A bit-field cannot appear in a map clause.
9430 //
9431 if (FD->isBitField()) {
Samuel Antao661c0902016-05-26 17:39:58 +00009432 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
9433 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +00009434 break;
9435 }
9436
9437 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9438 // If the type of a list item is a reference to a type T then the type
9439 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009440 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +00009441
9442 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
9443 // A list item cannot be a variable that is a member of a structure with
9444 // a union type.
9445 //
9446 if (auto *RT = CurType->getAs<RecordType>())
9447 if (RT->isUnionType()) {
9448 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
9449 << CurE->getSourceRange();
9450 break;
9451 }
9452
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009453 // If we got a member expression, we should not expect any array section
9454 // before that:
9455 //
9456 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
9457 // If a list item is an element of a structure, only the rightmost symbol
9458 // of the variable reference can be an array section.
9459 //
9460 AllowUnitySizeArraySection = false;
9461 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +00009462
9463 // Record the component.
9464 CurComponents.push_back(
9465 OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
Samuel Antao5de996e2016-01-22 20:21:36 +00009466 continue;
9467 }
9468
9469 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
9470 E = CurE->getBase()->IgnoreParenImpCasts();
9471
9472 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
9473 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
9474 << 0 << CurE->getSourceRange();
9475 break;
9476 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009477
9478 // If we got an array subscript that express the whole dimension we
9479 // can have any array expressions before. If it only expressing part of
9480 // the dimension, we can only have unitary-size array expressions.
9481 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
9482 E->getType()))
9483 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +00009484
9485 // Record the component - we don't have any declaration associated.
9486 CurComponents.push_back(
9487 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +00009488 continue;
9489 }
9490
9491 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009492 E = CurE->getBase()->IgnoreParenImpCasts();
9493
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009494 auto CurType =
9495 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
9496
Samuel Antao5de996e2016-01-22 20:21:36 +00009497 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9498 // If the type of a list item is a reference to a type T then the type
9499 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +00009500 if (CurType->isReferenceType())
9501 CurType = CurType->getPointeeType();
9502
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009503 bool IsPointer = CurType->isAnyPointerType();
9504
9505 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009506 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
9507 << 0 << CurE->getSourceRange();
9508 break;
9509 }
9510
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009511 bool NotWhole =
9512 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
9513 bool NotUnity =
9514 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
9515
Samuel Antaodab51bb2016-07-18 23:22:11 +00009516 if (AllowWholeSizeArraySection) {
9517 // Any array section is currently allowed. Allowing a whole size array
9518 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009519 //
9520 // If this array section refers to the whole dimension we can still
9521 // accept other array sections before this one, except if the base is a
9522 // pointer. Otherwise, only unitary sections are accepted.
9523 if (NotWhole || IsPointer)
9524 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +00009525 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009526 // A unity or whole array section is not allowed and that is not
9527 // compatible with the properties of the current array section.
9528 SemaRef.Diag(
9529 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
9530 << CurE->getSourceRange();
9531 break;
9532 }
Samuel Antao90927002016-04-26 14:54:23 +00009533
9534 // Record the component - we don't have any declaration associated.
9535 CurComponents.push_back(
9536 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +00009537 continue;
9538 }
9539
9540 // If nothing else worked, this is not a valid map clause expression.
9541 SemaRef.Diag(ELoc,
9542 diag::err_omp_expected_named_var_member_or_array_expression)
9543 << ERange;
9544 break;
9545 }
9546
9547 return RelevantExpr;
9548}
9549
9550// Return true if expression E associated with value VD has conflicts with other
9551// map information.
Samuel Antao90927002016-04-26 14:54:23 +00009552static bool CheckMapConflicts(
9553 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
9554 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +00009555 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
9556 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009557 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +00009558 SourceLocation ELoc = E->getExprLoc();
9559 SourceRange ERange = E->getSourceRange();
9560
9561 // In order to easily check the conflicts we need to match each component of
9562 // the expression under test with the components of the expressions that are
9563 // already in the stack.
9564
Samuel Antao5de996e2016-01-22 20:21:36 +00009565 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +00009566 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +00009567 "Map clause expression with unexpected base!");
9568
9569 // Variables to help detecting enclosing problems in data environment nests.
9570 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +00009571 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +00009572
Samuel Antao90927002016-04-26 14:54:23 +00009573 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
9574 VD, CurrentRegionOnly,
9575 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00009576 StackComponents,
9577 OpenMPClauseKind) -> bool {
Samuel Antao90927002016-04-26 14:54:23 +00009578
Samuel Antao5de996e2016-01-22 20:21:36 +00009579 assert(!StackComponents.empty() &&
9580 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +00009581 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +00009582 "Map clause expression with unexpected base!");
9583
Samuel Antao90927002016-04-26 14:54:23 +00009584 // The whole expression in the stack.
9585 auto *RE = StackComponents.front().getAssociatedExpression();
9586
Samuel Antao5de996e2016-01-22 20:21:36 +00009587 // Expressions must start from the same base. Here we detect at which
9588 // point both expressions diverge from each other and see if we can
9589 // detect if the memory referred to both expressions is contiguous and
9590 // do not overlap.
9591 auto CI = CurComponents.rbegin();
9592 auto CE = CurComponents.rend();
9593 auto SI = StackComponents.rbegin();
9594 auto SE = StackComponents.rend();
9595 for (; CI != CE && SI != SE; ++CI, ++SI) {
9596
9597 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
9598 // At most one list item can be an array item derived from a given
9599 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +00009600 if (CurrentRegionOnly &&
9601 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
9602 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
9603 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
9604 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
9605 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +00009606 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +00009607 << CI->getAssociatedExpression()->getSourceRange();
9608 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
9609 diag::note_used_here)
9610 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +00009611 return true;
9612 }
9613
9614 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +00009615 if (CI->getAssociatedExpression()->getStmtClass() !=
9616 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +00009617 break;
9618
9619 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +00009620 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +00009621 break;
9622 }
Kelvin Li9f645ae2016-07-18 22:49:16 +00009623 // Check if the extra components of the expressions in the enclosing
9624 // data environment are redundant for the current base declaration.
9625 // If they are, the maps completely overlap, which is legal.
9626 for (; SI != SE; ++SI) {
9627 QualType Type;
9628 if (auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +00009629 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +00009630 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
David Majnemer9d168222016-08-05 17:44:54 +00009631 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
9632 SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +00009633 auto *E = OASE->getBase()->IgnoreParenImpCasts();
9634 Type =
9635 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
9636 }
9637 if (Type.isNull() || Type->isAnyPointerType() ||
9638 CheckArrayExpressionDoesNotReferToWholeSize(
9639 SemaRef, SI->getAssociatedExpression(), Type))
9640 break;
9641 }
Samuel Antao5de996e2016-01-22 20:21:36 +00009642
9643 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
9644 // List items of map clauses in the same construct must not share
9645 // original storage.
9646 //
9647 // If the expressions are exactly the same or one is a subset of the
9648 // other, it means they are sharing storage.
9649 if (CI == CE && SI == SE) {
9650 if (CurrentRegionOnly) {
Samuel Antao661c0902016-05-26 17:39:58 +00009651 if (CKind == OMPC_map)
9652 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
9653 else {
Samuel Antaoec172c62016-05-26 17:49:04 +00009654 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +00009655 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
9656 << ERange;
9657 }
Samuel Antao5de996e2016-01-22 20:21:36 +00009658 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
9659 << RE->getSourceRange();
9660 return true;
9661 } else {
9662 // If we find the same expression in the enclosing data environment,
9663 // that is legal.
9664 IsEnclosedByDataEnvironmentExpr = true;
9665 return false;
9666 }
9667 }
9668
Samuel Antao90927002016-04-26 14:54:23 +00009669 QualType DerivedType =
9670 std::prev(CI)->getAssociatedDeclaration()->getType();
9671 SourceLocation DerivedLoc =
9672 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +00009673
9674 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9675 // If the type of a list item is a reference to a type T then the type
9676 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +00009677 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +00009678
9679 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
9680 // A variable for which the type is pointer and an array section
9681 // derived from that variable must not appear as list items of map
9682 // clauses of the same construct.
9683 //
9684 // Also, cover one of the cases in:
9685 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
9686 // If any part of the original storage of a list item has corresponding
9687 // storage in the device data environment, all of the original storage
9688 // must have corresponding storage in the device data environment.
9689 //
9690 if (DerivedType->isAnyPointerType()) {
9691 if (CI == CE || SI == SE) {
9692 SemaRef.Diag(
9693 DerivedLoc,
9694 diag::err_omp_pointer_mapped_along_with_derived_section)
9695 << DerivedLoc;
9696 } else {
9697 assert(CI != CE && SI != SE);
9698 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
9699 << DerivedLoc;
9700 }
9701 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
9702 << RE->getSourceRange();
9703 return true;
9704 }
9705
9706 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
9707 // List items of map clauses in the same construct must not share
9708 // original storage.
9709 //
9710 // An expression is a subset of the other.
9711 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Samuel Antao661c0902016-05-26 17:39:58 +00009712 if (CKind == OMPC_map)
9713 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
9714 else {
Samuel Antaoec172c62016-05-26 17:49:04 +00009715 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +00009716 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
9717 << ERange;
9718 }
Samuel Antao5de996e2016-01-22 20:21:36 +00009719 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
9720 << RE->getSourceRange();
9721 return true;
9722 }
9723
9724 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +00009725 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +00009726 if (!CurrentRegionOnly && SI != SE)
9727 EnclosingExpr = RE;
9728
9729 // The current expression is a subset of the expression in the data
9730 // environment.
9731 IsEnclosedByDataEnvironmentExpr |=
9732 (!CurrentRegionOnly && CI != CE && SI == SE);
9733
9734 return false;
9735 });
9736
9737 if (CurrentRegionOnly)
9738 return FoundError;
9739
9740 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
9741 // If any part of the original storage of a list item has corresponding
9742 // storage in the device data environment, all of the original storage must
9743 // have corresponding storage in the device data environment.
9744 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
9745 // If a list item is an element of a structure, and a different element of
9746 // the structure has a corresponding list item in the device data environment
9747 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +00009748 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +00009749 // data environment prior to the task encountering the construct.
9750 //
9751 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
9752 SemaRef.Diag(ELoc,
9753 diag::err_omp_original_storage_is_shared_and_does_not_contain)
9754 << ERange;
9755 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
9756 << EnclosingExpr->getSourceRange();
9757 return true;
9758 }
9759
9760 return FoundError;
9761}
9762
Samuel Antao661c0902016-05-26 17:39:58 +00009763namespace {
9764// Utility struct that gathers all the related lists associated with a mappable
9765// expression.
9766struct MappableVarListInfo final {
9767 // The list of expressions.
9768 ArrayRef<Expr *> VarList;
9769 // The list of processed expressions.
9770 SmallVector<Expr *, 16> ProcessedVarList;
9771 // The mappble components for each expression.
9772 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
9773 // The base declaration of the variable.
9774 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
9775
9776 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
9777 // We have a list of components and base declarations for each entry in the
9778 // variable list.
9779 VarComponents.reserve(VarList.size());
9780 VarBaseDeclarations.reserve(VarList.size());
9781 }
9782};
9783}
9784
9785// Check the validity of the provided variable list for the provided clause kind
9786// \a CKind. In the check process the valid expressions, and mappable expression
9787// components and variables are extracted and used to fill \a Vars,
9788// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
9789// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
9790static void
9791checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
9792 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
9793 SourceLocation StartLoc,
9794 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
9795 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +00009796 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
9797 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +00009798 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +00009799
Samuel Antao90927002016-04-26 14:54:23 +00009800 // Keep track of the mappable components and base declarations in this clause.
9801 // Each entry in the list is going to have a list of components associated. We
9802 // record each set of the components so that we can build the clause later on.
9803 // In the end we should have the same amount of declarations and component
9804 // lists.
Samuel Antao90927002016-04-26 14:54:23 +00009805
Samuel Antao661c0902016-05-26 17:39:58 +00009806 for (auto &RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +00009807 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +00009808 SourceLocation ELoc = RE->getExprLoc();
9809
Kelvin Li0bff7af2015-11-23 05:32:03 +00009810 auto *VE = RE->IgnoreParenLValueCasts();
9811
9812 if (VE->isValueDependent() || VE->isTypeDependent() ||
9813 VE->isInstantiationDependent() ||
9814 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009815 // We can only analyze this information once the missing information is
9816 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +00009817 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +00009818 continue;
9819 }
9820
9821 auto *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +00009822
Samuel Antao5de996e2016-01-22 20:21:36 +00009823 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +00009824 SemaRef.Diag(ELoc,
9825 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +00009826 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +00009827 continue;
9828 }
9829
Samuel Antao90927002016-04-26 14:54:23 +00009830 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
9831 ValueDecl *CurDeclaration = nullptr;
9832
9833 // Obtain the array or member expression bases if required. Also, fill the
9834 // components array with all the components identified in the process.
Samuel Antao661c0902016-05-26 17:39:58 +00009835 auto *BE =
9836 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +00009837 if (!BE)
9838 continue;
9839
Samuel Antao90927002016-04-26 14:54:23 +00009840 assert(!CurComponents.empty() &&
9841 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +00009842
Samuel Antao90927002016-04-26 14:54:23 +00009843 // For the following checks, we rely on the base declaration which is
9844 // expected to be associated with the last component. The declaration is
9845 // expected to be a variable or a field (if 'this' is being mapped).
9846 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
9847 assert(CurDeclaration && "Null decl on map clause.");
9848 assert(
9849 CurDeclaration->isCanonicalDecl() &&
9850 "Expecting components to have associated only canonical declarations.");
9851
9852 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
9853 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +00009854
9855 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +00009856 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +00009857
9858 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +00009859 // threadprivate variables cannot appear in a map clause.
9860 // OpenMP 4.5 [2.10.5, target update Construct]
9861 // threadprivate variables cannot appear in a from clause.
9862 if (VD && DSAS->isThreadPrivate(VD)) {
9863 auto DVar = DSAS->getTopDSA(VD, false);
9864 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
9865 << getOpenMPClauseName(CKind);
9866 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +00009867 continue;
9868 }
9869
Samuel Antao5de996e2016-01-22 20:21:36 +00009870 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
9871 // A list item cannot appear in both a map clause and a data-sharing
9872 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +00009873
Samuel Antao5de996e2016-01-22 20:21:36 +00009874 // Check conflicts with other map clause expressions. We check the conflicts
9875 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +00009876 // environment, because the restrictions are different. We only have to
9877 // check conflicts across regions for the map clauses.
9878 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
9879 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +00009880 break;
Samuel Antao661c0902016-05-26 17:39:58 +00009881 if (CKind == OMPC_map &&
9882 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
9883 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +00009884 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +00009885
Samuel Antao661c0902016-05-26 17:39:58 +00009886 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +00009887 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9888 // If the type of a list item is a reference to a type T then the type will
9889 // be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +00009890 QualType Type = CurDeclaration->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +00009891
Samuel Antao661c0902016-05-26 17:39:58 +00009892 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
9893 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +00009894 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +00009895 // A list item must have a mappable type.
Samuel Antao661c0902016-05-26 17:39:58 +00009896 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
9897 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +00009898 continue;
9899
Samuel Antao661c0902016-05-26 17:39:58 +00009900 if (CKind == OMPC_map) {
9901 // target enter data
9902 // OpenMP [2.10.2, Restrictions, p. 99]
9903 // A map-type must be specified in all map clauses and must be either
9904 // to or alloc.
9905 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
9906 if (DKind == OMPD_target_enter_data &&
9907 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
9908 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
9909 << (IsMapTypeImplicit ? 1 : 0)
9910 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
9911 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009912 continue;
9913 }
Samuel Antao661c0902016-05-26 17:39:58 +00009914
9915 // target exit_data
9916 // OpenMP [2.10.3, Restrictions, p. 102]
9917 // A map-type must be specified in all map clauses and must be either
9918 // from, release, or delete.
9919 if (DKind == OMPD_target_exit_data &&
9920 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
9921 MapType == OMPC_MAP_delete)) {
9922 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
9923 << (IsMapTypeImplicit ? 1 : 0)
9924 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
9925 << getOpenMPDirectiveName(DKind);
9926 continue;
9927 }
9928
9929 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
9930 // A list item cannot appear in both a map clause and a data-sharing
9931 // attribute clause on the same construct
9932 if (DKind == OMPD_target && VD) {
9933 auto DVar = DSAS->getTopDSA(VD, false);
9934 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +00009935 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +00009936 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +00009937 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +00009938 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
9939 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
9940 continue;
9941 }
9942 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009943 }
9944
Samuel Antao90927002016-04-26 14:54:23 +00009945 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +00009946 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +00009947
9948 // Store the components in the stack so that they can be used to check
9949 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +00009950 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
9951 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +00009952
9953 // Save the components and declaration to create the clause. For purposes of
9954 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +00009955 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +00009956 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
9957 MVLI.VarComponents.back().append(CurComponents.begin(),
9958 CurComponents.end());
9959 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
9960 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +00009961 }
Samuel Antao661c0902016-05-26 17:39:58 +00009962}
9963
9964OMPClause *
9965Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
9966 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
9967 SourceLocation MapLoc, SourceLocation ColonLoc,
9968 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9969 SourceLocation LParenLoc, SourceLocation EndLoc) {
9970 MappableVarListInfo MVLI(VarList);
9971 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
9972 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +00009973
Samuel Antao5de996e2016-01-22 20:21:36 +00009974 // We need to produce a map clause even if we don't have variables so that
9975 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +00009976 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9977 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
9978 MVLI.VarComponents, MapTypeModifier, MapType,
9979 IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +00009980}
Kelvin Li099bb8c2015-11-24 20:50:12 +00009981
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00009982QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
9983 TypeResult ParsedType) {
9984 assert(ParsedType.isUsable());
9985
9986 QualType ReductionType = GetTypeFromParser(ParsedType.get());
9987 if (ReductionType.isNull())
9988 return QualType();
9989
9990 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
9991 // A type name in a declare reduction directive cannot be a function type, an
9992 // array type, a reference type, or a type qualified with const, volatile or
9993 // restrict.
9994 if (ReductionType.hasQualifiers()) {
9995 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
9996 return QualType();
9997 }
9998
9999 if (ReductionType->isFunctionType()) {
10000 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
10001 return QualType();
10002 }
10003 if (ReductionType->isReferenceType()) {
10004 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
10005 return QualType();
10006 }
10007 if (ReductionType->isArrayType()) {
10008 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
10009 return QualType();
10010 }
10011 return ReductionType;
10012}
10013
10014Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
10015 Scope *S, DeclContext *DC, DeclarationName Name,
10016 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
10017 AccessSpecifier AS, Decl *PrevDeclInScope) {
10018 SmallVector<Decl *, 8> Decls;
10019 Decls.reserve(ReductionTypes.size());
10020
10021 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
10022 ForRedeclaration);
10023 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
10024 // A reduction-identifier may not be re-declared in the current scope for the
10025 // same type or for a type that is compatible according to the base language
10026 // rules.
10027 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
10028 OMPDeclareReductionDecl *PrevDRD = nullptr;
10029 bool InCompoundScope = true;
10030 if (S != nullptr) {
10031 // Find previous declaration with the same name not referenced in other
10032 // declarations.
10033 FunctionScopeInfo *ParentFn = getEnclosingFunction();
10034 InCompoundScope =
10035 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
10036 LookupName(Lookup, S);
10037 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
10038 /*AllowInlineNamespace=*/false);
10039 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
10040 auto Filter = Lookup.makeFilter();
10041 while (Filter.hasNext()) {
10042 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
10043 if (InCompoundScope) {
10044 auto I = UsedAsPrevious.find(PrevDecl);
10045 if (I == UsedAsPrevious.end())
10046 UsedAsPrevious[PrevDecl] = false;
10047 if (auto *D = PrevDecl->getPrevDeclInScope())
10048 UsedAsPrevious[D] = true;
10049 }
10050 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
10051 PrevDecl->getLocation();
10052 }
10053 Filter.done();
10054 if (InCompoundScope) {
10055 for (auto &PrevData : UsedAsPrevious) {
10056 if (!PrevData.second) {
10057 PrevDRD = PrevData.first;
10058 break;
10059 }
10060 }
10061 }
10062 } else if (PrevDeclInScope != nullptr) {
10063 auto *PrevDRDInScope = PrevDRD =
10064 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
10065 do {
10066 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
10067 PrevDRDInScope->getLocation();
10068 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
10069 } while (PrevDRDInScope != nullptr);
10070 }
10071 for (auto &TyData : ReductionTypes) {
10072 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
10073 bool Invalid = false;
10074 if (I != PreviousRedeclTypes.end()) {
10075 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
10076 << TyData.first;
10077 Diag(I->second, diag::note_previous_definition);
10078 Invalid = true;
10079 }
10080 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
10081 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
10082 Name, TyData.first, PrevDRD);
10083 DC->addDecl(DRD);
10084 DRD->setAccess(AS);
10085 Decls.push_back(DRD);
10086 if (Invalid)
10087 DRD->setInvalidDecl();
10088 else
10089 PrevDRD = DRD;
10090 }
10091
10092 return DeclGroupPtrTy::make(
10093 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
10094}
10095
10096void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
10097 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10098
10099 // Enter new function scope.
10100 PushFunctionScope();
10101 getCurFunction()->setHasBranchProtectedScope();
10102 getCurFunction()->setHasOMPDeclareReductionCombiner();
10103
10104 if (S != nullptr)
10105 PushDeclContext(S, DRD);
10106 else
10107 CurContext = DRD;
10108
10109 PushExpressionEvaluationContext(PotentiallyEvaluated);
10110
10111 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010112 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
10113 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
10114 // uses semantics of argument handles by value, but it should be passed by
10115 // reference. C lang does not support references, so pass all parameters as
10116 // pointers.
10117 // Create 'T omp_in;' variable.
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010118 auto *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010119 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010120 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
10121 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
10122 // uses semantics of argument handles by value, but it should be passed by
10123 // reference. C lang does not support references, so pass all parameters as
10124 // pointers.
10125 // Create 'T omp_out;' variable.
10126 auto *OmpOutParm =
10127 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
10128 if (S != nullptr) {
10129 PushOnScopeChains(OmpInParm, S);
10130 PushOnScopeChains(OmpOutParm, S);
10131 } else {
10132 DRD->addDecl(OmpInParm);
10133 DRD->addDecl(OmpOutParm);
10134 }
10135}
10136
10137void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
10138 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10139 DiscardCleanupsInEvaluationContext();
10140 PopExpressionEvaluationContext();
10141
10142 PopDeclContext();
10143 PopFunctionScopeInfo();
10144
10145 if (Combiner != nullptr)
10146 DRD->setCombiner(Combiner);
10147 else
10148 DRD->setInvalidDecl();
10149}
10150
10151void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
10152 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10153
10154 // Enter new function scope.
10155 PushFunctionScope();
10156 getCurFunction()->setHasBranchProtectedScope();
10157
10158 if (S != nullptr)
10159 PushDeclContext(S, DRD);
10160 else
10161 CurContext = DRD;
10162
10163 PushExpressionEvaluationContext(PotentiallyEvaluated);
10164
10165 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010166 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
10167 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
10168 // uses semantics of argument handles by value, but it should be passed by
10169 // reference. C lang does not support references, so pass all parameters as
10170 // pointers.
10171 // Create 'T omp_priv;' variable.
10172 auto *OmpPrivParm =
10173 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010174 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
10175 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
10176 // uses semantics of argument handles by value, but it should be passed by
10177 // reference. C lang does not support references, so pass all parameters as
10178 // pointers.
10179 // Create 'T omp_orig;' variable.
10180 auto *OmpOrigParm =
10181 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010182 if (S != nullptr) {
10183 PushOnScopeChains(OmpPrivParm, S);
10184 PushOnScopeChains(OmpOrigParm, S);
10185 } else {
10186 DRD->addDecl(OmpPrivParm);
10187 DRD->addDecl(OmpOrigParm);
10188 }
10189}
10190
10191void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D,
10192 Expr *Initializer) {
10193 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10194 DiscardCleanupsInEvaluationContext();
10195 PopExpressionEvaluationContext();
10196
10197 PopDeclContext();
10198 PopFunctionScopeInfo();
10199
10200 if (Initializer != nullptr)
10201 DRD->setInitializer(Initializer);
10202 else
10203 DRD->setInvalidDecl();
10204}
10205
10206Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
10207 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
10208 for (auto *D : DeclReductions.get()) {
10209 if (IsValid) {
10210 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10211 if (S != nullptr)
10212 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
10213 } else
10214 D->setInvalidDecl();
10215 }
10216 return DeclReductions;
10217}
10218
David Majnemer9d168222016-08-05 17:44:54 +000010219OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000010220 SourceLocation StartLoc,
10221 SourceLocation LParenLoc,
10222 SourceLocation EndLoc) {
10223 Expr *ValExpr = NumTeams;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010224
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010225 // OpenMP [teams Constrcut, Restrictions]
10226 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000010227 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
10228 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010229 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010230
10231 return new (Context) OMPNumTeamsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10232}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010233
10234OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
10235 SourceLocation StartLoc,
10236 SourceLocation LParenLoc,
10237 SourceLocation EndLoc) {
10238 Expr *ValExpr = ThreadLimit;
10239
10240 // OpenMP [teams Constrcut, Restrictions]
10241 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000010242 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
10243 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010244 return nullptr;
10245
David Majnemer9d168222016-08-05 17:44:54 +000010246 return new (Context)
10247 OMPThreadLimitClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010248}
Alexey Bataeva0569352015-12-01 10:17:31 +000010249
10250OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
10251 SourceLocation StartLoc,
10252 SourceLocation LParenLoc,
10253 SourceLocation EndLoc) {
10254 Expr *ValExpr = Priority;
10255
10256 // OpenMP [2.9.1, task Constrcut]
10257 // The priority-value is a non-negative numerical scalar expression.
10258 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
10259 /*StrictlyPositive=*/false))
10260 return nullptr;
10261
10262 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10263}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010264
10265OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
10266 SourceLocation StartLoc,
10267 SourceLocation LParenLoc,
10268 SourceLocation EndLoc) {
10269 Expr *ValExpr = Grainsize;
10270
10271 // OpenMP [2.9.2, taskloop Constrcut]
10272 // The parameter of the grainsize clause must be a positive integer
10273 // expression.
10274 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
10275 /*StrictlyPositive=*/true))
10276 return nullptr;
10277
10278 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10279}
Alexey Bataev382967a2015-12-08 12:06:20 +000010280
10281OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
10282 SourceLocation StartLoc,
10283 SourceLocation LParenLoc,
10284 SourceLocation EndLoc) {
10285 Expr *ValExpr = NumTasks;
10286
10287 // OpenMP [2.9.2, taskloop Constrcut]
10288 // The parameter of the num_tasks clause must be a positive integer
10289 // expression.
10290 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
10291 /*StrictlyPositive=*/true))
10292 return nullptr;
10293
10294 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10295}
10296
Alexey Bataev28c75412015-12-15 08:19:24 +000010297OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
10298 SourceLocation LParenLoc,
10299 SourceLocation EndLoc) {
10300 // OpenMP [2.13.2, critical construct, Description]
10301 // ... where hint-expression is an integer constant expression that evaluates
10302 // to a valid lock hint.
10303 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
10304 if (HintExpr.isInvalid())
10305 return nullptr;
10306 return new (Context)
10307 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
10308}
10309
Carlo Bertollib4adf552016-01-15 18:50:31 +000010310OMPClause *Sema::ActOnOpenMPDistScheduleClause(
10311 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
10312 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
10313 SourceLocation EndLoc) {
10314 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
10315 std::string Values;
10316 Values += "'";
10317 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
10318 Values += "'";
10319 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
10320 << Values << getOpenMPClauseName(OMPC_dist_schedule);
10321 return nullptr;
10322 }
10323 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000010324 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000010325 if (ChunkSize) {
10326 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
10327 !ChunkSize->isInstantiationDependent() &&
10328 !ChunkSize->containsUnexpandedParameterPack()) {
10329 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
10330 ExprResult Val =
10331 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
10332 if (Val.isInvalid())
10333 return nullptr;
10334
10335 ValExpr = Val.get();
10336
10337 // OpenMP [2.7.1, Restrictions]
10338 // chunk_size must be a loop invariant integer expression with a positive
10339 // value.
10340 llvm::APSInt Result;
10341 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
10342 if (Result.isSigned() && !Result.isStrictlyPositive()) {
10343 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
10344 << "dist_schedule" << ChunkSize->getSourceRange();
10345 return nullptr;
10346 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +000010347 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
10348 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +000010349 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
10350 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
10351 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000010352 }
10353 }
10354 }
10355
10356 return new (Context)
10357 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000010358 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000010359}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010360
10361OMPClause *Sema::ActOnOpenMPDefaultmapClause(
10362 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
10363 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
10364 SourceLocation KindLoc, SourceLocation EndLoc) {
10365 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000010366 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010367 std::string Value;
10368 SourceLocation Loc;
10369 Value += "'";
10370 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
10371 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000010372 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010373 Loc = MLoc;
10374 } else {
10375 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000010376 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010377 Loc = KindLoc;
10378 }
10379 Value += "'";
10380 Diag(Loc, diag::err_omp_unexpected_clause_value)
10381 << Value << getOpenMPClauseName(OMPC_defaultmap);
10382 return nullptr;
10383 }
10384
10385 return new (Context)
10386 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
10387}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010388
10389bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
10390 DeclContext *CurLexicalContext = getCurLexicalContext();
10391 if (!CurLexicalContext->isFileContext() &&
10392 !CurLexicalContext->isExternCContext() &&
10393 !CurLexicalContext->isExternCXXContext()) {
10394 Diag(Loc, diag::err_omp_region_not_file_context);
10395 return false;
10396 }
10397 if (IsInOpenMPDeclareTargetContext) {
10398 Diag(Loc, diag::err_omp_enclosed_declare_target);
10399 return false;
10400 }
10401
10402 IsInOpenMPDeclareTargetContext = true;
10403 return true;
10404}
10405
10406void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
10407 assert(IsInOpenMPDeclareTargetContext &&
10408 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
10409
10410 IsInOpenMPDeclareTargetContext = false;
10411}
10412
David Majnemer9d168222016-08-05 17:44:54 +000010413void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
10414 CXXScopeSpec &ScopeSpec,
10415 const DeclarationNameInfo &Id,
10416 OMPDeclareTargetDeclAttr::MapTypeTy MT,
10417 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010418 LookupResult Lookup(*this, Id, LookupOrdinaryName);
10419 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
10420
10421 if (Lookup.isAmbiguous())
10422 return;
10423 Lookup.suppressDiagnostics();
10424
10425 if (!Lookup.isSingleResult()) {
10426 if (TypoCorrection Corrected =
10427 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
10428 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
10429 CTK_ErrorRecovery)) {
10430 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
10431 << Id.getName());
10432 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
10433 return;
10434 }
10435
10436 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
10437 return;
10438 }
10439
10440 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
10441 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
10442 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
10443 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
10444
10445 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
10446 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
10447 ND->addAttr(A);
10448 if (ASTMutationListener *ML = Context.getASTMutationListener())
10449 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
10450 checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
10451 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
10452 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
10453 << Id.getName();
10454 }
10455 } else
10456 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
10457}
10458
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010459static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
10460 Sema &SemaRef, Decl *D) {
10461 if (!D)
10462 return;
10463 Decl *LD = nullptr;
10464 if (isa<TagDecl>(D)) {
10465 LD = cast<TagDecl>(D)->getDefinition();
10466 } else if (isa<VarDecl>(D)) {
10467 LD = cast<VarDecl>(D)->getDefinition();
10468
10469 // If this is an implicit variable that is legal and we do not need to do
10470 // anything.
10471 if (cast<VarDecl>(D)->isImplicit()) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010472 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10473 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10474 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010475 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010476 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010477 return;
10478 }
10479
10480 } else if (isa<FunctionDecl>(D)) {
10481 const FunctionDecl *FD = nullptr;
10482 if (cast<FunctionDecl>(D)->hasBody(FD))
10483 LD = const_cast<FunctionDecl *>(FD);
10484
10485 // If the definition is associated with the current declaration in the
10486 // target region (it can be e.g. a lambda) that is legal and we do not need
10487 // to do anything else.
10488 if (LD == D) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010489 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10490 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10491 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010492 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010493 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010494 return;
10495 }
10496 }
10497 if (!LD)
10498 LD = D;
10499 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
10500 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
10501 // Outlined declaration is not declared target.
10502 if (LD->isOutOfLine()) {
10503 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
10504 SemaRef.Diag(SL, diag::note_used_here) << SR;
10505 } else {
10506 DeclContext *DC = LD->getDeclContext();
10507 while (DC) {
10508 if (isa<FunctionDecl>(DC) &&
10509 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
10510 break;
10511 DC = DC->getParent();
10512 }
10513 if (DC)
10514 return;
10515
10516 // Is not declared in target context.
10517 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
10518 SemaRef.Diag(SL, diag::note_used_here) << SR;
10519 }
10520 // Mark decl as declared target to prevent further diagnostic.
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010521 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10522 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10523 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010524 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010525 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010526 }
10527}
10528
10529static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
10530 Sema &SemaRef, DSAStackTy *Stack,
10531 ValueDecl *VD) {
10532 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
10533 return true;
10534 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
10535 return false;
10536 return true;
10537}
10538
10539void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
10540 if (!D || D->isInvalidDecl())
10541 return;
10542 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
10543 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
10544 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
10545 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10546 if (DSAStack->isThreadPrivate(VD)) {
10547 Diag(SL, diag::err_omp_threadprivate_in_target);
10548 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
10549 return;
10550 }
10551 }
10552 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
10553 // Problem if any with var declared with incomplete type will be reported
10554 // as normal, so no need to check it here.
10555 if ((E || !VD->getType()->isIncompleteType()) &&
10556 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
10557 // Mark decl as declared target to prevent further diagnostic.
10558 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010559 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10560 Context, OMPDeclareTargetDeclAttr::MT_To);
10561 VD->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010562 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010563 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010564 }
10565 return;
10566 }
10567 }
10568 if (!E) {
10569 // Checking declaration inside declare target region.
10570 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
10571 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010572 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10573 Context, OMPDeclareTargetDeclAttr::MT_To);
10574 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010575 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010576 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010577 }
10578 return;
10579 }
10580 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
10581}
Samuel Antao661c0902016-05-26 17:39:58 +000010582
10583OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
10584 SourceLocation StartLoc,
10585 SourceLocation LParenLoc,
10586 SourceLocation EndLoc) {
10587 MappableVarListInfo MVLI(VarList);
10588 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
10589 if (MVLI.ProcessedVarList.empty())
10590 return nullptr;
10591
10592 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10593 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10594 MVLI.VarComponents);
10595}
Samuel Antaoec172c62016-05-26 17:49:04 +000010596
10597OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
10598 SourceLocation StartLoc,
10599 SourceLocation LParenLoc,
10600 SourceLocation EndLoc) {
10601 MappableVarListInfo MVLI(VarList);
10602 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
10603 if (MVLI.ProcessedVarList.empty())
10604 return nullptr;
10605
10606 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10607 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10608 MVLI.VarComponents);
10609}
Carlo Bertolli2404b172016-07-13 15:37:16 +000010610
10611OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
10612 SourceLocation StartLoc,
10613 SourceLocation LParenLoc,
10614 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000010615 MappableVarListInfo MVLI(VarList);
10616 SmallVector<Expr *, 8> PrivateCopies;
10617 SmallVector<Expr *, 8> Inits;
10618
Carlo Bertolli2404b172016-07-13 15:37:16 +000010619 for (auto &RefExpr : VarList) {
10620 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
10621 SourceLocation ELoc;
10622 SourceRange ERange;
10623 Expr *SimpleRefExpr = RefExpr;
10624 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10625 if (Res.second) {
10626 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000010627 MVLI.ProcessedVarList.push_back(RefExpr);
10628 PrivateCopies.push_back(nullptr);
10629 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000010630 }
10631 ValueDecl *D = Res.first;
10632 if (!D)
10633 continue;
10634
10635 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000010636 Type = Type.getNonReferenceType().getUnqualifiedType();
10637
10638 auto *VD = dyn_cast<VarDecl>(D);
10639
10640 // Item should be a pointer or reference to pointer.
10641 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000010642 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
10643 << 0 << RefExpr->getSourceRange();
10644 continue;
10645 }
Samuel Antaocc10b852016-07-28 14:23:26 +000010646
10647 // Build the private variable and the expression that refers to it.
10648 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
10649 D->hasAttrs() ? &D->getAttrs() : nullptr);
10650 if (VDPrivate->isInvalidDecl())
10651 continue;
10652
10653 CurContext->addDecl(VDPrivate);
10654 auto VDPrivateRefExpr = buildDeclRefExpr(
10655 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
10656
10657 // Add temporary variable to initialize the private copy of the pointer.
10658 auto *VDInit =
10659 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
10660 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
10661 RefExpr->getExprLoc());
10662 AddInitializerToDecl(VDPrivate,
10663 DefaultLvalueConversion(VDInitRefExpr).get(),
10664 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
10665
10666 // If required, build a capture to implement the privatization initialized
10667 // with the current list item value.
10668 DeclRefExpr *Ref = nullptr;
10669 if (!VD)
10670 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
10671 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
10672 PrivateCopies.push_back(VDPrivateRefExpr);
10673 Inits.push_back(VDInitRefExpr);
10674
10675 // We need to add a data sharing attribute for this variable to make sure it
10676 // is correctly captured. A variable that shows up in a use_device_ptr has
10677 // similar properties of a first private variable.
10678 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
10679
10680 // Create a mappable component for the list item. List items in this clause
10681 // only need a component.
10682 MVLI.VarBaseDeclarations.push_back(D);
10683 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
10684 MVLI.VarComponents.back().push_back(
10685 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000010686 }
10687
Samuel Antaocc10b852016-07-28 14:23:26 +000010688 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000010689 return nullptr;
10690
Samuel Antaocc10b852016-07-28 14:23:26 +000010691 return OMPUseDevicePtrClause::Create(
10692 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
10693 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000010694}
Carlo Bertolli70594e92016-07-13 17:16:49 +000010695
10696OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
10697 SourceLocation StartLoc,
10698 SourceLocation LParenLoc,
10699 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000010700 MappableVarListInfo MVLI(VarList);
Carlo Bertolli70594e92016-07-13 17:16:49 +000010701 for (auto &RefExpr : VarList) {
10702 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
10703 SourceLocation ELoc;
10704 SourceRange ERange;
10705 Expr *SimpleRefExpr = RefExpr;
10706 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10707 if (Res.second) {
10708 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000010709 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000010710 }
10711 ValueDecl *D = Res.first;
10712 if (!D)
10713 continue;
10714
10715 QualType Type = D->getType();
10716 // item should be a pointer or array or reference to pointer or array
10717 if (!Type.getNonReferenceType()->isPointerType() &&
10718 !Type.getNonReferenceType()->isArrayType()) {
10719 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
10720 << 0 << RefExpr->getSourceRange();
10721 continue;
10722 }
Samuel Antao6890b092016-07-28 14:25:09 +000010723
10724 // Check if the declaration in the clause does not show up in any data
10725 // sharing attribute.
10726 auto DVar = DSAStack->getTopDSA(D, false);
10727 if (isOpenMPPrivate(DVar.CKind)) {
10728 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
10729 << getOpenMPClauseName(DVar.CKind)
10730 << getOpenMPClauseName(OMPC_is_device_ptr)
10731 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
10732 ReportOriginalDSA(*this, DSAStack, D, DVar);
10733 continue;
10734 }
10735
10736 Expr *ConflictExpr;
10737 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000010738 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000010739 [&ConflictExpr](
10740 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
10741 OpenMPClauseKind) -> bool {
10742 ConflictExpr = R.front().getAssociatedExpression();
10743 return true;
10744 })) {
10745 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
10746 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
10747 << ConflictExpr->getSourceRange();
10748 continue;
10749 }
10750
10751 // Store the components in the stack so that they can be used to check
10752 // against other clauses later on.
10753 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
10754 DSAStack->addMappableExpressionComponents(
10755 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
10756
10757 // Record the expression we've just processed.
10758 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
10759
10760 // Create a mappable component for the list item. List items in this clause
10761 // only need a component. We use a null declaration to signal fields in
10762 // 'this'.
10763 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
10764 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
10765 "Unexpected device pointer expression!");
10766 MVLI.VarBaseDeclarations.push_back(
10767 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
10768 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
10769 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000010770 }
10771
Samuel Antao6890b092016-07-28 14:25:09 +000010772 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000010773 return nullptr;
10774
Samuel Antao6890b092016-07-28 14:25:09 +000010775 return OMPIsDevicePtrClause::Create(
10776 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
10777 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000010778}