blob: 804aadc0ff77ed2d3ac08e66ab1f309d67d05169 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
Alexey Bataeva769e072013-03-22 06:34:35 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// \brief This file implements semantic analysis for OpenMP directives and
Alexey Bataev6f6f3b42013-05-13 04:18:18 +000011/// clauses.
Alexey Bataeva769e072013-03-22 06:34:35 +000012///
13//===----------------------------------------------------------------------===//
14
Alexey Bataevb08f89f2015-08-14 12:25:37 +000015#include "TreeTransform.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000016#include "clang/AST/ASTContext.h"
Alexey Bataev97720002014-11-11 04:05:39 +000017#include "clang/AST/ASTMutationListener.h"
Alexey Bataeva839ddd2016-03-17 10:19:46 +000018#include "clang/AST/CXXInheritance.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000019#include "clang/AST/Decl.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000020#include "clang/AST/DeclCXX.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000021#include "clang/AST/DeclOpenMP.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000022#include "clang/AST/StmtCXX.h"
23#include "clang/AST/StmtOpenMP.h"
24#include "clang/AST/StmtVisitor.h"
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000025#include "clang/AST/TypeOrdering.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000026#include "clang/Basic/OpenMPKinds.h"
Samuel Antaof8b50122015-07-13 22:54:53 +000027#include "clang/Basic/TargetInfo.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000028#include "clang/Lex/Preprocessor.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000029#include "clang/Sema/Initialization.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000030#include "clang/Sema/Lookup.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000031#include "clang/Sema/Scope.h"
32#include "clang/Sema/ScopeInfo.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000033#include "clang/Sema/SemaInternal.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000034using namespace clang;
35
Alexey Bataev758e55e2013-09-06 18:03:48 +000036//===----------------------------------------------------------------------===//
37// Stack of data-sharing attributes for variables
38//===----------------------------------------------------------------------===//
39
40namespace {
41/// \brief Default data sharing attributes, which can be applied to directive.
42enum DefaultDataSharingAttributes {
Alexey Bataeved09d242014-05-28 05:53:51 +000043 DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
44 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
45 DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'.
Alexey Bataev758e55e2013-09-06 18:03:48 +000046};
Alexey Bataev7ff55242014-06-19 09:13:45 +000047
Alexey Bataev758e55e2013-09-06 18:03:48 +000048/// \brief Stack for tracking declarations used in OpenMP directives and
49/// clauses and their data-sharing attributes.
Alexey Bataev7ace49d2016-05-17 08:55:33 +000050class DSAStackTy final {
Alexey Bataev758e55e2013-09-06 18:03:48 +000051public:
Alexey Bataev7ace49d2016-05-17 08:55:33 +000052 struct DSAVarData final {
53 OpenMPDirectiveKind DKind = OMPD_unknown;
54 OpenMPClauseKind CKind = OMPC_unknown;
55 Expr *RefExpr = nullptr;
56 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000057 SourceLocation ImplicitDSALoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000058 DSAVarData() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +000059 };
Alexey Bataev8b427062016-05-25 12:36:08 +000060 typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>
61 OperatorOffsetTy;
Alexey Bataeved09d242014-05-28 05:53:51 +000062
Alexey Bataev758e55e2013-09-06 18:03:48 +000063private:
Alexey Bataev7ace49d2016-05-17 08:55:33 +000064 struct DSAInfo final {
65 OpenMPClauseKind Attributes = OMPC_unknown;
66 /// Pointer to a reference expression and a flag which shows that the
67 /// variable is marked as lastprivate(true) or not (false).
68 llvm::PointerIntPair<Expr *, 1, bool> RefExpr;
69 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000070 };
Alexey Bataev90c228f2016-02-08 09:29:13 +000071 typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy;
72 typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +000073 typedef std::pair<unsigned, VarDecl *> LCDeclInfo;
74 typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy;
Samuel Antao6890b092016-07-28 14:25:09 +000075 /// Struct that associates a component with the clause kind where they are
76 /// found.
77 struct MappedExprComponentTy {
78 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
79 OpenMPClauseKind Kind = OMPC_unknown;
80 };
81 typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy>
Samuel Antao90927002016-04-26 14:54:23 +000082 MappedExprComponentsTy;
Alexey Bataev28c75412015-12-15 08:19:24 +000083 typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
84 CriticalsWithHintsTy;
Alexey Bataev8b427062016-05-25 12:36:08 +000085 typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>
86 DoacrossDependMapTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +000087
Alexey Bataev7ace49d2016-05-17 08:55:33 +000088 struct SharingMapTy final {
Alexey Bataev758e55e2013-09-06 18:03:48 +000089 DeclSAMapTy SharingMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000090 AlignedMapTy AlignedMap;
Samuel Antao90927002016-04-26 14:54:23 +000091 MappedExprComponentsTy MappedExprComponents;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000092 LoopControlVariablesMapTy LCVMap;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000093 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
Alexey Bataevbae9a792014-06-27 10:37:06 +000094 SourceLocation DefaultAttrLoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000095 OpenMPDirectiveKind Directive = OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +000096 DeclarationNameInfo DirectiveName;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000097 Scope *CurScope = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000098 SourceLocation ConstructLoc;
Alexey Bataev8b427062016-05-25 12:36:08 +000099 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
100 /// get the data (loop counters etc.) about enclosing loop-based construct.
101 /// This data is required during codegen.
102 DoacrossDependMapTy DoacrossDepends;
Alexey Bataev346265e2015-09-25 10:37:12 +0000103 /// \brief first argument (Expr *) contains optional argument of the
104 /// 'ordered' clause, the second one is true if the regions has 'ordered'
105 /// clause, false otherwise.
106 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000107 bool NowaitRegion = false;
108 bool CancelRegion = false;
109 unsigned AssociatedLoops = 1;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000110 SourceLocation InnerTeamsRegionLoc;
Alexey Bataeved09d242014-05-28 05:53:51 +0000111 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000112 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000113 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
114 ConstructLoc(Loc) {}
115 SharingMapTy() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +0000116 };
117
Axel Naumann323862e2016-02-03 10:45:22 +0000118 typedef SmallVector<SharingMapTy, 4> StackTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000119
120 /// \brief Stack of used declaration and their data-sharing attributes.
121 StackTy Stack;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000122 /// \brief true, if check for DSA must be from parent directive, false, if
123 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000124 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000125 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000126 bool ForceCapturing = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000127 CriticalsWithHintsTy Criticals;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000128
129 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
130
David Majnemer9d168222016-08-05 17:44:54 +0000131 DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D);
Alexey Bataevec3da872014-01-31 05:15:34 +0000132
133 /// \brief Checks if the variable is a local for OpenMP region.
134 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
Alexey Bataeved09d242014-05-28 05:53:51 +0000135
Alexey Bataev758e55e2013-09-06 18:03:48 +0000136public:
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000137 explicit DSAStackTy(Sema &S) : Stack(1), SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000138
Alexey Bataevaac108a2015-06-23 04:51:00 +0000139 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
140 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000141
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000142 bool isForceVarCapturing() const { return ForceCapturing; }
143 void setForceVarCapturing(bool V) { ForceCapturing = V; }
144
Alexey Bataev758e55e2013-09-06 18:03:48 +0000145 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000146 Scope *CurScope, SourceLocation Loc) {
147 Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
148 Stack.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000149 }
150
151 void pop() {
152 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
153 Stack.pop_back();
154 }
155
Alexey Bataev28c75412015-12-15 08:19:24 +0000156 void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
157 Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
158 }
159 const std::pair<OMPCriticalDirective *, llvm::APSInt>
160 getCriticalWithHint(const DeclarationNameInfo &Name) const {
161 auto I = Criticals.find(Name.getAsString());
162 if (I != Criticals.end())
163 return I->second;
164 return std::make_pair(nullptr, llvm::APSInt());
165 }
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000166 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000167 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000168 /// for diagnostics.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000169 Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000170
Alexey Bataev9c821032015-04-30 04:23:23 +0000171 /// \brief Register specified variable as loop control variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000172 void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
Alexey Bataev9c821032015-04-30 04:23:23 +0000173 /// \brief Check if the specified variable is a loop control variable for
174 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000175 /// \return The index of the loop control variable in the list of associated
176 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000177 LCDeclInfo isLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000178 /// \brief Check if the specified variable is a loop control variable for
179 /// parent region.
180 /// \return The index of the loop control variable in the list of associated
181 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000182 LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000183 /// \brief Get the loop control variable for the I-th loop (or nullptr) in
184 /// parent directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000185 ValueDecl *getParentLoopControlVariable(unsigned I);
Alexey Bataev9c821032015-04-30 04:23:23 +0000186
Alexey Bataev758e55e2013-09-06 18:03:48 +0000187 /// \brief Adds explicit data sharing attribute to the specified declaration.
Alexey Bataev90c228f2016-02-08 09:29:13 +0000188 void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
189 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000190
Alexey Bataev758e55e2013-09-06 18:03:48 +0000191 /// \brief Returns data sharing attributes from top of the stack for the
192 /// specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000193 DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000194 /// \brief Returns data-sharing attributes for the specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000195 DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000196 /// \brief Checks if the specified variables has data-sharing attributes which
197 /// match specified \a CPred predicate in any directive which matches \a DPred
198 /// predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000199 DSAVarData hasDSA(ValueDecl *D,
200 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
201 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
202 bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000203 /// \brief Checks if the specified variables has data-sharing attributes which
204 /// match specified \a CPred predicate in any innermost directive which
205 /// matches \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000206 DSAVarData
207 hasInnermostDSA(ValueDecl *D,
208 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
209 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
210 bool FromParent);
Alexey Bataevaac108a2015-06-23 04:51:00 +0000211 /// \brief Checks if the specified variables has explicit data-sharing
212 /// attributes which match specified \a CPred predicate at the specified
213 /// OpenMP region.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000214 bool hasExplicitDSA(ValueDecl *D,
Alexey Bataevaac108a2015-06-23 04:51:00 +0000215 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000216 unsigned Level, bool NotLastprivate = false);
Samuel Antao4be30e92015-10-02 17:14:03 +0000217
218 /// \brief Returns true if the directive at level \Level matches in the
219 /// specified \a DPred predicate.
220 bool hasExplicitDirective(
221 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
222 unsigned Level);
223
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000224 /// \brief Finds a directive which matches specified \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000225 bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind,
226 const DeclarationNameInfo &,
227 SourceLocation)> &DPred,
228 bool FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000229
Alexey Bataev758e55e2013-09-06 18:03:48 +0000230 /// \brief Returns currently analyzed directive.
231 OpenMPDirectiveKind getCurrentDirective() const {
232 return Stack.back().Directive;
233 }
Alexey Bataev549210e2014-06-24 04:39:47 +0000234 /// \brief Returns parent directive.
235 OpenMPDirectiveKind getParentDirective() const {
236 if (Stack.size() > 2)
237 return Stack[Stack.size() - 2].Directive;
238 return OMPD_unknown;
239 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000240
241 /// \brief Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000242 void setDefaultDSANone(SourceLocation Loc) {
243 Stack.back().DefaultAttr = DSA_none;
244 Stack.back().DefaultAttrLoc = Loc;
245 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000246 /// \brief Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000247 void setDefaultDSAShared(SourceLocation Loc) {
248 Stack.back().DefaultAttr = DSA_shared;
249 Stack.back().DefaultAttrLoc = Loc;
250 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000251
252 DefaultDataSharingAttributes getDefaultDSA() const {
253 return Stack.back().DefaultAttr;
254 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000255 SourceLocation getDefaultDSALocation() const {
256 return Stack.back().DefaultAttrLoc;
257 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000258
Alexey Bataevf29276e2014-06-18 04:14:57 +0000259 /// \brief Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000260 bool isThreadPrivate(VarDecl *D) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000261 DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000262 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000263 }
264
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000265 /// \brief Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataev346265e2015-09-25 10:37:12 +0000266 void setOrderedRegion(bool IsOrdered, Expr *Param) {
267 Stack.back().OrderedRegion.setInt(IsOrdered);
268 Stack.back().OrderedRegion.setPointer(Param);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000269 }
270 /// \brief Returns true, if parent region is ordered (has associated
271 /// 'ordered' clause), false - otherwise.
272 bool isParentOrderedRegion() const {
273 if (Stack.size() > 2)
Alexey Bataev346265e2015-09-25 10:37:12 +0000274 return Stack[Stack.size() - 2].OrderedRegion.getInt();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000275 return false;
276 }
Alexey Bataev346265e2015-09-25 10:37:12 +0000277 /// \brief Returns optional parameter for the ordered region.
278 Expr *getParentOrderedRegionParam() const {
279 if (Stack.size() > 2)
280 return Stack[Stack.size() - 2].OrderedRegion.getPointer();
281 return nullptr;
282 }
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000283 /// \brief Marks current region as nowait (it has a 'nowait' clause).
284 void setNowaitRegion(bool IsNowait = true) {
285 Stack.back().NowaitRegion = IsNowait;
286 }
287 /// \brief Returns true, if parent region is nowait (has associated
288 /// 'nowait' clause), false - otherwise.
289 bool isParentNowaitRegion() const {
290 if (Stack.size() > 2)
291 return Stack[Stack.size() - 2].NowaitRegion;
292 return false;
293 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000294 /// \brief Marks parent region as cancel region.
295 void setParentCancelRegion(bool Cancel = true) {
296 if (Stack.size() > 2)
297 Stack[Stack.size() - 2].CancelRegion =
298 Stack[Stack.size() - 2].CancelRegion || Cancel;
299 }
300 /// \brief Return true if current region has inner cancel construct.
David Majnemer9d168222016-08-05 17:44:54 +0000301 bool isCancelRegion() const { return Stack.back().CancelRegion; }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000302
Alexey Bataev9c821032015-04-30 04:23:23 +0000303 /// \brief Set collapse value for the region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000304 void setAssociatedLoops(unsigned Val) { Stack.back().AssociatedLoops = Val; }
Alexey Bataev9c821032015-04-30 04:23:23 +0000305 /// \brief Return collapse value for region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000306 unsigned getAssociatedLoops() const { return Stack.back().AssociatedLoops; }
Alexey Bataev9c821032015-04-30 04:23:23 +0000307
Alexey Bataev13314bf2014-10-09 04:18:56 +0000308 /// \brief Marks current target region as one with closely nested teams
309 /// region.
310 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
311 if (Stack.size() > 2)
312 Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
313 }
314 /// \brief Returns true, if current region has closely nested teams region.
315 bool hasInnerTeamsRegion() const {
316 return getInnerTeamsRegionLoc().isValid();
317 }
318 /// \brief Returns location of the nested teams region (if any).
319 SourceLocation getInnerTeamsRegionLoc() const {
320 if (Stack.size() > 1)
321 return Stack.back().InnerTeamsRegionLoc;
322 return SourceLocation();
323 }
324
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000325 Scope *getCurScope() const { return Stack.back().CurScope; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000326 Scope *getCurScope() { return Stack.back().CurScope; }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000327 SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000328
Samuel Antao4c8035b2016-12-12 18:00:20 +0000329 /// Do the check specified in \a Check to all component lists and return true
330 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000331 bool checkMappableExprComponentListsForDecl(
332 ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000333 const llvm::function_ref<
334 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
335 OpenMPClauseKind)> &Check) {
Samuel Antao5de996e2016-01-22 20:21:36 +0000336 auto SI = Stack.rbegin();
337 auto SE = Stack.rend();
338
339 if (SI == SE)
340 return false;
341
342 if (CurrentRegionOnly) {
343 SE = std::next(SI);
344 } else {
345 ++SI;
346 }
347
348 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000349 auto MI = SI->MappedExprComponents.find(VD);
350 if (MI != SI->MappedExprComponents.end())
Samuel Antao6890b092016-07-28 14:25:09 +0000351 for (auto &L : MI->second.Components)
352 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000353 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000354 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000355 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000356 }
357
Samuel Antao4c8035b2016-12-12 18:00:20 +0000358 /// Create a new mappable expression component list associated with a given
359 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000360 void addMappableExpressionComponents(
361 ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000362 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
363 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao90927002016-04-26 14:54:23 +0000364 assert(Stack.size() > 1 &&
365 "Not expecting to retrieve components from a empty stack!");
366 auto &MEC = Stack.back().MappedExprComponents[VD];
367 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000368 MEC.Components.resize(MEC.Components.size() + 1);
369 MEC.Components.back().append(Components.begin(), Components.end());
370 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000371 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000372
373 unsigned getNestingLevel() const {
374 assert(Stack.size() > 1);
375 return Stack.size() - 2;
376 }
Alexey Bataev8b427062016-05-25 12:36:08 +0000377 void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) {
378 assert(Stack.size() > 2);
379 assert(isOpenMPWorksharingDirective(Stack[Stack.size() - 2].Directive));
380 Stack[Stack.size() - 2].DoacrossDepends.insert({C, OpsOffs});
381 }
382 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
383 getDoacrossDependClauses() const {
384 assert(Stack.size() > 1);
385 if (isOpenMPWorksharingDirective(Stack[Stack.size() - 1].Directive)) {
386 auto &Ref = Stack[Stack.size() - 1].DoacrossDepends;
387 return llvm::make_range(Ref.begin(), Ref.end());
388 }
389 return llvm::make_range(Stack[0].DoacrossDepends.end(),
390 Stack[0].DoacrossDepends.end());
391 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000392};
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000393bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
Alexey Bataev35aaee62016-04-13 13:36:48 +0000394 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
395 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000396}
Alexey Bataeved09d242014-05-28 05:53:51 +0000397} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000398
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000399static ValueDecl *getCanonicalDecl(ValueDecl *D) {
400 auto *VD = dyn_cast<VarDecl>(D);
401 auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000402 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000403 VD = VD->getCanonicalDecl();
404 D = VD;
405 } else {
406 assert(FD);
407 FD = FD->getCanonicalDecl();
408 D = FD;
409 }
410 return D;
411}
412
David Majnemer9d168222016-08-05 17:44:54 +0000413DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000414 ValueDecl *D) {
415 D = getCanonicalDecl(D);
416 auto *VD = dyn_cast<VarDecl>(D);
417 auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000418 DSAVarData DVar;
Alexey Bataevdf9b1592014-06-25 04:09:13 +0000419 if (Iter == std::prev(Stack.rend())) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000420 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
421 // in a region but not in construct]
422 // File-scope or namespace-scope variables referenced in called routines
423 // in the region are shared unless they appear in a threadprivate
424 // directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000425 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000426 DVar.CKind = OMPC_shared;
427
428 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
429 // in a region but not in construct]
430 // Variables with static storage duration that are declared in called
431 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000432 if (VD && VD->hasGlobalStorage())
433 DVar.CKind = OMPC_shared;
434
435 // Non-static data members are shared by default.
436 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000437 DVar.CKind = OMPC_shared;
438
Alexey Bataev758e55e2013-09-06 18:03:48 +0000439 return DVar;
440 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000441
Alexey Bataev758e55e2013-09-06 18:03:48 +0000442 DVar.DKind = Iter->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +0000443 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
444 // in a Construct, C/C++, predetermined, p.1]
445 // Variables with automatic storage duration that are declared in a scope
446 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000447 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
448 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000449 DVar.CKind = OMPC_private;
450 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000451 }
452
Alexey Bataev758e55e2013-09-06 18:03:48 +0000453 // Explicitly specified attributes and local variables with predetermined
454 // attributes.
455 if (Iter->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000456 DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000457 DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000458 DVar.CKind = Iter->SharingMap[D].Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000459 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000460 return DVar;
461 }
462
463 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
464 // in a Construct, C/C++, implicitly determined, p.1]
465 // In a parallel or task construct, the data-sharing attributes of these
466 // variables are determined by the default clause, if present.
467 switch (Iter->DefaultAttr) {
468 case DSA_shared:
469 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000470 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000471 return DVar;
472 case DSA_none:
473 return DVar;
474 case DSA_unspecified:
475 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
476 // in a Construct, implicitly determined, p.2]
477 // In a parallel construct, if no default clause is present, these
478 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000479 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000480 if (isOpenMPParallelDirective(DVar.DKind) ||
481 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000482 DVar.CKind = OMPC_shared;
483 return DVar;
484 }
485
486 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
487 // in a Construct, implicitly determined, p.4]
488 // In a task construct, if no default clause is present, a variable that in
489 // the enclosing context is determined to be shared by all implicit tasks
490 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000491 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000492 DSAVarData DVarTemp;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000493 for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000494 I != EE; ++I) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000495 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000496 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000497 // In a task construct, if no default clause is present, a variable
498 // whose data-sharing attribute is not determined by the rules above is
499 // firstprivate.
500 DVarTemp = getDSA(I, D);
501 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000502 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000503 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000504 return DVar;
505 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000506 if (isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000507 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000508 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000509 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000510 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000511 return DVar;
512 }
513 }
514 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
515 // in a Construct, implicitly determined, p.3]
516 // For constructs other than task, if no default clause is present, these
517 // variables inherit their data-sharing attributes from the enclosing
518 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000519 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000520}
521
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000522Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000523 assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000524 D = getCanonicalDecl(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000525 auto It = Stack.back().AlignedMap.find(D);
526 if (It == Stack.back().AlignedMap.end()) {
527 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
528 Stack.back().AlignedMap[D] = NewDE;
529 return nullptr;
530 } else {
531 assert(It->second && "Unexpected nullptr expr in the aligned map");
532 return It->second;
533 }
534 return nullptr;
535}
536
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000537void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
Alexey Bataev9c821032015-04-30 04:23:23 +0000538 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000539 D = getCanonicalDecl(D);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000540 Stack.back().LCVMap.insert(
541 std::make_pair(D, LCDeclInfo(Stack.back().LCVMap.size() + 1, Capture)));
Alexey Bataev9c821032015-04-30 04:23:23 +0000542}
543
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000544DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
Alexey Bataev9c821032015-04-30 04:23:23 +0000545 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000546 D = getCanonicalDecl(D);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000547 return Stack.back().LCVMap.count(D) > 0 ? Stack.back().LCVMap[D]
548 : LCDeclInfo(0, nullptr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000549}
550
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000551DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000552 assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000553 D = getCanonicalDecl(D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000554 return Stack[Stack.size() - 2].LCVMap.count(D) > 0
555 ? Stack[Stack.size() - 2].LCVMap[D]
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000556 : LCDeclInfo(0, nullptr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000557}
558
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000559ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000560 assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
561 if (Stack[Stack.size() - 2].LCVMap.size() < I)
562 return nullptr;
563 for (auto &Pair : Stack[Stack.size() - 2].LCVMap) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000564 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000565 return Pair.first;
566 }
567 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +0000568}
569
Alexey Bataev90c228f2016-02-08 09:29:13 +0000570void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
571 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000572 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000573 if (A == OMPC_threadprivate) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000574 auto &Data = Stack[0].SharingMap[D];
575 Data.Attributes = A;
576 Data.RefExpr.setPointer(E);
577 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000578 } else {
579 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000580 auto &Data = Stack.back().SharingMap[D];
581 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
582 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
583 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
584 (isLoopControlVariable(D).first && A == OMPC_private));
585 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
586 Data.RefExpr.setInt(/*IntVal=*/true);
587 return;
588 }
589 const bool IsLastprivate =
590 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
591 Data.Attributes = A;
592 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
593 Data.PrivateCopy = PrivateCopy;
594 if (PrivateCopy) {
595 auto &Data = Stack.back().SharingMap[PrivateCopy->getDecl()];
596 Data.Attributes = A;
597 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
598 Data.PrivateCopy = nullptr;
599 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000600 }
601}
602
Alexey Bataeved09d242014-05-28 05:53:51 +0000603bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000604 D = D->getCanonicalDecl();
Alexey Bataevec3da872014-01-31 05:15:34 +0000605 if (Stack.size() > 2) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000606 reverse_iterator I = Iter, E = std::prev(Stack.rend());
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000607 Scope *TopScope = nullptr;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000608 while (I != E && !isParallelOrTaskRegion(I->Directive)) {
Alexey Bataevec3da872014-01-31 05:15:34 +0000609 ++I;
610 }
Alexey Bataeved09d242014-05-28 05:53:51 +0000611 if (I == E)
612 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000613 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000614 Scope *CurScope = getCurScope();
615 while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000616 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000617 }
618 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000619 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000620 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000621}
622
Alexey Bataev39f915b82015-05-08 10:41:21 +0000623/// \brief Build a variable declaration for OpenMP loop iteration variable.
624static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000625 StringRef Name, const AttrVec *Attrs = nullptr) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000626 DeclContext *DC = SemaRef.CurContext;
627 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
628 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
629 VarDecl *Decl =
630 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000631 if (Attrs) {
632 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
633 I != E; ++I)
634 Decl->addAttr(*I);
635 }
Alexey Bataev39f915b82015-05-08 10:41:21 +0000636 Decl->setImplicit();
637 return Decl;
638}
639
640static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
641 SourceLocation Loc,
642 bool RefersToCapture = false) {
643 D->setReferenced();
644 D->markUsed(S.Context);
645 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
646 SourceLocation(), D, RefersToCapture, Loc, Ty,
647 VK_LValue);
648}
649
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000650DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
651 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000652 DSAVarData DVar;
653
654 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
655 // in a Construct, C/C++, predetermined, p.1]
656 // Variables appearing in threadprivate directives are threadprivate.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000657 auto *VD = dyn_cast<VarDecl>(D);
658 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
659 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
Samuel Antaof8b50122015-07-13 22:54:53 +0000660 SemaRef.getLangOpts().OpenMPUseTLS &&
661 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000662 (VD && VD->getStorageClass() == SC_Register &&
663 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
664 addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
Alexey Bataev39f915b82015-05-08 10:41:21 +0000665 D->getLocation()),
Alexey Bataevf2453a02015-05-06 07:25:08 +0000666 OMPC_threadprivate);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000667 }
668 if (Stack[0].SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000669 DVar.RefExpr = Stack[0].SharingMap[D].RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000670 DVar.CKind = OMPC_threadprivate;
671 return DVar;
672 }
673
Dmitry Polukhin0b0da292016-04-06 11:38:59 +0000674 if (Stack.size() == 1) {
675 // Not in OpenMP execution region and top scope was already checked.
676 return DVar;
677 }
678
Alexey Bataev758e55e2013-09-06 18:03:48 +0000679 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000680 // in a Construct, C/C++, predetermined, p.4]
681 // Static data members are shared.
682 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
683 // in a Construct, C/C++, predetermined, p.7]
684 // Variables with static storage duration that are declared in a scope
685 // inside the construct are shared.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000686 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000687 if (VD && VD->isStaticDataMember()) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000688 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000689 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
Alexey Bataevec3da872014-01-31 05:15:34 +0000690 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000691
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000692 DVar.CKind = OMPC_shared;
693 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000694 }
695
696 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000697 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
698 Type = SemaRef.getASTContext().getBaseElementType(Type);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000699 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
700 // in a Construct, C/C++, predetermined, p.6]
701 // Variables with const qualified type having no mutable member are
702 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000703 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +0000704 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataevc9bd03d2015-12-17 06:55:08 +0000705 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
706 if (auto *CTD = CTSD->getSpecializedTemplate())
707 RD = CTD->getTemplatedDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000708 if (IsConstant &&
Alexey Bataev4bcad7f2016-02-10 10:50:12 +0000709 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
710 RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000711 // Variables with const-qualified type having no mutable member may be
712 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000713 DSAVarData DVarTemp = hasDSA(
714 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
715 MatchesAlways, FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000716 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
717 return DVar;
718
Alexey Bataev758e55e2013-09-06 18:03:48 +0000719 DVar.CKind = OMPC_shared;
720 return DVar;
721 }
722
Alexey Bataev758e55e2013-09-06 18:03:48 +0000723 // Explicitly specified attributes and local variables with predetermined
724 // attributes.
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000725 auto StartI = std::next(Stack.rbegin());
726 auto EndI = std::prev(Stack.rend());
727 if (FromParent && StartI != EndI) {
728 StartI = std::next(StartI);
729 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000730 auto I = std::prev(StartI);
731 if (I->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000732 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000733 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000734 DVar.CKind = I->SharingMap[D].Attributes;
735 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000736 }
737
738 return DVar;
739}
740
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000741DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
742 bool FromParent) {
743 D = getCanonicalDecl(D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000744 auto StartI = Stack.rbegin();
745 auto EndI = std::prev(Stack.rend());
746 if (FromParent && StartI != EndI) {
747 StartI = std::next(StartI);
748 }
749 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000750}
751
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000752DSAStackTy::DSAVarData
753DSAStackTy::hasDSA(ValueDecl *D,
754 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
755 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
756 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000757 D = getCanonicalDecl(D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000758 auto StartI = std::next(Stack.rbegin());
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000759 auto EndI = Stack.rend();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000760 if (FromParent && StartI != EndI) {
761 StartI = std::next(StartI);
762 }
763 for (auto I = StartI, EE = EndI; I != EE; ++I) {
764 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000765 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000766 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000767 if (CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000768 return DVar;
769 }
770 return DSAVarData();
771}
772
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000773DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
774 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
775 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
776 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000777 D = getCanonicalDecl(D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000778 auto StartI = std::next(Stack.rbegin());
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000779 auto EndI = Stack.rend();
Alexey Bataeve3978122016-07-19 05:06:39 +0000780 if (FromParent && StartI != EndI)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000781 StartI = std::next(StartI);
Alexey Bataeve3978122016-07-19 05:06:39 +0000782 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataevc5e02582014-06-16 07:08:35 +0000783 return DSAVarData();
Alexey Bataeve3978122016-07-19 05:06:39 +0000784 DSAVarData DVar = getDSA(StartI, D);
785 return CPred(DVar.CKind) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +0000786}
787
Alexey Bataevaac108a2015-06-23 04:51:00 +0000788bool DSAStackTy::hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000789 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000790 unsigned Level, bool NotLastprivate) {
Alexey Bataevaac108a2015-06-23 04:51:00 +0000791 if (CPred(ClauseKindMode))
792 return true;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000793 D = getCanonicalDecl(D);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000794 auto StartI = std::next(Stack.begin());
795 auto EndI = Stack.end();
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +0000796 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +0000797 return false;
798 std::advance(StartI, Level);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000799 return (StartI->SharingMap.count(D) > 0) &&
800 StartI->SharingMap[D].RefExpr.getPointer() &&
801 CPred(StartI->SharingMap[D].Attributes) &&
802 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
Alexey Bataevaac108a2015-06-23 04:51:00 +0000803}
804
Samuel Antao4be30e92015-10-02 17:14:03 +0000805bool DSAStackTy::hasExplicitDirective(
806 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
807 unsigned Level) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000808 auto StartI = std::next(Stack.begin());
809 auto EndI = Stack.end();
Samuel Antao4be30e92015-10-02 17:14:03 +0000810 if (std::distance(StartI, EndI) <= (int)Level)
811 return false;
812 std::advance(StartI, Level);
813 return DPred(StartI->Directive);
814}
815
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000816bool DSAStackTy::hasDirective(
817 const llvm::function_ref<bool(OpenMPDirectiveKind,
818 const DeclarationNameInfo &, SourceLocation)>
819 &DPred,
820 bool FromParent) {
Samuel Antaof0d79752016-05-27 15:21:27 +0000821 // We look only in the enclosing region.
822 if (Stack.size() < 2)
823 return false;
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000824 auto StartI = std::next(Stack.rbegin());
825 auto EndI = std::prev(Stack.rend());
826 if (FromParent && StartI != EndI) {
827 StartI = std::next(StartI);
828 }
829 for (auto I = StartI, EE = EndI; I != EE; ++I) {
830 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
831 return true;
832 }
833 return false;
834}
835
Alexey Bataev758e55e2013-09-06 18:03:48 +0000836void Sema::InitDataSharingAttributesStack() {
837 VarDataSharingAttributesStack = new DSAStackTy(*this);
838}
839
840#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
841
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000842bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000843 assert(LangOpts.OpenMP && "OpenMP is not allowed");
844
845 auto &Ctx = getASTContext();
846 bool IsByRef = true;
847
848 // Find the directive that is associated with the provided scope.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000849 auto Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000850
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000851 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000852 // This table summarizes how a given variable should be passed to the device
853 // given its type and the clauses where it appears. This table is based on
854 // the description in OpenMP 4.5 [2.10.4, target Construct] and
855 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
856 //
857 // =========================================================================
858 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
859 // | |(tofrom:scalar)| | pvt | | | |
860 // =========================================================================
861 // | scl | | | | - | | bycopy|
862 // | scl | | - | x | - | - | bycopy|
863 // | scl | | x | - | - | - | null |
864 // | scl | x | | | - | | byref |
865 // | scl | x | - | x | - | - | bycopy|
866 // | scl | x | x | - | - | - | null |
867 // | scl | | - | - | - | x | byref |
868 // | scl | x | - | - | - | x | byref |
869 //
870 // | agg | n.a. | | | - | | byref |
871 // | agg | n.a. | - | x | - | - | byref |
872 // | agg | n.a. | x | - | - | - | null |
873 // | agg | n.a. | - | - | - | x | byref |
874 // | agg | n.a. | - | - | - | x[] | byref |
875 //
876 // | ptr | n.a. | | | - | | bycopy|
877 // | ptr | n.a. | - | x | - | - | bycopy|
878 // | ptr | n.a. | x | - | - | - | null |
879 // | ptr | n.a. | - | - | - | x | byref |
880 // | ptr | n.a. | - | - | - | x[] | bycopy|
881 // | ptr | n.a. | - | - | x | | bycopy|
882 // | ptr | n.a. | - | - | x | x | bycopy|
883 // | ptr | n.a. | - | - | x | x[] | bycopy|
884 // =========================================================================
885 // Legend:
886 // scl - scalar
887 // ptr - pointer
888 // agg - aggregate
889 // x - applies
890 // - - invalid in this combination
891 // [] - mapped with an array section
892 // byref - should be mapped by reference
893 // byval - should be mapped by value
894 // null - initialize a local variable to null on the device
895 //
896 // Observations:
897 // - All scalar declarations that show up in a map clause have to be passed
898 // by reference, because they may have been mapped in the enclosing data
899 // environment.
900 // - If the scalar value does not fit the size of uintptr, it has to be
901 // passed by reference, regardless the result in the table above.
902 // - For pointers mapped by value that have either an implicit map or an
903 // array section, the runtime library may pass the NULL value to the
904 // device instead of the value passed to it by the compiler.
905
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000906 if (Ty->isReferenceType())
907 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +0000908
909 // Locate map clauses and see if the variable being captured is referred to
910 // in any of those clauses. Here we only care about variables, not fields,
911 // because fields are part of aggregates.
912 bool IsVariableUsedInMapClause = false;
913 bool IsVariableAssociatedWithSection = false;
914
915 DSAStack->checkMappableExprComponentListsForDecl(
916 D, /*CurrentRegionOnly=*/true,
917 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +0000918 MapExprComponents,
919 OpenMPClauseKind WhereFoundClauseKind) {
920 // Only the map clause information influences how a variable is
921 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +0000922 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +0000923 if (WhereFoundClauseKind != OMPC_map)
924 return false;
Samuel Antao86ace552016-04-27 22:40:57 +0000925
926 auto EI = MapExprComponents.rbegin();
927 auto EE = MapExprComponents.rend();
928
929 assert(EI != EE && "Invalid map expression!");
930
931 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
932 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
933
934 ++EI;
935 if (EI == EE)
936 return false;
937
938 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
939 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
940 isa<MemberExpr>(EI->getAssociatedExpression())) {
941 IsVariableAssociatedWithSection = true;
942 // There is nothing more we need to know about this variable.
943 return true;
944 }
945
946 // Keep looking for more map info.
947 return false;
948 });
949
950 if (IsVariableUsedInMapClause) {
951 // If variable is identified in a map clause it is always captured by
952 // reference except if it is a pointer that is dereferenced somehow.
953 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
954 } else {
955 // By default, all the data that has a scalar type is mapped by copy.
956 IsByRef = !Ty->isScalarType();
957 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000958 }
959
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000960 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
961 IsByRef = !DSAStack->hasExplicitDSA(
962 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
963 Level, /*NotLastprivate=*/true);
964 }
965
Samuel Antao86ace552016-04-27 22:40:57 +0000966 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000967 // and alignment, because the runtime library only deals with uintptr types.
968 // If it does not fit the uintptr size, we need to pass the data by reference
969 // instead.
970 if (!IsByRef &&
971 (Ctx.getTypeSizeInChars(Ty) >
972 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000973 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000974 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000975 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000976
977 return IsByRef;
978}
979
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000980unsigned Sema::getOpenMPNestingLevel() const {
981 assert(getLangOpts().OpenMP);
982 return DSAStack->getNestingLevel();
983}
984
Alexey Bataev90c228f2016-02-08 09:29:13 +0000985VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
Alexey Bataevf841bd92014-12-16 07:00:22 +0000986 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000987 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +0000988
989 // If we are attempting to capture a global variable in a directive with
990 // 'target' we return true so that this global is also mapped to the device.
991 //
992 // FIXME: If the declaration is enclosed in a 'declare target' directive,
993 // then it should not be captured. Therefore, an extra check has to be
994 // inserted here once support for 'declare target' is added.
995 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000996 auto *VD = dyn_cast<VarDecl>(D);
997 if (VD && !VD->hasLocalStorage()) {
Samuel Antao4be30e92015-10-02 17:14:03 +0000998 if (DSAStack->getCurrentDirective() == OMPD_target &&
Alexey Bataev90c228f2016-02-08 09:29:13 +0000999 !DSAStack->isClauseParsingMode())
1000 return VD;
Samuel Antaof0d79752016-05-27 15:21:27 +00001001 if (DSAStack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001002 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1003 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001004 return isOpenMPTargetExecutionDirective(K);
Samuel Antao4be30e92015-10-02 17:14:03 +00001005 },
Alexey Bataev90c228f2016-02-08 09:29:13 +00001006 false))
1007 return VD;
Samuel Antao4be30e92015-10-02 17:14:03 +00001008 }
1009
Alexey Bataev48977c32015-08-04 08:10:48 +00001010 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1011 (!DSAStack->isClauseParsingMode() ||
1012 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001013 auto &&Info = DSAStack->isLoopControlVariable(D);
1014 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001015 (VD && VD->hasLocalStorage() &&
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001016 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001017 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001018 return VD ? VD : Info.second;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001019 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001020 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001021 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001022 DVarPrivate = DSAStack->hasDSA(
1023 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1024 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +00001025 if (DVarPrivate.CKind != OMPC_unknown)
1026 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001027 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001028 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001029}
1030
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001031bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001032 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1033 return DSAStack->hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001034 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
Alexey Bataevaac108a2015-06-23 04:51:00 +00001035}
1036
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001037bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
Samuel Antao4be30e92015-10-02 17:14:03 +00001038 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1039 // Return true if the current level is no longer enclosed in a target region.
1040
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001041 auto *VD = dyn_cast<VarDecl>(D);
1042 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001043 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1044 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001045}
1046
Alexey Bataeved09d242014-05-28 05:53:51 +00001047void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001048
1049void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1050 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001051 Scope *CurScope, SourceLocation Loc) {
1052 DSAStack->push(DKind, DirName, CurScope, Loc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001053 PushExpressionEvaluationContext(PotentiallyEvaluated);
1054}
1055
Alexey Bataevaac108a2015-06-23 04:51:00 +00001056void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1057 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001058}
1059
Alexey Bataevaac108a2015-06-23 04:51:00 +00001060void Sema::EndOpenMPClause() {
1061 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001062}
1063
Alexey Bataev758e55e2013-09-06 18:03:48 +00001064void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001065 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1066 // A variable of class type (or array thereof) that appears in a lastprivate
1067 // clause requires an accessible, unambiguous default constructor for the
1068 // class type, unless the list item is also specified in a firstprivate
1069 // clause.
David Majnemer9d168222016-08-05 17:44:54 +00001070 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001071 for (auto *C : D->clauses()) {
1072 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1073 SmallVector<Expr *, 8> PrivateCopies;
1074 for (auto *DE : Clause->varlists()) {
1075 if (DE->isValueDependent() || DE->isTypeDependent()) {
1076 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001077 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001078 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001079 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataev005248a2016-02-25 05:25:57 +00001080 VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1081 QualType Type = VD->getType().getNonReferenceType();
1082 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001083 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001084 // Generate helper private variable and initialize it with the
1085 // default value. The address of the original variable is replaced
1086 // by the address of the new private variable in CodeGen. This new
1087 // variable is not added to IdResolver, so the code in the OpenMP
1088 // region uses original variable for proper diagnostics.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001089 auto *VDPrivate = buildVarDecl(
1090 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev005248a2016-02-25 05:25:57 +00001091 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev38e89532015-04-16 04:54:05 +00001092 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
1093 if (VDPrivate->isInvalidDecl())
1094 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001095 PrivateCopies.push_back(buildDeclRefExpr(
1096 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001097 } else {
1098 // The variable is also a firstprivate, so initialization sequence
1099 // for private copy is generated already.
1100 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001101 }
1102 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001103 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001104 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001105 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001106 }
1107 }
1108 }
1109
Alexey Bataev758e55e2013-09-06 18:03:48 +00001110 DSAStack->pop();
1111 DiscardCleanupsInEvaluationContext();
1112 PopExpressionEvaluationContext();
1113}
1114
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001115static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1116 Expr *NumIterations, Sema &SemaRef,
1117 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001118
Alexey Bataeva769e072013-03-22 06:34:35 +00001119namespace {
1120
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001121class VarDeclFilterCCC : public CorrectionCandidateCallback {
1122private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001123 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001124
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001125public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001126 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001127 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001128 NamedDecl *ND = Candidate.getCorrectionDecl();
David Majnemer9d168222016-08-05 17:44:54 +00001129 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001130 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001131 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1132 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001133 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001134 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001135 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001136};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001137
1138class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1139private:
1140 Sema &SemaRef;
1141
1142public:
1143 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1144 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1145 NamedDecl *ND = Candidate.getCorrectionDecl();
1146 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
1147 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1148 SemaRef.getCurScope());
1149 }
1150 return false;
1151 }
1152};
1153
Alexey Bataeved09d242014-05-28 05:53:51 +00001154} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001155
1156ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1157 CXXScopeSpec &ScopeSpec,
1158 const DeclarationNameInfo &Id) {
1159 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1160 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1161
1162 if (Lookup.isAmbiguous())
1163 return ExprError();
1164
1165 VarDecl *VD;
1166 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001167 if (TypoCorrection Corrected = CorrectTypo(
1168 Id, LookupOrdinaryName, CurScope, nullptr,
1169 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001170 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001171 PDiag(Lookup.empty()
1172 ? diag::err_undeclared_var_use_suggest
1173 : diag::err_omp_expected_var_arg_suggest)
1174 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001175 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001176 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001177 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1178 : diag::err_omp_expected_var_arg)
1179 << Id.getName();
1180 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001181 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001182 } else {
1183 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00001184 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001185 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1186 return ExprError();
1187 }
1188 }
1189 Lookup.suppressDiagnostics();
1190
1191 // OpenMP [2.9.2, Syntax, C/C++]
1192 // Variables must be file-scope, namespace-scope, or static block-scope.
1193 if (!VD->hasGlobalStorage()) {
1194 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001195 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1196 bool IsDecl =
1197 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001198 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00001199 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1200 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001201 return ExprError();
1202 }
1203
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001204 VarDecl *CanonicalVD = VD->getCanonicalDecl();
1205 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001206 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1207 // A threadprivate directive for file-scope variables must appear outside
1208 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001209 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1210 !getCurLexicalContext()->isTranslationUnit()) {
1211 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001212 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1213 bool IsDecl =
1214 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1215 Diag(VD->getLocation(),
1216 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1217 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001218 return ExprError();
1219 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001220 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1221 // A threadprivate directive for static class member variables must appear
1222 // in the class definition, in the same scope in which the member
1223 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001224 if (CanonicalVD->isStaticDataMember() &&
1225 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1226 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001227 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1228 bool IsDecl =
1229 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1230 Diag(VD->getLocation(),
1231 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1232 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001233 return ExprError();
1234 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001235 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1236 // A threadprivate directive for namespace-scope variables must appear
1237 // outside any definition or declaration other than the namespace
1238 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001239 if (CanonicalVD->getDeclContext()->isNamespace() &&
1240 (!getCurLexicalContext()->isFileContext() ||
1241 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1242 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001243 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1244 bool IsDecl =
1245 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1246 Diag(VD->getLocation(),
1247 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1248 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001249 return ExprError();
1250 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001251 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1252 // A threadprivate directive for static block-scope variables must appear
1253 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001254 if (CanonicalVD->isStaticLocal() && CurScope &&
1255 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001256 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001257 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1258 bool IsDecl =
1259 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1260 Diag(VD->getLocation(),
1261 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1262 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001263 return ExprError();
1264 }
1265
1266 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1267 // A threadprivate directive must lexically precede all references to any
1268 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001269 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001270 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +00001271 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001272 return ExprError();
1273 }
1274
1275 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00001276 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1277 SourceLocation(), VD,
1278 /*RefersToEnclosingVariableOrCapture=*/false,
1279 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001280}
1281
Alexey Bataeved09d242014-05-28 05:53:51 +00001282Sema::DeclGroupPtrTy
1283Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1284 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001285 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001286 CurContext->addDecl(D);
1287 return DeclGroupPtrTy::make(DeclGroupRef(D));
1288 }
David Blaikie0403cb12016-01-15 23:43:25 +00001289 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00001290}
1291
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001292namespace {
1293class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1294 Sema &SemaRef;
1295
1296public:
1297 bool VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer9d168222016-08-05 17:44:54 +00001298 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001299 if (VD->hasLocalStorage()) {
1300 SemaRef.Diag(E->getLocStart(),
1301 diag::err_omp_local_var_in_threadprivate_init)
1302 << E->getSourceRange();
1303 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1304 << VD << VD->getSourceRange();
1305 return true;
1306 }
1307 }
1308 return false;
1309 }
1310 bool VisitStmt(const Stmt *S) {
1311 for (auto Child : S->children()) {
1312 if (Child && Visit(Child))
1313 return true;
1314 }
1315 return false;
1316 }
Alexey Bataev23b69422014-06-18 07:08:49 +00001317 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001318};
1319} // namespace
1320
Alexey Bataeved09d242014-05-28 05:53:51 +00001321OMPThreadPrivateDecl *
1322Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001323 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00001324 for (auto &RefExpr : VarList) {
1325 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001326 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1327 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00001328
Alexey Bataev376b4a42016-02-09 09:41:09 +00001329 // Mark variable as used.
1330 VD->setReferenced();
1331 VD->markUsed(Context);
1332
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001333 QualType QType = VD->getType();
1334 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1335 // It will be analyzed later.
1336 Vars.push_back(DE);
1337 continue;
1338 }
1339
Alexey Bataeva769e072013-03-22 06:34:35 +00001340 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1341 // A threadprivate variable must not have an incomplete type.
1342 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001343 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001344 continue;
1345 }
1346
1347 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1348 // A threadprivate variable must not have a reference type.
1349 if (VD->getType()->isReferenceType()) {
1350 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001351 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1352 bool IsDecl =
1353 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1354 Diag(VD->getLocation(),
1355 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1356 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001357 continue;
1358 }
1359
Samuel Antaof8b50122015-07-13 22:54:53 +00001360 // Check if this is a TLS variable. If TLS is not being supported, produce
1361 // the corresponding diagnostic.
1362 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1363 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1364 getLangOpts().OpenMPUseTLS &&
1365 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00001366 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1367 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00001368 Diag(ILoc, diag::err_omp_var_thread_local)
1369 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00001370 bool IsDecl =
1371 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1372 Diag(VD->getLocation(),
1373 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1374 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001375 continue;
1376 }
1377
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001378 // Check if initial value of threadprivate variable reference variable with
1379 // local storage (it is not supported by runtime).
1380 if (auto Init = VD->getAnyInitializer()) {
1381 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001382 if (Checker.Visit(Init))
1383 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001384 }
1385
Alexey Bataeved09d242014-05-28 05:53:51 +00001386 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00001387 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00001388 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1389 Context, SourceRange(Loc, Loc)));
1390 if (auto *ML = Context.getASTMutationListener())
1391 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00001392 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001393 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001394 if (!Vars.empty()) {
1395 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1396 Vars);
1397 D->setAccess(AS_public);
1398 }
1399 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00001400}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001401
Alexey Bataev7ff55242014-06-19 09:13:45 +00001402static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001403 const ValueDecl *D, DSAStackTy::DSAVarData DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00001404 bool IsLoopIterVar = false) {
1405 if (DVar.RefExpr) {
1406 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1407 << getOpenMPClauseName(DVar.CKind);
1408 return;
1409 }
1410 enum {
1411 PDSA_StaticMemberShared,
1412 PDSA_StaticLocalVarShared,
1413 PDSA_LoopIterVarPrivate,
1414 PDSA_LoopIterVarLinear,
1415 PDSA_LoopIterVarLastprivate,
1416 PDSA_ConstVarShared,
1417 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001418 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001419 PDSA_LocalVarPrivate,
1420 PDSA_Implicit
1421 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001422 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001423 auto ReportLoc = D->getLocation();
1424 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00001425 if (IsLoopIterVar) {
1426 if (DVar.CKind == OMPC_private)
1427 Reason = PDSA_LoopIterVarPrivate;
1428 else if (DVar.CKind == OMPC_lastprivate)
1429 Reason = PDSA_LoopIterVarLastprivate;
1430 else
1431 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00001432 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1433 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001434 Reason = PDSA_TaskVarFirstprivate;
1435 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001436 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001437 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001438 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001439 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001440 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001441 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001442 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00001443 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001444 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001445 ReportHint = true;
1446 Reason = PDSA_LocalVarPrivate;
1447 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001448 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001449 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001450 << Reason << ReportHint
1451 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1452 } else if (DVar.ImplicitDSALoc.isValid()) {
1453 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1454 << getOpenMPClauseName(DVar.CKind);
1455 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001456}
1457
Alexey Bataev758e55e2013-09-06 18:03:48 +00001458namespace {
1459class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1460 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001461 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001462 bool ErrorFound;
1463 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001464 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001465 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataeved09d242014-05-28 05:53:51 +00001466
Alexey Bataev758e55e2013-09-06 18:03:48 +00001467public:
1468 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001469 if (E->isTypeDependent() || E->isValueDependent() ||
1470 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1471 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001472 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001473 // Skip internally declared variables.
Alexey Bataeved09d242014-05-28 05:53:51 +00001474 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1475 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001476
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001477 auto DVar = Stack->getTopDSA(VD, false);
1478 // Check if the variable has explicit DSA set and stop analysis if it so.
David Majnemer9d168222016-08-05 17:44:54 +00001479 if (DVar.RefExpr)
1480 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001481
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001482 auto ELoc = E->getExprLoc();
1483 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001484 // The default(none) clause requires that each variable that is referenced
1485 // in the construct, and does not have a predetermined data-sharing
1486 // attribute, must have its data-sharing attribute explicitly determined
1487 // by being listed in a data-sharing attribute clause.
1488 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001489 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001490 VarsWithInheritedDSA.count(VD) == 0) {
1491 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001492 return;
1493 }
1494
1495 // OpenMP [2.9.3.6, Restrictions, p.2]
1496 // A list item that appears in a reduction clause of the innermost
1497 // enclosing worksharing or parallel construct may not be accessed in an
1498 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001499 DVar = Stack->hasInnermostDSA(
1500 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1501 [](OpenMPDirectiveKind K) -> bool {
1502 return isOpenMPParallelDirective(K) ||
1503 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1504 },
1505 false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001506 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00001507 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001508 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1509 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001510 return;
1511 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001512
1513 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001514 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001515 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1516 !Stack->isLoopControlVariable(VD).first)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001517 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001518 }
1519 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001520 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001521 if (E->isTypeDependent() || E->isValueDependent() ||
1522 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1523 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001524 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
1525 if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
1526 auto DVar = Stack->getTopDSA(FD, false);
1527 // Check if the variable has explicit DSA set and stop analysis if it
1528 // so.
1529 if (DVar.RefExpr)
1530 return;
1531
1532 auto ELoc = E->getExprLoc();
1533 auto DKind = Stack->getCurrentDirective();
1534 // OpenMP [2.9.3.6, Restrictions, p.2]
1535 // A list item that appears in a reduction clause of the innermost
1536 // enclosing worksharing or parallel construct may not be accessed in
Alexey Bataevd985eda2016-02-10 11:29:16 +00001537 // an explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001538 DVar = Stack->hasInnermostDSA(
1539 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1540 [](OpenMPDirectiveKind K) -> bool {
1541 return isOpenMPParallelDirective(K) ||
1542 isOpenMPWorksharingDirective(K) ||
1543 isOpenMPTeamsDirective(K);
1544 },
1545 false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001546 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001547 ErrorFound = true;
1548 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1549 ReportOriginalDSA(SemaRef, Stack, FD, DVar);
1550 return;
1551 }
1552
1553 // Define implicit data-sharing attributes for task.
1554 DVar = Stack->getImplicitDSA(FD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001555 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1556 !Stack->isLoopControlVariable(FD).first)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001557 ImplicitFirstprivate.push_back(E);
1558 }
Alexey Bataev7fcacd82016-11-28 15:55:15 +00001559 } else
1560 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001561 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001562 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001563 for (auto *C : S->clauses()) {
1564 // Skip analysis of arguments of implicitly defined firstprivate clause
1565 // for task directives.
1566 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1567 for (auto *CC : C->children()) {
1568 if (CC)
1569 Visit(CC);
1570 }
1571 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001572 }
1573 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001574 for (auto *C : S->children()) {
1575 if (C && !isa<OMPExecutableDirective>(C))
1576 Visit(C);
1577 }
Alexey Bataeved09d242014-05-28 05:53:51 +00001578 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001579
1580 bool isErrorFound() { return ErrorFound; }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001581 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001582 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
Alexey Bataev4acb8592014-07-07 13:01:15 +00001583 return VarsWithInheritedDSA;
1584 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001585
Alexey Bataev7ff55242014-06-19 09:13:45 +00001586 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1587 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00001588};
Alexey Bataeved09d242014-05-28 05:53:51 +00001589} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00001590
Alexey Bataevbae9a792014-06-27 10:37:06 +00001591void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001592 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00001593 case OMPD_parallel:
1594 case OMPD_parallel_for:
1595 case OMPD_parallel_for_simd:
1596 case OMPD_parallel_sections:
Kelvin Libf594a52016-12-17 05:48:59 +00001597 case OMPD_teams:
1598 case OMPD_target_teams: {
Alexey Bataev9959db52014-05-06 10:08:46 +00001599 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001600 QualType KmpInt32PtrTy =
1601 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001602 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001603 std::make_pair(".global_tid.", KmpInt32PtrTy),
1604 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1605 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001606 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001607 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1608 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001609 break;
1610 }
Kelvin Li70a12c52016-07-13 21:51:49 +00001611 case OMPD_simd:
1612 case OMPD_for:
1613 case OMPD_for_simd:
1614 case OMPD_sections:
1615 case OMPD_section:
1616 case OMPD_single:
1617 case OMPD_master:
1618 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00001619 case OMPD_taskgroup:
1620 case OMPD_distribute:
Kelvin Li70a12c52016-07-13 21:51:49 +00001621 case OMPD_ordered:
1622 case OMPD_atomic:
1623 case OMPD_target_data:
1624 case OMPD_target:
1625 case OMPD_target_parallel:
1626 case OMPD_target_parallel_for:
Kelvin Li986330c2016-07-20 22:57:10 +00001627 case OMPD_target_parallel_for_simd:
1628 case OMPD_target_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001629 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001630 std::make_pair(StringRef(), QualType()) // __context with shared vars
1631 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001632 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1633 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001634 break;
1635 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001636 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001637 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001638 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1639 FunctionProtoType::ExtProtoInfo EPI;
1640 EPI.Variadic = true;
1641 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001642 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001643 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataev48591dd2016-04-20 04:01:36 +00001644 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1645 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
1646 std::make_pair(".copy_fn.",
1647 Context.getPointerType(CopyFnType).withConst()),
1648 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001649 std::make_pair(StringRef(), QualType()) // __context with shared vars
1650 };
1651 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1652 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001653 // Mark this captured region as inlined, because we don't use outlined
1654 // function directly.
1655 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1656 AlwaysInlineAttr::CreateImplicit(
1657 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001658 break;
1659 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00001660 case OMPD_taskloop:
1661 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00001662 QualType KmpInt32Ty =
1663 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1664 QualType KmpUInt64Ty =
1665 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
1666 QualType KmpInt64Ty =
1667 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
1668 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1669 FunctionProtoType::ExtProtoInfo EPI;
1670 EPI.Variadic = true;
1671 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00001672 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00001673 std::make_pair(".global_tid.", KmpInt32Ty),
1674 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1675 std::make_pair(".privates.",
1676 Context.VoidPtrTy.withConst().withRestrict()),
1677 std::make_pair(
1678 ".copy_fn.",
1679 Context.getPointerType(CopyFnType).withConst().withRestrict()),
1680 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1681 std::make_pair(".lb.", KmpUInt64Ty),
1682 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
1683 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataev49f6e782015-12-01 04:18:41 +00001684 std::make_pair(StringRef(), QualType()) // __context with shared vars
1685 };
1686 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1687 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00001688 // Mark this captured region as inlined, because we don't use outlined
1689 // function directly.
1690 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1691 AlwaysInlineAttr::CreateImplicit(
1692 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev49f6e782015-12-01 04:18:41 +00001693 break;
1694 }
Kelvin Li4a39add2016-07-05 05:00:15 +00001695 case OMPD_distribute_parallel_for_simd:
Kelvin Li787f3fc2016-07-06 04:45:38 +00001696 case OMPD_distribute_simd:
Kelvin Li02532872016-08-05 14:37:37 +00001697 case OMPD_distribute_parallel_for:
Kelvin Li4e325f72016-10-25 12:50:55 +00001698 case OMPD_teams_distribute:
Kelvin Li579e41c2016-11-30 23:51:03 +00001699 case OMPD_teams_distribute_simd:
Kelvin Li7ade93f2016-12-09 03:24:30 +00001700 case OMPD_teams_distribute_parallel_for_simd:
Kelvin Li83c451e2016-12-25 04:52:54 +00001701 case OMPD_teams_distribute_parallel_for:
Kelvin Li80e8f562016-12-29 22:16:30 +00001702 case OMPD_target_teams_distribute:
1703 case OMPD_target_teams_distribute_parallel_for: {
Carlo Bertolli9925f152016-06-27 14:55:37 +00001704 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1705 QualType KmpInt32PtrTy =
1706 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1707 Sema::CapturedParamNameType Params[] = {
1708 std::make_pair(".global_tid.", KmpInt32PtrTy),
1709 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1710 std::make_pair(".previous.lb.", Context.getSizeType()),
1711 std::make_pair(".previous.ub.", Context.getSizeType()),
1712 std::make_pair(StringRef(), QualType()) // __context with shared vars
1713 };
1714 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1715 Params);
1716 break;
1717 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001718 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001719 case OMPD_taskyield:
1720 case OMPD_barrier:
1721 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001722 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00001723 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00001724 case OMPD_flush:
Samuel Antaodf67fc42016-01-19 19:15:56 +00001725 case OMPD_target_enter_data:
Samuel Antao72590762016-01-19 20:04:50 +00001726 case OMPD_target_exit_data:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00001727 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00001728 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001729 case OMPD_declare_target:
1730 case OMPD_end_declare_target:
Samuel Antao686c70c2016-05-26 17:30:50 +00001731 case OMPD_target_update:
Alexey Bataev9959db52014-05-06 10:08:46 +00001732 llvm_unreachable("OpenMP Directive is not allowed");
1733 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001734 llvm_unreachable("Unknown OpenMP directive");
1735 }
1736}
1737
Alexey Bataev3392d762016-02-16 11:18:12 +00001738static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00001739 Expr *CaptureExpr, bool WithInit,
1740 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001741 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00001742 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00001743 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00001744 QualType Ty = Init->getType();
1745 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
1746 if (S.getLangOpts().CPlusPlus)
1747 Ty = C.getLValueReferenceType(Ty);
1748 else {
1749 Ty = C.getPointerType(Ty);
1750 ExprResult Res =
1751 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
1752 if (!Res.isUsable())
1753 return nullptr;
1754 Init = Res.get();
1755 }
Alexey Bataev61205072016-03-02 04:57:40 +00001756 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00001757 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00001758 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
1759 CaptureExpr->getLocStart());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001760 if (!WithInit)
1761 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
Alexey Bataev4244be22016-02-11 05:35:55 +00001762 S.CurContext->addHiddenDecl(CED);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001763 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false,
1764 /*TypeMayContainAuto=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00001765 return CED;
1766}
1767
Alexey Bataev61205072016-03-02 04:57:40 +00001768static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
1769 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00001770 OMPCapturedExprDecl *CD;
1771 if (auto *VD = S.IsOpenMPCapturedDecl(D))
1772 CD = cast<OMPCapturedExprDecl>(VD);
1773 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00001774 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
1775 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001776 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00001777 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00001778}
1779
Alexey Bataev5a3af132016-03-29 08:58:54 +00001780static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
1781 if (!Ref) {
1782 auto *CD =
1783 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
1784 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
1785 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
1786 CaptureExpr->getExprLoc());
1787 }
1788 ExprResult Res = Ref;
1789 if (!S.getLangOpts().CPlusPlus &&
1790 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
1791 Ref->getType()->isPointerType())
1792 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
1793 if (!Res.isUsable())
1794 return ExprError();
1795 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00001796}
1797
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001798StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1799 ArrayRef<OMPClause *> Clauses) {
1800 if (!S.isUsable()) {
1801 ActOnCapturedRegionError();
1802 return StmtError();
1803 }
Alexey Bataev993d2802015-12-28 06:23:08 +00001804
1805 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00001806 OMPScheduleClause *SC = nullptr;
Alexey Bataev993d2802015-12-28 06:23:08 +00001807 SmallVector<OMPLinearClause *, 4> LCs;
Alexey Bataev040d5402015-05-12 08:35:28 +00001808 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001809 for (auto *Clause : Clauses) {
Alexey Bataev16dc7b62015-05-20 03:46:04 +00001810 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001811 Clause->getClauseKind() == OMPC_copyprivate ||
1812 (getLangOpts().OpenMPUseTLS &&
1813 getASTContext().getTargetInfo().isTLSSupported() &&
1814 Clause->getClauseKind() == OMPC_copyin)) {
1815 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00001816 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001817 for (auto *VarRef : Clause->children()) {
1818 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00001819 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001820 }
1821 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001822 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001823 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
Alexey Bataev040d5402015-05-12 08:35:28 +00001824 // Mark all variables in private list clauses as used in inner region.
1825 // Required for proper codegen of combined directives.
1826 // TODO: add processing for other clauses.
Alexey Bataev3392d762016-02-16 11:18:12 +00001827 if (auto *C = OMPClauseWithPreInit::get(Clause)) {
Alexey Bataev005248a2016-02-25 05:25:57 +00001828 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
1829 for (auto *D : DS->decls())
Alexey Bataev3392d762016-02-16 11:18:12 +00001830 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
1831 }
Alexey Bataev4244be22016-02-11 05:35:55 +00001832 }
Alexey Bataev005248a2016-02-25 05:25:57 +00001833 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
1834 if (auto *E = C->getPostUpdateExpr())
1835 MarkDeclarationsReferencedInExpr(E);
1836 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001837 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001838 if (Clause->getClauseKind() == OMPC_schedule)
1839 SC = cast<OMPScheduleClause>(Clause);
1840 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00001841 OC = cast<OMPOrderedClause>(Clause);
1842 else if (Clause->getClauseKind() == OMPC_linear)
1843 LCs.push_back(cast<OMPLinearClause>(Clause));
1844 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001845 bool ErrorFound = false;
1846 // OpenMP, 2.7.1 Loop Construct, Restrictions
1847 // The nonmonotonic modifier cannot be specified if an ordered clause is
1848 // specified.
1849 if (SC &&
1850 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
1851 SC->getSecondScheduleModifier() ==
1852 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
1853 OC) {
1854 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
1855 ? SC->getFirstScheduleModifierLoc()
1856 : SC->getSecondScheduleModifierLoc(),
1857 diag::err_omp_schedule_nonmonotonic_ordered)
1858 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1859 ErrorFound = true;
1860 }
Alexey Bataev993d2802015-12-28 06:23:08 +00001861 if (!LCs.empty() && OC && OC->getNumForLoops()) {
1862 for (auto *C : LCs) {
1863 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
1864 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1865 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001866 ErrorFound = true;
1867 }
Alexey Bataev113438c2015-12-30 12:06:23 +00001868 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
1869 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
1870 OC->getNumForLoops()) {
1871 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
1872 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
1873 ErrorFound = true;
1874 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001875 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00001876 ActOnCapturedRegionError();
1877 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001878 }
1879 return ActOnCapturedRegionEnd(S.get());
1880}
1881
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001882static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1883 OpenMPDirectiveKind CurrentRegion,
1884 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001885 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001886 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001887 if (Stack->getCurScope()) {
1888 auto ParentRegion = Stack->getParentDirective();
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001889 auto OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00001890 bool NestingProhibited = false;
1891 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00001892 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001893 enum {
1894 NoRecommend,
1895 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00001896 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00001897 ShouldBeInTargetRegion,
1898 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001899 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00001900 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001901 // OpenMP [2.16, Nesting of Regions]
1902 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00001903 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00001904 // An ordered construct with the simd clause is the only OpenMP
1905 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00001906 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00001907 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
1908 // message.
1909 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
1910 ? diag::err_omp_prohibited_region_simd
1911 : diag::warn_omp_nesting_simd);
1912 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00001913 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001914 if (ParentRegion == OMPD_atomic) {
1915 // OpenMP [2.16, Nesting of Regions]
1916 // OpenMP constructs may not be nested inside an atomic region.
1917 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1918 return true;
1919 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001920 if (CurrentRegion == OMPD_section) {
1921 // OpenMP [2.7.2, sections Construct, Restrictions]
1922 // Orphaned section directives are prohibited. That is, the section
1923 // directives must appear within the sections construct and must not be
1924 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001925 if (ParentRegion != OMPD_sections &&
1926 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001927 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
1928 << (ParentRegion != OMPD_unknown)
1929 << getOpenMPDirectiveName(ParentRegion);
1930 return true;
1931 }
1932 return false;
1933 }
Kelvin Li2b51f722016-07-26 04:32:50 +00001934 // Allow some constructs (except teams) to be orphaned (they could be
David Majnemer9d168222016-08-05 17:44:54 +00001935 // used in functions, called from OpenMP regions with the required
Kelvin Li2b51f722016-07-26 04:32:50 +00001936 // preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00001937 if (ParentRegion == OMPD_unknown &&
1938 !isOpenMPNestingTeamsDirective(CurrentRegion))
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001939 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00001940 if (CurrentRegion == OMPD_cancellation_point ||
1941 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001942 // OpenMP [2.16, Nesting of Regions]
1943 // A cancellation point construct for which construct-type-clause is
1944 // taskgroup must be nested inside a task construct. A cancellation
1945 // point construct for which construct-type-clause is not taskgroup must
1946 // be closely nested inside an OpenMP construct that matches the type
1947 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00001948 // A cancel construct for which construct-type-clause is taskgroup must be
1949 // nested inside a task construct. A cancel construct for which
1950 // construct-type-clause is not taskgroup must be closely nested inside an
1951 // OpenMP construct that matches the type specified in
1952 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001953 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00001954 !((CancelRegion == OMPD_parallel &&
1955 (ParentRegion == OMPD_parallel ||
1956 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00001957 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00001958 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
1959 ParentRegion == OMPD_target_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001960 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
1961 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00001962 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
1963 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001964 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00001965 // OpenMP [2.16, Nesting of Regions]
1966 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001967 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00001968 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00001969 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001970 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
1971 // OpenMP [2.16, Nesting of Regions]
1972 // A critical region may not be nested (closely or otherwise) inside a
1973 // critical region with the same name. Note that this restriction is not
1974 // sufficient to prevent deadlock.
1975 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00001976 bool DeadLock = Stack->hasDirective(
1977 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
1978 const DeclarationNameInfo &DNI,
1979 SourceLocation Loc) -> bool {
1980 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
1981 PreviousCriticalLoc = Loc;
1982 return true;
1983 } else
1984 return false;
1985 },
1986 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001987 if (DeadLock) {
1988 SemaRef.Diag(StartLoc,
1989 diag::err_omp_prohibited_region_critical_same_name)
1990 << CurrentName.getName();
1991 if (PreviousCriticalLoc.isValid())
1992 SemaRef.Diag(PreviousCriticalLoc,
1993 diag::note_omp_previous_critical_region);
1994 return true;
1995 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001996 } else if (CurrentRegion == OMPD_barrier) {
1997 // OpenMP [2.16, Nesting of Regions]
1998 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001999 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002000 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2001 isOpenMPTaskingDirective(ParentRegion) ||
2002 ParentRegion == OMPD_master ||
2003 ParentRegion == OMPD_critical ||
2004 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00002005 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00002006 !isOpenMPParallelDirective(CurrentRegion) &&
2007 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002008 // OpenMP [2.16, Nesting of Regions]
2009 // A worksharing region may not be closely nested inside a worksharing,
2010 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002011 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2012 isOpenMPTaskingDirective(ParentRegion) ||
2013 ParentRegion == OMPD_master ||
2014 ParentRegion == OMPD_critical ||
2015 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002016 Recommend = ShouldBeInParallelRegion;
2017 } else if (CurrentRegion == OMPD_ordered) {
2018 // OpenMP [2.16, Nesting of Regions]
2019 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002020 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002021 // An ordered region must be closely nested inside a loop region (or
2022 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002023 // OpenMP [2.8.1,simd Construct, Restrictions]
2024 // An ordered construct with the simd clause is the only OpenMP construct
2025 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002026 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002027 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002028 !(isOpenMPSimdDirective(ParentRegion) ||
2029 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002030 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00002031 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002032 // OpenMP [2.16, Nesting of Regions]
2033 // If specified, a teams construct must be contained within a target
2034 // construct.
2035 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00002036 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002037 Recommend = ShouldBeInTargetRegion;
2038 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2039 }
Kelvin Libf594a52016-12-17 05:48:59 +00002040 if (!NestingProhibited &&
2041 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2042 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2043 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002044 // OpenMP [2.16, Nesting of Regions]
2045 // distribute, parallel, parallel sections, parallel workshare, and the
2046 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2047 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002048 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2049 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002050 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002051 }
David Majnemer9d168222016-08-05 17:44:54 +00002052 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00002053 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002054 // OpenMP 4.5 [2.17 Nesting of Regions]
2055 // The region associated with the distribute construct must be strictly
2056 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00002057 NestingProhibited =
2058 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002059 Recommend = ShouldBeInTeamsRegion;
2060 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002061 if (!NestingProhibited &&
2062 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2063 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2064 // OpenMP 4.5 [2.17 Nesting of Regions]
2065 // If a target, target update, target data, target enter data, or
2066 // target exit data construct is encountered during execution of a
2067 // target region, the behavior is unspecified.
2068 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002069 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2070 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002071 if (isOpenMPTargetExecutionDirective(K)) {
2072 OffendingRegion = K;
2073 return true;
2074 } else
2075 return false;
2076 },
2077 false /* don't skip top directive */);
2078 CloseNesting = false;
2079 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002080 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00002081 if (OrphanSeen) {
2082 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2083 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2084 } else {
2085 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2086 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2087 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2088 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002089 return true;
2090 }
2091 }
2092 return false;
2093}
2094
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002095static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2096 ArrayRef<OMPClause *> Clauses,
2097 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2098 bool ErrorFound = false;
2099 unsigned NamedModifiersNumber = 0;
2100 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2101 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002102 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002103 for (const auto *C : Clauses) {
2104 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2105 // At most one if clause without a directive-name-modifier can appear on
2106 // the directive.
2107 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2108 if (FoundNameModifiers[CurNM]) {
2109 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2110 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2111 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2112 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002113 } else if (CurNM != OMPD_unknown) {
2114 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002115 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002116 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002117 FoundNameModifiers[CurNM] = IC;
2118 if (CurNM == OMPD_unknown)
2119 continue;
2120 // Check if the specified name modifier is allowed for the current
2121 // directive.
2122 // At most one if clause with the particular directive-name-modifier can
2123 // appear on the directive.
2124 bool MatchFound = false;
2125 for (auto NM : AllowedNameModifiers) {
2126 if (CurNM == NM) {
2127 MatchFound = true;
2128 break;
2129 }
2130 }
2131 if (!MatchFound) {
2132 S.Diag(IC->getNameModifierLoc(),
2133 diag::err_omp_wrong_if_directive_name_modifier)
2134 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2135 ErrorFound = true;
2136 }
2137 }
2138 }
2139 // If any if clause on the directive includes a directive-name-modifier then
2140 // all if clauses on the directive must include a directive-name-modifier.
2141 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2142 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2143 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2144 diag::err_omp_no_more_if_clause);
2145 } else {
2146 std::string Values;
2147 std::string Sep(", ");
2148 unsigned AllowedCnt = 0;
2149 unsigned TotalAllowedNum =
2150 AllowedNameModifiers.size() - NamedModifiersNumber;
2151 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2152 ++Cnt) {
2153 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2154 if (!FoundNameModifiers[NM]) {
2155 Values += "'";
2156 Values += getOpenMPDirectiveName(NM);
2157 Values += "'";
2158 if (AllowedCnt + 2 == TotalAllowedNum)
2159 Values += " or ";
2160 else if (AllowedCnt + 1 != TotalAllowedNum)
2161 Values += Sep;
2162 ++AllowedCnt;
2163 }
2164 }
2165 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2166 diag::err_omp_unnamed_if_clause)
2167 << (TotalAllowedNum > 1) << Values;
2168 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002169 for (auto Loc : NameModifierLoc) {
2170 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2171 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002172 ErrorFound = true;
2173 }
2174 return ErrorFound;
2175}
2176
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002177StmtResult Sema::ActOnOpenMPExecutableDirective(
2178 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2179 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2180 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002181 StmtResult Res = StmtError();
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002182 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
2183 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002184 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002185
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002186 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002187 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002188 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002189 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00002190 if (AStmt) {
2191 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2192
2193 // Check default data sharing attributes for referenced variables.
2194 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
2195 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
2196 if (DSAChecker.isErrorFound())
2197 return StmtError();
2198 // Generate list of implicitly defined firstprivate variables.
2199 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00002200
2201 if (!DSAChecker.getImplicitFirstprivate().empty()) {
2202 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2203 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
2204 SourceLocation(), SourceLocation())) {
2205 ClausesWithImplicit.push_back(Implicit);
2206 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2207 DSAChecker.getImplicitFirstprivate().size();
2208 } else
2209 ErrorFound = true;
2210 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002211 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002212
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002213 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002214 switch (Kind) {
2215 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00002216 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2217 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002218 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002219 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002220 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002221 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2222 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002223 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002224 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002225 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2226 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002227 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00002228 case OMPD_for_simd:
2229 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2230 EndLoc, VarsWithInheritedDSA);
2231 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002232 case OMPD_sections:
2233 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2234 EndLoc);
2235 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002236 case OMPD_section:
2237 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00002238 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002239 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2240 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002241 case OMPD_single:
2242 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2243 EndLoc);
2244 break;
Alexander Musman80c22892014-07-17 08:54:58 +00002245 case OMPD_master:
2246 assert(ClausesWithImplicit.empty() &&
2247 "No clauses are allowed for 'omp master' directive");
2248 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2249 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002250 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00002251 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2252 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002253 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002254 case OMPD_parallel_for:
2255 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2256 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002257 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002258 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00002259 case OMPD_parallel_for_simd:
2260 Res = ActOnOpenMPParallelForSimdDirective(
2261 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002262 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002263 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002264 case OMPD_parallel_sections:
2265 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2266 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002267 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002268 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002269 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002270 Res =
2271 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002272 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002273 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00002274 case OMPD_taskyield:
2275 assert(ClausesWithImplicit.empty() &&
2276 "No clauses are allowed for 'omp taskyield' directive");
2277 assert(AStmt == nullptr &&
2278 "No associated statement allowed for 'omp taskyield' directive");
2279 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2280 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002281 case OMPD_barrier:
2282 assert(ClausesWithImplicit.empty() &&
2283 "No clauses are allowed for 'omp barrier' directive");
2284 assert(AStmt == nullptr &&
2285 "No associated statement allowed for 'omp barrier' directive");
2286 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2287 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00002288 case OMPD_taskwait:
2289 assert(ClausesWithImplicit.empty() &&
2290 "No clauses are allowed for 'omp taskwait' directive");
2291 assert(AStmt == nullptr &&
2292 "No associated statement allowed for 'omp taskwait' directive");
2293 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2294 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002295 case OMPD_taskgroup:
2296 assert(ClausesWithImplicit.empty() &&
2297 "No clauses are allowed for 'omp taskgroup' directive");
2298 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
2299 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00002300 case OMPD_flush:
2301 assert(AStmt == nullptr &&
2302 "No associated statement allowed for 'omp flush' directive");
2303 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2304 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002305 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00002306 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2307 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002308 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00002309 case OMPD_atomic:
2310 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2311 EndLoc);
2312 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002313 case OMPD_teams:
2314 Res =
2315 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2316 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002317 case OMPD_target:
2318 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2319 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002320 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002321 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002322 case OMPD_target_parallel:
2323 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2324 StartLoc, EndLoc);
2325 AllowedNameModifiers.push_back(OMPD_target);
2326 AllowedNameModifiers.push_back(OMPD_parallel);
2327 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002328 case OMPD_target_parallel_for:
2329 Res = ActOnOpenMPTargetParallelForDirective(
2330 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2331 AllowedNameModifiers.push_back(OMPD_target);
2332 AllowedNameModifiers.push_back(OMPD_parallel);
2333 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002334 case OMPD_cancellation_point:
2335 assert(ClausesWithImplicit.empty() &&
2336 "No clauses are allowed for 'omp cancellation point' directive");
2337 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2338 "cancellation point' directive");
2339 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2340 break;
Alexey Bataev80909872015-07-02 11:25:17 +00002341 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00002342 assert(AStmt == nullptr &&
2343 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00002344 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2345 CancelRegion);
2346 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00002347 break;
Michael Wong65f367f2015-07-21 13:44:28 +00002348 case OMPD_target_data:
2349 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2350 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002351 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00002352 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00002353 case OMPD_target_enter_data:
2354 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
2355 EndLoc);
2356 AllowedNameModifiers.push_back(OMPD_target_enter_data);
2357 break;
Samuel Antao72590762016-01-19 20:04:50 +00002358 case OMPD_target_exit_data:
2359 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
2360 EndLoc);
2361 AllowedNameModifiers.push_back(OMPD_target_exit_data);
2362 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00002363 case OMPD_taskloop:
2364 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
2365 EndLoc, VarsWithInheritedDSA);
2366 AllowedNameModifiers.push_back(OMPD_taskloop);
2367 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002368 case OMPD_taskloop_simd:
2369 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2370 EndLoc, VarsWithInheritedDSA);
2371 AllowedNameModifiers.push_back(OMPD_taskloop);
2372 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002373 case OMPD_distribute:
2374 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
2375 EndLoc, VarsWithInheritedDSA);
2376 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00002377 case OMPD_target_update:
2378 assert(!AStmt && "Statement is not allowed for target update");
2379 Res =
2380 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc);
2381 AllowedNameModifiers.push_back(OMPD_target_update);
2382 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00002383 case OMPD_distribute_parallel_for:
2384 Res = ActOnOpenMPDistributeParallelForDirective(
2385 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2386 AllowedNameModifiers.push_back(OMPD_parallel);
2387 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00002388 case OMPD_distribute_parallel_for_simd:
2389 Res = ActOnOpenMPDistributeParallelForSimdDirective(
2390 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2391 AllowedNameModifiers.push_back(OMPD_parallel);
2392 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00002393 case OMPD_distribute_simd:
2394 Res = ActOnOpenMPDistributeSimdDirective(
2395 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2396 break;
Kelvin Lia579b912016-07-14 02:54:56 +00002397 case OMPD_target_parallel_for_simd:
2398 Res = ActOnOpenMPTargetParallelForSimdDirective(
2399 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2400 AllowedNameModifiers.push_back(OMPD_target);
2401 AllowedNameModifiers.push_back(OMPD_parallel);
2402 break;
Kelvin Li986330c2016-07-20 22:57:10 +00002403 case OMPD_target_simd:
2404 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2405 EndLoc, VarsWithInheritedDSA);
2406 AllowedNameModifiers.push_back(OMPD_target);
2407 break;
Kelvin Li02532872016-08-05 14:37:37 +00002408 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00002409 Res = ActOnOpenMPTeamsDistributeDirective(
2410 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00002411 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00002412 case OMPD_teams_distribute_simd:
2413 Res = ActOnOpenMPTeamsDistributeSimdDirective(
2414 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2415 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00002416 case OMPD_teams_distribute_parallel_for_simd:
2417 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
2418 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2419 AllowedNameModifiers.push_back(OMPD_parallel);
2420 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00002421 case OMPD_teams_distribute_parallel_for:
2422 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
2423 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2424 AllowedNameModifiers.push_back(OMPD_parallel);
2425 break;
Kelvin Libf594a52016-12-17 05:48:59 +00002426 case OMPD_target_teams:
2427 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
2428 EndLoc);
2429 AllowedNameModifiers.push_back(OMPD_target);
2430 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00002431 case OMPD_target_teams_distribute:
2432 Res = ActOnOpenMPTargetTeamsDistributeDirective(
2433 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2434 AllowedNameModifiers.push_back(OMPD_target);
2435 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00002436 case OMPD_target_teams_distribute_parallel_for:
2437 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
2438 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2439 AllowedNameModifiers.push_back(OMPD_target);
2440 AllowedNameModifiers.push_back(OMPD_parallel);
2441 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002442 case OMPD_declare_target:
2443 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002444 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002445 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002446 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002447 llvm_unreachable("OpenMP Directive is not allowed");
2448 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002449 llvm_unreachable("Unknown OpenMP directive");
2450 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002451
Alexey Bataev4acb8592014-07-07 13:01:15 +00002452 for (auto P : VarsWithInheritedDSA) {
2453 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2454 << P.first << P.second->getSourceRange();
2455 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002456 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
2457
2458 if (!AllowedNameModifiers.empty())
2459 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
2460 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002461
Alexey Bataeved09d242014-05-28 05:53:51 +00002462 if (ErrorFound)
2463 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002464 return Res;
2465}
2466
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002467Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
2468 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00002469 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00002470 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
2471 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00002472 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00002473 assert(Linears.size() == LinModifiers.size());
2474 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00002475 if (!DG || DG.get().isNull())
2476 return DeclGroupPtrTy();
2477
2478 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00002479 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002480 return DG;
2481 }
2482 auto *ADecl = DG.get().getSingleDecl();
2483 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
2484 ADecl = FTD->getTemplatedDecl();
2485
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002486 auto *FD = dyn_cast<FunctionDecl>(ADecl);
2487 if (!FD) {
2488 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002489 return DeclGroupPtrTy();
2490 }
2491
Alexey Bataev2af33e32016-04-07 12:45:37 +00002492 // OpenMP [2.8.2, declare simd construct, Description]
2493 // The parameter of the simdlen clause must be a constant positive integer
2494 // expression.
2495 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002496 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00002497 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002498 // OpenMP [2.8.2, declare simd construct, Description]
2499 // The special this pointer can be used as if was one of the arguments to the
2500 // function in any of the linear, aligned, or uniform clauses.
2501 // The uniform clause declares one or more arguments to have an invariant
2502 // value for all concurrent invocations of the function in the execution of a
2503 // single SIMD loop.
Alexey Bataevecba70f2016-04-12 11:02:11 +00002504 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
2505 Expr *UniformedLinearThis = nullptr;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002506 for (auto *E : Uniforms) {
2507 E = E->IgnoreParenImpCasts();
2508 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2509 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
2510 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2511 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00002512 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
2513 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002514 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002515 }
2516 if (isa<CXXThisExpr>(E)) {
2517 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002518 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002519 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002520 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2521 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00002522 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00002523 // OpenMP [2.8.2, declare simd construct, Description]
2524 // The aligned clause declares that the object to which each list item points
2525 // is aligned to the number of bytes expressed in the optional parameter of
2526 // the aligned clause.
2527 // The special this pointer can be used as if was one of the arguments to the
2528 // function in any of the linear, aligned, or uniform clauses.
2529 // The type of list items appearing in the aligned clause must be array,
2530 // pointer, reference to array, or reference to pointer.
2531 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
2532 Expr *AlignedThis = nullptr;
2533 for (auto *E : Aligneds) {
2534 E = E->IgnoreParenImpCasts();
2535 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2536 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2537 auto *CanonPVD = PVD->getCanonicalDecl();
2538 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2539 FD->getParamDecl(PVD->getFunctionScopeIndex())
2540 ->getCanonicalDecl() == CanonPVD) {
2541 // OpenMP [2.8.1, simd construct, Restrictions]
2542 // A list-item cannot appear in more than one aligned clause.
2543 if (AlignedArgs.count(CanonPVD) > 0) {
2544 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2545 << 1 << E->getSourceRange();
2546 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
2547 diag::note_omp_explicit_dsa)
2548 << getOpenMPClauseName(OMPC_aligned);
2549 continue;
2550 }
2551 AlignedArgs[CanonPVD] = E;
2552 QualType QTy = PVD->getType()
2553 .getNonReferenceType()
2554 .getUnqualifiedType()
2555 .getCanonicalType();
2556 const Type *Ty = QTy.getTypePtrOrNull();
2557 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
2558 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
2559 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
2560 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
2561 }
2562 continue;
2563 }
2564 }
2565 if (isa<CXXThisExpr>(E)) {
2566 if (AlignedThis) {
2567 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2568 << 2 << E->getSourceRange();
2569 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
2570 << getOpenMPClauseName(OMPC_aligned);
2571 }
2572 AlignedThis = E;
2573 continue;
2574 }
2575 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2576 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2577 }
2578 // The optional parameter of the aligned clause, alignment, must be a constant
2579 // positive integer expression. If no optional parameter is specified,
2580 // implementation-defined default alignments for SIMD instructions on the
2581 // target platforms are assumed.
2582 SmallVector<Expr *, 4> NewAligns;
2583 for (auto *E : Alignments) {
2584 ExprResult Align;
2585 if (E)
2586 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
2587 NewAligns.push_back(Align.get());
2588 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00002589 // OpenMP [2.8.2, declare simd construct, Description]
2590 // The linear clause declares one or more list items to be private to a SIMD
2591 // lane and to have a linear relationship with respect to the iteration space
2592 // of a loop.
2593 // The special this pointer can be used as if was one of the arguments to the
2594 // function in any of the linear, aligned, or uniform clauses.
2595 // When a linear-step expression is specified in a linear clause it must be
2596 // either a constant integer expression or an integer-typed parameter that is
2597 // specified in a uniform clause on the directive.
2598 llvm::DenseMap<Decl *, Expr *> LinearArgs;
2599 const bool IsUniformedThis = UniformedLinearThis != nullptr;
2600 auto MI = LinModifiers.begin();
2601 for (auto *E : Linears) {
2602 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
2603 ++MI;
2604 E = E->IgnoreParenImpCasts();
2605 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2606 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2607 auto *CanonPVD = PVD->getCanonicalDecl();
2608 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2609 FD->getParamDecl(PVD->getFunctionScopeIndex())
2610 ->getCanonicalDecl() == CanonPVD) {
2611 // OpenMP [2.15.3.7, linear Clause, Restrictions]
2612 // A list-item cannot appear in more than one linear clause.
2613 if (LinearArgs.count(CanonPVD) > 0) {
2614 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2615 << getOpenMPClauseName(OMPC_linear)
2616 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
2617 Diag(LinearArgs[CanonPVD]->getExprLoc(),
2618 diag::note_omp_explicit_dsa)
2619 << getOpenMPClauseName(OMPC_linear);
2620 continue;
2621 }
2622 // Each argument can appear in at most one uniform or linear clause.
2623 if (UniformedArgs.count(CanonPVD) > 0) {
2624 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2625 << getOpenMPClauseName(OMPC_linear)
2626 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
2627 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
2628 diag::note_omp_explicit_dsa)
2629 << getOpenMPClauseName(OMPC_uniform);
2630 continue;
2631 }
2632 LinearArgs[CanonPVD] = E;
2633 if (E->isValueDependent() || E->isTypeDependent() ||
2634 E->isInstantiationDependent() ||
2635 E->containsUnexpandedParameterPack())
2636 continue;
2637 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
2638 PVD->getOriginalType());
2639 continue;
2640 }
2641 }
2642 if (isa<CXXThisExpr>(E)) {
2643 if (UniformedLinearThis) {
2644 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2645 << getOpenMPClauseName(OMPC_linear)
2646 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
2647 << E->getSourceRange();
2648 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
2649 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
2650 : OMPC_linear);
2651 continue;
2652 }
2653 UniformedLinearThis = E;
2654 if (E->isValueDependent() || E->isTypeDependent() ||
2655 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
2656 continue;
2657 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
2658 E->getType());
2659 continue;
2660 }
2661 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2662 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2663 }
2664 Expr *Step = nullptr;
2665 Expr *NewStep = nullptr;
2666 SmallVector<Expr *, 4> NewSteps;
2667 for (auto *E : Steps) {
2668 // Skip the same step expression, it was checked already.
2669 if (Step == E || !E) {
2670 NewSteps.push_back(E ? NewStep : nullptr);
2671 continue;
2672 }
2673 Step = E;
2674 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
2675 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2676 auto *CanonPVD = PVD->getCanonicalDecl();
2677 if (UniformedArgs.count(CanonPVD) == 0) {
2678 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
2679 << Step->getSourceRange();
2680 } else if (E->isValueDependent() || E->isTypeDependent() ||
2681 E->isInstantiationDependent() ||
2682 E->containsUnexpandedParameterPack() ||
2683 CanonPVD->getType()->hasIntegerRepresentation())
2684 NewSteps.push_back(Step);
2685 else {
2686 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
2687 << Step->getSourceRange();
2688 }
2689 continue;
2690 }
2691 NewStep = Step;
2692 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
2693 !Step->isInstantiationDependent() &&
2694 !Step->containsUnexpandedParameterPack()) {
2695 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
2696 .get();
2697 if (NewStep)
2698 NewStep = VerifyIntegerConstantExpression(NewStep).get();
2699 }
2700 NewSteps.push_back(NewStep);
2701 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002702 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
2703 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00002704 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00002705 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
2706 const_cast<Expr **>(Linears.data()), Linears.size(),
2707 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
2708 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002709 ADecl->addAttr(NewAttr);
2710 return ConvertDeclToDeclGroup(ADecl);
2711}
2712
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002713StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2714 Stmt *AStmt,
2715 SourceLocation StartLoc,
2716 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002717 if (!AStmt)
2718 return StmtError();
2719
Alexey Bataev9959db52014-05-06 10:08:46 +00002720 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2721 // 1.2.2 OpenMP Language Terminology
2722 // Structured block - An executable statement with a single entry at the
2723 // top and a single exit at the bottom.
2724 // The point of exit cannot be a branch out of the structured block.
2725 // longjmp() and throw() must not violate the entry/exit criteria.
2726 CS->getCapturedDecl()->setNothrow();
2727
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002728 getCurFunction()->setHasBranchProtectedScope();
2729
Alexey Bataev25e5b442015-09-15 12:52:43 +00002730 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
2731 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002732}
2733
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002734namespace {
2735/// \brief Helper class for checking canonical form of the OpenMP loops and
2736/// extracting iteration space of each loop in the loop nest, that will be used
2737/// for IR generation.
2738class OpenMPIterationSpaceChecker {
2739 /// \brief Reference to Sema.
2740 Sema &SemaRef;
2741 /// \brief A location for diagnostics (when there is no some better location).
2742 SourceLocation DefaultLoc;
2743 /// \brief A location for diagnostics (when increment is not compatible).
2744 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002745 /// \brief A source location for referring to loop init later.
2746 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002747 /// \brief A source location for referring to condition later.
2748 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002749 /// \brief A source location for referring to increment later.
2750 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002751 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002752 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002753 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002754 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002755 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002756 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002757 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002758 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002759 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002760 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002761 /// \brief This flag is true when condition is one of:
2762 /// Var < UB
2763 /// Var <= UB
2764 /// UB > Var
2765 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002766 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002767 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002768 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002769 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002770 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002771
2772public:
2773 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002774 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002775 /// \brief Check init-expr for canonical loop form and save loop counter
2776 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00002777 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002778 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2779 /// for less/greater and for strict/non-strict comparison.
2780 bool CheckCond(Expr *S);
2781 /// \brief Check incr-expr for canonical loop form and return true if it
2782 /// does not conform, otherwise save loop step (#Step).
2783 bool CheckInc(Expr *S);
2784 /// \brief Return the loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002785 ValueDecl *GetLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002786 /// \brief Return the reference expression to loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002787 Expr *GetLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002788 /// \brief Source range of the loop init.
2789 SourceRange GetInitSrcRange() const { return InitSrcRange; }
2790 /// \brief Source range of the loop condition.
2791 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2792 /// \brief Source range of the loop increment.
2793 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2794 /// \brief True if the step should be subtracted.
2795 bool ShouldSubtractStep() const { return SubtractStep; }
2796 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00002797 Expr *
2798 BuildNumIterations(Scope *S, const bool LimitedType,
2799 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00002800 /// \brief Build the precondition expression for the loops.
Alexey Bataev5a3af132016-03-29 08:58:54 +00002801 Expr *BuildPreCond(Scope *S, Expr *Cond,
2802 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002803 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002804 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
2805 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00002806 /// \brief Build reference expression to the private counter be used for
2807 /// codegen.
2808 Expr *BuildPrivateCounterVar() const;
David Majnemer9d168222016-08-05 17:44:54 +00002809 /// \brief Build initialization of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002810 Expr *BuildCounterInit() const;
2811 /// \brief Build step of the counter be used for codegen.
2812 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002813 /// \brief Return true if any expression is dependent.
2814 bool Dependent() const;
2815
2816private:
2817 /// \brief Check the right-hand side of an assignment in the increment
2818 /// expression.
2819 bool CheckIncRHS(Expr *RHS);
2820 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002821 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002822 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00002823 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00002824 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002825 /// \brief Helper to set loop increment.
2826 bool SetStep(Expr *NewStep, bool Subtract);
2827};
2828
2829bool OpenMPIterationSpaceChecker::Dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002830 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002831 assert(!LB && !UB && !Step);
2832 return false;
2833 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002834 return LCDecl->getType()->isDependentType() ||
2835 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
2836 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002837}
2838
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002839static Expr *getExprAsWritten(Expr *E) {
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002840 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
2841 E = ExprTemp->getSubExpr();
2842
2843 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2844 E = MTE->GetTemporaryExpr();
2845
2846 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
2847 E = Binder->getSubExpr();
2848
2849 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2850 E = ICE->getSubExprAsWritten();
2851 return E->IgnoreParens();
2852}
2853
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002854bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
2855 Expr *NewLCRefExpr,
2856 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002857 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002858 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002859 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002860 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002861 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002862 LCDecl = getCanonicalDecl(NewLCDecl);
2863 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002864 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
2865 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00002866 if ((Ctor->isCopyOrMoveConstructor() ||
2867 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2868 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002869 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002870 LB = NewLB;
2871 return false;
2872}
2873
2874bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00002875 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002876 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002877 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
2878 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002879 if (!NewUB)
2880 return true;
2881 UB = NewUB;
2882 TestIsLessOp = LessOp;
2883 TestIsStrictOp = StrictOp;
2884 ConditionSrcRange = SR;
2885 ConditionLoc = SL;
2886 return false;
2887}
2888
2889bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2890 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002891 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002892 if (!NewStep)
2893 return true;
2894 if (!NewStep->isValueDependent()) {
2895 // Check that the step is integer expression.
2896 SourceLocation StepLoc = NewStep->getLocStart();
2897 ExprResult Val =
2898 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2899 if (Val.isInvalid())
2900 return true;
2901 NewStep = Val.get();
2902
2903 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2904 // If test-expr is of form var relational-op b and relational-op is < or
2905 // <= then incr-expr must cause var to increase on each iteration of the
2906 // loop. If test-expr is of form var relational-op b and relational-op is
2907 // > or >= then incr-expr must cause var to decrease on each iteration of
2908 // the loop.
2909 // If test-expr is of form b relational-op var and relational-op is < or
2910 // <= then incr-expr must cause var to decrease on each iteration of the
2911 // loop. If test-expr is of form b relational-op var and relational-op is
2912 // > or >= then incr-expr must cause var to increase on each iteration of
2913 // the loop.
2914 llvm::APSInt Result;
2915 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
2916 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
2917 bool IsConstNeg =
2918 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002919 bool IsConstPos =
2920 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002921 bool IsConstZero = IsConstant && !Result.getBoolValue();
2922 if (UB && (IsConstZero ||
2923 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00002924 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002925 SemaRef.Diag(NewStep->getExprLoc(),
2926 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002927 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002928 SemaRef.Diag(ConditionLoc,
2929 diag::note_omp_loop_cond_requres_compatible_incr)
2930 << TestIsLessOp << ConditionSrcRange;
2931 return true;
2932 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002933 if (TestIsLessOp == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00002934 NewStep =
2935 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
2936 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00002937 Subtract = !Subtract;
2938 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002939 }
2940
2941 Step = NewStep;
2942 SubtractStep = Subtract;
2943 return false;
2944}
2945
Alexey Bataev9c821032015-04-30 04:23:23 +00002946bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002947 // Check init-expr for canonical loop form and save loop counter
2948 // variable - #Var and its initialization value - #LB.
2949 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
2950 // var = lb
2951 // integer-type var = lb
2952 // random-access-iterator-type var = lb
2953 // pointer-type var = lb
2954 //
2955 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00002956 if (EmitDiags) {
2957 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
2958 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002959 return true;
2960 }
Tim Shen4a05bb82016-06-21 20:29:17 +00002961 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
2962 if (!ExprTemp->cleanupsHaveSideEffects())
2963 S = ExprTemp->getSubExpr();
2964
Alexander Musmana5f070a2014-10-01 06:03:56 +00002965 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002966 if (Expr *E = dyn_cast<Expr>(S))
2967 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00002968 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002969 if (BO->getOpcode() == BO_Assign) {
2970 auto *LHS = BO->getLHS()->IgnoreParens();
2971 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
2972 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
2973 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
2974 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
2975 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
2976 }
2977 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
2978 if (ME->isArrow() &&
2979 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
2980 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
2981 }
2982 }
David Majnemer9d168222016-08-05 17:44:54 +00002983 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002984 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00002985 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00002986 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002987 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00002988 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002989 SemaRef.Diag(S->getLocStart(),
2990 diag::ext_omp_loop_not_canonical_init)
2991 << S->getSourceRange();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002992 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002993 }
2994 }
2995 }
David Majnemer9d168222016-08-05 17:44:54 +00002996 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002997 if (CE->getOperator() == OO_Equal) {
2998 auto *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00002999 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003000 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3001 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3002 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3003 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3004 }
3005 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3006 if (ME->isArrow() &&
3007 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3008 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3009 }
3010 }
3011 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003012
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003013 if (Dependent() || SemaRef.CurContext->isDependentContext())
3014 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00003015 if (EmitDiags) {
3016 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3017 << S->getSourceRange();
3018 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003019 return true;
3020}
3021
Alexey Bataev23b69422014-06-18 07:08:49 +00003022/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003023/// variable (which may be the loop variable) if possible.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003024static const ValueDecl *GetInitLCDecl(Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003025 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00003026 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003027 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003028 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3029 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003030 if ((Ctor->isCopyOrMoveConstructor() ||
3031 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3032 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003033 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003034 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
3035 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
3036 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
3037 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3038 return getCanonicalDecl(ME->getMemberDecl());
3039 return getCanonicalDecl(VD);
3040 }
3041 }
3042 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3043 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3044 return getCanonicalDecl(ME->getMemberDecl());
3045 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003046}
3047
3048bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3049 // Check test-expr for canonical form, save upper-bound UB, flags for
3050 // less/greater and for strict/non-strict comparison.
3051 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3052 // var relational-op b
3053 // b relational-op var
3054 //
3055 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003056 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003057 return true;
3058 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003059 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003060 SourceLocation CondLoc = S->getLocStart();
David Majnemer9d168222016-08-05 17:44:54 +00003061 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003062 if (BO->isRelationalOp()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003063 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003064 return SetUB(BO->getRHS(),
3065 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3066 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3067 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003068 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003069 return SetUB(BO->getLHS(),
3070 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3071 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3072 BO->getSourceRange(), BO->getOperatorLoc());
3073 }
David Majnemer9d168222016-08-05 17:44:54 +00003074 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003075 if (CE->getNumArgs() == 2) {
3076 auto Op = CE->getOperator();
3077 switch (Op) {
3078 case OO_Greater:
3079 case OO_GreaterEqual:
3080 case OO_Less:
3081 case OO_LessEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003082 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003083 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3084 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3085 CE->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003086 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003087 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3088 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3089 CE->getOperatorLoc());
3090 break;
3091 default:
3092 break;
3093 }
3094 }
3095 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003096 if (Dependent() || SemaRef.CurContext->isDependentContext())
3097 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003098 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003099 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003100 return true;
3101}
3102
3103bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3104 // RHS of canonical loop form increment can be:
3105 // var + incr
3106 // incr + var
3107 // var - incr
3108 //
3109 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00003110 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003111 if (BO->isAdditiveOp()) {
3112 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003113 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003114 return SetStep(BO->getRHS(), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003115 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003116 return SetStep(BO->getLHS(), false);
3117 }
David Majnemer9d168222016-08-05 17:44:54 +00003118 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003119 bool IsAdd = CE->getOperator() == OO_Plus;
3120 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003121 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003122 return SetStep(CE->getArg(1), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003123 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003124 return SetStep(CE->getArg(0), false);
3125 }
3126 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003127 if (Dependent() || SemaRef.CurContext->isDependentContext())
3128 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003129 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003130 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003131 return true;
3132}
3133
3134bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3135 // Check incr-expr for canonical loop form and return true if it
3136 // does not conform.
3137 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3138 // ++var
3139 // var++
3140 // --var
3141 // var--
3142 // var += incr
3143 // var -= incr
3144 // var = var + incr
3145 // var = incr + var
3146 // var = var - incr
3147 //
3148 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003149 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003150 return true;
3151 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003152 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3153 if (!ExprTemp->cleanupsHaveSideEffects())
3154 S = ExprTemp->getSubExpr();
3155
Alexander Musmana5f070a2014-10-01 06:03:56 +00003156 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003157 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003158 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003159 if (UO->isIncrementDecrementOp() &&
3160 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003161 return SetStep(SemaRef
3162 .ActOnIntegerConstant(UO->getLocStart(),
3163 (UO->isDecrementOp() ? -1 : 1))
3164 .get(),
3165 false);
3166 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003167 switch (BO->getOpcode()) {
3168 case BO_AddAssign:
3169 case BO_SubAssign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003170 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003171 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3172 break;
3173 case BO_Assign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003174 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003175 return CheckIncRHS(BO->getRHS());
3176 break;
3177 default:
3178 break;
3179 }
David Majnemer9d168222016-08-05 17:44:54 +00003180 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003181 switch (CE->getOperator()) {
3182 case OO_PlusPlus:
3183 case OO_MinusMinus:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003184 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003185 return SetStep(SemaRef
3186 .ActOnIntegerConstant(
3187 CE->getLocStart(),
3188 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3189 .get(),
3190 false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003191 break;
3192 case OO_PlusEqual:
3193 case OO_MinusEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003194 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003195 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3196 break;
3197 case OO_Equal:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003198 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003199 return CheckIncRHS(CE->getArg(1));
3200 break;
3201 default:
3202 break;
3203 }
3204 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003205 if (Dependent() || SemaRef.CurContext->isDependentContext())
3206 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003207 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003208 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003209 return true;
3210}
Alexander Musmana5f070a2014-10-01 06:03:56 +00003211
Alexey Bataev5a3af132016-03-29 08:58:54 +00003212static ExprResult
3213tryBuildCapture(Sema &SemaRef, Expr *Capture,
3214 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00003215 if (SemaRef.CurContext->isDependentContext())
3216 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003217 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3218 return SemaRef.PerformImplicitConversion(
3219 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3220 /*AllowExplicit=*/true);
3221 auto I = Captures.find(Capture);
3222 if (I != Captures.end())
3223 return buildCapture(SemaRef, Capture, I->second);
3224 DeclRefExpr *Ref = nullptr;
3225 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3226 Captures[Capture] = Ref;
3227 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003228}
3229
Alexander Musmana5f070a2014-10-01 06:03:56 +00003230/// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003231Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3232 Scope *S, const bool LimitedType,
3233 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003234 ExprResult Diff;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003235 auto VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003236 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003237 SemaRef.getLangOpts().CPlusPlus) {
3238 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003239 auto *UBExpr = TestIsLessOp ? UB : LB;
3240 auto *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00003241 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3242 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003243 if (!Upper || !Lower)
3244 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003245
3246 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3247
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003248 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003249 // BuildBinOp already emitted error, this one is to point user to upper
3250 // and lower bound, and to tell what is passed to 'operator-'.
3251 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3252 << Upper->getSourceRange() << Lower->getSourceRange();
3253 return nullptr;
3254 }
3255 }
3256
3257 if (!Diff.isUsable())
3258 return nullptr;
3259
3260 // Upper - Lower [- 1]
3261 if (TestIsStrictOp)
3262 Diff = SemaRef.BuildBinOp(
3263 S, DefaultLoc, BO_Sub, Diff.get(),
3264 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3265 if (!Diff.isUsable())
3266 return nullptr;
3267
3268 // Upper - Lower [- 1] + Step
Alexey Bataev5a3af132016-03-29 08:58:54 +00003269 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3270 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003271 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003272 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003273 if (!Diff.isUsable())
3274 return nullptr;
3275
3276 // Parentheses (for dumping/debugging purposes only).
3277 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3278 if (!Diff.isUsable())
3279 return nullptr;
3280
3281 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003282 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003283 if (!Diff.isUsable())
3284 return nullptr;
3285
Alexander Musman174b3ca2014-10-06 11:16:29 +00003286 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003287 QualType Type = Diff.get()->getType();
3288 auto &C = SemaRef.Context;
3289 bool UseVarType = VarType->hasIntegerRepresentation() &&
3290 C.getTypeSize(Type) > C.getTypeSize(VarType);
3291 if (!Type->isIntegerType() || UseVarType) {
3292 unsigned NewSize =
3293 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3294 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3295 : Type->hasSignedIntegerRepresentation();
3296 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00003297 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3298 Diff = SemaRef.PerformImplicitConversion(
3299 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3300 if (!Diff.isUsable())
3301 return nullptr;
3302 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003303 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003304 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00003305 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3306 if (NewSize != C.getTypeSize(Type)) {
3307 if (NewSize < C.getTypeSize(Type)) {
3308 assert(NewSize == 64 && "incorrect loop var size");
3309 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3310 << InitSrcRange << ConditionSrcRange;
3311 }
3312 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003313 NewSize, Type->hasSignedIntegerRepresentation() ||
3314 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00003315 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3316 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3317 Sema::AA_Converting, true);
3318 if (!Diff.isUsable())
3319 return nullptr;
3320 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003321 }
3322 }
3323
Alexander Musmana5f070a2014-10-01 06:03:56 +00003324 return Diff.get();
3325}
3326
Alexey Bataev5a3af132016-03-29 08:58:54 +00003327Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3328 Scope *S, Expr *Cond,
3329 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003330 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3331 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3332 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003333
Alexey Bataev5a3af132016-03-29 08:58:54 +00003334 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3335 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3336 if (!NewLB.isUsable() || !NewUB.isUsable())
3337 return nullptr;
3338
Alexey Bataev62dbb972015-04-22 11:59:37 +00003339 auto CondExpr = SemaRef.BuildBinOp(
3340 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3341 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003342 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003343 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003344 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
3345 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00003346 CondExpr = SemaRef.PerformImplicitConversion(
3347 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3348 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003349 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00003350 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3351 // Otherwise use original loop conditon and evaluate it in runtime.
3352 return CondExpr.isUsable() ? CondExpr.get() : Cond;
3353}
3354
Alexander Musmana5f070a2014-10-01 06:03:56 +00003355/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003356DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003357 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003358 auto *VD = dyn_cast<VarDecl>(LCDecl);
3359 if (!VD) {
3360 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
3361 auto *Ref = buildDeclRefExpr(
3362 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003363 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
3364 // If the loop control decl is explicitly marked as private, do not mark it
3365 // as captured again.
3366 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
3367 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003368 return Ref;
3369 }
3370 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00003371 DefaultLoc);
3372}
3373
3374Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003375 if (LCDecl && !LCDecl->isInvalidDecl()) {
3376 auto Type = LCDecl->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00003377 auto *PrivateVar =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003378 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
3379 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00003380 if (PrivateVar->isInvalidDecl())
3381 return nullptr;
3382 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3383 }
3384 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003385}
3386
Samuel Antao4c8035b2016-12-12 18:00:20 +00003387/// \brief Build initialization of the counter to be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003388Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3389
3390/// \brief Build step of the counter be used for codegen.
3391Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3392
3393/// \brief Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003394struct LoopIterationSpace final {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003395 /// \brief Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003396 Expr *PreCond = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003397 /// \brief This expression calculates the number of iterations in the loop.
3398 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003399 Expr *NumIterations = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003400 /// \brief The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003401 Expr *CounterVar = nullptr;
Alexey Bataeva8899172015-08-06 12:30:57 +00003402 /// \brief Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003403 Expr *PrivateCounterVar = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003404 /// \brief This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00003405 Expr *CounterInit = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003406 /// \brief This is step for the #CounterVar used to generate its update:
3407 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00003408 Expr *CounterStep = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003409 /// \brief Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00003410 bool Subtract = false;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003411 /// \brief Source range of the loop init.
3412 SourceRange InitSrcRange;
3413 /// \brief Source range of the loop condition.
3414 SourceRange CondSrcRange;
3415 /// \brief Source range of the loop increment.
3416 SourceRange IncSrcRange;
3417};
3418
Alexey Bataev23b69422014-06-18 07:08:49 +00003419} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003420
Alexey Bataev9c821032015-04-30 04:23:23 +00003421void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
3422 assert(getLangOpts().OpenMP && "OpenMP is not active.");
3423 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003424 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
3425 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00003426 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
3427 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003428 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
3429 if (auto *D = ISC.GetLoopDecl()) {
3430 auto *VD = dyn_cast<VarDecl>(D);
3431 if (!VD) {
3432 if (auto *Private = IsOpenMPCapturedDecl(D))
3433 VD = Private;
3434 else {
3435 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
3436 /*WithInit=*/false);
3437 VD = cast<VarDecl>(Ref->getDecl());
3438 }
3439 }
3440 DSAStack->addLoopControlVariable(D, VD);
3441 }
3442 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003443 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00003444 }
3445}
3446
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003447/// \brief Called on a for stmt to check and extract its iteration space
3448/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00003449static bool CheckOpenMPIterationSpace(
3450 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3451 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003452 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003453 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003454 LoopIterationSpace &ResultIterSpace,
3455 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003456 // OpenMP [2.6, Canonical Loop Form]
3457 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00003458 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003459 if (!For) {
3460 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003461 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
3462 << getOpenMPDirectiveName(DKind) << NestedLoopCount
3463 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
3464 if (NestedLoopCount > 1) {
3465 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
3466 SemaRef.Diag(DSA.getConstructLoc(),
3467 diag::note_omp_collapse_ordered_expr)
3468 << 2 << CollapseLoopCountExpr->getSourceRange()
3469 << OrderedLoopCountExpr->getSourceRange();
3470 else if (CollapseLoopCountExpr)
3471 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3472 diag::note_omp_collapse_ordered_expr)
3473 << 0 << CollapseLoopCountExpr->getSourceRange();
3474 else
3475 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3476 diag::note_omp_collapse_ordered_expr)
3477 << 1 << OrderedLoopCountExpr->getSourceRange();
3478 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003479 return true;
3480 }
3481 assert(For->getBody());
3482
3483 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3484
3485 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003486 auto Init = For->getInit();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003487 if (ISC.CheckInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003488 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003489
3490 bool HasErrors = false;
3491
3492 // Check loop variable's type.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003493 if (auto *LCDecl = ISC.GetLoopDecl()) {
3494 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003495
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003496 // OpenMP [2.6, Canonical Loop Form]
3497 // Var is one of the following:
3498 // A variable of signed or unsigned integer type.
3499 // For C++, a variable of a random access iterator type.
3500 // For C, a variable of a pointer type.
3501 auto VarType = LCDecl->getType().getNonReferenceType();
3502 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
3503 !VarType->isPointerType() &&
3504 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
3505 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
3506 << SemaRef.getLangOpts().CPlusPlus;
3507 HasErrors = true;
3508 }
3509
3510 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
3511 // a Construct
3512 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3513 // parallel for construct is (are) private.
3514 // The loop iteration variable in the associated for-loop of a simd
3515 // construct with just one associated for-loop is linear with a
3516 // constant-linear-step that is the increment of the associated for-loop.
3517 // Exclude loop var from the list of variables with implicitly defined data
3518 // sharing attributes.
3519 VarsWithImplicitDSA.erase(LCDecl);
3520
3521 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
3522 // in a Construct, C/C++].
3523 // The loop iteration variable in the associated for-loop of a simd
3524 // construct with just one associated for-loop may be listed in a linear
3525 // clause with a constant-linear-step that is the increment of the
3526 // associated for-loop.
3527 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3528 // parallel for construct may be listed in a private or lastprivate clause.
3529 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
3530 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
3531 // declared in the loop and it is predetermined as a private.
3532 auto PredeterminedCKind =
3533 isOpenMPSimdDirective(DKind)
3534 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
3535 : OMPC_private;
3536 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3537 DVar.CKind != PredeterminedCKind) ||
3538 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
3539 isOpenMPDistributeDirective(DKind)) &&
3540 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3541 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
3542 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
3543 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
3544 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
3545 << getOpenMPClauseName(PredeterminedCKind);
3546 if (DVar.RefExpr == nullptr)
3547 DVar.CKind = PredeterminedCKind;
3548 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
3549 HasErrors = true;
3550 } else if (LoopDeclRefExpr != nullptr) {
3551 // Make the loop iteration variable private (for worksharing constructs),
3552 // linear (for simd directives with the only one associated loop) or
3553 // lastprivate (for simd directives with several collapsed or ordered
3554 // loops).
3555 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003556 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
3557 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003558 /*FromParent=*/false);
3559 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
3560 }
3561
3562 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
3563
3564 // Check test-expr.
3565 HasErrors |= ISC.CheckCond(For->getCond());
3566
3567 // Check incr-expr.
3568 HasErrors |= ISC.CheckInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003569 }
3570
Alexander Musmana5f070a2014-10-01 06:03:56 +00003571 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003572 return HasErrors;
3573
Alexander Musmana5f070a2014-10-01 06:03:56 +00003574 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003575 ResultIterSpace.PreCond =
3576 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexander Musman174b3ca2014-10-06 11:16:29 +00003577 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00003578 DSA.getCurScope(),
3579 (isOpenMPWorksharingDirective(DKind) ||
3580 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
3581 Captures);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003582 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
Alexey Bataeva8899172015-08-06 12:30:57 +00003583 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003584 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
3585 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
3586 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
3587 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
3588 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
3589 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
3590
Alexey Bataev62dbb972015-04-22 11:59:37 +00003591 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
3592 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003593 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00003594 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003595 ResultIterSpace.CounterInit == nullptr ||
3596 ResultIterSpace.CounterStep == nullptr);
3597
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003598 return HasErrors;
3599}
3600
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003601/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003602static ExprResult
3603BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
3604 ExprResult Start,
3605 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003606 // Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003607 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
3608 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003609 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00003610 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00003611 VarRef.get()->getType())) {
3612 NewStart = SemaRef.PerformImplicitConversion(
3613 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
3614 /*AllowExplicit=*/true);
3615 if (!NewStart.isUsable())
3616 return ExprError();
3617 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003618
3619 auto Init =
3620 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3621 return Init;
3622}
3623
Alexander Musmana5f070a2014-10-01 06:03:56 +00003624/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003625static ExprResult
3626BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
3627 ExprResult VarRef, ExprResult Start, ExprResult Iter,
3628 ExprResult Step, bool Subtract,
3629 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003630 // Add parentheses (for debugging purposes only).
3631 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
3632 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
3633 !Step.isUsable())
3634 return ExprError();
3635
Alexey Bataev5a3af132016-03-29 08:58:54 +00003636 ExprResult NewStep = Step;
3637 if (Captures)
3638 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003639 if (NewStep.isInvalid())
3640 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003641 ExprResult Update =
3642 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003643 if (!Update.isUsable())
3644 return ExprError();
3645
Alexey Bataevc0214e02016-02-16 12:13:49 +00003646 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
3647 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003648 ExprResult NewStart = Start;
3649 if (Captures)
3650 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003651 if (NewStart.isInvalid())
3652 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003653
Alexey Bataevc0214e02016-02-16 12:13:49 +00003654 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
3655 ExprResult SavedUpdate = Update;
3656 ExprResult UpdateVal;
3657 if (VarRef.get()->getType()->isOverloadableType() ||
3658 NewStart.get()->getType()->isOverloadableType() ||
3659 Update.get()->getType()->isOverloadableType()) {
3660 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3661 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3662 Update =
3663 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3664 if (Update.isUsable()) {
3665 UpdateVal =
3666 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
3667 VarRef.get(), SavedUpdate.get());
3668 if (UpdateVal.isUsable()) {
3669 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
3670 UpdateVal.get());
3671 }
3672 }
3673 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3674 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003675
Alexey Bataevc0214e02016-02-16 12:13:49 +00003676 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
3677 if (!Update.isUsable() || !UpdateVal.isUsable()) {
3678 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
3679 NewStart.get(), SavedUpdate.get());
3680 if (!Update.isUsable())
3681 return ExprError();
3682
Alexey Bataev11481f52016-02-17 10:29:05 +00003683 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
3684 VarRef.get()->getType())) {
3685 Update = SemaRef.PerformImplicitConversion(
3686 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
3687 if (!Update.isUsable())
3688 return ExprError();
3689 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00003690
3691 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
3692 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003693 return Update;
3694}
3695
3696/// \brief Convert integer expression \a E to make it have at least \a Bits
3697/// bits.
David Majnemer9d168222016-08-05 17:44:54 +00003698static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003699 if (E == nullptr)
3700 return ExprError();
3701 auto &C = SemaRef.Context;
3702 QualType OldType = E->getType();
3703 unsigned HasBits = C.getTypeSize(OldType);
3704 if (HasBits >= Bits)
3705 return ExprResult(E);
3706 // OK to convert to signed, because new type has more bits than old.
3707 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
3708 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
3709 true);
3710}
3711
3712/// \brief Check if the given expression \a E is a constant integer that fits
3713/// into \a Bits bits.
3714static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
3715 if (E == nullptr)
3716 return false;
3717 llvm::APSInt Result;
3718 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
3719 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
3720 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003721}
3722
Alexey Bataev5a3af132016-03-29 08:58:54 +00003723/// Build preinits statement for the given declarations.
3724static Stmt *buildPreInits(ASTContext &Context,
3725 SmallVectorImpl<Decl *> &PreInits) {
3726 if (!PreInits.empty()) {
3727 return new (Context) DeclStmt(
3728 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
3729 SourceLocation(), SourceLocation());
3730 }
3731 return nullptr;
3732}
3733
3734/// Build preinits statement for the given declarations.
3735static Stmt *buildPreInits(ASTContext &Context,
3736 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3737 if (!Captures.empty()) {
3738 SmallVector<Decl *, 16> PreInits;
3739 for (auto &Pair : Captures)
3740 PreInits.push_back(Pair.second->getDecl());
3741 return buildPreInits(Context, PreInits);
3742 }
3743 return nullptr;
3744}
3745
3746/// Build postupdate expression for the given list of postupdates expressions.
3747static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
3748 Expr *PostUpdate = nullptr;
3749 if (!PostUpdates.empty()) {
3750 for (auto *E : PostUpdates) {
3751 Expr *ConvE = S.BuildCStyleCastExpr(
3752 E->getExprLoc(),
3753 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
3754 E->getExprLoc(), E)
3755 .get();
3756 PostUpdate = PostUpdate
3757 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
3758 PostUpdate, ConvE)
3759 .get()
3760 : ConvE;
3761 }
3762 }
3763 return PostUpdate;
3764}
3765
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003766/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00003767/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
3768/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003769static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00003770CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
3771 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
3772 DSAStackTy &DSA,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003773 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00003774 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003775 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003776 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003777 // Found 'collapse' clause - calculate collapse number.
3778 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003779 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003780 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00003781 }
3782 if (OrderedLoopCountExpr) {
3783 // Found 'ordered' clause - calculate collapse number.
3784 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003785 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
3786 if (Result.getLimitedValue() < NestedLoopCount) {
3787 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3788 diag::err_omp_wrong_ordered_loop_count)
3789 << OrderedLoopCountExpr->getSourceRange();
3790 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3791 diag::note_collapse_loop_count)
3792 << CollapseLoopCountExpr->getSourceRange();
3793 }
3794 NestedLoopCount = Result.getLimitedValue();
3795 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003796 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003797 // This is helper routine for loop directives (e.g., 'for', 'simd',
3798 // 'for simd', etc.).
Alexey Bataev5a3af132016-03-29 08:58:54 +00003799 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003800 SmallVector<LoopIterationSpace, 4> IterSpaces;
3801 IterSpaces.resize(NestedLoopCount);
3802 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003803 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003804 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003805 NestedLoopCount, CollapseLoopCountExpr,
3806 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003807 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00003808 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003809 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003810 // OpenMP [2.8.1, simd construct, Restrictions]
3811 // All loops associated with the construct must be perfectly nested; that
3812 // is, there must be no intervening code nor any OpenMP directive between
3813 // any two loops.
3814 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003815 }
3816
Alexander Musmana5f070a2014-10-01 06:03:56 +00003817 Built.clear(/* size */ NestedLoopCount);
3818
3819 if (SemaRef.CurContext->isDependentContext())
3820 return NestedLoopCount;
3821
3822 // An example of what is generated for the following code:
3823 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00003824 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00003825 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003826 // for (k = 0; k < NK; ++k)
3827 // for (j = J0; j < NJ; j+=2) {
3828 // <loop body>
3829 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003830 //
3831 // We generate the code below.
3832 // Note: the loop body may be outlined in CodeGen.
3833 // Note: some counters may be C++ classes, operator- is used to find number of
3834 // iterations and operator+= to calculate counter value.
3835 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
3836 // or i64 is currently supported).
3837 //
3838 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
3839 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
3840 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
3841 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
3842 // // similar updates for vars in clauses (e.g. 'linear')
3843 // <loop body (using local i and j)>
3844 // }
3845 // i = NI; // assign final values of counters
3846 // j = NJ;
3847 //
3848
3849 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
3850 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00003851 // Precondition tests if there is at least one iteration (all conditions are
3852 // true).
3853 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003854 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003855 ExprResult LastIteration32 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00003856 32 /* Bits */, SemaRef
3857 .PerformImplicitConversion(
3858 N0->IgnoreImpCasts(), N0->getType(),
3859 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003860 .get(),
3861 SemaRef);
3862 ExprResult LastIteration64 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00003863 64 /* Bits */, SemaRef
3864 .PerformImplicitConversion(
3865 N0->IgnoreImpCasts(), N0->getType(),
3866 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003867 .get(),
3868 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003869
3870 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
3871 return NestedLoopCount;
3872
3873 auto &C = SemaRef.Context;
3874 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
3875
3876 Scope *CurScope = DSA.getCurScope();
3877 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003878 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00003879 PreCond =
3880 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
3881 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00003882 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003883 auto N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00003884 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003885 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
3886 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003887 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00003888 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00003889 SemaRef
3890 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3891 Sema::AA_Converting,
3892 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003893 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003894 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003895 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00003896 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00003897 SemaRef
3898 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3899 Sema::AA_Converting,
3900 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003901 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003902 }
3903
3904 // Choose either the 32-bit or 64-bit version.
3905 ExprResult LastIteration = LastIteration64;
3906 if (LastIteration32.isUsable() &&
3907 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
3908 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
3909 FitsInto(
3910 32 /* Bits */,
3911 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
3912 LastIteration64.get(), SemaRef)))
3913 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00003914 QualType VType = LastIteration.get()->getType();
3915 QualType RealVType = VType;
3916 QualType StrideVType = VType;
3917 if (isOpenMPTaskLoopDirective(DKind)) {
3918 VType =
3919 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3920 StrideVType =
3921 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3922 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003923
3924 if (!LastIteration.isUsable())
3925 return 0;
3926
3927 // Save the number of iterations.
3928 ExprResult NumIterations = LastIteration;
3929 {
3930 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00003931 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
3932 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00003933 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3934 if (!LastIteration.isUsable())
3935 return 0;
3936 }
3937
3938 // Calculate the last iteration number beforehand instead of doing this on
3939 // each iteration. Do not do this if the number of iterations may be kfold-ed.
3940 llvm::APSInt Result;
3941 bool IsConstant =
3942 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
3943 ExprResult CalcLastIteration;
3944 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003945 ExprResult SaveRef =
3946 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003947 LastIteration = SaveRef;
3948
3949 // Prepare SaveRef + 1.
3950 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00003951 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00003952 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3953 if (!NumIterations.isUsable())
3954 return 0;
3955 }
3956
3957 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
3958
David Majnemer9d168222016-08-05 17:44:54 +00003959 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolli9925f152016-06-27 14:55:37 +00003960 ExprResult LB, UB, IL, ST, EUB, PrevLB, PrevUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003961 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
3962 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003963 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00003964 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
3965 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003966 SemaRef.AddInitializerToDecl(
3967 LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3968 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3969
3970 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00003971 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
3972 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003973 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
3974 /*DirectInit*/ false,
3975 /*TypeMayContainAuto*/ false);
3976
3977 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
3978 // This will be used to implement clause 'lastprivate'.
3979 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00003980 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
3981 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003982 SemaRef.AddInitializerToDecl(
3983 ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3984 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3985
3986 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00003987 VarDecl *STDecl =
3988 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
3989 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003990 SemaRef.AddInitializerToDecl(
3991 STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
3992 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3993
3994 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00003995 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00003996 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
3997 UB.get(), LastIteration.get());
3998 ExprResult CondOp = SemaRef.ActOnConditionalOp(
3999 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4000 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4001 CondOp.get());
4002 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
Carlo Bertolli9925f152016-06-27 14:55:37 +00004003
4004 // If we have a combined directive that combines 'distribute', 'for' or
4005 // 'simd' we need to be able to access the bounds of the schedule of the
4006 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4007 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4008 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4009 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
4010
4011 // We expect to have at least 2 more parameters than the 'parallel'
4012 // directive does - the lower and upper bounds of the previous schedule.
4013 assert(CD->getNumParams() >= 4 &&
4014 "Unexpected number of parameters in loop combined directive");
4015
4016 // Set the proper type for the bounds given what we learned from the
4017 // enclosed loops.
4018 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4019 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4020
4021 // Previous lower and upper bounds are obtained from the region
4022 // parameters.
4023 PrevLB =
4024 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4025 PrevUB =
4026 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4027 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004028 }
4029
4030 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004031 ExprResult IV;
4032 ExprResult Init;
4033 {
Alexey Bataev7292c292016-04-25 12:22:29 +00004034 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4035 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00004036 Expr *RHS =
4037 (isOpenMPWorksharingDirective(DKind) ||
4038 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4039 ? LB.get()
4040 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004041 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4042 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004043 }
4044
Alexander Musmanc6388682014-12-15 07:07:06 +00004045 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004046 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00004047 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004048 (isOpenMPWorksharingDirective(DKind) ||
4049 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004050 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4051 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4052 NumIterations.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004053
4054 // Loop increment (IV = IV + 1)
4055 SourceLocation IncLoc;
4056 ExprResult Inc =
4057 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4058 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4059 if (!Inc.isUsable())
4060 return 0;
4061 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00004062 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4063 if (!Inc.isUsable())
4064 return 0;
4065
4066 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4067 // Used for directives with static scheduling.
4068 ExprResult NextLB, NextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004069 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4070 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004071 // LB + ST
4072 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4073 if (!NextLB.isUsable())
4074 return 0;
4075 // LB = LB + ST
4076 NextLB =
4077 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4078 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4079 if (!NextLB.isUsable())
4080 return 0;
4081 // UB + ST
4082 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4083 if (!NextUB.isUsable())
4084 return 0;
4085 // UB = UB + ST
4086 NextUB =
4087 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4088 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4089 if (!NextUB.isUsable())
4090 return 0;
4091 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004092
4093 // Build updates and final values of the loop counters.
4094 bool HasErrors = false;
4095 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004096 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004097 Built.Updates.resize(NestedLoopCount);
4098 Built.Finals.resize(NestedLoopCount);
Alexey Bataev8b427062016-05-25 12:36:08 +00004099 SmallVector<Expr *, 4> LoopMultipliers;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004100 {
4101 ExprResult Div;
4102 // Go from inner nested loop to outer.
4103 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4104 LoopIterationSpace &IS = IterSpaces[Cnt];
4105 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4106 // Build: Iter = (IV / Div) % IS.NumIters
4107 // where Div is product of previous iterations' IS.NumIters.
4108 ExprResult Iter;
4109 if (Div.isUsable()) {
4110 Iter =
4111 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4112 } else {
4113 Iter = IV;
4114 assert((Cnt == (int)NestedLoopCount - 1) &&
4115 "unusable div expected on first iteration only");
4116 }
4117
4118 if (Cnt != 0 && Iter.isUsable())
4119 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4120 IS.NumIterations);
4121 if (!Iter.isUsable()) {
4122 HasErrors = true;
4123 break;
4124 }
4125
Alexey Bataev39f915b82015-05-08 10:41:21 +00004126 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004127 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4128 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4129 IS.CounterVar->getExprLoc(),
4130 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004131 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004132 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004133 if (!Init.isUsable()) {
4134 HasErrors = true;
4135 break;
4136 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00004137 ExprResult Update = BuildCounterUpdate(
4138 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4139 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004140 if (!Update.isUsable()) {
4141 HasErrors = true;
4142 break;
4143 }
4144
4145 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4146 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00004147 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004148 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004149 if (!Final.isUsable()) {
4150 HasErrors = true;
4151 break;
4152 }
4153
4154 // Build Div for the next iteration: Div <- Div * IS.NumIters
4155 if (Cnt != 0) {
4156 if (Div.isUnset())
4157 Div = IS.NumIterations;
4158 else
4159 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4160 IS.NumIterations);
4161
4162 // Add parentheses (for debugging purposes only).
4163 if (Div.isUsable())
Alexey Bataev8b427062016-05-25 12:36:08 +00004164 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004165 if (!Div.isUsable()) {
4166 HasErrors = true;
4167 break;
4168 }
Alexey Bataev8b427062016-05-25 12:36:08 +00004169 LoopMultipliers.push_back(Div.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004170 }
4171 if (!Update.isUsable() || !Final.isUsable()) {
4172 HasErrors = true;
4173 break;
4174 }
4175 // Save results
4176 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00004177 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004178 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004179 Built.Updates[Cnt] = Update.get();
4180 Built.Finals[Cnt] = Final.get();
4181 }
4182 }
4183
4184 if (HasErrors)
4185 return 0;
4186
4187 // Save results
4188 Built.IterationVarRef = IV.get();
4189 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00004190 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004191 Built.CalcLastIteration =
4192 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004193 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00004194 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004195 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004196 Built.Init = Init.get();
4197 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004198 Built.LB = LB.get();
4199 Built.UB = UB.get();
4200 Built.IL = IL.get();
4201 Built.ST = ST.get();
4202 Built.EUB = EUB.get();
4203 Built.NLB = NextLB.get();
4204 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004205 Built.PrevLB = PrevLB.get();
4206 Built.PrevUB = PrevUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004207
Alexey Bataev8b427062016-05-25 12:36:08 +00004208 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4209 // Fill data for doacross depend clauses.
4210 for (auto Pair : DSA.getDoacrossDependClauses()) {
4211 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4212 Pair.first->setCounterValue(CounterVal);
4213 else {
4214 if (NestedLoopCount != Pair.second.size() ||
4215 NestedLoopCount != LoopMultipliers.size() + 1) {
4216 // Erroneous case - clause has some problems.
4217 Pair.first->setCounterValue(CounterVal);
4218 continue;
4219 }
4220 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4221 auto I = Pair.second.rbegin();
4222 auto IS = IterSpaces.rbegin();
4223 auto ILM = LoopMultipliers.rbegin();
4224 Expr *UpCounterVal = CounterVal;
4225 Expr *Multiplier = nullptr;
4226 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4227 if (I->first) {
4228 assert(IS->CounterStep);
4229 Expr *NormalizedOffset =
4230 SemaRef
4231 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4232 I->first, IS->CounterStep)
4233 .get();
4234 if (Multiplier) {
4235 NormalizedOffset =
4236 SemaRef
4237 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
4238 NormalizedOffset, Multiplier)
4239 .get();
4240 }
4241 assert(I->second == OO_Plus || I->second == OO_Minus);
4242 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
David Majnemer9d168222016-08-05 17:44:54 +00004243 UpCounterVal = SemaRef
4244 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
4245 UpCounterVal, NormalizedOffset)
4246 .get();
Alexey Bataev8b427062016-05-25 12:36:08 +00004247 }
4248 Multiplier = *ILM;
4249 ++I;
4250 ++IS;
4251 ++ILM;
4252 }
4253 Pair.first->setCounterValue(UpCounterVal);
4254 }
4255 }
4256
Alexey Bataevabfc0692014-06-25 06:52:00 +00004257 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004258}
4259
Alexey Bataev10e775f2015-07-30 11:36:16 +00004260static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004261 auto CollapseClauses =
4262 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4263 if (CollapseClauses.begin() != CollapseClauses.end())
4264 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004265 return nullptr;
4266}
4267
Alexey Bataev10e775f2015-07-30 11:36:16 +00004268static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004269 auto OrderedClauses =
4270 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4271 if (OrderedClauses.begin() != OrderedClauses.end())
4272 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004273 return nullptr;
4274}
4275
Kelvin Lic5609492016-07-15 04:39:07 +00004276static bool checkSimdlenSafelenSpecified(Sema &S,
4277 const ArrayRef<OMPClause *> Clauses) {
4278 OMPSafelenClause *Safelen = nullptr;
4279 OMPSimdlenClause *Simdlen = nullptr;
4280
4281 for (auto *Clause : Clauses) {
4282 if (Clause->getClauseKind() == OMPC_safelen)
4283 Safelen = cast<OMPSafelenClause>(Clause);
4284 else if (Clause->getClauseKind() == OMPC_simdlen)
4285 Simdlen = cast<OMPSimdlenClause>(Clause);
4286 if (Safelen && Simdlen)
4287 break;
4288 }
4289
4290 if (Simdlen && Safelen) {
4291 llvm::APSInt SimdlenRes, SafelenRes;
4292 auto SimdlenLength = Simdlen->getSimdlen();
4293 auto SafelenLength = Safelen->getSafelen();
4294 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
4295 SimdlenLength->isInstantiationDependent() ||
4296 SimdlenLength->containsUnexpandedParameterPack())
4297 return false;
4298 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
4299 SafelenLength->isInstantiationDependent() ||
4300 SafelenLength->containsUnexpandedParameterPack())
4301 return false;
4302 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
4303 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
4304 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
4305 // If both simdlen and safelen clauses are specified, the value of the
4306 // simdlen parameter must be less than or equal to the value of the safelen
4307 // parameter.
4308 if (SimdlenRes > SafelenRes) {
4309 S.Diag(SimdlenLength->getExprLoc(),
4310 diag::err_omp_wrong_simdlen_safelen_values)
4311 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
4312 return true;
4313 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00004314 }
4315 return false;
4316}
4317
Alexey Bataev4acb8592014-07-07 13:01:15 +00004318StmtResult Sema::ActOnOpenMPSimdDirective(
4319 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4320 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004321 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004322 if (!AStmt)
4323 return StmtError();
4324
4325 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004326 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004327 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4328 // define the nested loops number.
4329 unsigned NestedLoopCount = CheckOpenMPLoop(
4330 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4331 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004332 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004333 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004334
Alexander Musmana5f070a2014-10-01 06:03:56 +00004335 assert((CurContext->isDependentContext() || B.builtAll()) &&
4336 "omp simd loop exprs were not built");
4337
Alexander Musman3276a272015-03-21 10:12:56 +00004338 if (!CurContext->isDependentContext()) {
4339 // Finalize the clauses that need pre-built expressions for CodeGen.
4340 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004341 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00004342 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004343 B.NumIterations, *this, CurScope,
4344 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00004345 return StmtError();
4346 }
4347 }
4348
Kelvin Lic5609492016-07-15 04:39:07 +00004349 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004350 return StmtError();
4351
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004352 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004353 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4354 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004355}
4356
Alexey Bataev4acb8592014-07-07 13:01:15 +00004357StmtResult Sema::ActOnOpenMPForDirective(
4358 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4359 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004360 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004361 if (!AStmt)
4362 return StmtError();
4363
4364 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004365 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004366 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4367 // define the nested loops number.
4368 unsigned NestedLoopCount = CheckOpenMPLoop(
4369 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4370 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004371 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00004372 return StmtError();
4373
Alexander Musmana5f070a2014-10-01 06:03:56 +00004374 assert((CurContext->isDependentContext() || B.builtAll()) &&
4375 "omp for loop exprs were not built");
4376
Alexey Bataev54acd402015-08-04 11:18:19 +00004377 if (!CurContext->isDependentContext()) {
4378 // Finalize the clauses that need pre-built expressions for CodeGen.
4379 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004380 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004381 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004382 B.NumIterations, *this, CurScope,
4383 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004384 return StmtError();
4385 }
4386 }
4387
Alexey Bataevf29276e2014-06-18 04:14:57 +00004388 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004389 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004390 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00004391}
4392
Alexander Musmanf82886e2014-09-18 05:12:34 +00004393StmtResult Sema::ActOnOpenMPForSimdDirective(
4394 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4395 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004396 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004397 if (!AStmt)
4398 return StmtError();
4399
4400 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004401 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004402 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4403 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00004404 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004405 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
4406 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4407 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004408 if (NestedLoopCount == 0)
4409 return StmtError();
4410
Alexander Musmanc6388682014-12-15 07:07:06 +00004411 assert((CurContext->isDependentContext() || B.builtAll()) &&
4412 "omp for simd loop exprs were not built");
4413
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004414 if (!CurContext->isDependentContext()) {
4415 // Finalize the clauses that need pre-built expressions for CodeGen.
4416 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004417 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004418 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004419 B.NumIterations, *this, CurScope,
4420 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004421 return StmtError();
4422 }
4423 }
4424
Kelvin Lic5609492016-07-15 04:39:07 +00004425 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004426 return StmtError();
4427
Alexander Musmanf82886e2014-09-18 05:12:34 +00004428 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004429 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4430 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004431}
4432
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004433StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
4434 Stmt *AStmt,
4435 SourceLocation StartLoc,
4436 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004437 if (!AStmt)
4438 return StmtError();
4439
4440 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004441 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004442 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004443 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004444 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004445 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004446 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004447 return StmtError();
4448 // All associated statements must be '#pragma omp section' except for
4449 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004450 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004451 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4452 if (SectionStmt)
4453 Diag(SectionStmt->getLocStart(),
4454 diag::err_omp_sections_substmt_not_section);
4455 return StmtError();
4456 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004457 cast<OMPSectionDirective>(SectionStmt)
4458 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004459 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004460 } else {
4461 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
4462 return StmtError();
4463 }
4464
4465 getCurFunction()->setHasBranchProtectedScope();
4466
Alexey Bataev25e5b442015-09-15 12:52:43 +00004467 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4468 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004469}
4470
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004471StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
4472 SourceLocation StartLoc,
4473 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004474 if (!AStmt)
4475 return StmtError();
4476
4477 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004478
4479 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00004480 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004481
Alexey Bataev25e5b442015-09-15 12:52:43 +00004482 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
4483 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004484}
4485
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004486StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
4487 Stmt *AStmt,
4488 SourceLocation StartLoc,
4489 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004490 if (!AStmt)
4491 return StmtError();
4492
4493 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00004494
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004495 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00004496
Alexey Bataev3255bf32015-01-19 05:20:46 +00004497 // OpenMP [2.7.3, single Construct, Restrictions]
4498 // The copyprivate clause must not be used with the nowait clause.
4499 OMPClause *Nowait = nullptr;
4500 OMPClause *Copyprivate = nullptr;
4501 for (auto *Clause : Clauses) {
4502 if (Clause->getClauseKind() == OMPC_nowait)
4503 Nowait = Clause;
4504 else if (Clause->getClauseKind() == OMPC_copyprivate)
4505 Copyprivate = Clause;
4506 if (Copyprivate && Nowait) {
4507 Diag(Copyprivate->getLocStart(),
4508 diag::err_omp_single_copyprivate_with_nowait);
4509 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
4510 return StmtError();
4511 }
4512 }
4513
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004514 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4515}
4516
Alexander Musman80c22892014-07-17 08:54:58 +00004517StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
4518 SourceLocation StartLoc,
4519 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004520 if (!AStmt)
4521 return StmtError();
4522
4523 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00004524
4525 getCurFunction()->setHasBranchProtectedScope();
4526
4527 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
4528}
4529
Alexey Bataev28c75412015-12-15 08:19:24 +00004530StmtResult Sema::ActOnOpenMPCriticalDirective(
4531 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
4532 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004533 if (!AStmt)
4534 return StmtError();
4535
4536 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004537
Alexey Bataev28c75412015-12-15 08:19:24 +00004538 bool ErrorFound = false;
4539 llvm::APSInt Hint;
4540 SourceLocation HintLoc;
4541 bool DependentHint = false;
4542 for (auto *C : Clauses) {
4543 if (C->getClauseKind() == OMPC_hint) {
4544 if (!DirName.getName()) {
4545 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
4546 ErrorFound = true;
4547 }
4548 Expr *E = cast<OMPHintClause>(C)->getHint();
4549 if (E->isTypeDependent() || E->isValueDependent() ||
4550 E->isInstantiationDependent())
4551 DependentHint = true;
4552 else {
4553 Hint = E->EvaluateKnownConstInt(Context);
4554 HintLoc = C->getLocStart();
4555 }
4556 }
4557 }
4558 if (ErrorFound)
4559 return StmtError();
4560 auto Pair = DSAStack->getCriticalWithHint(DirName);
4561 if (Pair.first && DirName.getName() && !DependentHint) {
4562 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
4563 Diag(StartLoc, diag::err_omp_critical_with_hint);
4564 if (HintLoc.isValid()) {
4565 Diag(HintLoc, diag::note_omp_critical_hint_here)
4566 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
4567 } else
4568 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
4569 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
4570 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
4571 << 1
4572 << C->getHint()->EvaluateKnownConstInt(Context).toString(
4573 /*Radix=*/10, /*Signed=*/false);
4574 } else
4575 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
4576 }
4577 }
4578
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004579 getCurFunction()->setHasBranchProtectedScope();
4580
Alexey Bataev28c75412015-12-15 08:19:24 +00004581 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
4582 Clauses, AStmt);
4583 if (!Pair.first && DirName.getName() && !DependentHint)
4584 DSAStack->addCriticalWithHint(Dir, Hint);
4585 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004586}
4587
Alexey Bataev4acb8592014-07-07 13:01:15 +00004588StmtResult Sema::ActOnOpenMPParallelForDirective(
4589 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4590 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004591 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004592 if (!AStmt)
4593 return StmtError();
4594
Alexey Bataev4acb8592014-07-07 13:01:15 +00004595 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4596 // 1.2.2 OpenMP Language Terminology
4597 // Structured block - An executable statement with a single entry at the
4598 // top and a single exit at the bottom.
4599 // The point of exit cannot be a branch out of the structured block.
4600 // longjmp() and throw() must not violate the entry/exit criteria.
4601 CS->getCapturedDecl()->setNothrow();
4602
Alexander Musmanc6388682014-12-15 07:07:06 +00004603 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004604 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4605 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004606 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004607 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
4608 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4609 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004610 if (NestedLoopCount == 0)
4611 return StmtError();
4612
Alexander Musmana5f070a2014-10-01 06:03:56 +00004613 assert((CurContext->isDependentContext() || B.builtAll()) &&
4614 "omp parallel for loop exprs were not built");
4615
Alexey Bataev54acd402015-08-04 11:18:19 +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 Bataev54acd402015-08-04 11:18:19 +00004620 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004621 B.NumIterations, *this, CurScope,
4622 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004623 return StmtError();
4624 }
4625 }
4626
Alexey Bataev4acb8592014-07-07 13:01:15 +00004627 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004628 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004629 NestedLoopCount, Clauses, AStmt, B,
4630 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00004631}
4632
Alexander Musmane4e893b2014-09-23 09:33:00 +00004633StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
4634 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4635 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004636 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004637 if (!AStmt)
4638 return StmtError();
4639
Alexander Musmane4e893b2014-09-23 09:33:00 +00004640 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4641 // 1.2.2 OpenMP Language Terminology
4642 // Structured block - An executable statement with a single entry at the
4643 // top and a single exit at the bottom.
4644 // The point of exit cannot be a branch out of the structured block.
4645 // longjmp() and throw() must not violate the entry/exit criteria.
4646 CS->getCapturedDecl()->setNothrow();
4647
Alexander Musmanc6388682014-12-15 07:07:06 +00004648 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004649 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4650 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00004651 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004652 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
4653 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4654 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004655 if (NestedLoopCount == 0)
4656 return StmtError();
4657
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004658 if (!CurContext->isDependentContext()) {
4659 // Finalize the clauses that need pre-built expressions for CodeGen.
4660 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004661 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004662 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004663 B.NumIterations, *this, CurScope,
4664 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004665 return StmtError();
4666 }
4667 }
4668
Kelvin Lic5609492016-07-15 04:39:07 +00004669 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004670 return StmtError();
4671
Alexander Musmane4e893b2014-09-23 09:33:00 +00004672 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004673 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00004674 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004675}
4676
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004677StmtResult
4678Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
4679 Stmt *AStmt, SourceLocation StartLoc,
4680 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004681 if (!AStmt)
4682 return StmtError();
4683
4684 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004685 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004686 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004687 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004688 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004689 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004690 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004691 return StmtError();
4692 // All associated statements must be '#pragma omp section' except for
4693 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004694 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004695 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4696 if (SectionStmt)
4697 Diag(SectionStmt->getLocStart(),
4698 diag::err_omp_parallel_sections_substmt_not_section);
4699 return StmtError();
4700 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004701 cast<OMPSectionDirective>(SectionStmt)
4702 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004703 }
4704 } else {
4705 Diag(AStmt->getLocStart(),
4706 diag::err_omp_parallel_sections_not_compound_stmt);
4707 return StmtError();
4708 }
4709
4710 getCurFunction()->setHasBranchProtectedScope();
4711
Alexey Bataev25e5b442015-09-15 12:52:43 +00004712 return OMPParallelSectionsDirective::Create(
4713 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004714}
4715
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004716StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
4717 Stmt *AStmt, SourceLocation StartLoc,
4718 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004719 if (!AStmt)
4720 return StmtError();
4721
David Majnemer9d168222016-08-05 17:44:54 +00004722 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004723 // 1.2.2 OpenMP Language Terminology
4724 // Structured block - An executable statement with a single entry at the
4725 // top and a single exit at the bottom.
4726 // The point of exit cannot be a branch out of the structured block.
4727 // longjmp() and throw() must not violate the entry/exit criteria.
4728 CS->getCapturedDecl()->setNothrow();
4729
4730 getCurFunction()->setHasBranchProtectedScope();
4731
Alexey Bataev25e5b442015-09-15 12:52:43 +00004732 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4733 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004734}
4735
Alexey Bataev68446b72014-07-18 07:47:19 +00004736StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
4737 SourceLocation EndLoc) {
4738 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
4739}
4740
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004741StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
4742 SourceLocation EndLoc) {
4743 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
4744}
4745
Alexey Bataev2df347a2014-07-18 10:17:07 +00004746StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
4747 SourceLocation EndLoc) {
4748 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
4749}
4750
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004751StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
4752 SourceLocation StartLoc,
4753 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004754 if (!AStmt)
4755 return StmtError();
4756
4757 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004758
4759 getCurFunction()->setHasBranchProtectedScope();
4760
4761 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
4762}
4763
Alexey Bataev6125da92014-07-21 11:26:11 +00004764StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
4765 SourceLocation StartLoc,
4766 SourceLocation EndLoc) {
4767 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
4768 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
4769}
4770
Alexey Bataev346265e2015-09-25 10:37:12 +00004771StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
4772 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004773 SourceLocation StartLoc,
4774 SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00004775 OMPClause *DependFound = nullptr;
4776 OMPClause *DependSourceClause = nullptr;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004777 OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00004778 bool ErrorFound = false;
Alexey Bataev346265e2015-09-25 10:37:12 +00004779 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004780 OMPSIMDClause *SC = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00004781 for (auto *C : Clauses) {
4782 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
4783 DependFound = C;
4784 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
4785 if (DependSourceClause) {
4786 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
4787 << getOpenMPDirectiveName(OMPD_ordered)
4788 << getOpenMPClauseName(OMPC_depend) << 2;
4789 ErrorFound = true;
4790 } else
4791 DependSourceClause = C;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004792 if (DependSinkClause) {
4793 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4794 << 0;
4795 ErrorFound = true;
4796 }
4797 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
4798 if (DependSourceClause) {
4799 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4800 << 1;
4801 ErrorFound = true;
4802 }
4803 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00004804 }
4805 } else if (C->getClauseKind() == OMPC_threads)
Alexey Bataev346265e2015-09-25 10:37:12 +00004806 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004807 else if (C->getClauseKind() == OMPC_simd)
4808 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00004809 }
Alexey Bataeveb482352015-12-18 05:05:56 +00004810 if (!ErrorFound && !SC &&
4811 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004812 // OpenMP [2.8.1,simd Construct, Restrictions]
4813 // An ordered construct with the simd clause is the only OpenMP construct
4814 // that can appear in the simd region.
4815 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00004816 ErrorFound = true;
4817 } else if (DependFound && (TC || SC)) {
4818 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
4819 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
4820 ErrorFound = true;
4821 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
4822 Diag(DependFound->getLocStart(),
4823 diag::err_omp_ordered_directive_without_param);
4824 ErrorFound = true;
4825 } else if (TC || Clauses.empty()) {
4826 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
4827 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
4828 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
4829 << (TC != nullptr);
4830 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
4831 ErrorFound = true;
4832 }
4833 }
4834 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004835 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00004836
4837 if (AStmt) {
4838 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4839
4840 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004841 }
Alexey Bataev346265e2015-09-25 10:37:12 +00004842
4843 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004844}
4845
Alexey Bataev1d160b12015-03-13 12:27:31 +00004846namespace {
4847/// \brief Helper class for checking expression in 'omp atomic [update]'
4848/// construct.
4849class OpenMPAtomicUpdateChecker {
4850 /// \brief Error results for atomic update expressions.
4851 enum ExprAnalysisErrorCode {
4852 /// \brief A statement is not an expression statement.
4853 NotAnExpression,
4854 /// \brief Expression is not builtin binary or unary operation.
4855 NotABinaryOrUnaryExpression,
4856 /// \brief Unary operation is not post-/pre- increment/decrement operation.
4857 NotAnUnaryIncDecExpression,
4858 /// \brief An expression is not of scalar type.
4859 NotAScalarType,
4860 /// \brief A binary operation is not an assignment operation.
4861 NotAnAssignmentOp,
4862 /// \brief RHS part of the binary operation is not a binary expression.
4863 NotABinaryExpression,
4864 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
4865 /// expression.
4866 NotABinaryOperator,
4867 /// \brief RHS binary operation does not have reference to the updated LHS
4868 /// part.
4869 NotAnUpdateExpression,
4870 /// \brief No errors is found.
4871 NoError
4872 };
4873 /// \brief Reference to Sema.
4874 Sema &SemaRef;
4875 /// \brief A location for note diagnostics (when error is found).
4876 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004877 /// \brief 'x' lvalue part of the source atomic expression.
4878 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004879 /// \brief 'expr' rvalue part of the source atomic expression.
4880 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004881 /// \brief Helper expression of the form
4882 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4883 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4884 Expr *UpdateExpr;
4885 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
4886 /// important for non-associative operations.
4887 bool IsXLHSInRHSPart;
4888 BinaryOperatorKind Op;
4889 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00004890 /// \brief true if the source expression is a postfix unary operation, false
4891 /// if it is a prefix unary operation.
4892 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004893
4894public:
4895 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00004896 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00004897 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00004898 /// \brief Check specified statement that it is suitable for 'atomic update'
4899 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00004900 /// expression. If DiagId and NoteId == 0, then only check is performed
4901 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00004902 /// \param DiagId Diagnostic which should be emitted if error is found.
4903 /// \param NoteId Diagnostic note for the main error message.
4904 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00004905 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00004906 /// \brief Return the 'x' lvalue part of the source atomic expression.
4907 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00004908 /// \brief Return the 'expr' rvalue part of the source atomic expression.
4909 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00004910 /// \brief Return the update expression used in calculation of the updated
4911 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4912 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4913 Expr *getUpdateExpr() const { return UpdateExpr; }
4914 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
4915 /// false otherwise.
4916 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
4917
Alexey Bataevb78ca832015-04-01 03:33:17 +00004918 /// \brief true if the source expression is a postfix unary operation, false
4919 /// if it is a prefix unary operation.
4920 bool isPostfixUpdate() const { return IsPostfixUpdate; }
4921
Alexey Bataev1d160b12015-03-13 12:27:31 +00004922private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00004923 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
4924 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00004925};
4926} // namespace
4927
4928bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
4929 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
4930 ExprAnalysisErrorCode ErrorFound = NoError;
4931 SourceLocation ErrorLoc, NoteLoc;
4932 SourceRange ErrorRange, NoteRange;
4933 // Allowed constructs are:
4934 // x = x binop expr;
4935 // x = expr binop x;
4936 if (AtomicBinOp->getOpcode() == BO_Assign) {
4937 X = AtomicBinOp->getLHS();
4938 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
4939 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
4940 if (AtomicInnerBinOp->isMultiplicativeOp() ||
4941 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
4942 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00004943 Op = AtomicInnerBinOp->getOpcode();
4944 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00004945 auto *LHS = AtomicInnerBinOp->getLHS();
4946 auto *RHS = AtomicInnerBinOp->getRHS();
4947 llvm::FoldingSetNodeID XId, LHSId, RHSId;
4948 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
4949 /*Canonical=*/true);
4950 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
4951 /*Canonical=*/true);
4952 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
4953 /*Canonical=*/true);
4954 if (XId == LHSId) {
4955 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004956 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004957 } else if (XId == RHSId) {
4958 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004959 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004960 } else {
4961 ErrorLoc = AtomicInnerBinOp->getExprLoc();
4962 ErrorRange = AtomicInnerBinOp->getSourceRange();
4963 NoteLoc = X->getExprLoc();
4964 NoteRange = X->getSourceRange();
4965 ErrorFound = NotAnUpdateExpression;
4966 }
4967 } else {
4968 ErrorLoc = AtomicInnerBinOp->getExprLoc();
4969 ErrorRange = AtomicInnerBinOp->getSourceRange();
4970 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
4971 NoteRange = SourceRange(NoteLoc, NoteLoc);
4972 ErrorFound = NotABinaryOperator;
4973 }
4974 } else {
4975 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
4976 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
4977 ErrorFound = NotABinaryExpression;
4978 }
4979 } else {
4980 ErrorLoc = AtomicBinOp->getExprLoc();
4981 ErrorRange = AtomicBinOp->getSourceRange();
4982 NoteLoc = AtomicBinOp->getOperatorLoc();
4983 NoteRange = SourceRange(NoteLoc, NoteLoc);
4984 ErrorFound = NotAnAssignmentOp;
4985 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00004986 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00004987 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
4988 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
4989 return true;
4990 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00004991 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00004992 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004993}
4994
4995bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
4996 unsigned NoteId) {
4997 ExprAnalysisErrorCode ErrorFound = NoError;
4998 SourceLocation ErrorLoc, NoteLoc;
4999 SourceRange ErrorRange, NoteRange;
5000 // Allowed constructs are:
5001 // x++;
5002 // x--;
5003 // ++x;
5004 // --x;
5005 // x binop= expr;
5006 // x = x binop expr;
5007 // x = expr binop x;
5008 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5009 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5010 if (AtomicBody->getType()->isScalarType() ||
5011 AtomicBody->isInstantiationDependent()) {
5012 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5013 AtomicBody->IgnoreParenImpCasts())) {
5014 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00005015 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00005016 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00005017 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005018 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005019 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005020 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005021 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5022 AtomicBody->IgnoreParenImpCasts())) {
5023 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00005024 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00005025 return true;
David Majnemer9d168222016-08-05 17:44:54 +00005026 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5027 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005028 // Check for Unary Operation
5029 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005030 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005031 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5032 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005033 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005034 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5035 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005036 } else {
5037 ErrorFound = NotAnUnaryIncDecExpression;
5038 ErrorLoc = AtomicUnaryOp->getExprLoc();
5039 ErrorRange = AtomicUnaryOp->getSourceRange();
5040 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5041 NoteRange = SourceRange(NoteLoc, NoteLoc);
5042 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005043 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005044 ErrorFound = NotABinaryOrUnaryExpression;
5045 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5046 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5047 }
5048 } else {
5049 ErrorFound = NotAScalarType;
5050 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5051 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5052 }
5053 } else {
5054 ErrorFound = NotAnExpression;
5055 NoteLoc = ErrorLoc = S->getLocStart();
5056 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5057 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005058 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005059 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5060 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5061 return true;
5062 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005063 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005064 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005065 // Build an update expression of form 'OpaqueValueExpr(x) binop
5066 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5067 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5068 auto *OVEX = new (SemaRef.getASTContext())
5069 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5070 auto *OVEExpr = new (SemaRef.getASTContext())
5071 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5072 auto Update =
5073 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5074 IsXLHSInRHSPart ? OVEExpr : OVEX);
5075 if (Update.isInvalid())
5076 return true;
5077 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5078 Sema::AA_Casting);
5079 if (Update.isInvalid())
5080 return true;
5081 UpdateExpr = Update.get();
5082 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00005083 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005084}
5085
Alexey Bataev0162e452014-07-22 10:10:35 +00005086StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5087 Stmt *AStmt,
5088 SourceLocation StartLoc,
5089 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005090 if (!AStmt)
5091 return StmtError();
5092
David Majnemer9d168222016-08-05 17:44:54 +00005093 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00005094 // 1.2.2 OpenMP Language Terminology
5095 // Structured block - An executable statement with a single entry at the
5096 // top and a single exit at the bottom.
5097 // The point of exit cannot be a branch out of the structured block.
5098 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00005099 OpenMPClauseKind AtomicKind = OMPC_unknown;
5100 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005101 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00005102 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00005103 C->getClauseKind() == OMPC_update ||
5104 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00005105 if (AtomicKind != OMPC_unknown) {
5106 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5107 << SourceRange(C->getLocStart(), C->getLocEnd());
5108 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5109 << getOpenMPClauseName(AtomicKind);
5110 } else {
5111 AtomicKind = C->getClauseKind();
5112 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005113 }
5114 }
5115 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005116
Alexey Bataev459dec02014-07-24 06:46:57 +00005117 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00005118 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5119 Body = EWC->getSubExpr();
5120
Alexey Bataev62cec442014-11-18 10:14:22 +00005121 Expr *X = nullptr;
5122 Expr *V = nullptr;
5123 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005124 Expr *UE = nullptr;
5125 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005126 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00005127 // OpenMP [2.12.6, atomic Construct]
5128 // In the next expressions:
5129 // * x and v (as applicable) are both l-value expressions with scalar type.
5130 // * During the execution of an atomic region, multiple syntactic
5131 // occurrences of x must designate the same storage location.
5132 // * Neither of v and expr (as applicable) may access the storage location
5133 // designated by x.
5134 // * Neither of x and expr (as applicable) may access the storage location
5135 // designated by v.
5136 // * expr is an expression with scalar type.
5137 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5138 // * binop, binop=, ++, and -- are not overloaded operators.
5139 // * The expression x binop expr must be numerically equivalent to x binop
5140 // (expr). This requirement is satisfied if the operators in expr have
5141 // precedence greater than binop, or by using parentheses around expr or
5142 // subexpressions of expr.
5143 // * The expression expr binop x must be numerically equivalent to (expr)
5144 // binop x. This requirement is satisfied if the operators in expr have
5145 // precedence equal to or greater than binop, or by using parentheses around
5146 // expr or subexpressions of expr.
5147 // * For forms that allow multiple occurrences of x, the number of times
5148 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00005149 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005150 enum {
5151 NotAnExpression,
5152 NotAnAssignmentOp,
5153 NotAScalarType,
5154 NotAnLValue,
5155 NoError
5156 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00005157 SourceLocation ErrorLoc, NoteLoc;
5158 SourceRange ErrorRange, NoteRange;
5159 // If clause is read:
5160 // v = x;
David Majnemer9d168222016-08-05 17:44:54 +00005161 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5162 auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00005163 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5164 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5165 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5166 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5167 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5168 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5169 if (!X->isLValue() || !V->isLValue()) {
5170 auto NotLValueExpr = X->isLValue() ? V : X;
5171 ErrorFound = NotAnLValue;
5172 ErrorLoc = AtomicBinOp->getExprLoc();
5173 ErrorRange = AtomicBinOp->getSourceRange();
5174 NoteLoc = NotLValueExpr->getExprLoc();
5175 NoteRange = NotLValueExpr->getSourceRange();
5176 }
5177 } else if (!X->isInstantiationDependent() ||
5178 !V->isInstantiationDependent()) {
5179 auto NotScalarExpr =
5180 (X->isInstantiationDependent() || X->getType()->isScalarType())
5181 ? V
5182 : X;
5183 ErrorFound = NotAScalarType;
5184 ErrorLoc = AtomicBinOp->getExprLoc();
5185 ErrorRange = AtomicBinOp->getSourceRange();
5186 NoteLoc = NotScalarExpr->getExprLoc();
5187 NoteRange = NotScalarExpr->getSourceRange();
5188 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005189 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00005190 ErrorFound = NotAnAssignmentOp;
5191 ErrorLoc = AtomicBody->getExprLoc();
5192 ErrorRange = AtomicBody->getSourceRange();
5193 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5194 : AtomicBody->getExprLoc();
5195 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5196 : AtomicBody->getSourceRange();
5197 }
5198 } else {
5199 ErrorFound = NotAnExpression;
5200 NoteLoc = ErrorLoc = Body->getLocStart();
5201 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005202 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005203 if (ErrorFound != NoError) {
5204 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5205 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005206 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5207 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00005208 return StmtError();
5209 } else if (CurContext->isDependentContext())
5210 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00005211 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005212 enum {
5213 NotAnExpression,
5214 NotAnAssignmentOp,
5215 NotAScalarType,
5216 NotAnLValue,
5217 NoError
5218 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005219 SourceLocation ErrorLoc, NoteLoc;
5220 SourceRange ErrorRange, NoteRange;
5221 // If clause is write:
5222 // x = expr;
David Majnemer9d168222016-08-05 17:44:54 +00005223 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5224 auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00005225 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5226 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00005227 X = AtomicBinOp->getLHS();
5228 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00005229 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5230 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5231 if (!X->isLValue()) {
5232 ErrorFound = NotAnLValue;
5233 ErrorLoc = AtomicBinOp->getExprLoc();
5234 ErrorRange = AtomicBinOp->getSourceRange();
5235 NoteLoc = X->getExprLoc();
5236 NoteRange = X->getSourceRange();
5237 }
5238 } else if (!X->isInstantiationDependent() ||
5239 !E->isInstantiationDependent()) {
5240 auto NotScalarExpr =
5241 (X->isInstantiationDependent() || X->getType()->isScalarType())
5242 ? E
5243 : X;
5244 ErrorFound = NotAScalarType;
5245 ErrorLoc = AtomicBinOp->getExprLoc();
5246 ErrorRange = AtomicBinOp->getSourceRange();
5247 NoteLoc = NotScalarExpr->getExprLoc();
5248 NoteRange = NotScalarExpr->getSourceRange();
5249 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005250 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00005251 ErrorFound = NotAnAssignmentOp;
5252 ErrorLoc = AtomicBody->getExprLoc();
5253 ErrorRange = AtomicBody->getSourceRange();
5254 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5255 : AtomicBody->getExprLoc();
5256 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5257 : AtomicBody->getSourceRange();
5258 }
5259 } else {
5260 ErrorFound = NotAnExpression;
5261 NoteLoc = ErrorLoc = Body->getLocStart();
5262 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005263 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00005264 if (ErrorFound != NoError) {
5265 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
5266 << ErrorRange;
5267 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5268 << NoteRange;
5269 return StmtError();
5270 } else if (CurContext->isDependentContext())
5271 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00005272 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005273 // If clause is update:
5274 // x++;
5275 // x--;
5276 // ++x;
5277 // --x;
5278 // x binop= expr;
5279 // x = x binop expr;
5280 // x = expr binop x;
5281 OpenMPAtomicUpdateChecker Checker(*this);
5282 if (Checker.checkStatement(
5283 Body, (AtomicKind == OMPC_update)
5284 ? diag::err_omp_atomic_update_not_expression_statement
5285 : diag::err_omp_atomic_not_expression_statement,
5286 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00005287 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005288 if (!CurContext->isDependentContext()) {
5289 E = Checker.getExpr();
5290 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005291 UE = Checker.getUpdateExpr();
5292 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00005293 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005294 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005295 enum {
5296 NotAnAssignmentOp,
5297 NotACompoundStatement,
5298 NotTwoSubstatements,
5299 NotASpecificExpression,
5300 NoError
5301 } ErrorFound = NoError;
5302 SourceLocation ErrorLoc, NoteLoc;
5303 SourceRange ErrorRange, NoteRange;
5304 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5305 // If clause is a capture:
5306 // v = x++;
5307 // v = x--;
5308 // v = ++x;
5309 // v = --x;
5310 // v = x binop= expr;
5311 // v = x = x binop expr;
5312 // v = x = expr binop x;
5313 auto *AtomicBinOp =
5314 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5315 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5316 V = AtomicBinOp->getLHS();
5317 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5318 OpenMPAtomicUpdateChecker Checker(*this);
5319 if (Checker.checkStatement(
5320 Body, diag::err_omp_atomic_capture_not_expression_statement,
5321 diag::note_omp_atomic_update))
5322 return StmtError();
5323 E = Checker.getExpr();
5324 X = Checker.getX();
5325 UE = Checker.getUpdateExpr();
5326 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5327 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00005328 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005329 ErrorLoc = AtomicBody->getExprLoc();
5330 ErrorRange = AtomicBody->getSourceRange();
5331 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5332 : AtomicBody->getExprLoc();
5333 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5334 : AtomicBody->getSourceRange();
5335 ErrorFound = NotAnAssignmentOp;
5336 }
5337 if (ErrorFound != NoError) {
5338 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
5339 << ErrorRange;
5340 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5341 return StmtError();
5342 } else if (CurContext->isDependentContext()) {
5343 UE = V = E = X = nullptr;
5344 }
5345 } else {
5346 // If clause is a capture:
5347 // { v = x; x = expr; }
5348 // { v = x; x++; }
5349 // { v = x; x--; }
5350 // { v = x; ++x; }
5351 // { v = x; --x; }
5352 // { v = x; x binop= expr; }
5353 // { v = x; x = x binop expr; }
5354 // { v = x; x = expr binop x; }
5355 // { x++; v = x; }
5356 // { x--; v = x; }
5357 // { ++x; v = x; }
5358 // { --x; v = x; }
5359 // { x binop= expr; v = x; }
5360 // { x = x binop expr; v = x; }
5361 // { x = expr binop x; v = x; }
5362 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
5363 // Check that this is { expr1; expr2; }
5364 if (CS->size() == 2) {
5365 auto *First = CS->body_front();
5366 auto *Second = CS->body_back();
5367 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
5368 First = EWC->getSubExpr()->IgnoreParenImpCasts();
5369 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
5370 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
5371 // Need to find what subexpression is 'v' and what is 'x'.
5372 OpenMPAtomicUpdateChecker Checker(*this);
5373 bool IsUpdateExprFound = !Checker.checkStatement(Second);
5374 BinaryOperator *BinOp = nullptr;
5375 if (IsUpdateExprFound) {
5376 BinOp = dyn_cast<BinaryOperator>(First);
5377 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5378 }
5379 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5380 // { v = x; x++; }
5381 // { v = x; x--; }
5382 // { v = x; ++x; }
5383 // { v = x; --x; }
5384 // { v = x; x binop= expr; }
5385 // { v = x; x = x binop expr; }
5386 // { v = x; x = expr binop x; }
5387 // Check that the first expression has form v = x.
5388 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5389 llvm::FoldingSetNodeID XId, PossibleXId;
5390 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5391 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5392 IsUpdateExprFound = XId == PossibleXId;
5393 if (IsUpdateExprFound) {
5394 V = BinOp->getLHS();
5395 X = Checker.getX();
5396 E = Checker.getExpr();
5397 UE = Checker.getUpdateExpr();
5398 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005399 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005400 }
5401 }
5402 if (!IsUpdateExprFound) {
5403 IsUpdateExprFound = !Checker.checkStatement(First);
5404 BinOp = nullptr;
5405 if (IsUpdateExprFound) {
5406 BinOp = dyn_cast<BinaryOperator>(Second);
5407 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5408 }
5409 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5410 // { x++; v = x; }
5411 // { x--; v = x; }
5412 // { ++x; v = x; }
5413 // { --x; v = x; }
5414 // { x binop= expr; v = x; }
5415 // { x = x binop expr; v = x; }
5416 // { x = expr binop x; v = x; }
5417 // Check that the second expression has form v = x.
5418 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5419 llvm::FoldingSetNodeID XId, PossibleXId;
5420 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5421 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5422 IsUpdateExprFound = XId == PossibleXId;
5423 if (IsUpdateExprFound) {
5424 V = BinOp->getLHS();
5425 X = Checker.getX();
5426 E = Checker.getExpr();
5427 UE = Checker.getUpdateExpr();
5428 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005429 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005430 }
5431 }
5432 }
5433 if (!IsUpdateExprFound) {
5434 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00005435 auto *FirstExpr = dyn_cast<Expr>(First);
5436 auto *SecondExpr = dyn_cast<Expr>(Second);
5437 if (!FirstExpr || !SecondExpr ||
5438 !(FirstExpr->isInstantiationDependent() ||
5439 SecondExpr->isInstantiationDependent())) {
5440 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
5441 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005442 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00005443 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
5444 : First->getLocStart();
5445 NoteRange = ErrorRange = FirstBinOp
5446 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00005447 : SourceRange(ErrorLoc, ErrorLoc);
5448 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005449 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
5450 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
5451 ErrorFound = NotAnAssignmentOp;
5452 NoteLoc = ErrorLoc = SecondBinOp
5453 ? SecondBinOp->getOperatorLoc()
5454 : Second->getLocStart();
5455 NoteRange = ErrorRange =
5456 SecondBinOp ? SecondBinOp->getSourceRange()
5457 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00005458 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005459 auto *PossibleXRHSInFirst =
5460 FirstBinOp->getRHS()->IgnoreParenImpCasts();
5461 auto *PossibleXLHSInSecond =
5462 SecondBinOp->getLHS()->IgnoreParenImpCasts();
5463 llvm::FoldingSetNodeID X1Id, X2Id;
5464 PossibleXRHSInFirst->Profile(X1Id, Context,
5465 /*Canonical=*/true);
5466 PossibleXLHSInSecond->Profile(X2Id, Context,
5467 /*Canonical=*/true);
5468 IsUpdateExprFound = X1Id == X2Id;
5469 if (IsUpdateExprFound) {
5470 V = FirstBinOp->getLHS();
5471 X = SecondBinOp->getLHS();
5472 E = SecondBinOp->getRHS();
5473 UE = nullptr;
5474 IsXLHSInRHSPart = false;
5475 IsPostfixUpdate = true;
5476 } else {
5477 ErrorFound = NotASpecificExpression;
5478 ErrorLoc = FirstBinOp->getExprLoc();
5479 ErrorRange = FirstBinOp->getSourceRange();
5480 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
5481 NoteRange = SecondBinOp->getRHS()->getSourceRange();
5482 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005483 }
5484 }
5485 }
5486 }
5487 } else {
5488 NoteLoc = ErrorLoc = Body->getLocStart();
5489 NoteRange = ErrorRange =
5490 SourceRange(Body->getLocStart(), Body->getLocStart());
5491 ErrorFound = NotTwoSubstatements;
5492 }
5493 } else {
5494 NoteLoc = ErrorLoc = Body->getLocStart();
5495 NoteRange = ErrorRange =
5496 SourceRange(Body->getLocStart(), Body->getLocStart());
5497 ErrorFound = NotACompoundStatement;
5498 }
5499 if (ErrorFound != NoError) {
5500 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
5501 << ErrorRange;
5502 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5503 return StmtError();
5504 } else if (CurContext->isDependentContext()) {
5505 UE = V = E = X = nullptr;
5506 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005507 }
Alexey Bataevdea47612014-07-23 07:46:59 +00005508 }
Alexey Bataev0162e452014-07-22 10:10:35 +00005509
5510 getCurFunction()->setHasBranchProtectedScope();
5511
Alexey Bataev62cec442014-11-18 10:14:22 +00005512 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00005513 X, V, E, UE, IsXLHSInRHSPart,
5514 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00005515}
5516
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005517StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
5518 Stmt *AStmt,
5519 SourceLocation StartLoc,
5520 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005521 if (!AStmt)
5522 return StmtError();
5523
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005524 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5525 // 1.2.2 OpenMP Language Terminology
5526 // Structured block - An executable statement with a single entry at the
5527 // top and a single exit at the bottom.
5528 // The point of exit cannot be a branch out of the structured block.
5529 // longjmp() and throw() must not violate the entry/exit criteria.
5530 CS->getCapturedDecl()->setNothrow();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005531
Alexey Bataev13314bf2014-10-09 04:18:56 +00005532 // OpenMP [2.16, Nesting of Regions]
5533 // If specified, a teams construct must be contained within a target
5534 // construct. That target construct must contain no statements or directives
5535 // outside of the teams construct.
5536 if (DSAStack->hasInnerTeamsRegion()) {
5537 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
5538 bool OMPTeamsFound = true;
5539 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
5540 auto I = CS->body_begin();
5541 while (I != CS->body_end()) {
David Majnemer9d168222016-08-05 17:44:54 +00005542 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00005543 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
5544 OMPTeamsFound = false;
5545 break;
5546 }
5547 ++I;
5548 }
5549 assert(I != CS->body_end() && "Not found statement");
5550 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00005551 } else {
5552 auto *OED = dyn_cast<OMPExecutableDirective>(S);
5553 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00005554 }
5555 if (!OMPTeamsFound) {
5556 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
5557 Diag(DSAStack->getInnerTeamsRegionLoc(),
5558 diag::note_omp_nested_teams_construct_here);
5559 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
5560 << isa<OMPExecutableDirective>(S);
5561 return StmtError();
5562 }
5563 }
5564
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005565 getCurFunction()->setHasBranchProtectedScope();
5566
5567 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5568}
5569
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005570StmtResult
5571Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
5572 Stmt *AStmt, SourceLocation StartLoc,
5573 SourceLocation EndLoc) {
5574 if (!AStmt)
5575 return StmtError();
5576
5577 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5578 // 1.2.2 OpenMP Language Terminology
5579 // Structured block - An executable statement with a single entry at the
5580 // top and a single exit at the bottom.
5581 // The point of exit cannot be a branch out of the structured block.
5582 // longjmp() and throw() must not violate the entry/exit criteria.
5583 CS->getCapturedDecl()->setNothrow();
5584
5585 getCurFunction()->setHasBranchProtectedScope();
5586
5587 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5588 AStmt);
5589}
5590
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005591StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
5592 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5593 SourceLocation EndLoc,
5594 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5595 if (!AStmt)
5596 return StmtError();
5597
5598 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5599 // 1.2.2 OpenMP Language Terminology
5600 // Structured block - An executable statement with a single entry at the
5601 // top and a single exit at the bottom.
5602 // The point of exit cannot be a branch out of the structured block.
5603 // longjmp() and throw() must not violate the entry/exit criteria.
5604 CS->getCapturedDecl()->setNothrow();
5605
5606 OMPLoopDirective::HelperExprs B;
5607 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5608 // define the nested loops number.
5609 unsigned NestedLoopCount =
5610 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
5611 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5612 VarsWithImplicitDSA, B);
5613 if (NestedLoopCount == 0)
5614 return StmtError();
5615
5616 assert((CurContext->isDependentContext() || B.builtAll()) &&
5617 "omp target parallel for loop exprs were not built");
5618
5619 if (!CurContext->isDependentContext()) {
5620 // Finalize the clauses that need pre-built expressions for CodeGen.
5621 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005622 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005623 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005624 B.NumIterations, *this, CurScope,
5625 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005626 return StmtError();
5627 }
5628 }
5629
5630 getCurFunction()->setHasBranchProtectedScope();
5631 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
5632 NestedLoopCount, Clauses, AStmt,
5633 B, DSAStack->isCancelRegion());
5634}
5635
Samuel Antaodf67fc42016-01-19 19:15:56 +00005636/// \brief Check for existence of a map clause in the list of clauses.
5637static bool HasMapClause(ArrayRef<OMPClause *> Clauses) {
5638 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
5639 I != E; ++I) {
5640 if (*I != nullptr && (*I)->getClauseKind() == OMPC_map) {
5641 return true;
5642 }
5643 }
5644
5645 return false;
5646}
5647
Michael Wong65f367f2015-07-21 13:44:28 +00005648StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
5649 Stmt *AStmt,
5650 SourceLocation StartLoc,
5651 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005652 if (!AStmt)
5653 return StmtError();
5654
5655 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5656
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005657 // OpenMP [2.10.1, Restrictions, p. 97]
5658 // At least one map clause must appear on the directive.
5659 if (!HasMapClause(Clauses)) {
David Majnemer9d168222016-08-05 17:44:54 +00005660 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5661 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005662 return StmtError();
5663 }
5664
Michael Wong65f367f2015-07-21 13:44:28 +00005665 getCurFunction()->setHasBranchProtectedScope();
5666
5667 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
5668 AStmt);
5669}
5670
Samuel Antaodf67fc42016-01-19 19:15:56 +00005671StmtResult
5672Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
5673 SourceLocation StartLoc,
5674 SourceLocation EndLoc) {
5675 // OpenMP [2.10.2, Restrictions, p. 99]
5676 // At least one map clause must appear on the directive.
5677 if (!HasMapClause(Clauses)) {
5678 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5679 << getOpenMPDirectiveName(OMPD_target_enter_data);
5680 return StmtError();
5681 }
5682
5683 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
5684 Clauses);
5685}
5686
Samuel Antao72590762016-01-19 20:04:50 +00005687StmtResult
5688Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
5689 SourceLocation StartLoc,
5690 SourceLocation EndLoc) {
5691 // OpenMP [2.10.3, Restrictions, p. 102]
5692 // At least one map clause must appear on the directive.
5693 if (!HasMapClause(Clauses)) {
5694 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5695 << getOpenMPDirectiveName(OMPD_target_exit_data);
5696 return StmtError();
5697 }
5698
5699 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
5700}
5701
Samuel Antao686c70c2016-05-26 17:30:50 +00005702StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
5703 SourceLocation StartLoc,
5704 SourceLocation EndLoc) {
Samuel Antao686c70c2016-05-26 17:30:50 +00005705 bool seenMotionClause = false;
Samuel Antao661c0902016-05-26 17:39:58 +00005706 for (auto *C : Clauses) {
Samuel Antaoec172c62016-05-26 17:49:04 +00005707 if (C->getClauseKind() == OMPC_to || C->getClauseKind() == OMPC_from)
Samuel Antao661c0902016-05-26 17:39:58 +00005708 seenMotionClause = true;
5709 }
Samuel Antao686c70c2016-05-26 17:30:50 +00005710 if (!seenMotionClause) {
5711 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
5712 return StmtError();
5713 }
5714 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses);
5715}
5716
Alexey Bataev13314bf2014-10-09 04:18:56 +00005717StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
5718 Stmt *AStmt, SourceLocation StartLoc,
5719 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005720 if (!AStmt)
5721 return StmtError();
5722
Alexey Bataev13314bf2014-10-09 04:18:56 +00005723 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5724 // 1.2.2 OpenMP Language Terminology
5725 // Structured block - An executable statement with a single entry at the
5726 // top and a single exit at the bottom.
5727 // The point of exit cannot be a branch out of the structured block.
5728 // longjmp() and throw() must not violate the entry/exit criteria.
5729 CS->getCapturedDecl()->setNothrow();
5730
5731 getCurFunction()->setHasBranchProtectedScope();
5732
5733 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5734}
5735
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005736StmtResult
5737Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
5738 SourceLocation EndLoc,
5739 OpenMPDirectiveKind CancelRegion) {
5740 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5741 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5742 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5743 << getOpenMPDirectiveName(CancelRegion);
5744 return StmtError();
5745 }
5746 if (DSAStack->isParentNowaitRegion()) {
5747 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
5748 return StmtError();
5749 }
5750 if (DSAStack->isParentOrderedRegion()) {
5751 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
5752 return StmtError();
5753 }
5754 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
5755 CancelRegion);
5756}
5757
Alexey Bataev87933c72015-09-18 08:07:34 +00005758StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
5759 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00005760 SourceLocation EndLoc,
5761 OpenMPDirectiveKind CancelRegion) {
5762 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5763 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5764 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5765 << getOpenMPDirectiveName(CancelRegion);
5766 return StmtError();
5767 }
5768 if (DSAStack->isParentNowaitRegion()) {
5769 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
5770 return StmtError();
5771 }
5772 if (DSAStack->isParentOrderedRegion()) {
5773 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
5774 return StmtError();
5775 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005776 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00005777 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5778 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00005779}
5780
Alexey Bataev382967a2015-12-08 12:06:20 +00005781static bool checkGrainsizeNumTasksClauses(Sema &S,
5782 ArrayRef<OMPClause *> Clauses) {
5783 OMPClause *PrevClause = nullptr;
5784 bool ErrorFound = false;
5785 for (auto *C : Clauses) {
5786 if (C->getClauseKind() == OMPC_grainsize ||
5787 C->getClauseKind() == OMPC_num_tasks) {
5788 if (!PrevClause)
5789 PrevClause = C;
5790 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
5791 S.Diag(C->getLocStart(),
5792 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
5793 << getOpenMPClauseName(C->getClauseKind())
5794 << getOpenMPClauseName(PrevClause->getClauseKind());
5795 S.Diag(PrevClause->getLocStart(),
5796 diag::note_omp_previous_grainsize_num_tasks)
5797 << getOpenMPClauseName(PrevClause->getClauseKind());
5798 ErrorFound = true;
5799 }
5800 }
5801 }
5802 return ErrorFound;
5803}
5804
Alexey Bataev49f6e782015-12-01 04:18:41 +00005805StmtResult Sema::ActOnOpenMPTaskLoopDirective(
5806 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5807 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005808 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00005809 if (!AStmt)
5810 return StmtError();
5811
5812 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5813 OMPLoopDirective::HelperExprs B;
5814 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5815 // define the nested loops number.
5816 unsigned NestedLoopCount =
5817 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005818 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00005819 VarsWithImplicitDSA, B);
5820 if (NestedLoopCount == 0)
5821 return StmtError();
5822
5823 assert((CurContext->isDependentContext() || B.builtAll()) &&
5824 "omp for loop exprs were not built");
5825
Alexey Bataev382967a2015-12-08 12:06:20 +00005826 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5827 // The grainsize clause and num_tasks clause are mutually exclusive and may
5828 // not appear on the same taskloop directive.
5829 if (checkGrainsizeNumTasksClauses(*this, Clauses))
5830 return StmtError();
5831
Alexey Bataev49f6e782015-12-01 04:18:41 +00005832 getCurFunction()->setHasBranchProtectedScope();
5833 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
5834 NestedLoopCount, Clauses, AStmt, B);
5835}
5836
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005837StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
5838 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5839 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005840 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005841 if (!AStmt)
5842 return StmtError();
5843
5844 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5845 OMPLoopDirective::HelperExprs B;
5846 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5847 // define the nested loops number.
5848 unsigned NestedLoopCount =
5849 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
5850 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
5851 VarsWithImplicitDSA, B);
5852 if (NestedLoopCount == 0)
5853 return StmtError();
5854
5855 assert((CurContext->isDependentContext() || B.builtAll()) &&
5856 "omp for loop exprs were not built");
5857
Alexey Bataev5a3af132016-03-29 08:58:54 +00005858 if (!CurContext->isDependentContext()) {
5859 // Finalize the clauses that need pre-built expressions for CodeGen.
5860 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005861 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00005862 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005863 B.NumIterations, *this, CurScope,
5864 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00005865 return StmtError();
5866 }
5867 }
5868
Alexey Bataev382967a2015-12-08 12:06:20 +00005869 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5870 // The grainsize clause and num_tasks clause are mutually exclusive and may
5871 // not appear on the same taskloop directive.
5872 if (checkGrainsizeNumTasksClauses(*this, Clauses))
5873 return StmtError();
5874
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005875 getCurFunction()->setHasBranchProtectedScope();
5876 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
5877 NestedLoopCount, Clauses, AStmt, B);
5878}
5879
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005880StmtResult Sema::ActOnOpenMPDistributeDirective(
5881 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5882 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005883 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005884 if (!AStmt)
5885 return StmtError();
5886
5887 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5888 OMPLoopDirective::HelperExprs B;
5889 // In presence of clause 'collapse' with number of loops, it will
5890 // define the nested loops number.
5891 unsigned NestedLoopCount =
5892 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
5893 nullptr /*ordered not a clause on distribute*/, AStmt,
5894 *this, *DSAStack, VarsWithImplicitDSA, B);
5895 if (NestedLoopCount == 0)
5896 return StmtError();
5897
5898 assert((CurContext->isDependentContext() || B.builtAll()) &&
5899 "omp for loop exprs were not built");
5900
5901 getCurFunction()->setHasBranchProtectedScope();
5902 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
5903 NestedLoopCount, Clauses, AStmt, B);
5904}
5905
Carlo Bertolli9925f152016-06-27 14:55:37 +00005906StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
5907 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5908 SourceLocation EndLoc,
5909 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5910 if (!AStmt)
5911 return StmtError();
5912
5913 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5914 // 1.2.2 OpenMP Language Terminology
5915 // Structured block - An executable statement with a single entry at the
5916 // top and a single exit at the bottom.
5917 // The point of exit cannot be a branch out of the structured block.
5918 // longjmp() and throw() must not violate the entry/exit criteria.
5919 CS->getCapturedDecl()->setNothrow();
5920
5921 OMPLoopDirective::HelperExprs B;
5922 // In presence of clause 'collapse' with number of loops, it will
5923 // define the nested loops number.
5924 unsigned NestedLoopCount = CheckOpenMPLoop(
5925 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
5926 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
5927 VarsWithImplicitDSA, B);
5928 if (NestedLoopCount == 0)
5929 return StmtError();
5930
5931 assert((CurContext->isDependentContext() || B.builtAll()) &&
5932 "omp for loop exprs were not built");
5933
5934 getCurFunction()->setHasBranchProtectedScope();
5935 return OMPDistributeParallelForDirective::Create(
5936 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
5937}
5938
Kelvin Li4a39add2016-07-05 05:00:15 +00005939StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
5940 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5941 SourceLocation EndLoc,
5942 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5943 if (!AStmt)
5944 return StmtError();
5945
5946 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5947 // 1.2.2 OpenMP Language Terminology
5948 // Structured block - An executable statement with a single entry at the
5949 // top and a single exit at the bottom.
5950 // The point of exit cannot be a branch out of the structured block.
5951 // longjmp() and throw() must not violate the entry/exit criteria.
5952 CS->getCapturedDecl()->setNothrow();
5953
5954 OMPLoopDirective::HelperExprs B;
5955 // In presence of clause 'collapse' with number of loops, it will
5956 // define the nested loops number.
5957 unsigned NestedLoopCount = CheckOpenMPLoop(
5958 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
5959 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
5960 VarsWithImplicitDSA, B);
5961 if (NestedLoopCount == 0)
5962 return StmtError();
5963
5964 assert((CurContext->isDependentContext() || B.builtAll()) &&
5965 "omp for loop exprs were not built");
5966
Kelvin Lic5609492016-07-15 04:39:07 +00005967 if (checkSimdlenSafelenSpecified(*this, Clauses))
5968 return StmtError();
5969
Kelvin Li4a39add2016-07-05 05:00:15 +00005970 getCurFunction()->setHasBranchProtectedScope();
5971 return OMPDistributeParallelForSimdDirective::Create(
5972 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
5973}
5974
Kelvin Li787f3fc2016-07-06 04:45:38 +00005975StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
5976 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5977 SourceLocation EndLoc,
5978 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5979 if (!AStmt)
5980 return StmtError();
5981
5982 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5983 // 1.2.2 OpenMP Language Terminology
5984 // Structured block - An executable statement with a single entry at the
5985 // top and a single exit at the bottom.
5986 // The point of exit cannot be a branch out of the structured block.
5987 // longjmp() and throw() must not violate the entry/exit criteria.
5988 CS->getCapturedDecl()->setNothrow();
5989
5990 OMPLoopDirective::HelperExprs B;
5991 // In presence of clause 'collapse' with number of loops, it will
5992 // define the nested loops number.
5993 unsigned NestedLoopCount =
5994 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
5995 nullptr /*ordered not a clause on distribute*/, AStmt,
5996 *this, *DSAStack, VarsWithImplicitDSA, B);
5997 if (NestedLoopCount == 0)
5998 return StmtError();
5999
6000 assert((CurContext->isDependentContext() || B.builtAll()) &&
6001 "omp for loop exprs were not built");
6002
Kelvin Lic5609492016-07-15 04:39:07 +00006003 if (checkSimdlenSafelenSpecified(*this, Clauses))
6004 return StmtError();
6005
Kelvin Li787f3fc2016-07-06 04:45:38 +00006006 getCurFunction()->setHasBranchProtectedScope();
6007 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
6008 NestedLoopCount, Clauses, AStmt, B);
6009}
6010
Kelvin Lia579b912016-07-14 02:54:56 +00006011StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
6012 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6013 SourceLocation EndLoc,
6014 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6015 if (!AStmt)
6016 return StmtError();
6017
6018 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6019 // 1.2.2 OpenMP Language Terminology
6020 // Structured block - An executable statement with a single entry at the
6021 // top and a single exit at the bottom.
6022 // The point of exit cannot be a branch out of the structured block.
6023 // longjmp() and throw() must not violate the entry/exit criteria.
6024 CS->getCapturedDecl()->setNothrow();
6025
6026 OMPLoopDirective::HelperExprs B;
6027 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6028 // define the nested loops number.
6029 unsigned NestedLoopCount = CheckOpenMPLoop(
6030 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
6031 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6032 VarsWithImplicitDSA, B);
6033 if (NestedLoopCount == 0)
6034 return StmtError();
6035
6036 assert((CurContext->isDependentContext() || B.builtAll()) &&
6037 "omp target parallel for simd loop exprs were not built");
6038
6039 if (!CurContext->isDependentContext()) {
6040 // Finalize the clauses that need pre-built expressions for CodeGen.
6041 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006042 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00006043 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6044 B.NumIterations, *this, CurScope,
6045 DSAStack))
6046 return StmtError();
6047 }
6048 }
Kelvin Lic5609492016-07-15 04:39:07 +00006049 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00006050 return StmtError();
6051
6052 getCurFunction()->setHasBranchProtectedScope();
6053 return OMPTargetParallelForSimdDirective::Create(
6054 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6055}
6056
Kelvin Li986330c2016-07-20 22:57:10 +00006057StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6058 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6059 SourceLocation EndLoc,
6060 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6061 if (!AStmt)
6062 return StmtError();
6063
6064 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6065 // 1.2.2 OpenMP Language Terminology
6066 // Structured block - An executable statement with a single entry at the
6067 // top and a single exit at the bottom.
6068 // The point of exit cannot be a branch out of the structured block.
6069 // longjmp() and throw() must not violate the entry/exit criteria.
6070 CS->getCapturedDecl()->setNothrow();
6071
6072 OMPLoopDirective::HelperExprs B;
6073 // In presence of clause 'collapse' with number of loops, it will define the
6074 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00006075 unsigned NestedLoopCount =
Kelvin Li986330c2016-07-20 22:57:10 +00006076 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
6077 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6078 VarsWithImplicitDSA, B);
6079 if (NestedLoopCount == 0)
6080 return StmtError();
6081
6082 assert((CurContext->isDependentContext() || B.builtAll()) &&
6083 "omp target simd loop exprs were not built");
6084
6085 if (!CurContext->isDependentContext()) {
6086 // Finalize the clauses that need pre-built expressions for CodeGen.
6087 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006088 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00006089 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6090 B.NumIterations, *this, CurScope,
6091 DSAStack))
6092 return StmtError();
6093 }
6094 }
6095
6096 if (checkSimdlenSafelenSpecified(*this, Clauses))
6097 return StmtError();
6098
6099 getCurFunction()->setHasBranchProtectedScope();
6100 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
6101 NestedLoopCount, Clauses, AStmt, B);
6102}
6103
Kelvin Li02532872016-08-05 14:37:37 +00006104StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
6105 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6106 SourceLocation EndLoc,
6107 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6108 if (!AStmt)
6109 return StmtError();
6110
6111 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6112 // 1.2.2 OpenMP Language Terminology
6113 // Structured block - An executable statement with a single entry at the
6114 // top and a single exit at the bottom.
6115 // The point of exit cannot be a branch out of the structured block.
6116 // longjmp() and throw() must not violate the entry/exit criteria.
6117 CS->getCapturedDecl()->setNothrow();
6118
6119 OMPLoopDirective::HelperExprs B;
6120 // In presence of clause 'collapse' with number of loops, it will
6121 // define the nested loops number.
6122 unsigned NestedLoopCount =
6123 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
6124 nullptr /*ordered not a clause on distribute*/, AStmt,
6125 *this, *DSAStack, VarsWithImplicitDSA, B);
6126 if (NestedLoopCount == 0)
6127 return StmtError();
6128
6129 assert((CurContext->isDependentContext() || B.builtAll()) &&
6130 "omp teams distribute loop exprs were not built");
6131
6132 getCurFunction()->setHasBranchProtectedScope();
David Majnemer9d168222016-08-05 17:44:54 +00006133 return OMPTeamsDistributeDirective::Create(
6134 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00006135}
6136
Kelvin Li4e325f72016-10-25 12:50:55 +00006137StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
6138 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6139 SourceLocation EndLoc,
6140 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6141 if (!AStmt)
6142 return StmtError();
6143
6144 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6145 // 1.2.2 OpenMP Language Terminology
6146 // Structured block - An executable statement with a single entry at the
6147 // top and a single exit at the bottom.
6148 // The point of exit cannot be a branch out of the structured block.
6149 // longjmp() and throw() must not violate the entry/exit criteria.
6150 CS->getCapturedDecl()->setNothrow();
6151
6152 OMPLoopDirective::HelperExprs B;
6153 // In presence of clause 'collapse' with number of loops, it will
6154 // define the nested loops number.
Samuel Antao4c8035b2016-12-12 18:00:20 +00006155 unsigned NestedLoopCount = CheckOpenMPLoop(
6156 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6157 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6158 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00006159
6160 if (NestedLoopCount == 0)
6161 return StmtError();
6162
6163 assert((CurContext->isDependentContext() || B.builtAll()) &&
6164 "omp teams distribute simd loop exprs were not built");
6165
6166 if (!CurContext->isDependentContext()) {
6167 // Finalize the clauses that need pre-built expressions for CodeGen.
6168 for (auto C : Clauses) {
6169 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6170 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6171 B.NumIterations, *this, CurScope,
6172 DSAStack))
6173 return StmtError();
6174 }
6175 }
6176
6177 if (checkSimdlenSafelenSpecified(*this, Clauses))
6178 return StmtError();
6179
6180 getCurFunction()->setHasBranchProtectedScope();
6181 return OMPTeamsDistributeSimdDirective::Create(
6182 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6183}
6184
Kelvin Li579e41c2016-11-30 23:51:03 +00006185StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6186 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6187 SourceLocation EndLoc,
6188 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6189 if (!AStmt)
6190 return StmtError();
6191
6192 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6193 // 1.2.2 OpenMP Language Terminology
6194 // Structured block - An executable statement with a single entry at the
6195 // top and a single exit at the bottom.
6196 // The point of exit cannot be a branch out of the structured block.
6197 // longjmp() and throw() must not violate the entry/exit criteria.
6198 CS->getCapturedDecl()->setNothrow();
6199
6200 OMPLoopDirective::HelperExprs B;
6201 // In presence of clause 'collapse' with number of loops, it will
6202 // define the nested loops number.
6203 auto NestedLoopCount = CheckOpenMPLoop(
6204 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6205 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6206 VarsWithImplicitDSA, B);
6207
6208 if (NestedLoopCount == 0)
6209 return StmtError();
6210
6211 assert((CurContext->isDependentContext() || B.builtAll()) &&
6212 "omp for loop exprs were not built");
6213
6214 if (!CurContext->isDependentContext()) {
6215 // Finalize the clauses that need pre-built expressions for CodeGen.
6216 for (auto C : Clauses) {
6217 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6218 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6219 B.NumIterations, *this, CurScope,
6220 DSAStack))
6221 return StmtError();
6222 }
6223 }
6224
6225 if (checkSimdlenSafelenSpecified(*this, Clauses))
6226 return StmtError();
6227
6228 getCurFunction()->setHasBranchProtectedScope();
6229 return OMPTeamsDistributeParallelForSimdDirective::Create(
6230 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6231}
6232
Kelvin Li7ade93f2016-12-09 03:24:30 +00006233StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
6234 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6235 SourceLocation EndLoc,
6236 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6237 if (!AStmt)
6238 return StmtError();
6239
6240 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6241 // 1.2.2 OpenMP Language Terminology
6242 // Structured block - An executable statement with a single entry at the
6243 // top and a single exit at the bottom.
6244 // The point of exit cannot be a branch out of the structured block.
6245 // longjmp() and throw() must not violate the entry/exit criteria.
6246 CS->getCapturedDecl()->setNothrow();
6247
6248 OMPLoopDirective::HelperExprs B;
6249 // In presence of clause 'collapse' with number of loops, it will
6250 // define the nested loops number.
6251 unsigned NestedLoopCount = CheckOpenMPLoop(
6252 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6253 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6254 VarsWithImplicitDSA, B);
6255
6256 if (NestedLoopCount == 0)
6257 return StmtError();
6258
6259 assert((CurContext->isDependentContext() || B.builtAll()) &&
6260 "omp for loop exprs were not built");
6261
6262 if (!CurContext->isDependentContext()) {
6263 // Finalize the clauses that need pre-built expressions for CodeGen.
6264 for (auto C : Clauses) {
6265 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6266 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6267 B.NumIterations, *this, CurScope,
6268 DSAStack))
6269 return StmtError();
6270 }
6271 }
6272
6273 getCurFunction()->setHasBranchProtectedScope();
6274 return OMPTeamsDistributeParallelForDirective::Create(
6275 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6276}
6277
Kelvin Libf594a52016-12-17 05:48:59 +00006278StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
6279 Stmt *AStmt,
6280 SourceLocation StartLoc,
6281 SourceLocation EndLoc) {
6282 if (!AStmt)
6283 return StmtError();
6284
6285 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6286 // 1.2.2 OpenMP Language Terminology
6287 // Structured block - An executable statement with a single entry at the
6288 // top and a single exit at the bottom.
6289 // The point of exit cannot be a branch out of the structured block.
6290 // longjmp() and throw() must not violate the entry/exit criteria.
6291 CS->getCapturedDecl()->setNothrow();
6292
6293 getCurFunction()->setHasBranchProtectedScope();
6294
6295 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
6296 AStmt);
6297}
6298
Kelvin Li83c451e2016-12-25 04:52:54 +00006299StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
6300 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6301 SourceLocation EndLoc,
6302 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6303 if (!AStmt)
6304 return StmtError();
6305
6306 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6307 // 1.2.2 OpenMP Language Terminology
6308 // Structured block - An executable statement with a single entry at the
6309 // top and a single exit at the bottom.
6310 // The point of exit cannot be a branch out of the structured block.
6311 // longjmp() and throw() must not violate the entry/exit criteria.
6312 CS->getCapturedDecl()->setNothrow();
6313
6314 OMPLoopDirective::HelperExprs B;
6315 // In presence of clause 'collapse' with number of loops, it will
6316 // define the nested loops number.
6317 auto NestedLoopCount = CheckOpenMPLoop(
6318 OMPD_target_teams_distribute,
6319 getCollapseNumberExpr(Clauses),
6320 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6321 VarsWithImplicitDSA, B);
6322 if (NestedLoopCount == 0)
6323 return StmtError();
6324
6325 assert((CurContext->isDependentContext() || B.builtAll()) &&
6326 "omp target teams distribute loop exprs were not built");
6327
6328 getCurFunction()->setHasBranchProtectedScope();
6329 return OMPTargetTeamsDistributeDirective::Create(
6330 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6331}
6332
Kelvin Li80e8f562016-12-29 22:16:30 +00006333StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
6334 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6335 SourceLocation EndLoc,
6336 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6337 if (!AStmt)
6338 return StmtError();
6339
6340 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6341 // 1.2.2 OpenMP Language Terminology
6342 // Structured block - An executable statement with a single entry at the
6343 // top and a single exit at the bottom.
6344 // The point of exit cannot be a branch out of the structured block.
6345 // longjmp() and throw() must not violate the entry/exit criteria.
6346 CS->getCapturedDecl()->setNothrow();
6347
6348 OMPLoopDirective::HelperExprs B;
6349 // In presence of clause 'collapse' with number of loops, it will
6350 // define the nested loops number.
6351 auto NestedLoopCount = CheckOpenMPLoop(
6352 OMPD_target_teams_distribute_parallel_for,
6353 getCollapseNumberExpr(Clauses),
6354 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6355 VarsWithImplicitDSA, B);
6356 if (NestedLoopCount == 0)
6357 return StmtError();
6358
6359 assert((CurContext->isDependentContext() || B.builtAll()) &&
6360 "omp target teams distribute parallel for loop exprs were not built");
6361
6362 if (!CurContext->isDependentContext()) {
6363 // Finalize the clauses that need pre-built expressions for CodeGen.
6364 for (auto C : Clauses) {
6365 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6366 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6367 B.NumIterations, *this, CurScope,
6368 DSAStack))
6369 return StmtError();
6370 }
6371 }
6372
6373 getCurFunction()->setHasBranchProtectedScope();
6374 return OMPTargetTeamsDistributeParallelForDirective::Create(
6375 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6376}
6377
Alexey Bataeved09d242014-05-28 05:53:51 +00006378OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006379 SourceLocation StartLoc,
6380 SourceLocation LParenLoc,
6381 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006382 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006383 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00006384 case OMPC_final:
6385 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
6386 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00006387 case OMPC_num_threads:
6388 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
6389 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006390 case OMPC_safelen:
6391 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
6392 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00006393 case OMPC_simdlen:
6394 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
6395 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00006396 case OMPC_collapse:
6397 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
6398 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006399 case OMPC_ordered:
6400 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
6401 break;
Michael Wonge710d542015-08-07 16:16:36 +00006402 case OMPC_device:
6403 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
6404 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00006405 case OMPC_num_teams:
6406 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
6407 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006408 case OMPC_thread_limit:
6409 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
6410 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00006411 case OMPC_priority:
6412 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
6413 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006414 case OMPC_grainsize:
6415 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
6416 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00006417 case OMPC_num_tasks:
6418 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
6419 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00006420 case OMPC_hint:
6421 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
6422 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006423 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006424 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006425 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006426 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006427 case OMPC_private:
6428 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00006429 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006430 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00006431 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00006432 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006433 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006434 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006435 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00006436 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006437 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006438 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006439 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006440 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006441 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006442 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006443 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006444 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006445 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006446 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00006447 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006448 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006449 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00006450 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00006451 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006452 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006453 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006454 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006455 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006456 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006457 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006458 case OMPC_is_device_ptr:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006459 llvm_unreachable("Clause is not allowed.");
6460 }
6461 return Res;
6462}
6463
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006464OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
6465 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006466 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006467 SourceLocation NameModifierLoc,
6468 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006469 SourceLocation EndLoc) {
6470 Expr *ValExpr = Condition;
6471 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6472 !Condition->isInstantiationDependent() &&
6473 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00006474 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006475 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006476 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006477
Richard Smith03a4aa32016-06-23 19:02:52 +00006478 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006479 }
6480
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006481 return new (Context) OMPIfClause(NameModifier, ValExpr, StartLoc, LParenLoc,
6482 NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006483}
6484
Alexey Bataev3778b602014-07-17 07:32:53 +00006485OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
6486 SourceLocation StartLoc,
6487 SourceLocation LParenLoc,
6488 SourceLocation EndLoc) {
6489 Expr *ValExpr = Condition;
6490 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6491 !Condition->isInstantiationDependent() &&
6492 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00006493 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00006494 if (Val.isInvalid())
6495 return nullptr;
6496
Richard Smith03a4aa32016-06-23 19:02:52 +00006497 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00006498 }
6499
6500 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
6501}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006502ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
6503 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00006504 if (!Op)
6505 return ExprError();
6506
6507 class IntConvertDiagnoser : public ICEConvertDiagnoser {
6508 public:
6509 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00006510 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00006511 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
6512 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006513 return S.Diag(Loc, diag::err_omp_not_integral) << T;
6514 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006515 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
6516 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006517 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
6518 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006519 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
6520 QualType T,
6521 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006522 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
6523 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006524 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
6525 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006526 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00006527 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00006528 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006529 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
6530 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006531 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
6532 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006533 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
6534 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006535 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00006536 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00006537 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006538 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
6539 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006540 llvm_unreachable("conversion functions are permitted");
6541 }
6542 } ConvertDiagnoser;
6543 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
6544}
6545
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006546static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00006547 OpenMPClauseKind CKind,
6548 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006549 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
6550 !ValExpr->isInstantiationDependent()) {
6551 SourceLocation Loc = ValExpr->getExprLoc();
6552 ExprResult Value =
6553 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
6554 if (Value.isInvalid())
6555 return false;
6556
6557 ValExpr = Value.get();
6558 // The expression must evaluate to a non-negative integer value.
6559 llvm::APSInt Result;
6560 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00006561 Result.isSigned() &&
6562 !((!StrictlyPositive && Result.isNonNegative()) ||
6563 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006564 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00006565 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
6566 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006567 return false;
6568 }
6569 }
6570 return true;
6571}
6572
Alexey Bataev568a8332014-03-06 06:15:19 +00006573OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
6574 SourceLocation StartLoc,
6575 SourceLocation LParenLoc,
6576 SourceLocation EndLoc) {
6577 Expr *ValExpr = NumThreads;
Alexey Bataev568a8332014-03-06 06:15:19 +00006578
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006579 // OpenMP [2.5, Restrictions]
6580 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00006581 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
6582 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006583 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00006584
Alexey Bataeved09d242014-05-28 05:53:51 +00006585 return new (Context)
6586 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00006587}
6588
Alexey Bataev62c87d22014-03-21 04:51:18 +00006589ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006590 OpenMPClauseKind CKind,
6591 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00006592 if (!E)
6593 return ExprError();
6594 if (E->isValueDependent() || E->isTypeDependent() ||
6595 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006596 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006597 llvm::APSInt Result;
6598 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
6599 if (ICE.isInvalid())
6600 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006601 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
6602 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00006603 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006604 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
6605 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00006606 return ExprError();
6607 }
Alexander Musman09184fe2014-09-30 05:29:28 +00006608 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
6609 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
6610 << E->getSourceRange();
6611 return ExprError();
6612 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006613 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
6614 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00006615 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006616 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00006617 return ICE;
6618}
6619
6620OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
6621 SourceLocation LParenLoc,
6622 SourceLocation EndLoc) {
6623 // OpenMP [2.8.1, simd construct, Description]
6624 // The parameter of the safelen clause must be a constant
6625 // positive integer expression.
6626 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
6627 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006628 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006629 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006630 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00006631}
6632
Alexey Bataev66b15b52015-08-21 11:14:16 +00006633OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
6634 SourceLocation LParenLoc,
6635 SourceLocation EndLoc) {
6636 // OpenMP [2.8.1, simd construct, Description]
6637 // The parameter of the simdlen clause must be a constant
6638 // positive integer expression.
6639 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
6640 if (Simdlen.isInvalid())
6641 return nullptr;
6642 return new (Context)
6643 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
6644}
6645
Alexander Musman64d33f12014-06-04 07:53:32 +00006646OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
6647 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00006648 SourceLocation LParenLoc,
6649 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00006650 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00006651 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00006652 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00006653 // The parameter of the collapse clause must be a constant
6654 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00006655 ExprResult NumForLoopsResult =
6656 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
6657 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00006658 return nullptr;
6659 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00006660 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00006661}
6662
Alexey Bataev10e775f2015-07-30 11:36:16 +00006663OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
6664 SourceLocation EndLoc,
6665 SourceLocation LParenLoc,
6666 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00006667 // OpenMP [2.7.1, loop construct, Description]
6668 // OpenMP [2.8.1, simd construct, Description]
6669 // OpenMP [2.9.6, distribute construct, Description]
6670 // The parameter of the ordered clause must be a constant
6671 // positive integer expression if any.
6672 if (NumForLoops && LParenLoc.isValid()) {
6673 ExprResult NumForLoopsResult =
6674 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
6675 if (NumForLoopsResult.isInvalid())
6676 return nullptr;
6677 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00006678 } else
6679 NumForLoops = nullptr;
6680 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00006681 return new (Context)
6682 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
6683}
6684
Alexey Bataeved09d242014-05-28 05:53:51 +00006685OMPClause *Sema::ActOnOpenMPSimpleClause(
6686 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
6687 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006688 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006689 switch (Kind) {
6690 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00006691 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00006692 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
6693 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006694 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006695 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00006696 Res = ActOnOpenMPProcBindClause(
6697 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
6698 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006699 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006700 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00006701 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00006702 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00006703 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00006704 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00006705 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006706 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006707 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006708 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00006709 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00006710 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00006711 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00006712 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006713 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006714 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006715 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006716 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00006717 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006718 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006719 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006720 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006721 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006722 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006723 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006724 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006725 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006726 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006727 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00006728 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00006729 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006730 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006731 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00006732 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006733 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00006734 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006735 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00006736 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00006737 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00006738 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00006739 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006740 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006741 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006742 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006743 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006744 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006745 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006746 case OMPC_is_device_ptr:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006747 llvm_unreachable("Clause is not allowed.");
6748 }
6749 return Res;
6750}
6751
Alexey Bataev6402bca2015-12-28 07:25:51 +00006752static std::string
6753getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
6754 ArrayRef<unsigned> Exclude = llvm::None) {
6755 std::string Values;
6756 unsigned Bound = Last >= 2 ? Last - 2 : 0;
6757 unsigned Skipped = Exclude.size();
6758 auto S = Exclude.begin(), E = Exclude.end();
6759 for (unsigned i = First; i < Last; ++i) {
6760 if (std::find(S, E, i) != E) {
6761 --Skipped;
6762 continue;
6763 }
6764 Values += "'";
6765 Values += getOpenMPSimpleClauseTypeName(K, i);
6766 Values += "'";
6767 if (i == Bound - Skipped)
6768 Values += " or ";
6769 else if (i != Bound + 1 - Skipped)
6770 Values += ", ";
6771 }
6772 return Values;
6773}
6774
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006775OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
6776 SourceLocation KindKwLoc,
6777 SourceLocation StartLoc,
6778 SourceLocation LParenLoc,
6779 SourceLocation EndLoc) {
6780 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00006781 static_assert(OMPC_DEFAULT_unknown > 0,
6782 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006783 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00006784 << getListOfPossibleValues(OMPC_default, /*First=*/0,
6785 /*Last=*/OMPC_DEFAULT_unknown)
6786 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006787 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006788 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00006789 switch (Kind) {
6790 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006791 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00006792 break;
6793 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006794 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00006795 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006796 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006797 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00006798 break;
6799 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006800 return new (Context)
6801 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006802}
6803
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006804OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
6805 SourceLocation KindKwLoc,
6806 SourceLocation StartLoc,
6807 SourceLocation LParenLoc,
6808 SourceLocation EndLoc) {
6809 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006810 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00006811 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
6812 /*Last=*/OMPC_PROC_BIND_unknown)
6813 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006814 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006815 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006816 return new (Context)
6817 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006818}
6819
Alexey Bataev56dafe82014-06-20 07:16:17 +00006820OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00006821 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00006822 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00006823 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00006824 SourceLocation EndLoc) {
6825 OMPClause *Res = nullptr;
6826 switch (Kind) {
6827 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00006828 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
6829 assert(Argument.size() == NumberOfElements &&
6830 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00006831 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00006832 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
6833 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
6834 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
6835 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
6836 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00006837 break;
6838 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00006839 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
6840 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
6841 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
6842 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006843 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00006844 case OMPC_dist_schedule:
6845 Res = ActOnOpenMPDistScheduleClause(
6846 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
6847 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
6848 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006849 case OMPC_defaultmap:
6850 enum { Modifier, DefaultmapKind };
6851 Res = ActOnOpenMPDefaultmapClause(
6852 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
6853 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00006854 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
6855 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006856 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00006857 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006858 case OMPC_num_threads:
6859 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00006860 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006861 case OMPC_collapse:
6862 case OMPC_default:
6863 case OMPC_proc_bind:
6864 case OMPC_private:
6865 case OMPC_firstprivate:
6866 case OMPC_lastprivate:
6867 case OMPC_shared:
6868 case OMPC_reduction:
6869 case OMPC_linear:
6870 case OMPC_aligned:
6871 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006872 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006873 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00006874 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006875 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006876 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006877 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006878 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006879 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006880 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006881 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006882 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006883 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006884 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00006885 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00006886 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006887 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006888 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00006889 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006890 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00006891 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006892 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00006893 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00006894 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00006895 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006896 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006897 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006898 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006899 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006900 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006901 case OMPC_is_device_ptr:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006902 llvm_unreachable("Clause is not allowed.");
6903 }
6904 return Res;
6905}
6906
Alexey Bataev6402bca2015-12-28 07:25:51 +00006907static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
6908 OpenMPScheduleClauseModifier M2,
6909 SourceLocation M1Loc, SourceLocation M2Loc) {
6910 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
6911 SmallVector<unsigned, 2> Excluded;
6912 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
6913 Excluded.push_back(M2);
6914 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
6915 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
6916 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
6917 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
6918 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
6919 << getListOfPossibleValues(OMPC_schedule,
6920 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
6921 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
6922 Excluded)
6923 << getOpenMPClauseName(OMPC_schedule);
6924 return true;
6925 }
6926 return false;
6927}
6928
Alexey Bataev56dafe82014-06-20 07:16:17 +00006929OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00006930 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00006931 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00006932 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
6933 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
6934 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
6935 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
6936 return nullptr;
6937 // OpenMP, 2.7.1, Loop Construct, Restrictions
6938 // Either the monotonic modifier or the nonmonotonic modifier can be specified
6939 // but not both.
6940 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
6941 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
6942 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
6943 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
6944 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
6945 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
6946 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
6947 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
6948 return nullptr;
6949 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00006950 if (Kind == OMPC_SCHEDULE_unknown) {
6951 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00006952 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
6953 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
6954 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
6955 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
6956 Exclude);
6957 } else {
6958 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
6959 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00006960 }
6961 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
6962 << Values << getOpenMPClauseName(OMPC_schedule);
6963 return nullptr;
6964 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00006965 // OpenMP, 2.7.1, Loop Construct, Restrictions
6966 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
6967 // schedule(guided).
6968 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
6969 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
6970 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
6971 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
6972 diag::err_omp_schedule_nonmonotonic_static);
6973 return nullptr;
6974 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00006975 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00006976 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00006977 if (ChunkSize) {
6978 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
6979 !ChunkSize->isInstantiationDependent() &&
6980 !ChunkSize->containsUnexpandedParameterPack()) {
6981 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
6982 ExprResult Val =
6983 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
6984 if (Val.isInvalid())
6985 return nullptr;
6986
6987 ValExpr = Val.get();
6988
6989 // OpenMP [2.7.1, Restrictions]
6990 // chunk_size must be a loop invariant integer expression with a positive
6991 // value.
6992 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00006993 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
6994 if (Result.isSigned() && !Result.isStrictlyPositive()) {
6995 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00006996 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00006997 return nullptr;
6998 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +00006999 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
7000 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007001 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7002 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7003 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007004 }
7005 }
7006 }
7007
Alexey Bataev6402bca2015-12-28 07:25:51 +00007008 return new (Context)
7009 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00007010 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007011}
7012
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007013OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
7014 SourceLocation StartLoc,
7015 SourceLocation EndLoc) {
7016 OMPClause *Res = nullptr;
7017 switch (Kind) {
7018 case OMPC_ordered:
7019 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
7020 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00007021 case OMPC_nowait:
7022 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
7023 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007024 case OMPC_untied:
7025 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
7026 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007027 case OMPC_mergeable:
7028 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
7029 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007030 case OMPC_read:
7031 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
7032 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00007033 case OMPC_write:
7034 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
7035 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00007036 case OMPC_update:
7037 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
7038 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00007039 case OMPC_capture:
7040 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
7041 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007042 case OMPC_seq_cst:
7043 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
7044 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00007045 case OMPC_threads:
7046 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
7047 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007048 case OMPC_simd:
7049 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
7050 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00007051 case OMPC_nogroup:
7052 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
7053 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007054 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007055 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007056 case OMPC_num_threads:
7057 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007058 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007059 case OMPC_collapse:
7060 case OMPC_schedule:
7061 case OMPC_private:
7062 case OMPC_firstprivate:
7063 case OMPC_lastprivate:
7064 case OMPC_shared:
7065 case OMPC_reduction:
7066 case OMPC_linear:
7067 case OMPC_aligned:
7068 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007069 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007070 case OMPC_default:
7071 case OMPC_proc_bind:
7072 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007073 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007074 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007075 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007076 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007077 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007078 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007079 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007080 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00007081 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007082 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007083 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007084 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007085 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007086 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007087 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007088 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007089 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007090 case OMPC_is_device_ptr:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007091 llvm_unreachable("Clause is not allowed.");
7092 }
7093 return Res;
7094}
7095
Alexey Bataev236070f2014-06-20 11:19:47 +00007096OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
7097 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007098 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00007099 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
7100}
7101
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007102OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
7103 SourceLocation EndLoc) {
7104 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
7105}
7106
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007107OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
7108 SourceLocation EndLoc) {
7109 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
7110}
7111
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007112OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
7113 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007114 return new (Context) OMPReadClause(StartLoc, EndLoc);
7115}
7116
Alexey Bataevdea47612014-07-23 07:46:59 +00007117OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
7118 SourceLocation EndLoc) {
7119 return new (Context) OMPWriteClause(StartLoc, EndLoc);
7120}
7121
Alexey Bataev67a4f222014-07-23 10:25:33 +00007122OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
7123 SourceLocation EndLoc) {
7124 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
7125}
7126
Alexey Bataev459dec02014-07-24 06:46:57 +00007127OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
7128 SourceLocation EndLoc) {
7129 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
7130}
7131
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007132OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
7133 SourceLocation EndLoc) {
7134 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
7135}
7136
Alexey Bataev346265e2015-09-25 10:37:12 +00007137OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
7138 SourceLocation EndLoc) {
7139 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
7140}
7141
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007142OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
7143 SourceLocation EndLoc) {
7144 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
7145}
7146
Alexey Bataevb825de12015-12-07 10:51:44 +00007147OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
7148 SourceLocation EndLoc) {
7149 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
7150}
7151
Alexey Bataevc5e02582014-06-16 07:08:35 +00007152OMPClause *Sema::ActOnOpenMPVarListClause(
7153 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
7154 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
7155 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007156 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00007157 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
7158 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
7159 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007160 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007161 switch (Kind) {
7162 case OMPC_private:
7163 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7164 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007165 case OMPC_firstprivate:
7166 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7167 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007168 case OMPC_lastprivate:
7169 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7170 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00007171 case OMPC_shared:
7172 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
7173 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00007174 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00007175 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
7176 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00007177 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00007178 case OMPC_linear:
7179 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00007180 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00007181 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007182 case OMPC_aligned:
7183 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
7184 ColonLoc, EndLoc);
7185 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007186 case OMPC_copyin:
7187 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
7188 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00007189 case OMPC_copyprivate:
7190 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7191 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00007192 case OMPC_flush:
7193 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
7194 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007195 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00007196 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00007197 StartLoc, LParenLoc, EndLoc);
7198 break;
7199 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00007200 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
7201 DepLinMapLoc, ColonLoc, VarList, StartLoc,
7202 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007203 break;
Samuel Antao661c0902016-05-26 17:39:58 +00007204 case OMPC_to:
7205 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
7206 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00007207 case OMPC_from:
7208 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
7209 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00007210 case OMPC_use_device_ptr:
7211 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7212 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00007213 case OMPC_is_device_ptr:
7214 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7215 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007216 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007217 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00007218 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00007219 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007220 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00007221 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007222 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007223 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007224 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007225 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007226 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007227 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007228 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007229 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007230 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007231 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007232 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007233 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007234 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00007235 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007236 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007237 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007238 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007239 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007240 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007241 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007242 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007243 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007244 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007245 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007246 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007247 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007248 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007249 llvm_unreachable("Clause is not allowed.");
7250 }
7251 return Res;
7252}
7253
Alexey Bataev90c228f2016-02-08 09:29:13 +00007254ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00007255 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00007256 ExprResult Res = BuildDeclRefExpr(
7257 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
7258 if (!Res.isUsable())
7259 return ExprError();
7260 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
7261 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
7262 if (!Res.isUsable())
7263 return ExprError();
7264 }
7265 if (VK != VK_LValue && Res.get()->isGLValue()) {
7266 Res = DefaultLvalueConversion(Res.get());
7267 if (!Res.isUsable())
7268 return ExprError();
7269 }
7270 return Res;
7271}
7272
Alexey Bataev60da77e2016-02-29 05:54:20 +00007273static std::pair<ValueDecl *, bool>
7274getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
7275 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007276 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
7277 RefExpr->containsUnexpandedParameterPack())
7278 return std::make_pair(nullptr, true);
7279
Alexey Bataevd985eda2016-02-10 11:29:16 +00007280 // OpenMP [3.1, C/C++]
7281 // A list item is a variable name.
7282 // OpenMP [2.9.3.3, Restrictions, p.1]
7283 // A variable that is part of another variable (as an array or
7284 // structure element) cannot appear in a private clause.
7285 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00007286 enum {
7287 NoArrayExpr = -1,
7288 ArraySubscript = 0,
7289 OMPArraySection = 1
7290 } IsArrayExpr = NoArrayExpr;
7291 if (AllowArraySection) {
7292 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
7293 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
7294 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7295 Base = TempASE->getBase()->IgnoreParenImpCasts();
7296 RefExpr = Base;
7297 IsArrayExpr = ArraySubscript;
7298 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
7299 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
7300 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
7301 Base = TempOASE->getBase()->IgnoreParenImpCasts();
7302 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7303 Base = TempASE->getBase()->IgnoreParenImpCasts();
7304 RefExpr = Base;
7305 IsArrayExpr = OMPArraySection;
7306 }
7307 }
7308 ELoc = RefExpr->getExprLoc();
7309 ERange = RefExpr->getSourceRange();
7310 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00007311 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
7312 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
7313 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
7314 (S.getCurrentThisType().isNull() || !ME ||
7315 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
7316 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00007317 if (IsArrayExpr != NoArrayExpr)
7318 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
7319 << ERange;
7320 else {
7321 S.Diag(ELoc,
7322 AllowArraySection
7323 ? diag::err_omp_expected_var_name_member_expr_or_array_item
7324 : diag::err_omp_expected_var_name_member_expr)
7325 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
7326 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007327 return std::make_pair(nullptr, false);
7328 }
7329 return std::make_pair(DE ? DE->getDecl() : ME->getMemberDecl(), false);
7330}
7331
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007332OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
7333 SourceLocation StartLoc,
7334 SourceLocation LParenLoc,
7335 SourceLocation EndLoc) {
7336 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00007337 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00007338 for (auto &RefExpr : VarList) {
7339 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007340 SourceLocation ELoc;
7341 SourceRange ERange;
7342 Expr *SimpleRefExpr = RefExpr;
7343 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007344 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007345 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007346 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007347 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007348 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007349 ValueDecl *D = Res.first;
7350 if (!D)
7351 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007352
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007353 QualType Type = D->getType();
7354 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007355
7356 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7357 // A variable that appears in a private clause must not have an incomplete
7358 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007359 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007360 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007361 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007362
Alexey Bataev758e55e2013-09-06 18:03:48 +00007363 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7364 // in a Construct]
7365 // Variables with the predetermined data-sharing attributes may not be
7366 // listed in data-sharing attributes clauses, except for the cases
7367 // listed below. For these exceptions only, listing a predetermined
7368 // variable in a data-sharing attribute clause is allowed and overrides
7369 // the variable's predetermined data-sharing attributes.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007370 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007371 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00007372 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7373 << getOpenMPClauseName(OMPC_private);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007374 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007375 continue;
7376 }
7377
Kelvin Libf594a52016-12-17 05:48:59 +00007378 auto CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007379 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00007380 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +00007381 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007382 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7383 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +00007384 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007385 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007386 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007387 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007388 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007389 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007390 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007391 continue;
7392 }
7393
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007394 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
7395 // A list item cannot appear in both a map clause and a data-sharing
7396 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00007397 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Li83c451e2016-12-25 04:52:54 +00007398 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00007399 CurrDir == OMPD_target_teams_distribute ||
7400 CurrDir == OMPD_target_teams_distribute_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00007401 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00007402 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00007403 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00007404 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
7405 OpenMPClauseKind WhereFoundClauseKind) -> bool {
7406 ConflictKind = WhereFoundClauseKind;
7407 return true;
7408 })) {
7409 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007410 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00007411 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +00007412 << getOpenMPDirectiveName(CurrDir);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007413 ReportOriginalDSA(*this, DSAStack, D, DVar);
7414 continue;
7415 }
7416 }
7417
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007418 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
7419 // A variable of class type (or array thereof) that appears in a private
7420 // clause requires an accessible, unambiguous default constructor for the
7421 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00007422 // Generate helper private variable and initialize it with the default
7423 // value. The address of the original variable is replaced by the address of
7424 // the new private variable in CodeGen. This new variable is not added to
7425 // IdResolver, so the code in the OpenMP region uses original variable for
7426 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007427 Type = Type.getUnqualifiedType();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007428 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7429 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00007430 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007431 if (VDPrivate->isInvalidDecl())
7432 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007433 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007434 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007435
Alexey Bataev90c228f2016-02-08 09:29:13 +00007436 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007437 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00007438 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00007439 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007440 Vars.push_back((VD || CurContext->isDependentContext())
7441 ? RefExpr->IgnoreParens()
7442 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007443 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007444 }
7445
Alexey Bataeved09d242014-05-28 05:53:51 +00007446 if (Vars.empty())
7447 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007448
Alexey Bataev03b340a2014-10-21 03:16:40 +00007449 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
7450 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007451}
7452
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007453namespace {
7454class DiagsUninitializedSeveretyRAII {
7455private:
7456 DiagnosticsEngine &Diags;
7457 SourceLocation SavedLoc;
7458 bool IsIgnored;
7459
7460public:
7461 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
7462 bool IsIgnored)
7463 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
7464 if (!IsIgnored) {
7465 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
7466 /*Map*/ diag::Severity::Ignored, Loc);
7467 }
7468 }
7469 ~DiagsUninitializedSeveretyRAII() {
7470 if (!IsIgnored)
7471 Diags.popMappings(SavedLoc);
7472 }
7473};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007474}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007475
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007476OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
7477 SourceLocation StartLoc,
7478 SourceLocation LParenLoc,
7479 SourceLocation EndLoc) {
7480 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007481 SmallVector<Expr *, 8> PrivateCopies;
7482 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00007483 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007484 bool IsImplicitClause =
7485 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
7486 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
7487
Alexey Bataeved09d242014-05-28 05:53:51 +00007488 for (auto &RefExpr : VarList) {
7489 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007490 SourceLocation ELoc;
7491 SourceRange ERange;
7492 Expr *SimpleRefExpr = RefExpr;
7493 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007494 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007495 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007496 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007497 PrivateCopies.push_back(nullptr);
7498 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007499 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007500 ValueDecl *D = Res.first;
7501 if (!D)
7502 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007503
Alexey Bataev60da77e2016-02-29 05:54:20 +00007504 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00007505 QualType Type = D->getType();
7506 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007507
7508 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7509 // A variable that appears in a private clause must not have an incomplete
7510 // type or a reference type.
7511 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00007512 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007513 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007514 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007515
7516 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
7517 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00007518 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007519 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007520 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007521
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007522 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00007523 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007524 if (!IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007525 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev005248a2016-02-25 05:25:57 +00007526 TopDVar = DVar;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007527 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007528 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
7529 // A list item that specifies a given variable may not appear in more
7530 // than one clause on the same directive, except that a variable may be
7531 // specified in both firstprivate and lastprivate clauses.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007532 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevf29276e2014-06-18 04:14:57 +00007533 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007534 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00007535 << getOpenMPClauseName(DVar.CKind)
7536 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007537 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007538 continue;
7539 }
7540
7541 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7542 // in a Construct]
7543 // Variables with the predetermined data-sharing attributes may not be
7544 // listed in data-sharing attributes clauses, except for the cases
7545 // listed below. For these exceptions only, listing a predetermined
7546 // variable in a data-sharing attribute clause is allowed and overrides
7547 // the variable's predetermined data-sharing attributes.
7548 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7549 // in a Construct, C/C++, p.2]
7550 // Variables with const-qualified type having no mutable member may be
7551 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00007552 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007553 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
7554 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00007555 << getOpenMPClauseName(DVar.CKind)
7556 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007557 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007558 continue;
7559 }
7560
Alexey Bataevf29276e2014-06-18 04:14:57 +00007561 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007562 // OpenMP [2.9.3.4, Restrictions, p.2]
7563 // A list item that is private within a parallel region must not appear
7564 // in a firstprivate clause on a worksharing construct if any of the
7565 // worksharing regions arising from the worksharing construct ever bind
7566 // to any of the parallel regions arising from the parallel construct.
Alexey Bataev549210e2014-06-24 04:39:47 +00007567 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00007568 !isOpenMPParallelDirective(CurrDir) &&
7569 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007570 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007571 if (DVar.CKind != OMPC_shared &&
7572 (isOpenMPParallelDirective(DVar.DKind) ||
7573 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00007574 Diag(ELoc, diag::err_omp_required_access)
7575 << getOpenMPClauseName(OMPC_firstprivate)
7576 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007577 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00007578 continue;
7579 }
7580 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007581 // OpenMP [2.9.3.4, Restrictions, p.3]
7582 // A list item that appears in a reduction clause of a parallel construct
7583 // must not appear in a firstprivate clause on a worksharing or task
7584 // construct if any of the worksharing or task regions arising from the
7585 // worksharing or task construct ever bind to any of the parallel regions
7586 // arising from the parallel construct.
7587 // OpenMP [2.9.3.4, Restrictions, p.4]
7588 // A list item that appears in a reduction clause in worksharing
7589 // construct must not appear in a firstprivate clause in a task construct
7590 // encountered during execution of any of the worksharing regions arising
7591 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00007592 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007593 DVar = DSAStack->hasInnermostDSA(
7594 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
7595 [](OpenMPDirectiveKind K) -> bool {
7596 return isOpenMPParallelDirective(K) ||
7597 isOpenMPWorksharingDirective(K);
7598 },
7599 false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007600 if (DVar.CKind == OMPC_reduction &&
7601 (isOpenMPParallelDirective(DVar.DKind) ||
7602 isOpenMPWorksharingDirective(DVar.DKind))) {
7603 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
7604 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007605 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007606 continue;
7607 }
7608 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007609
7610 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
7611 // A list item that is private within a teams region must not appear in a
7612 // firstprivate clause on a distribute construct if any of the distribute
7613 // regions arising from the distribute construct ever bind to any of the
7614 // teams regions arising from the teams construct.
7615 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
7616 // A list item that appears in a reduction clause of a teams construct
7617 // must not appear in a firstprivate clause on a distribute construct if
7618 // any of the distribute regions arising from the distribute construct
7619 // ever bind to any of the teams regions arising from the teams construct.
7620 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
7621 // A list item may appear in a firstprivate or lastprivate clause but not
7622 // both.
7623 if (CurrDir == OMPD_distribute) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007624 DVar = DSAStack->hasInnermostDSA(
7625 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_private; },
7626 [](OpenMPDirectiveKind K) -> bool {
7627 return isOpenMPTeamsDirective(K);
7628 },
7629 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007630 if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) {
7631 Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007632 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007633 continue;
7634 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007635 DVar = DSAStack->hasInnermostDSA(
7636 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
7637 [](OpenMPDirectiveKind K) -> bool {
7638 return isOpenMPTeamsDirective(K);
7639 },
7640 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007641 if (DVar.CKind == OMPC_reduction &&
7642 isOpenMPTeamsDirective(DVar.DKind)) {
7643 Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007644 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007645 continue;
7646 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007647 DVar = DSAStack->getTopDSA(D, false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007648 if (DVar.CKind == OMPC_lastprivate) {
7649 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007650 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007651 continue;
7652 }
7653 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007654 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
7655 // A list item cannot appear in both a map clause and a data-sharing
7656 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00007657 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Li83c451e2016-12-25 04:52:54 +00007658 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00007659 CurrDir == OMPD_target_teams_distribute ||
7660 CurrDir == OMPD_target_teams_distribute_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00007661 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00007662 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00007663 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00007664 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
7665 OpenMPClauseKind WhereFoundClauseKind) -> bool {
7666 ConflictKind = WhereFoundClauseKind;
7667 return true;
7668 })) {
7669 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007670 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +00007671 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007672 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7673 ReportOriginalDSA(*this, DSAStack, D, DVar);
7674 continue;
7675 }
7676 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007677 }
7678
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007679 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00007680 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00007681 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007682 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7683 << getOpenMPClauseName(OMPC_firstprivate) << Type
7684 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7685 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00007686 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007687 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00007688 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007689 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00007690 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007691 continue;
7692 }
7693
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007694 Type = Type.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00007695 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7696 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007697 // Generate helper private variable and initialize it with the value of the
7698 // original variable. The address of the original variable is replaced by
7699 // the address of the new private variable in the CodeGen. This new variable
7700 // is not added to IdResolver, so the code in the OpenMP region uses
7701 // original variable for proper diagnostics and variable capturing.
7702 Expr *VDInitRefExpr = nullptr;
7703 // For arrays generate initializer for single element and replace it by the
7704 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007705 if (Type->isArrayType()) {
7706 auto VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00007707 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007708 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007709 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007710 ElemType = ElemType.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00007711 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007712 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00007713 InitializedEntity Entity =
7714 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007715 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
7716
7717 InitializationSequence InitSeq(*this, Entity, Kind, Init);
7718 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
7719 if (Result.isInvalid())
7720 VDPrivate->setInvalidDecl();
7721 else
7722 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00007723 // Remove temp variable declaration.
7724 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007725 } else {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007726 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
7727 ".firstprivate.temp");
7728 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
7729 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00007730 AddInitializerToDecl(VDPrivate,
7731 DefaultLvalueConversion(VDInitRefExpr).get(),
7732 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007733 }
7734 if (VDPrivate->isInvalidDecl()) {
7735 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007736 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007737 diag::note_omp_task_predetermined_firstprivate_here);
7738 }
7739 continue;
7740 }
7741 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00007742 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00007743 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
7744 RefExpr->getExprLoc());
7745 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007746 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00007747 if (TopDVar.CKind == OMPC_lastprivate)
7748 Ref = TopDVar.PrivateCopy;
7749 else {
Alexey Bataev61205072016-03-02 04:57:40 +00007750 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataev005248a2016-02-25 05:25:57 +00007751 if (!IsOpenMPCapturedDecl(D))
7752 ExprCaptures.push_back(Ref->getDecl());
7753 }
Alexey Bataev417089f2016-02-17 13:19:37 +00007754 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007755 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007756 Vars.push_back((VD || CurContext->isDependentContext())
7757 ? RefExpr->IgnoreParens()
7758 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007759 PrivateCopies.push_back(VDPrivateRefExpr);
7760 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007761 }
7762
Alexey Bataeved09d242014-05-28 05:53:51 +00007763 if (Vars.empty())
7764 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007765
7766 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00007767 Vars, PrivateCopies, Inits,
7768 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007769}
7770
Alexander Musman1bb328c2014-06-04 13:06:39 +00007771OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
7772 SourceLocation StartLoc,
7773 SourceLocation LParenLoc,
7774 SourceLocation EndLoc) {
7775 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00007776 SmallVector<Expr *, 8> SrcExprs;
7777 SmallVector<Expr *, 8> DstExprs;
7778 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00007779 SmallVector<Decl *, 4> ExprCaptures;
7780 SmallVector<Expr *, 4> ExprPostUpdates;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007781 for (auto &RefExpr : VarList) {
7782 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007783 SourceLocation ELoc;
7784 SourceRange ERange;
7785 Expr *SimpleRefExpr = RefExpr;
7786 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00007787 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00007788 // It will be analyzed later.
7789 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00007790 SrcExprs.push_back(nullptr);
7791 DstExprs.push_back(nullptr);
7792 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007793 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00007794 ValueDecl *D = Res.first;
7795 if (!D)
7796 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007797
Alexey Bataev74caaf22016-02-20 04:09:36 +00007798 QualType Type = D->getType();
7799 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007800
7801 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
7802 // A variable that appears in a lastprivate clause must not have an
7803 // incomplete type or a reference type.
7804 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00007805 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00007806 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007807 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00007808
7809 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
7810 // in a Construct]
7811 // Variables with the predetermined data-sharing attributes may not be
7812 // listed in data-sharing attributes clauses, except for the cases
7813 // listed below.
Alexey Bataev74caaf22016-02-20 04:09:36 +00007814 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007815 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
7816 DVar.CKind != OMPC_firstprivate &&
7817 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
7818 Diag(ELoc, diag::err_omp_wrong_dsa)
7819 << getOpenMPClauseName(DVar.CKind)
7820 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev74caaf22016-02-20 04:09:36 +00007821 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007822 continue;
7823 }
7824
Alexey Bataevf29276e2014-06-18 04:14:57 +00007825 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
7826 // OpenMP [2.14.3.5, Restrictions, p.2]
7827 // A list item that is private within a parallel region, or that appears in
7828 // the reduction clause of a parallel construct, must not appear in a
7829 // lastprivate clause on a worksharing construct if any of the corresponding
7830 // worksharing regions ever binds to any of the corresponding parallel
7831 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00007832 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00007833 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00007834 !isOpenMPParallelDirective(CurrDir) &&
7835 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00007836 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00007837 if (DVar.CKind != OMPC_shared) {
7838 Diag(ELoc, diag::err_omp_required_access)
7839 << getOpenMPClauseName(OMPC_lastprivate)
7840 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev74caaf22016-02-20 04:09:36 +00007841 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00007842 continue;
7843 }
7844 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00007845
7846 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
7847 // A list item may appear in a firstprivate or lastprivate clause but not
7848 // both.
7849 if (CurrDir == OMPD_distribute) {
7850 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
7851 if (DVar.CKind == OMPC_firstprivate) {
7852 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
7853 ReportOriginalDSA(*this, DSAStack, D, DVar);
7854 continue;
7855 }
7856 }
7857
Alexander Musman1bb328c2014-06-04 13:06:39 +00007858 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00007859 // A variable of class type (or array thereof) that appears in a
7860 // lastprivate clause requires an accessible, unambiguous default
7861 // constructor for the class type, unless the list item is also specified
7862 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00007863 // A variable of class type (or array thereof) that appears in a
7864 // lastprivate clause requires an accessible, unambiguous copy assignment
7865 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00007866 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00007867 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00007868 Type.getUnqualifiedType(), ".lastprivate.src",
Alexey Bataev74caaf22016-02-20 04:09:36 +00007869 D->hasAttrs() ? &D->getAttrs() : nullptr);
7870 auto *PseudoSrcExpr =
7871 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00007872 auto *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00007873 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00007874 D->hasAttrs() ? &D->getAttrs() : nullptr);
7875 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00007876 // For arrays generate assignment operation for single element and replace
7877 // it by the original array element in CodeGen.
Alexey Bataev74caaf22016-02-20 04:09:36 +00007878 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
Alexey Bataev38e89532015-04-16 04:54:05 +00007879 PseudoDstExpr, PseudoSrcExpr);
7880 if (AssignmentOp.isInvalid())
7881 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00007882 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00007883 /*DiscardedValue=*/true);
7884 if (AssignmentOp.isInvalid())
7885 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007886
Alexey Bataev74caaf22016-02-20 04:09:36 +00007887 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007888 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00007889 if (TopDVar.CKind == OMPC_firstprivate)
7890 Ref = TopDVar.PrivateCopy;
7891 else {
Alexey Bataev61205072016-03-02 04:57:40 +00007892 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00007893 if (!IsOpenMPCapturedDecl(D))
7894 ExprCaptures.push_back(Ref->getDecl());
7895 }
7896 if (TopDVar.CKind == OMPC_firstprivate ||
7897 (!IsOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00007898 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00007899 ExprResult RefRes = DefaultLvalueConversion(Ref);
7900 if (!RefRes.isUsable())
7901 continue;
7902 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00007903 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
7904 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00007905 if (!PostUpdateRes.isUsable())
7906 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00007907 ExprPostUpdates.push_back(
7908 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00007909 }
7910 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007911 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007912 Vars.push_back((VD || CurContext->isDependentContext())
7913 ? RefExpr->IgnoreParens()
7914 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00007915 SrcExprs.push_back(PseudoSrcExpr);
7916 DstExprs.push_back(PseudoDstExpr);
7917 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00007918 }
7919
7920 if (Vars.empty())
7921 return nullptr;
7922
7923 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00007924 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00007925 buildPreInits(Context, ExprCaptures),
7926 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00007927}
7928
Alexey Bataev758e55e2013-09-06 18:03:48 +00007929OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
7930 SourceLocation StartLoc,
7931 SourceLocation LParenLoc,
7932 SourceLocation EndLoc) {
7933 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00007934 for (auto &RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007935 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007936 SourceLocation ELoc;
7937 SourceRange ERange;
7938 Expr *SimpleRefExpr = RefExpr;
7939 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007940 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00007941 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007942 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007943 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007944 ValueDecl *D = Res.first;
7945 if (!D)
7946 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00007947
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007948 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007949 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7950 // in a Construct]
7951 // Variables with the predetermined data-sharing attributes may not be
7952 // listed in data-sharing attributes clauses, except for the cases
7953 // listed below. For these exceptions only, listing a predetermined
7954 // variable in a data-sharing attribute clause is allowed and overrides
7955 // the variable's predetermined data-sharing attributes.
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007956 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00007957 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
7958 DVar.RefExpr) {
7959 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7960 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007961 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007962 continue;
7963 }
7964
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007965 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007966 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00007967 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007968 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007969 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
7970 ? RefExpr->IgnoreParens()
7971 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007972 }
7973
Alexey Bataeved09d242014-05-28 05:53:51 +00007974 if (Vars.empty())
7975 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00007976
7977 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
7978}
7979
Alexey Bataevc5e02582014-06-16 07:08:35 +00007980namespace {
7981class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
7982 DSAStackTy *Stack;
7983
7984public:
7985 bool VisitDeclRefExpr(DeclRefExpr *E) {
7986 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007987 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00007988 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
7989 return false;
7990 if (DVar.CKind != OMPC_unknown)
7991 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007992 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
7993 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
7994 false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00007995 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00007996 return true;
7997 return false;
7998 }
7999 return false;
8000 }
8001 bool VisitStmt(Stmt *S) {
8002 for (auto Child : S->children()) {
8003 if (Child && Visit(Child))
8004 return true;
8005 }
8006 return false;
8007 }
Alexey Bataev23b69422014-06-18 07:08:49 +00008008 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00008009};
Alexey Bataev23b69422014-06-18 07:08:49 +00008010} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00008011
Alexey Bataev60da77e2016-02-29 05:54:20 +00008012namespace {
8013// Transform MemberExpression for specified FieldDecl of current class to
8014// DeclRefExpr to specified OMPCapturedExprDecl.
8015class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
8016 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
8017 ValueDecl *Field;
8018 DeclRefExpr *CapturedExpr;
8019
8020public:
8021 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
8022 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
8023
8024 ExprResult TransformMemberExpr(MemberExpr *E) {
8025 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
8026 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00008027 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008028 return CapturedExpr;
8029 }
8030 return BaseTransform::TransformMemberExpr(E);
8031 }
8032 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
8033};
8034} // namespace
8035
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008036template <typename T>
8037static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
8038 const llvm::function_ref<T(ValueDecl *)> &Gen) {
8039 for (auto &Set : Lookups) {
8040 for (auto *D : Set) {
8041 if (auto Res = Gen(cast<ValueDecl>(D)))
8042 return Res;
8043 }
8044 }
8045 return T();
8046}
8047
8048static ExprResult
8049buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
8050 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
8051 const DeclarationNameInfo &ReductionId, QualType Ty,
8052 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
8053 if (ReductionIdScopeSpec.isInvalid())
8054 return ExprError();
8055 SmallVector<UnresolvedSet<8>, 4> Lookups;
8056 if (S) {
8057 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
8058 Lookup.suppressDiagnostics();
8059 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
8060 auto *D = Lookup.getRepresentativeDecl();
8061 do {
8062 S = S->getParent();
8063 } while (S && !S->isDeclScope(D));
8064 if (S)
8065 S = S->getParent();
8066 Lookups.push_back(UnresolvedSet<8>());
8067 Lookups.back().append(Lookup.begin(), Lookup.end());
8068 Lookup.clear();
8069 }
8070 } else if (auto *ULE =
8071 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
8072 Lookups.push_back(UnresolvedSet<8>());
8073 Decl *PrevD = nullptr;
David Majnemer9d168222016-08-05 17:44:54 +00008074 for (auto *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008075 if (D == PrevD)
8076 Lookups.push_back(UnresolvedSet<8>());
8077 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
8078 Lookups.back().addDecl(DRD);
8079 PrevD = D;
8080 }
8081 }
8082 if (Ty->isDependentType() || Ty->isInstantiationDependentType() ||
8083 Ty->containsUnexpandedParameterPack() ||
8084 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
8085 return !D->isInvalidDecl() &&
8086 (D->getType()->isDependentType() ||
8087 D->getType()->isInstantiationDependentType() ||
8088 D->getType()->containsUnexpandedParameterPack());
8089 })) {
8090 UnresolvedSet<8> ResSet;
8091 for (auto &Set : Lookups) {
8092 ResSet.append(Set.begin(), Set.end());
8093 // The last item marks the end of all declarations at the specified scope.
8094 ResSet.addDecl(Set[Set.size() - 1]);
8095 }
8096 return UnresolvedLookupExpr::Create(
8097 SemaRef.Context, /*NamingClass=*/nullptr,
8098 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
8099 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
8100 }
8101 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8102 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
8103 if (!D->isInvalidDecl() &&
8104 SemaRef.Context.hasSameType(D->getType(), Ty))
8105 return D;
8106 return nullptr;
8107 }))
8108 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8109 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8110 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
8111 if (!D->isInvalidDecl() &&
8112 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
8113 !Ty.isMoreQualifiedThan(D->getType()))
8114 return D;
8115 return nullptr;
8116 })) {
8117 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8118 /*DetectVirtual=*/false);
8119 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
8120 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
8121 VD->getType().getUnqualifiedType()))) {
8122 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
8123 /*DiagID=*/0) !=
8124 Sema::AR_inaccessible) {
8125 SemaRef.BuildBasePathArray(Paths, BasePath);
8126 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8127 }
8128 }
8129 }
8130 }
8131 if (ReductionIdScopeSpec.isSet()) {
8132 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
8133 return ExprError();
8134 }
8135 return ExprEmpty();
8136}
8137
Alexey Bataevc5e02582014-06-16 07:08:35 +00008138OMPClause *Sema::ActOnOpenMPReductionClause(
8139 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
8140 SourceLocation ColonLoc, SourceLocation EndLoc,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008141 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
8142 ArrayRef<Expr *> UnresolvedReductions) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00008143 auto DN = ReductionId.getName();
8144 auto OOK = DN.getCXXOverloadedOperator();
8145 BinaryOperatorKind BOK = BO_Comma;
8146
8147 // OpenMP [2.14.3.6, reduction clause]
8148 // C
8149 // reduction-identifier is either an identifier or one of the following
8150 // operators: +, -, *, &, |, ^, && and ||
8151 // C++
8152 // reduction-identifier is either an id-expression or one of the following
8153 // operators: +, -, *, &, |, ^, && and ||
8154 // FIXME: Only 'min' and 'max' identifiers are supported for now.
8155 switch (OOK) {
8156 case OO_Plus:
8157 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008158 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008159 break;
8160 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008161 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008162 break;
8163 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008164 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008165 break;
8166 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008167 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008168 break;
8169 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008170 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008171 break;
8172 case OO_AmpAmp:
8173 BOK = BO_LAnd;
8174 break;
8175 case OO_PipePipe:
8176 BOK = BO_LOr;
8177 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008178 case OO_New:
8179 case OO_Delete:
8180 case OO_Array_New:
8181 case OO_Array_Delete:
8182 case OO_Slash:
8183 case OO_Percent:
8184 case OO_Tilde:
8185 case OO_Exclaim:
8186 case OO_Equal:
8187 case OO_Less:
8188 case OO_Greater:
8189 case OO_LessEqual:
8190 case OO_GreaterEqual:
8191 case OO_PlusEqual:
8192 case OO_MinusEqual:
8193 case OO_StarEqual:
8194 case OO_SlashEqual:
8195 case OO_PercentEqual:
8196 case OO_CaretEqual:
8197 case OO_AmpEqual:
8198 case OO_PipeEqual:
8199 case OO_LessLess:
8200 case OO_GreaterGreater:
8201 case OO_LessLessEqual:
8202 case OO_GreaterGreaterEqual:
8203 case OO_EqualEqual:
8204 case OO_ExclaimEqual:
8205 case OO_PlusPlus:
8206 case OO_MinusMinus:
8207 case OO_Comma:
8208 case OO_ArrowStar:
8209 case OO_Arrow:
8210 case OO_Call:
8211 case OO_Subscript:
8212 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +00008213 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008214 case NUM_OVERLOADED_OPERATORS:
8215 llvm_unreachable("Unexpected reduction identifier");
8216 case OO_None:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008217 if (auto II = DN.getAsIdentifierInfo()) {
8218 if (II->isStr("max"))
8219 BOK = BO_GT;
8220 else if (II->isStr("min"))
8221 BOK = BO_LT;
8222 }
8223 break;
8224 }
8225 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008226 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +00008227 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008228 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008229
8230 SmallVector<Expr *, 8> Vars;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008231 SmallVector<Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008232 SmallVector<Expr *, 8> LHSs;
8233 SmallVector<Expr *, 8> RHSs;
8234 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev61205072016-03-02 04:57:40 +00008235 SmallVector<Decl *, 4> ExprCaptures;
8236 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008237 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
8238 bool FirstIter = true;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008239 for (auto RefExpr : VarList) {
8240 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +00008241 // OpenMP [2.1, C/C++]
8242 // A list item is a variable or array section, subject to the restrictions
8243 // specified in Section 2.4 on page 42 and in each of the sections
8244 // describing clauses and directives for which a list appears.
8245 // OpenMP [2.14.3.3, Restrictions, p.1]
8246 // A variable that is part of another variable (as an array or
8247 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008248 if (!FirstIter && IR != ER)
8249 ++IR;
8250 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008251 SourceLocation ELoc;
8252 SourceRange ERange;
8253 Expr *SimpleRefExpr = RefExpr;
8254 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8255 /*AllowArraySection=*/true);
8256 if (Res.second) {
8257 // It will be analyzed later.
8258 Vars.push_back(RefExpr);
8259 Privates.push_back(nullptr);
8260 LHSs.push_back(nullptr);
8261 RHSs.push_back(nullptr);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008262 // Try to find 'declare reduction' corresponding construct before using
8263 // builtin/overloaded operators.
8264 QualType Type = Context.DependentTy;
8265 CXXCastPath BasePath;
8266 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8267 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8268 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8269 if (CurContext->isDependentContext() &&
8270 (DeclareReductionRef.isUnset() ||
8271 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
8272 ReductionOps.push_back(DeclareReductionRef.get());
8273 else
8274 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008275 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00008276 ValueDecl *D = Res.first;
8277 if (!D)
8278 continue;
8279
Alexey Bataeva1764212015-09-30 09:22:36 +00008280 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008281 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
8282 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
8283 if (ASE)
Alexey Bataev31300ed2016-02-04 11:27:03 +00008284 Type = ASE->getType().getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008285 else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008286 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
8287 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
8288 Type = ATy->getElementType();
8289 else
8290 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00008291 Type = Type.getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008292 } else
8293 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
8294 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +00008295
Alexey Bataevc5e02582014-06-16 07:08:35 +00008296 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8297 // A variable that appears in a private clause must not have an incomplete
8298 // type or a reference type.
8299 if (RequireCompleteType(ELoc, Type,
8300 diag::err_omp_reduction_incomplete_type))
8301 continue;
8302 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +00008303 // A list item that appears in a reduction clause must not be
8304 // const-qualified.
8305 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008306 Diag(ELoc, diag::err_omp_const_reduction_list_item)
Alexey Bataevc5e02582014-06-16 07:08:35 +00008307 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008308 if (!ASE && !OASE) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008309 bool IsDecl = !VD ||
8310 VD->isThisDeclarationADefinition(Context) ==
8311 VarDecl::DeclarationOnly;
8312 Diag(D->getLocation(),
Alexey Bataeva1764212015-09-30 09:22:36 +00008313 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +00008314 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +00008315 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00008316 continue;
8317 }
8318 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
8319 // If a list-item is a reference type then it must bind to the same object
8320 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +00008321 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008322 VarDecl *VDDef = VD->getDefinition();
David Sheinkman92589992016-10-04 14:41:36 +00008323 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008324 DSARefChecker Check(DSAStack);
8325 if (Check.Visit(VDDef->getInit())) {
8326 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
8327 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
8328 continue;
8329 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00008330 }
8331 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008332
Alexey Bataevc5e02582014-06-16 07:08:35 +00008333 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8334 // in a Construct]
8335 // Variables with the predetermined data-sharing attributes may not be
8336 // listed in data-sharing attributes clauses, except for the cases
8337 // listed below. For these exceptions only, listing a predetermined
8338 // variable in a data-sharing attribute clause is allowed and overrides
8339 // the variable's predetermined data-sharing attributes.
8340 // OpenMP [2.14.3.6, Restrictions, p.3]
8341 // Any number of reduction clauses can be specified on the directive,
8342 // but a list item can appear only once in the reduction clauses for that
8343 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +00008344 DSAStackTy::DSAVarData DVar;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008345 DVar = DSAStack->getTopDSA(D, false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008346 if (DVar.CKind == OMPC_reduction) {
8347 Diag(ELoc, diag::err_omp_once_referenced)
8348 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008349 if (DVar.RefExpr)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008350 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008351 } else if (DVar.CKind != OMPC_unknown) {
8352 Diag(ELoc, diag::err_omp_wrong_dsa)
8353 << getOpenMPClauseName(DVar.CKind)
8354 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008355 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008356 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008357 }
8358
8359 // OpenMP [2.14.3.6, Restrictions, p.1]
8360 // A list item that appears in a reduction clause of a worksharing
8361 // construct must be shared in the parallel regions to which any of the
8362 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008363 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8364 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008365 !isOpenMPParallelDirective(CurrDir) &&
8366 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008367 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008368 if (DVar.CKind != OMPC_shared) {
8369 Diag(ELoc, diag::err_omp_required_access)
8370 << getOpenMPClauseName(OMPC_reduction)
8371 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008372 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008373 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +00008374 }
8375 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008376
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008377 // Try to find 'declare reduction' corresponding construct before using
8378 // builtin/overloaded operators.
8379 CXXCastPath BasePath;
8380 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8381 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8382 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8383 if (DeclareReductionRef.isInvalid())
8384 continue;
8385 if (CurContext->isDependentContext() &&
8386 (DeclareReductionRef.isUnset() ||
8387 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
8388 Vars.push_back(RefExpr);
8389 Privates.push_back(nullptr);
8390 LHSs.push_back(nullptr);
8391 RHSs.push_back(nullptr);
8392 ReductionOps.push_back(DeclareReductionRef.get());
8393 continue;
8394 }
8395 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
8396 // Not allowed reduction identifier is found.
8397 Diag(ReductionId.getLocStart(),
8398 diag::err_omp_unknown_reduction_identifier)
8399 << Type << ReductionIdRange;
8400 continue;
8401 }
8402
8403 // OpenMP [2.14.3.6, reduction clause, Restrictions]
8404 // The type of a list item that appears in a reduction clause must be valid
8405 // for the reduction-identifier. For a max or min reduction in C, the type
8406 // of the list item must be an allowed arithmetic data type: char, int,
8407 // float, double, or _Bool, possibly modified with long, short, signed, or
8408 // unsigned. For a max or min reduction in C++, the type of the list item
8409 // must be an allowed arithmetic data type: char, wchar_t, int, float,
8410 // double, or bool, possibly modified with long, short, signed, or unsigned.
8411 if (DeclareReductionRef.isUnset()) {
8412 if ((BOK == BO_GT || BOK == BO_LT) &&
8413 !(Type->isScalarType() ||
8414 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
8415 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
8416 << getLangOpts().CPlusPlus;
8417 if (!ASE && !OASE) {
8418 bool IsDecl = !VD ||
8419 VD->isThisDeclarationADefinition(Context) ==
8420 VarDecl::DeclarationOnly;
8421 Diag(D->getLocation(),
8422 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8423 << D;
8424 }
8425 continue;
8426 }
8427 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
8428 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
8429 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
8430 if (!ASE && !OASE) {
8431 bool IsDecl = !VD ||
8432 VD->isThisDeclarationADefinition(Context) ==
8433 VarDecl::DeclarationOnly;
8434 Diag(D->getLocation(),
8435 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8436 << D;
8437 }
8438 continue;
8439 }
8440 }
8441
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008442 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008443 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
Alexey Bataev60da77e2016-02-29 05:54:20 +00008444 D->hasAttrs() ? &D->getAttrs() : nullptr);
8445 auto *RHSVD = buildVarDecl(*this, ELoc, Type, D->getName(),
8446 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008447 auto PrivateTy = Type;
Alexey Bataev1189bd02016-01-26 12:20:39 +00008448 if (OASE ||
Alexey Bataev60da77e2016-02-29 05:54:20 +00008449 (!ASE &&
8450 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
David Majnemer9d168222016-08-05 17:44:54 +00008451 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008452 // Create pseudo array type for private copy. The size for this array will
8453 // be generated during codegen.
8454 // For array subscripts or single variables Private Ty is the same as Type
8455 // (type of the variable or single array element).
8456 PrivateTy = Context.getVariableArrayType(
8457 Type, new (Context) OpaqueValueExpr(SourceLocation(),
8458 Context.getSizeType(), VK_RValue),
8459 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +00008460 } else if (!ASE && !OASE &&
8461 Context.getAsArrayType(D->getType().getNonReferenceType()))
8462 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008463 // Private copy.
Alexey Bataev60da77e2016-02-29 05:54:20 +00008464 auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, D->getName(),
8465 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008466 // Add initializer for private variable.
8467 Expr *Init = nullptr;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008468 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
8469 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
8470 if (DeclareReductionRef.isUsable()) {
8471 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
8472 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
8473 if (DRD->getInitializer()) {
8474 Init = DRDRef;
8475 RHSVD->setInit(DRDRef);
8476 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008477 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008478 } else {
8479 switch (BOK) {
8480 case BO_Add:
8481 case BO_Xor:
8482 case BO_Or:
8483 case BO_LOr:
8484 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
8485 if (Type->isScalarType() || Type->isAnyComplexType())
8486 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
8487 break;
8488 case BO_Mul:
8489 case BO_LAnd:
8490 if (Type->isScalarType() || Type->isAnyComplexType()) {
8491 // '*' and '&&' reduction ops - initializer is '1'.
8492 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00008493 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008494 break;
8495 case BO_And: {
8496 // '&' reduction op - initializer is '~0'.
8497 QualType OrigType = Type;
8498 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
8499 Type = ComplexTy->getElementType();
8500 if (Type->isRealFloatingType()) {
8501 llvm::APFloat InitValue =
8502 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
8503 /*isIEEE=*/true);
8504 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
8505 Type, ELoc);
8506 } else if (Type->isScalarType()) {
8507 auto Size = Context.getTypeSize(Type);
8508 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
8509 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
8510 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
8511 }
8512 if (Init && OrigType->isAnyComplexType()) {
8513 // Init = 0xFFFF + 0xFFFFi;
8514 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
8515 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
8516 }
8517 Type = OrigType;
8518 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008519 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008520 case BO_LT:
8521 case BO_GT: {
8522 // 'min' reduction op - initializer is 'Largest representable number in
8523 // the reduction list item type'.
8524 // 'max' reduction op - initializer is 'Least representable number in
8525 // the reduction list item type'.
8526 if (Type->isIntegerType() || Type->isPointerType()) {
8527 bool IsSigned = Type->hasSignedIntegerRepresentation();
8528 auto Size = Context.getTypeSize(Type);
8529 QualType IntTy =
8530 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
8531 llvm::APInt InitValue =
8532 (BOK != BO_LT)
8533 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
8534 : llvm::APInt::getMinValue(Size)
8535 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
8536 : llvm::APInt::getMaxValue(Size);
8537 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
8538 if (Type->isPointerType()) {
8539 // Cast to pointer type.
8540 auto CastExpr = BuildCStyleCastExpr(
8541 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
8542 SourceLocation(), Init);
8543 if (CastExpr.isInvalid())
8544 continue;
8545 Init = CastExpr.get();
8546 }
8547 } else if (Type->isRealFloatingType()) {
8548 llvm::APFloat InitValue = llvm::APFloat::getLargest(
8549 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
8550 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
8551 Type, ELoc);
8552 }
8553 break;
8554 }
8555 case BO_PtrMemD:
8556 case BO_PtrMemI:
8557 case BO_MulAssign:
8558 case BO_Div:
8559 case BO_Rem:
8560 case BO_Sub:
8561 case BO_Shl:
8562 case BO_Shr:
8563 case BO_LE:
8564 case BO_GE:
8565 case BO_EQ:
8566 case BO_NE:
8567 case BO_AndAssign:
8568 case BO_XorAssign:
8569 case BO_OrAssign:
8570 case BO_Assign:
8571 case BO_AddAssign:
8572 case BO_SubAssign:
8573 case BO_DivAssign:
8574 case BO_RemAssign:
8575 case BO_ShlAssign:
8576 case BO_ShrAssign:
8577 case BO_Comma:
8578 llvm_unreachable("Unexpected reduction operation");
8579 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008580 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008581 if (Init && DeclareReductionRef.isUnset()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008582 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
8583 /*TypeMayContainAuto=*/false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008584 } else if (!Init)
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008585 ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008586 if (RHSVD->isInvalidDecl())
8587 continue;
8588 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008589 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
8590 << ReductionIdRange;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008591 bool IsDecl =
8592 !VD ||
8593 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8594 Diag(D->getLocation(),
8595 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8596 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008597 continue;
8598 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008599 // Store initializer for single element in private copy. Will be used during
8600 // codegen.
8601 PrivateVD->setInit(RHSVD->getInit());
8602 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008603 auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008604 ExprResult ReductionOp;
8605 if (DeclareReductionRef.isUsable()) {
8606 QualType RedTy = DeclareReductionRef.get()->getType();
8607 QualType PtrRedTy = Context.getPointerType(RedTy);
8608 ExprResult LHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
8609 ExprResult RHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
8610 if (!BasePath.empty()) {
8611 LHS = DefaultLvalueConversion(LHS.get());
8612 RHS = DefaultLvalueConversion(RHS.get());
8613 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
8614 CK_UncheckedDerivedToBase, LHS.get(),
8615 &BasePath, LHS.get()->getValueKind());
8616 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
8617 CK_UncheckedDerivedToBase, RHS.get(),
8618 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008619 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008620 FunctionProtoType::ExtProtoInfo EPI;
8621 QualType Params[] = {PtrRedTy, PtrRedTy};
8622 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
8623 auto *OVE = new (Context) OpaqueValueExpr(
8624 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
8625 DefaultLvalueConversion(DeclareReductionRef.get()).get());
8626 Expr *Args[] = {LHS.get(), RHS.get()};
8627 ReductionOp = new (Context)
8628 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
8629 } else {
8630 ReductionOp = BuildBinOp(DSAStack->getCurScope(),
8631 ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
8632 if (ReductionOp.isUsable()) {
8633 if (BOK != BO_LT && BOK != BO_GT) {
8634 ReductionOp =
8635 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
8636 BO_Assign, LHSDRE, ReductionOp.get());
8637 } else {
8638 auto *ConditionalOp = new (Context) ConditionalOperator(
8639 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
8640 RHSDRE, Type, VK_LValue, OK_Ordinary);
8641 ReductionOp =
8642 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
8643 BO_Assign, LHSDRE, ConditionalOp);
8644 }
8645 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
8646 }
8647 if (ReductionOp.isInvalid())
8648 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008649 }
8650
Alexey Bataev60da77e2016-02-29 05:54:20 +00008651 DeclRefExpr *Ref = nullptr;
8652 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008653 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008654 if (ASE || OASE) {
8655 TransformExprToCaptures RebuildToCapture(*this, D);
8656 VarsExpr =
8657 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
8658 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +00008659 } else {
8660 VarsExpr = Ref =
8661 buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +00008662 }
8663 if (!IsOpenMPCapturedDecl(D)) {
8664 ExprCaptures.push_back(Ref->getDecl());
8665 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
8666 ExprResult RefRes = DefaultLvalueConversion(Ref);
8667 if (!RefRes.isUsable())
8668 continue;
8669 ExprResult PostUpdateRes =
8670 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
8671 SimpleRefExpr, RefRes.get());
8672 if (!PostUpdateRes.isUsable())
8673 continue;
8674 ExprPostUpdates.push_back(
8675 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +00008676 }
8677 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00008678 }
8679 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
8680 Vars.push_back(VarsExpr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008681 Privates.push_back(PrivateDRE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008682 LHSs.push_back(LHSDRE);
8683 RHSs.push_back(RHSDRE);
8684 ReductionOps.push_back(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008685 }
8686
8687 if (Vars.empty())
8688 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +00008689
Alexey Bataevc5e02582014-06-16 07:08:35 +00008690 return OMPReductionClause::Create(
8691 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008692 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008693 LHSs, RHSs, ReductionOps, buildPreInits(Context, ExprCaptures),
8694 buildPostUpdate(*this, ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +00008695}
8696
Alexey Bataevecba70f2016-04-12 11:02:11 +00008697bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
8698 SourceLocation LinLoc) {
8699 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
8700 LinKind == OMPC_LINEAR_unknown) {
8701 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
8702 return true;
8703 }
8704 return false;
8705}
8706
8707bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
8708 OpenMPLinearClauseKind LinKind,
8709 QualType Type) {
8710 auto *VD = dyn_cast_or_null<VarDecl>(D);
8711 // A variable must not have an incomplete type or a reference type.
8712 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
8713 return true;
8714 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
8715 !Type->isReferenceType()) {
8716 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
8717 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
8718 return true;
8719 }
8720 Type = Type.getNonReferenceType();
8721
8722 // A list item must not be const-qualified.
8723 if (Type.isConstant(Context)) {
8724 Diag(ELoc, diag::err_omp_const_variable)
8725 << getOpenMPClauseName(OMPC_linear);
8726 if (D) {
8727 bool IsDecl =
8728 !VD ||
8729 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8730 Diag(D->getLocation(),
8731 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8732 << D;
8733 }
8734 return true;
8735 }
8736
8737 // A list item must be of integral or pointer type.
8738 Type = Type.getUnqualifiedType().getCanonicalType();
8739 const auto *Ty = Type.getTypePtrOrNull();
8740 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
8741 !Ty->isPointerType())) {
8742 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
8743 if (D) {
8744 bool IsDecl =
8745 !VD ||
8746 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8747 Diag(D->getLocation(),
8748 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8749 << D;
8750 }
8751 return true;
8752 }
8753 return false;
8754}
8755
Alexey Bataev182227b2015-08-20 10:54:39 +00008756OMPClause *Sema::ActOnOpenMPLinearClause(
8757 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
8758 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
8759 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +00008760 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008761 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +00008762 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +00008763 SmallVector<Decl *, 4> ExprCaptures;
8764 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +00008765 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +00008766 LinKind = OMPC_LINEAR_val;
Alexey Bataeved09d242014-05-28 05:53:51 +00008767 for (auto &RefExpr : VarList) {
8768 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008769 SourceLocation ELoc;
8770 SourceRange ERange;
8771 Expr *SimpleRefExpr = RefExpr;
8772 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8773 /*AllowArraySection=*/false);
8774 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +00008775 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008776 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008777 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +00008778 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00008779 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008780 ValueDecl *D = Res.first;
8781 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +00008782 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +00008783
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008784 QualType Type = D->getType();
8785 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +00008786
8787 // OpenMP [2.14.3.7, linear clause]
8788 // A list-item cannot appear in more than one linear clause.
8789 // A list-item that appears in a linear clause cannot appear in any
8790 // other data-sharing attribute clause.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008791 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00008792 if (DVar.RefExpr) {
8793 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8794 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008795 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00008796 continue;
8797 }
8798
Alexey Bataevecba70f2016-04-12 11:02:11 +00008799 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +00008800 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00008801 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +00008802
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008803 // Build private copy of original var.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008804 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
8805 D->hasAttrs() ? &D->getAttrs() : nullptr);
8806 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +00008807 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008808 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008809 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008810 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008811 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +00008812 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
8813 if (!IsOpenMPCapturedDecl(D)) {
8814 ExprCaptures.push_back(Ref->getDecl());
8815 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
8816 ExprResult RefRes = DefaultLvalueConversion(Ref);
8817 if (!RefRes.isUsable())
8818 continue;
8819 ExprResult PostUpdateRes =
8820 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
8821 SimpleRefExpr, RefRes.get());
8822 if (!PostUpdateRes.isUsable())
8823 continue;
8824 ExprPostUpdates.push_back(
8825 IgnoredValueConversions(PostUpdateRes.get()).get());
8826 }
8827 }
8828 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008829 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008830 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008831 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008832 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008833 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008834 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
8835 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
8836
8837 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008838 Vars.push_back((VD || CurContext->isDependentContext())
8839 ? RefExpr->IgnoreParens()
8840 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008841 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +00008842 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00008843 }
8844
8845 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008846 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00008847
8848 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00008849 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00008850 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
8851 !Step->isInstantiationDependent() &&
8852 !Step->containsUnexpandedParameterPack()) {
8853 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00008854 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00008855 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008856 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008857 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00008858
Alexander Musman3276a272015-03-21 10:12:56 +00008859 // Build var to save the step value.
8860 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00008861 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +00008862 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +00008863 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +00008864 ExprResult CalcStep =
8865 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008866 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +00008867
Alexander Musman8dba6642014-04-22 13:09:42 +00008868 // Warn about zero linear step (it would be probably better specified as
8869 // making corresponding variables 'const').
8870 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00008871 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
8872 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00008873 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
8874 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00008875 if (!IsConstant && CalcStep.isUsable()) {
8876 // Calculate the step beforehand instead of doing this on each iteration.
8877 // (This is not used if the number of iterations may be kfold-ed).
8878 CalcStepExpr = CalcStep.get();
8879 }
Alexander Musman8dba6642014-04-22 13:09:42 +00008880 }
8881
Alexey Bataev182227b2015-08-20 10:54:39 +00008882 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
8883 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008884 StepExpr, CalcStepExpr,
8885 buildPreInits(Context, ExprCaptures),
8886 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +00008887}
8888
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008889static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
8890 Expr *NumIterations, Sema &SemaRef,
8891 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +00008892 // Walk the vars and build update/final expressions for the CodeGen.
8893 SmallVector<Expr *, 8> Updates;
8894 SmallVector<Expr *, 8> Finals;
8895 Expr *Step = Clause.getStep();
8896 Expr *CalcStep = Clause.getCalcStep();
8897 // OpenMP [2.14.3.7, linear clause]
8898 // If linear-step is not specified it is assumed to be 1.
8899 if (Step == nullptr)
8900 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00008901 else if (CalcStep) {
Alexander Musman3276a272015-03-21 10:12:56 +00008902 Step = cast<BinaryOperator>(CalcStep)->getLHS();
Alexey Bataev5a3af132016-03-29 08:58:54 +00008903 }
Alexander Musman3276a272015-03-21 10:12:56 +00008904 bool HasErrors = false;
8905 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008906 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008907 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +00008908 for (auto &RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008909 SourceLocation ELoc;
8910 SourceRange ERange;
8911 Expr *SimpleRefExpr = RefExpr;
8912 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
8913 /*AllowArraySection=*/false);
8914 ValueDecl *D = Res.first;
8915 if (Res.second || !D) {
8916 Updates.push_back(nullptr);
8917 Finals.push_back(nullptr);
8918 HasErrors = true;
8919 continue;
8920 }
8921 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) {
8922 D = cast<MemberExpr>(CED->getInit()->IgnoreParenImpCasts())
8923 ->getMemberDecl();
8924 }
8925 auto &&Info = Stack->isLoopControlVariable(D);
Alexander Musman3276a272015-03-21 10:12:56 +00008926 Expr *InitExpr = *CurInit;
8927
8928 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +00008929 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008930 Expr *CapturedRef;
8931 if (LinKind == OMPC_LINEAR_uval)
8932 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
8933 else
8934 CapturedRef =
8935 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
8936 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
8937 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00008938
8939 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008940 ExprResult Update;
8941 if (!Info.first) {
8942 Update =
8943 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
8944 InitExpr, IV, Step, /* Subtract */ false);
8945 } else
8946 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008947 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
8948 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00008949
8950 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008951 ExprResult Final;
8952 if (!Info.first) {
8953 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
8954 InitExpr, NumIterations, Step,
8955 /* Subtract */ false);
8956 } else
8957 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008958 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
8959 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008960
Alexander Musman3276a272015-03-21 10:12:56 +00008961 if (!Update.isUsable() || !Final.isUsable()) {
8962 Updates.push_back(nullptr);
8963 Finals.push_back(nullptr);
8964 HasErrors = true;
8965 } else {
8966 Updates.push_back(Update.get());
8967 Finals.push_back(Final.get());
8968 }
Richard Trieucc3949d2016-02-18 22:34:54 +00008969 ++CurInit;
8970 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00008971 }
8972 Clause.setUpdates(Updates);
8973 Clause.setFinals(Finals);
8974 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00008975}
8976
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008977OMPClause *Sema::ActOnOpenMPAlignedClause(
8978 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
8979 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
8980
8981 SmallVector<Expr *, 8> Vars;
8982 for (auto &RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +00008983 assert(RefExpr && "NULL expr in OpenMP linear clause.");
8984 SourceLocation ELoc;
8985 SourceRange ERange;
8986 Expr *SimpleRefExpr = RefExpr;
8987 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8988 /*AllowArraySection=*/false);
8989 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008990 // It will be analyzed later.
8991 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008992 }
Alexey Bataev1efd1662016-03-29 10:59:56 +00008993 ValueDecl *D = Res.first;
8994 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008995 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008996
Alexey Bataev1efd1662016-03-29 10:59:56 +00008997 QualType QType = D->getType();
8998 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008999
9000 // OpenMP [2.8.1, simd construct, Restrictions]
9001 // The type of list items appearing in the aligned clause must be
9002 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009003 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009004 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +00009005 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009006 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +00009007 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009008 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +00009009 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009010 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +00009011 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009012 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +00009013 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009014 continue;
9015 }
9016
9017 // OpenMP [2.8.1, simd construct, Restrictions]
9018 // A list-item cannot appear in more than one aligned clause.
Alexey Bataev1efd1662016-03-29 10:59:56 +00009019 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00009020 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009021 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
9022 << getOpenMPClauseName(OMPC_aligned);
9023 continue;
9024 }
9025
Alexey Bataev1efd1662016-03-29 10:59:56 +00009026 DeclRefExpr *Ref = nullptr;
9027 if (!VD && IsOpenMPCapturedDecl(D))
9028 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
9029 Vars.push_back(DefaultFunctionArrayConversion(
9030 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
9031 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009032 }
9033
9034 // OpenMP [2.8.1, simd construct, Description]
9035 // The parameter of the aligned clause, alignment, must be a constant
9036 // positive integer expression.
9037 // If no optional parameter is specified, implementation-defined default
9038 // alignments for SIMD instructions on the target platforms are assumed.
9039 if (Alignment != nullptr) {
9040 ExprResult AlignResult =
9041 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
9042 if (AlignResult.isInvalid())
9043 return nullptr;
9044 Alignment = AlignResult.get();
9045 }
9046 if (Vars.empty())
9047 return nullptr;
9048
9049 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
9050 EndLoc, Vars, Alignment);
9051}
9052
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009053OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
9054 SourceLocation StartLoc,
9055 SourceLocation LParenLoc,
9056 SourceLocation EndLoc) {
9057 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009058 SmallVector<Expr *, 8> SrcExprs;
9059 SmallVector<Expr *, 8> DstExprs;
9060 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +00009061 for (auto &RefExpr : VarList) {
9062 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
9063 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009064 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009065 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009066 SrcExprs.push_back(nullptr);
9067 DstExprs.push_back(nullptr);
9068 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009069 continue;
9070 }
9071
Alexey Bataeved09d242014-05-28 05:53:51 +00009072 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009073 // OpenMP [2.1, C/C++]
9074 // A list item is a variable name.
9075 // OpenMP [2.14.4.1, Restrictions, p.1]
9076 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +00009077 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009078 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009079 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
9080 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009081 continue;
9082 }
9083
9084 Decl *D = DE->getDecl();
9085 VarDecl *VD = cast<VarDecl>(D);
9086
9087 QualType Type = VD->getType();
9088 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
9089 // It will be analyzed later.
9090 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009091 SrcExprs.push_back(nullptr);
9092 DstExprs.push_back(nullptr);
9093 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009094 continue;
9095 }
9096
9097 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
9098 // A list item that appears in a copyin clause must be threadprivate.
9099 if (!DSAStack->isThreadPrivate(VD)) {
9100 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +00009101 << getOpenMPClauseName(OMPC_copyin)
9102 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009103 continue;
9104 }
9105
9106 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9107 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +00009108 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009109 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009110 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009111 auto *SrcVD =
9112 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
9113 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00009114 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009115 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
9116 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009117 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
9118 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009119 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009120 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009121 // For arrays generate assignment operation for single element and replace
9122 // it by the original array element in CodeGen.
9123 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
9124 PseudoDstExpr, PseudoSrcExpr);
9125 if (AssignmentOp.isInvalid())
9126 continue;
9127 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
9128 /*DiscardedValue=*/true);
9129 if (AssignmentOp.isInvalid())
9130 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009131
9132 DSAStack->addDSA(VD, DE, OMPC_copyin);
9133 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009134 SrcExprs.push_back(PseudoSrcExpr);
9135 DstExprs.push_back(PseudoDstExpr);
9136 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009137 }
9138
Alexey Bataeved09d242014-05-28 05:53:51 +00009139 if (Vars.empty())
9140 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009141
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009142 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9143 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009144}
9145
Alexey Bataevbae9a792014-06-27 10:37:06 +00009146OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
9147 SourceLocation StartLoc,
9148 SourceLocation LParenLoc,
9149 SourceLocation EndLoc) {
9150 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +00009151 SmallVector<Expr *, 8> SrcExprs;
9152 SmallVector<Expr *, 8> DstExprs;
9153 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009154 for (auto &RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +00009155 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9156 SourceLocation ELoc;
9157 SourceRange ERange;
9158 Expr *SimpleRefExpr = RefExpr;
9159 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9160 /*AllowArraySection=*/false);
9161 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00009162 // It will be analyzed later.
9163 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +00009164 SrcExprs.push_back(nullptr);
9165 DstExprs.push_back(nullptr);
9166 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009167 }
Alexey Bataeve122da12016-03-17 10:50:17 +00009168 ValueDecl *D = Res.first;
9169 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +00009170 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009171
Alexey Bataeve122da12016-03-17 10:50:17 +00009172 QualType Type = D->getType();
9173 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009174
9175 // OpenMP [2.14.4.2, Restrictions, p.2]
9176 // A list item that appears in a copyprivate clause may not appear in a
9177 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +00009178 if (!VD || !DSAStack->isThreadPrivate(VD)) {
9179 auto DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +00009180 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
9181 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00009182 Diag(ELoc, diag::err_omp_wrong_dsa)
9183 << getOpenMPClauseName(DVar.CKind)
9184 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve122da12016-03-17 10:50:17 +00009185 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009186 continue;
9187 }
9188
9189 // OpenMP [2.11.4.2, Restrictions, p.1]
9190 // All list items that appear in a copyprivate clause must be either
9191 // threadprivate or private in the enclosing context.
9192 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +00009193 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009194 if (DVar.CKind == OMPC_shared) {
9195 Diag(ELoc, diag::err_omp_required_access)
9196 << getOpenMPClauseName(OMPC_copyprivate)
9197 << "threadprivate or private in the enclosing context";
Alexey Bataeve122da12016-03-17 10:50:17 +00009198 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009199 continue;
9200 }
9201 }
9202 }
9203
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009204 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009205 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009206 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009207 << getOpenMPClauseName(OMPC_copyprivate) << Type
9208 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009209 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +00009210 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009211 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +00009212 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009213 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +00009214 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009215 continue;
9216 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009217
Alexey Bataevbae9a792014-06-27 10:37:06 +00009218 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9219 // A variable of class type (or array thereof) that appears in a
9220 // copyin clause requires an accessible, unambiguous copy assignment
9221 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009222 Type = Context.getBaseElementType(Type.getNonReferenceType())
9223 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +00009224 auto *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +00009225 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
9226 D->hasAttrs() ? &D->getAttrs() : nullptr);
9227 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
Alexey Bataev420d45b2015-04-14 05:11:24 +00009228 auto *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +00009229 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
9230 D->hasAttrs() ? &D->getAttrs() : nullptr);
David Majnemer9d168222016-08-05 17:44:54 +00009231 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataeve122da12016-03-17 10:50:17 +00009232 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
Alexey Bataeva63048e2015-03-23 06:18:07 +00009233 PseudoDstExpr, PseudoSrcExpr);
9234 if (AssignmentOp.isInvalid())
9235 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +00009236 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +00009237 /*DiscardedValue=*/true);
9238 if (AssignmentOp.isInvalid())
9239 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009240
9241 // No need to mark vars as copyprivate, they are already threadprivate or
9242 // implicitly private.
Alexey Bataeve122da12016-03-17 10:50:17 +00009243 assert(VD || IsOpenMPCapturedDecl(D));
9244 Vars.push_back(
9245 VD ? RefExpr->IgnoreParens()
9246 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +00009247 SrcExprs.push_back(PseudoSrcExpr);
9248 DstExprs.push_back(PseudoDstExpr);
9249 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +00009250 }
9251
9252 if (Vars.empty())
9253 return nullptr;
9254
Alexey Bataeva63048e2015-03-23 06:18:07 +00009255 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9256 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009257}
9258
Alexey Bataev6125da92014-07-21 11:26:11 +00009259OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
9260 SourceLocation StartLoc,
9261 SourceLocation LParenLoc,
9262 SourceLocation EndLoc) {
9263 if (VarList.empty())
9264 return nullptr;
9265
9266 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
9267}
Alexey Bataevdea47612014-07-23 07:46:59 +00009268
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009269OMPClause *
9270Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
9271 SourceLocation DepLoc, SourceLocation ColonLoc,
9272 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9273 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00009274 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009275 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +00009276 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009277 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +00009278 return nullptr;
9279 }
9280 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009281 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
9282 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +00009283 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009284 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009285 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
9286 /*Last=*/OMPC_DEPEND_unknown, Except)
9287 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009288 return nullptr;
9289 }
9290 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +00009291 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009292 llvm::APSInt DepCounter(/*BitWidth=*/32);
9293 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
9294 if (DepKind == OMPC_DEPEND_sink) {
9295 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
9296 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
9297 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009298 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009299 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009300 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
9301 DSAStack->getParentOrderedRegionParam()) {
9302 for (auto &RefExpr : VarList) {
9303 assert(RefExpr && "NULL expr in OpenMP shared clause.");
Alexey Bataev8b427062016-05-25 12:36:08 +00009304 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009305 // It will be analyzed later.
9306 Vars.push_back(RefExpr);
9307 continue;
9308 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009309
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009310 SourceLocation ELoc = RefExpr->getExprLoc();
9311 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
9312 if (DepKind == OMPC_DEPEND_sink) {
9313 if (DepCounter >= TotalDepCount) {
9314 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
9315 continue;
9316 }
9317 ++DepCounter;
9318 // OpenMP [2.13.9, Summary]
9319 // depend(dependence-type : vec), where dependence-type is:
9320 // 'sink' and where vec is the iteration vector, which has the form:
9321 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
9322 // where n is the value specified by the ordered clause in the loop
9323 // directive, xi denotes the loop iteration variable of the i-th nested
9324 // loop associated with the loop directive, and di is a constant
9325 // non-negative integer.
Alexey Bataev8b427062016-05-25 12:36:08 +00009326 if (CurContext->isDependentContext()) {
9327 // It will be analyzed later.
9328 Vars.push_back(RefExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009329 continue;
9330 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009331 SimpleExpr = SimpleExpr->IgnoreImplicit();
9332 OverloadedOperatorKind OOK = OO_None;
9333 SourceLocation OOLoc;
9334 Expr *LHS = SimpleExpr;
9335 Expr *RHS = nullptr;
9336 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
9337 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
9338 OOLoc = BO->getOperatorLoc();
9339 LHS = BO->getLHS()->IgnoreParenImpCasts();
9340 RHS = BO->getRHS()->IgnoreParenImpCasts();
9341 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
9342 OOK = OCE->getOperator();
9343 OOLoc = OCE->getOperatorLoc();
9344 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9345 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
9346 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
9347 OOK = MCE->getMethodDecl()
9348 ->getNameInfo()
9349 .getName()
9350 .getCXXOverloadedOperator();
9351 OOLoc = MCE->getCallee()->getExprLoc();
9352 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
9353 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9354 }
9355 SourceLocation ELoc;
9356 SourceRange ERange;
9357 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
9358 /*AllowArraySection=*/false);
9359 if (Res.second) {
9360 // It will be analyzed later.
9361 Vars.push_back(RefExpr);
9362 }
9363 ValueDecl *D = Res.first;
9364 if (!D)
9365 continue;
9366
9367 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
9368 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
9369 continue;
9370 }
9371 if (RHS) {
9372 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
9373 RHS, OMPC_depend, /*StrictlyPositive=*/false);
9374 if (RHSRes.isInvalid())
9375 continue;
9376 }
9377 if (!CurContext->isDependentContext() &&
9378 DSAStack->getParentOrderedRegionParam() &&
9379 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
9380 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
9381 << DSAStack->getParentLoopControlVariable(
9382 DepCounter.getZExtValue());
9383 continue;
9384 }
9385 OpsOffs.push_back({RHS, OOK});
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009386 } else {
9387 // OpenMP [2.11.1.1, Restrictions, p.3]
9388 // A variable that is part of another variable (such as a field of a
9389 // structure) but is not an array element or an array section cannot
9390 // appear in a depend clause.
9391 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
9392 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
9393 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
9394 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
9395 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
Alexey Bataev31300ed2016-02-04 11:27:03 +00009396 (ASE &&
9397 !ASE->getBase()
9398 ->getType()
9399 .getNonReferenceType()
9400 ->isPointerType() &&
9401 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009402 Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item)
9403 << 0 << RefExpr->getSourceRange();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009404 continue;
9405 }
9406 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009407 Vars.push_back(RefExpr->IgnoreParenImpCasts());
9408 }
9409
9410 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
9411 TotalDepCount > VarList.size() &&
9412 DSAStack->getParentOrderedRegionParam()) {
9413 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
9414 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
9415 }
9416 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
9417 Vars.empty())
9418 return nullptr;
9419 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009420 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9421 DepKind, DepLoc, ColonLoc, Vars);
9422 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
9423 DSAStack->addDoacrossDependClause(C, OpsOffs);
9424 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009425}
Michael Wonge710d542015-08-07 16:16:36 +00009426
9427OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
9428 SourceLocation LParenLoc,
9429 SourceLocation EndLoc) {
9430 Expr *ValExpr = Device;
Michael Wonge710d542015-08-07 16:16:36 +00009431
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009432 // OpenMP [2.9.1, Restrictions]
9433 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00009434 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
9435 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009436 return nullptr;
9437
Michael Wonge710d542015-08-07 16:16:36 +00009438 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9439}
Kelvin Li0bff7af2015-11-23 05:32:03 +00009440
9441static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
9442 DSAStackTy *Stack, CXXRecordDecl *RD) {
9443 if (!RD || RD->isInvalidDecl())
9444 return true;
9445
9446 auto QTy = SemaRef.Context.getRecordType(RD);
9447 if (RD->isDynamicClass()) {
9448 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9449 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
9450 return false;
9451 }
9452 auto *DC = RD;
9453 bool IsCorrect = true;
9454 for (auto *I : DC->decls()) {
9455 if (I) {
9456 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
9457 if (MD->isStatic()) {
9458 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9459 SemaRef.Diag(MD->getLocation(),
9460 diag::note_omp_static_member_in_target);
9461 IsCorrect = false;
9462 }
9463 } else if (auto *VD = dyn_cast<VarDecl>(I)) {
9464 if (VD->isStaticDataMember()) {
9465 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9466 SemaRef.Diag(VD->getLocation(),
9467 diag::note_omp_static_member_in_target);
9468 IsCorrect = false;
9469 }
9470 }
9471 }
9472 }
9473
9474 for (auto &I : RD->bases()) {
9475 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
9476 I.getType()->getAsCXXRecordDecl()))
9477 IsCorrect = false;
9478 }
9479 return IsCorrect;
9480}
9481
9482static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
9483 DSAStackTy *Stack, QualType QTy) {
9484 NamedDecl *ND;
9485 if (QTy->isIncompleteType(&ND)) {
9486 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
9487 return false;
9488 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
David Majnemer9d168222016-08-05 17:44:54 +00009489 if (!RD->isInvalidDecl() && !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
Kelvin Li0bff7af2015-11-23 05:32:03 +00009490 return false;
9491 }
9492 return true;
9493}
9494
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009495/// \brief Return true if it can be proven that the provided array expression
9496/// (array section or array subscript) does NOT specify the whole size of the
9497/// array whose base type is \a BaseQTy.
9498static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
9499 const Expr *E,
9500 QualType BaseQTy) {
9501 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
9502
9503 // If this is an array subscript, it refers to the whole size if the size of
9504 // the dimension is constant and equals 1. Also, an array section assumes the
9505 // format of an array subscript if no colon is used.
9506 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
9507 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
9508 return ATy->getSize().getSExtValue() != 1;
9509 // Size can't be evaluated statically.
9510 return false;
9511 }
9512
9513 assert(OASE && "Expecting array section if not an array subscript.");
9514 auto *LowerBound = OASE->getLowerBound();
9515 auto *Length = OASE->getLength();
9516
9517 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +00009518 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009519 if (LowerBound) {
9520 llvm::APSInt ConstLowerBound;
9521 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
9522 return false; // Can't get the integer value as a constant.
9523 if (ConstLowerBound.getSExtValue())
9524 return true;
9525 }
9526
9527 // If we don't have a length we covering the whole dimension.
9528 if (!Length)
9529 return false;
9530
9531 // If the base is a pointer, we don't have a way to get the size of the
9532 // pointee.
9533 if (BaseQTy->isPointerType())
9534 return false;
9535
9536 // We can only check if the length is the same as the size of the dimension
9537 // if we have a constant array.
9538 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
9539 if (!CATy)
9540 return false;
9541
9542 llvm::APSInt ConstLength;
9543 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
9544 return false; // Can't get the integer value as a constant.
9545
9546 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
9547}
9548
9549// Return true if it can be proven that the provided array expression (array
9550// section or array subscript) does NOT specify a single element of the array
9551// whose base type is \a BaseQTy.
9552static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +00009553 const Expr *E,
9554 QualType BaseQTy) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009555 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
9556
9557 // An array subscript always refer to a single element. Also, an array section
9558 // assumes the format of an array subscript if no colon is used.
9559 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
9560 return false;
9561
9562 assert(OASE && "Expecting array section if not an array subscript.");
9563 auto *Length = OASE->getLength();
9564
9565 // If we don't have a length we have to check if the array has unitary size
9566 // for this dimension. Also, we should always expect a length if the base type
9567 // is pointer.
9568 if (!Length) {
9569 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
9570 return ATy->getSize().getSExtValue() != 1;
9571 // We cannot assume anything.
9572 return false;
9573 }
9574
9575 // Check if the length evaluates to 1.
9576 llvm::APSInt ConstLength;
9577 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
9578 return false; // Can't get the integer value as a constant.
9579
9580 return ConstLength.getSExtValue() != 1;
9581}
9582
Samuel Antao661c0902016-05-26 17:39:58 +00009583// Return the expression of the base of the mappable expression or null if it
9584// cannot be determined and do all the necessary checks to see if the expression
9585// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +00009586// components of the expression.
9587static Expr *CheckMapClauseExpressionBase(
9588 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +00009589 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
9590 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009591 SourceLocation ELoc = E->getExprLoc();
9592 SourceRange ERange = E->getSourceRange();
9593
9594 // The base of elements of list in a map clause have to be either:
9595 // - a reference to variable or field.
9596 // - a member expression.
9597 // - an array expression.
9598 //
9599 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
9600 // reference to 'r'.
9601 //
9602 // If we have:
9603 //
9604 // struct SS {
9605 // Bla S;
9606 // foo() {
9607 // #pragma omp target map (S.Arr[:12]);
9608 // }
9609 // }
9610 //
9611 // We want to retrieve the member expression 'this->S';
9612
9613 Expr *RelevantExpr = nullptr;
9614
Samuel Antao5de996e2016-01-22 20:21:36 +00009615 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
9616 // If a list item is an array section, it must specify contiguous storage.
9617 //
9618 // For this restriction it is sufficient that we make sure only references
9619 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009620 // exist except in the rightmost expression (unless they cover the whole
9621 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +00009622 //
9623 // r.ArrS[3:5].Arr[6:7]
9624 //
9625 // r.ArrS[3:5].x
9626 //
9627 // but these would be valid:
9628 // r.ArrS[3].Arr[6:7]
9629 //
9630 // r.ArrS[3].x
9631
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009632 bool AllowUnitySizeArraySection = true;
9633 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +00009634
Dmitry Polukhin644a9252016-03-11 07:58:34 +00009635 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009636 E = E->IgnoreParenImpCasts();
9637
9638 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
9639 if (!isa<VarDecl>(CurE->getDecl()))
9640 break;
9641
9642 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009643
9644 // If we got a reference to a declaration, we should not expect any array
9645 // section before that.
9646 AllowUnitySizeArraySection = false;
9647 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +00009648
9649 // Record the component.
9650 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
9651 CurE, CurE->getDecl()));
Samuel Antao5de996e2016-01-22 20:21:36 +00009652 continue;
9653 }
9654
9655 if (auto *CurE = dyn_cast<MemberExpr>(E)) {
9656 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
9657
9658 if (isa<CXXThisExpr>(BaseE))
9659 // We found a base expression: this->Val.
9660 RelevantExpr = CurE;
9661 else
9662 E = BaseE;
9663
9664 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
9665 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
9666 << CurE->getSourceRange();
9667 break;
9668 }
9669
9670 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
9671
9672 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
9673 // A bit-field cannot appear in a map clause.
9674 //
9675 if (FD->isBitField()) {
Samuel Antao661c0902016-05-26 17:39:58 +00009676 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
9677 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +00009678 break;
9679 }
9680
9681 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9682 // If the type of a list item is a reference to a type T then the type
9683 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009684 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +00009685
9686 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
9687 // A list item cannot be a variable that is a member of a structure with
9688 // a union type.
9689 //
9690 if (auto *RT = CurType->getAs<RecordType>())
9691 if (RT->isUnionType()) {
9692 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
9693 << CurE->getSourceRange();
9694 break;
9695 }
9696
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009697 // If we got a member expression, we should not expect any array section
9698 // before that:
9699 //
9700 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
9701 // If a list item is an element of a structure, only the rightmost symbol
9702 // of the variable reference can be an array section.
9703 //
9704 AllowUnitySizeArraySection = false;
9705 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +00009706
9707 // Record the component.
9708 CurComponents.push_back(
9709 OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
Samuel Antao5de996e2016-01-22 20:21:36 +00009710 continue;
9711 }
9712
9713 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
9714 E = CurE->getBase()->IgnoreParenImpCasts();
9715
9716 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
9717 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
9718 << 0 << CurE->getSourceRange();
9719 break;
9720 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009721
9722 // If we got an array subscript that express the whole dimension we
9723 // can have any array expressions before. If it only expressing part of
9724 // the dimension, we can only have unitary-size array expressions.
9725 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
9726 E->getType()))
9727 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +00009728
9729 // Record the component - we don't have any declaration associated.
9730 CurComponents.push_back(
9731 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +00009732 continue;
9733 }
9734
9735 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009736 E = CurE->getBase()->IgnoreParenImpCasts();
9737
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009738 auto CurType =
9739 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
9740
Samuel Antao5de996e2016-01-22 20:21:36 +00009741 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9742 // If the type of a list item is a reference to a type T then the type
9743 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +00009744 if (CurType->isReferenceType())
9745 CurType = CurType->getPointeeType();
9746
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009747 bool IsPointer = CurType->isAnyPointerType();
9748
9749 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009750 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
9751 << 0 << CurE->getSourceRange();
9752 break;
9753 }
9754
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009755 bool NotWhole =
9756 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
9757 bool NotUnity =
9758 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
9759
Samuel Antaodab51bb2016-07-18 23:22:11 +00009760 if (AllowWholeSizeArraySection) {
9761 // Any array section is currently allowed. Allowing a whole size array
9762 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009763 //
9764 // If this array section refers to the whole dimension we can still
9765 // accept other array sections before this one, except if the base is a
9766 // pointer. Otherwise, only unitary sections are accepted.
9767 if (NotWhole || IsPointer)
9768 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +00009769 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009770 // A unity or whole array section is not allowed and that is not
9771 // compatible with the properties of the current array section.
9772 SemaRef.Diag(
9773 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
9774 << CurE->getSourceRange();
9775 break;
9776 }
Samuel Antao90927002016-04-26 14:54:23 +00009777
9778 // Record the component - we don't have any declaration associated.
9779 CurComponents.push_back(
9780 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +00009781 continue;
9782 }
9783
9784 // If nothing else worked, this is not a valid map clause expression.
9785 SemaRef.Diag(ELoc,
9786 diag::err_omp_expected_named_var_member_or_array_expression)
9787 << ERange;
9788 break;
9789 }
9790
9791 return RelevantExpr;
9792}
9793
9794// Return true if expression E associated with value VD has conflicts with other
9795// map information.
Samuel Antao90927002016-04-26 14:54:23 +00009796static bool CheckMapConflicts(
9797 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
9798 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +00009799 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
9800 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009801 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +00009802 SourceLocation ELoc = E->getExprLoc();
9803 SourceRange ERange = E->getSourceRange();
9804
9805 // In order to easily check the conflicts we need to match each component of
9806 // the expression under test with the components of the expressions that are
9807 // already in the stack.
9808
Samuel Antao5de996e2016-01-22 20:21:36 +00009809 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +00009810 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +00009811 "Map clause expression with unexpected base!");
9812
9813 // Variables to help detecting enclosing problems in data environment nests.
9814 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +00009815 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +00009816
Samuel Antao90927002016-04-26 14:54:23 +00009817 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
9818 VD, CurrentRegionOnly,
9819 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00009820 StackComponents,
9821 OpenMPClauseKind) -> bool {
Samuel Antao90927002016-04-26 14:54:23 +00009822
Samuel Antao5de996e2016-01-22 20:21:36 +00009823 assert(!StackComponents.empty() &&
9824 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +00009825 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +00009826 "Map clause expression with unexpected base!");
9827
Samuel Antao90927002016-04-26 14:54:23 +00009828 // The whole expression in the stack.
9829 auto *RE = StackComponents.front().getAssociatedExpression();
9830
Samuel Antao5de996e2016-01-22 20:21:36 +00009831 // Expressions must start from the same base. Here we detect at which
9832 // point both expressions diverge from each other and see if we can
9833 // detect if the memory referred to both expressions is contiguous and
9834 // do not overlap.
9835 auto CI = CurComponents.rbegin();
9836 auto CE = CurComponents.rend();
9837 auto SI = StackComponents.rbegin();
9838 auto SE = StackComponents.rend();
9839 for (; CI != CE && SI != SE; ++CI, ++SI) {
9840
9841 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
9842 // At most one list item can be an array item derived from a given
9843 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +00009844 if (CurrentRegionOnly &&
9845 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
9846 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
9847 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
9848 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
9849 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +00009850 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +00009851 << CI->getAssociatedExpression()->getSourceRange();
9852 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
9853 diag::note_used_here)
9854 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +00009855 return true;
9856 }
9857
9858 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +00009859 if (CI->getAssociatedExpression()->getStmtClass() !=
9860 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +00009861 break;
9862
9863 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +00009864 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +00009865 break;
9866 }
Kelvin Li9f645ae2016-07-18 22:49:16 +00009867 // Check if the extra components of the expressions in the enclosing
9868 // data environment are redundant for the current base declaration.
9869 // If they are, the maps completely overlap, which is legal.
9870 for (; SI != SE; ++SI) {
9871 QualType Type;
9872 if (auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +00009873 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +00009874 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
David Majnemer9d168222016-08-05 17:44:54 +00009875 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
9876 SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +00009877 auto *E = OASE->getBase()->IgnoreParenImpCasts();
9878 Type =
9879 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
9880 }
9881 if (Type.isNull() || Type->isAnyPointerType() ||
9882 CheckArrayExpressionDoesNotReferToWholeSize(
9883 SemaRef, SI->getAssociatedExpression(), Type))
9884 break;
9885 }
Samuel Antao5de996e2016-01-22 20:21:36 +00009886
9887 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
9888 // List items of map clauses in the same construct must not share
9889 // original storage.
9890 //
9891 // If the expressions are exactly the same or one is a subset of the
9892 // other, it means they are sharing storage.
9893 if (CI == CE && SI == SE) {
9894 if (CurrentRegionOnly) {
Samuel Antao661c0902016-05-26 17:39:58 +00009895 if (CKind == OMPC_map)
9896 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
9897 else {
Samuel Antaoec172c62016-05-26 17:49:04 +00009898 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +00009899 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
9900 << ERange;
9901 }
Samuel Antao5de996e2016-01-22 20:21:36 +00009902 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
9903 << RE->getSourceRange();
9904 return true;
9905 } else {
9906 // If we find the same expression in the enclosing data environment,
9907 // that is legal.
9908 IsEnclosedByDataEnvironmentExpr = true;
9909 return false;
9910 }
9911 }
9912
Samuel Antao90927002016-04-26 14:54:23 +00009913 QualType DerivedType =
9914 std::prev(CI)->getAssociatedDeclaration()->getType();
9915 SourceLocation DerivedLoc =
9916 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +00009917
9918 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9919 // If the type of a list item is a reference to a type T then the type
9920 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +00009921 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +00009922
9923 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
9924 // A variable for which the type is pointer and an array section
9925 // derived from that variable must not appear as list items of map
9926 // clauses of the same construct.
9927 //
9928 // Also, cover one of the cases in:
9929 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
9930 // If any part of the original storage of a list item has corresponding
9931 // storage in the device data environment, all of the original storage
9932 // must have corresponding storage in the device data environment.
9933 //
9934 if (DerivedType->isAnyPointerType()) {
9935 if (CI == CE || SI == SE) {
9936 SemaRef.Diag(
9937 DerivedLoc,
9938 diag::err_omp_pointer_mapped_along_with_derived_section)
9939 << DerivedLoc;
9940 } else {
9941 assert(CI != CE && SI != SE);
9942 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
9943 << DerivedLoc;
9944 }
9945 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
9946 << RE->getSourceRange();
9947 return true;
9948 }
9949
9950 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
9951 // List items of map clauses in the same construct must not share
9952 // original storage.
9953 //
9954 // An expression is a subset of the other.
9955 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Samuel Antao661c0902016-05-26 17:39:58 +00009956 if (CKind == OMPC_map)
9957 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
9958 else {
Samuel Antaoec172c62016-05-26 17:49:04 +00009959 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +00009960 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
9961 << ERange;
9962 }
Samuel Antao5de996e2016-01-22 20:21:36 +00009963 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
9964 << RE->getSourceRange();
9965 return true;
9966 }
9967
9968 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +00009969 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +00009970 if (!CurrentRegionOnly && SI != SE)
9971 EnclosingExpr = RE;
9972
9973 // The current expression is a subset of the expression in the data
9974 // environment.
9975 IsEnclosedByDataEnvironmentExpr |=
9976 (!CurrentRegionOnly && CI != CE && SI == SE);
9977
9978 return false;
9979 });
9980
9981 if (CurrentRegionOnly)
9982 return FoundError;
9983
9984 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
9985 // If any part of the original storage of a list item has corresponding
9986 // storage in the device data environment, all of the original storage must
9987 // have corresponding storage in the device data environment.
9988 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
9989 // If a list item is an element of a structure, and a different element of
9990 // the structure has a corresponding list item in the device data environment
9991 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +00009992 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +00009993 // data environment prior to the task encountering the construct.
9994 //
9995 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
9996 SemaRef.Diag(ELoc,
9997 diag::err_omp_original_storage_is_shared_and_does_not_contain)
9998 << ERange;
9999 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
10000 << EnclosingExpr->getSourceRange();
10001 return true;
10002 }
10003
10004 return FoundError;
10005}
10006
Samuel Antao661c0902016-05-26 17:39:58 +000010007namespace {
10008// Utility struct that gathers all the related lists associated with a mappable
10009// expression.
10010struct MappableVarListInfo final {
10011 // The list of expressions.
10012 ArrayRef<Expr *> VarList;
10013 // The list of processed expressions.
10014 SmallVector<Expr *, 16> ProcessedVarList;
10015 // The mappble components for each expression.
10016 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
10017 // The base declaration of the variable.
10018 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
10019
10020 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
10021 // We have a list of components and base declarations for each entry in the
10022 // variable list.
10023 VarComponents.reserve(VarList.size());
10024 VarBaseDeclarations.reserve(VarList.size());
10025 }
10026};
10027}
10028
10029// Check the validity of the provided variable list for the provided clause kind
10030// \a CKind. In the check process the valid expressions, and mappable expression
10031// components and variables are extracted and used to fill \a Vars,
10032// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
10033// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
10034static void
10035checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
10036 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
10037 SourceLocation StartLoc,
10038 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
10039 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000010040 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
10041 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000010042 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010043
Samuel Antao90927002016-04-26 14:54:23 +000010044 // Keep track of the mappable components and base declarations in this clause.
10045 // Each entry in the list is going to have a list of components associated. We
10046 // record each set of the components so that we can build the clause later on.
10047 // In the end we should have the same amount of declarations and component
10048 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000010049
Samuel Antao661c0902016-05-26 17:39:58 +000010050 for (auto &RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000010051 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010052 SourceLocation ELoc = RE->getExprLoc();
10053
Kelvin Li0bff7af2015-11-23 05:32:03 +000010054 auto *VE = RE->IgnoreParenLValueCasts();
10055
10056 if (VE->isValueDependent() || VE->isTypeDependent() ||
10057 VE->isInstantiationDependent() ||
10058 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010059 // We can only analyze this information once the missing information is
10060 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000010061 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010062 continue;
10063 }
10064
10065 auto *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000010066
Samuel Antao5de996e2016-01-22 20:21:36 +000010067 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000010068 SemaRef.Diag(ELoc,
10069 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000010070 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000010071 continue;
10072 }
10073
Samuel Antao90927002016-04-26 14:54:23 +000010074 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
10075 ValueDecl *CurDeclaration = nullptr;
10076
10077 // Obtain the array or member expression bases if required. Also, fill the
10078 // components array with all the components identified in the process.
Samuel Antao661c0902016-05-26 17:39:58 +000010079 auto *BE =
10080 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000010081 if (!BE)
10082 continue;
10083
Samuel Antao90927002016-04-26 14:54:23 +000010084 assert(!CurComponents.empty() &&
10085 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010086
Samuel Antao90927002016-04-26 14:54:23 +000010087 // For the following checks, we rely on the base declaration which is
10088 // expected to be associated with the last component. The declaration is
10089 // expected to be a variable or a field (if 'this' is being mapped).
10090 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
10091 assert(CurDeclaration && "Null decl on map clause.");
10092 assert(
10093 CurDeclaration->isCanonicalDecl() &&
10094 "Expecting components to have associated only canonical declarations.");
10095
10096 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
10097 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000010098
10099 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000010100 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000010101
10102 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000010103 // threadprivate variables cannot appear in a map clause.
10104 // OpenMP 4.5 [2.10.5, target update Construct]
10105 // threadprivate variables cannot appear in a from clause.
10106 if (VD && DSAS->isThreadPrivate(VD)) {
10107 auto DVar = DSAS->getTopDSA(VD, false);
10108 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
10109 << getOpenMPClauseName(CKind);
10110 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010111 continue;
10112 }
10113
Samuel Antao5de996e2016-01-22 20:21:36 +000010114 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
10115 // A list item cannot appear in both a map clause and a data-sharing
10116 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000010117
Samuel Antao5de996e2016-01-22 20:21:36 +000010118 // Check conflicts with other map clause expressions. We check the conflicts
10119 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000010120 // environment, because the restrictions are different. We only have to
10121 // check conflicts across regions for the map clauses.
10122 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10123 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000010124 break;
Samuel Antao661c0902016-05-26 17:39:58 +000010125 if (CKind == OMPC_map &&
10126 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10127 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000010128 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000010129
Samuel Antao661c0902016-05-26 17:39:58 +000010130 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000010131 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10132 // If the type of a list item is a reference to a type T then the type will
10133 // be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000010134 QualType Type = CurDeclaration->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010135
Samuel Antao661c0902016-05-26 17:39:58 +000010136 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
10137 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000010138 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000010139 // A list item must have a mappable type.
Samuel Antao661c0902016-05-26 17:39:58 +000010140 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
10141 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000010142 continue;
10143
Samuel Antao661c0902016-05-26 17:39:58 +000010144 if (CKind == OMPC_map) {
10145 // target enter data
10146 // OpenMP [2.10.2, Restrictions, p. 99]
10147 // A map-type must be specified in all map clauses and must be either
10148 // to or alloc.
10149 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
10150 if (DKind == OMPD_target_enter_data &&
10151 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
10152 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10153 << (IsMapTypeImplicit ? 1 : 0)
10154 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10155 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010156 continue;
10157 }
Samuel Antao661c0902016-05-26 17:39:58 +000010158
10159 // target exit_data
10160 // OpenMP [2.10.3, Restrictions, p. 102]
10161 // A map-type must be specified in all map clauses and must be either
10162 // from, release, or delete.
10163 if (DKind == OMPD_target_exit_data &&
10164 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
10165 MapType == OMPC_MAP_delete)) {
10166 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10167 << (IsMapTypeImplicit ? 1 : 0)
10168 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10169 << getOpenMPDirectiveName(DKind);
10170 continue;
10171 }
10172
10173 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10174 // A list item cannot appear in both a map clause and a data-sharing
10175 // attribute clause on the same construct
Kelvin Li83c451e2016-12-25 04:52:54 +000010176 if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +000010177 DKind == OMPD_target_teams_distribute ||
10178 DKind == OMPD_target_teams_distribute_parallel_for) && VD) {
Samuel Antao661c0902016-05-26 17:39:58 +000010179 auto DVar = DSAS->getTopDSA(VD, false);
10180 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010181 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000010182 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000010183 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000010184 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
10185 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
10186 continue;
10187 }
10188 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010189 }
10190
Samuel Antao90927002016-04-26 14:54:23 +000010191 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000010192 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000010193
10194 // Store the components in the stack so that they can be used to check
10195 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000010196 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
10197 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000010198
10199 // Save the components and declaration to create the clause. For purposes of
10200 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000010201 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000010202 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
10203 MVLI.VarComponents.back().append(CurComponents.begin(),
10204 CurComponents.end());
10205 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
10206 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010207 }
Samuel Antao661c0902016-05-26 17:39:58 +000010208}
10209
10210OMPClause *
10211Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
10212 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
10213 SourceLocation MapLoc, SourceLocation ColonLoc,
10214 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10215 SourceLocation LParenLoc, SourceLocation EndLoc) {
10216 MappableVarListInfo MVLI(VarList);
10217 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
10218 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010219
Samuel Antao5de996e2016-01-22 20:21:36 +000010220 // We need to produce a map clause even if we don't have variables so that
10221 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +000010222 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10223 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10224 MVLI.VarComponents, MapTypeModifier, MapType,
10225 IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010226}
Kelvin Li099bb8c2015-11-24 20:50:12 +000010227
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010228QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
10229 TypeResult ParsedType) {
10230 assert(ParsedType.isUsable());
10231
10232 QualType ReductionType = GetTypeFromParser(ParsedType.get());
10233 if (ReductionType.isNull())
10234 return QualType();
10235
10236 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
10237 // A type name in a declare reduction directive cannot be a function type, an
10238 // array type, a reference type, or a type qualified with const, volatile or
10239 // restrict.
10240 if (ReductionType.hasQualifiers()) {
10241 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
10242 return QualType();
10243 }
10244
10245 if (ReductionType->isFunctionType()) {
10246 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
10247 return QualType();
10248 }
10249 if (ReductionType->isReferenceType()) {
10250 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
10251 return QualType();
10252 }
10253 if (ReductionType->isArrayType()) {
10254 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
10255 return QualType();
10256 }
10257 return ReductionType;
10258}
10259
10260Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
10261 Scope *S, DeclContext *DC, DeclarationName Name,
10262 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
10263 AccessSpecifier AS, Decl *PrevDeclInScope) {
10264 SmallVector<Decl *, 8> Decls;
10265 Decls.reserve(ReductionTypes.size());
10266
10267 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
10268 ForRedeclaration);
10269 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
10270 // A reduction-identifier may not be re-declared in the current scope for the
10271 // same type or for a type that is compatible according to the base language
10272 // rules.
10273 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
10274 OMPDeclareReductionDecl *PrevDRD = nullptr;
10275 bool InCompoundScope = true;
10276 if (S != nullptr) {
10277 // Find previous declaration with the same name not referenced in other
10278 // declarations.
10279 FunctionScopeInfo *ParentFn = getEnclosingFunction();
10280 InCompoundScope =
10281 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
10282 LookupName(Lookup, S);
10283 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
10284 /*AllowInlineNamespace=*/false);
10285 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
10286 auto Filter = Lookup.makeFilter();
10287 while (Filter.hasNext()) {
10288 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
10289 if (InCompoundScope) {
10290 auto I = UsedAsPrevious.find(PrevDecl);
10291 if (I == UsedAsPrevious.end())
10292 UsedAsPrevious[PrevDecl] = false;
10293 if (auto *D = PrevDecl->getPrevDeclInScope())
10294 UsedAsPrevious[D] = true;
10295 }
10296 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
10297 PrevDecl->getLocation();
10298 }
10299 Filter.done();
10300 if (InCompoundScope) {
10301 for (auto &PrevData : UsedAsPrevious) {
10302 if (!PrevData.second) {
10303 PrevDRD = PrevData.first;
10304 break;
10305 }
10306 }
10307 }
10308 } else if (PrevDeclInScope != nullptr) {
10309 auto *PrevDRDInScope = PrevDRD =
10310 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
10311 do {
10312 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
10313 PrevDRDInScope->getLocation();
10314 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
10315 } while (PrevDRDInScope != nullptr);
10316 }
10317 for (auto &TyData : ReductionTypes) {
10318 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
10319 bool Invalid = false;
10320 if (I != PreviousRedeclTypes.end()) {
10321 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
10322 << TyData.first;
10323 Diag(I->second, diag::note_previous_definition);
10324 Invalid = true;
10325 }
10326 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
10327 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
10328 Name, TyData.first, PrevDRD);
10329 DC->addDecl(DRD);
10330 DRD->setAccess(AS);
10331 Decls.push_back(DRD);
10332 if (Invalid)
10333 DRD->setInvalidDecl();
10334 else
10335 PrevDRD = DRD;
10336 }
10337
10338 return DeclGroupPtrTy::make(
10339 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
10340}
10341
10342void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
10343 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10344
10345 // Enter new function scope.
10346 PushFunctionScope();
10347 getCurFunction()->setHasBranchProtectedScope();
10348 getCurFunction()->setHasOMPDeclareReductionCombiner();
10349
10350 if (S != nullptr)
10351 PushDeclContext(S, DRD);
10352 else
10353 CurContext = DRD;
10354
10355 PushExpressionEvaluationContext(PotentiallyEvaluated);
10356
10357 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010358 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
10359 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
10360 // uses semantics of argument handles by value, but it should be passed by
10361 // reference. C lang does not support references, so pass all parameters as
10362 // pointers.
10363 // Create 'T omp_in;' variable.
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010364 auto *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010365 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010366 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
10367 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
10368 // uses semantics of argument handles by value, but it should be passed by
10369 // reference. C lang does not support references, so pass all parameters as
10370 // pointers.
10371 // Create 'T omp_out;' variable.
10372 auto *OmpOutParm =
10373 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
10374 if (S != nullptr) {
10375 PushOnScopeChains(OmpInParm, S);
10376 PushOnScopeChains(OmpOutParm, S);
10377 } else {
10378 DRD->addDecl(OmpInParm);
10379 DRD->addDecl(OmpOutParm);
10380 }
10381}
10382
10383void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
10384 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10385 DiscardCleanupsInEvaluationContext();
10386 PopExpressionEvaluationContext();
10387
10388 PopDeclContext();
10389 PopFunctionScopeInfo();
10390
10391 if (Combiner != nullptr)
10392 DRD->setCombiner(Combiner);
10393 else
10394 DRD->setInvalidDecl();
10395}
10396
10397void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
10398 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10399
10400 // Enter new function scope.
10401 PushFunctionScope();
10402 getCurFunction()->setHasBranchProtectedScope();
10403
10404 if (S != nullptr)
10405 PushDeclContext(S, DRD);
10406 else
10407 CurContext = DRD;
10408
10409 PushExpressionEvaluationContext(PotentiallyEvaluated);
10410
10411 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010412 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
10413 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
10414 // uses semantics of argument handles by value, but it should be passed by
10415 // reference. C lang does not support references, so pass all parameters as
10416 // pointers.
10417 // Create 'T omp_priv;' variable.
10418 auto *OmpPrivParm =
10419 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010420 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
10421 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
10422 // uses semantics of argument handles by value, but it should be passed by
10423 // reference. C lang does not support references, so pass all parameters as
10424 // pointers.
10425 // Create 'T omp_orig;' variable.
10426 auto *OmpOrigParm =
10427 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010428 if (S != nullptr) {
10429 PushOnScopeChains(OmpPrivParm, S);
10430 PushOnScopeChains(OmpOrigParm, S);
10431 } else {
10432 DRD->addDecl(OmpPrivParm);
10433 DRD->addDecl(OmpOrigParm);
10434 }
10435}
10436
10437void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D,
10438 Expr *Initializer) {
10439 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10440 DiscardCleanupsInEvaluationContext();
10441 PopExpressionEvaluationContext();
10442
10443 PopDeclContext();
10444 PopFunctionScopeInfo();
10445
10446 if (Initializer != nullptr)
10447 DRD->setInitializer(Initializer);
10448 else
10449 DRD->setInvalidDecl();
10450}
10451
10452Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
10453 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
10454 for (auto *D : DeclReductions.get()) {
10455 if (IsValid) {
10456 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10457 if (S != nullptr)
10458 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
10459 } else
10460 D->setInvalidDecl();
10461 }
10462 return DeclReductions;
10463}
10464
David Majnemer9d168222016-08-05 17:44:54 +000010465OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000010466 SourceLocation StartLoc,
10467 SourceLocation LParenLoc,
10468 SourceLocation EndLoc) {
10469 Expr *ValExpr = NumTeams;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010470
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010471 // OpenMP [teams Constrcut, Restrictions]
10472 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000010473 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
10474 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010475 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010476
10477 return new (Context) OMPNumTeamsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10478}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010479
10480OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
10481 SourceLocation StartLoc,
10482 SourceLocation LParenLoc,
10483 SourceLocation EndLoc) {
10484 Expr *ValExpr = ThreadLimit;
10485
10486 // OpenMP [teams Constrcut, Restrictions]
10487 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000010488 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
10489 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010490 return nullptr;
10491
David Majnemer9d168222016-08-05 17:44:54 +000010492 return new (Context)
10493 OMPThreadLimitClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010494}
Alexey Bataeva0569352015-12-01 10:17:31 +000010495
10496OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
10497 SourceLocation StartLoc,
10498 SourceLocation LParenLoc,
10499 SourceLocation EndLoc) {
10500 Expr *ValExpr = Priority;
10501
10502 // OpenMP [2.9.1, task Constrcut]
10503 // The priority-value is a non-negative numerical scalar expression.
10504 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
10505 /*StrictlyPositive=*/false))
10506 return nullptr;
10507
10508 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10509}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010510
10511OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
10512 SourceLocation StartLoc,
10513 SourceLocation LParenLoc,
10514 SourceLocation EndLoc) {
10515 Expr *ValExpr = Grainsize;
10516
10517 // OpenMP [2.9.2, taskloop Constrcut]
10518 // The parameter of the grainsize clause must be a positive integer
10519 // expression.
10520 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
10521 /*StrictlyPositive=*/true))
10522 return nullptr;
10523
10524 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10525}
Alexey Bataev382967a2015-12-08 12:06:20 +000010526
10527OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
10528 SourceLocation StartLoc,
10529 SourceLocation LParenLoc,
10530 SourceLocation EndLoc) {
10531 Expr *ValExpr = NumTasks;
10532
10533 // OpenMP [2.9.2, taskloop Constrcut]
10534 // The parameter of the num_tasks clause must be a positive integer
10535 // expression.
10536 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
10537 /*StrictlyPositive=*/true))
10538 return nullptr;
10539
10540 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10541}
10542
Alexey Bataev28c75412015-12-15 08:19:24 +000010543OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
10544 SourceLocation LParenLoc,
10545 SourceLocation EndLoc) {
10546 // OpenMP [2.13.2, critical construct, Description]
10547 // ... where hint-expression is an integer constant expression that evaluates
10548 // to a valid lock hint.
10549 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
10550 if (HintExpr.isInvalid())
10551 return nullptr;
10552 return new (Context)
10553 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
10554}
10555
Carlo Bertollib4adf552016-01-15 18:50:31 +000010556OMPClause *Sema::ActOnOpenMPDistScheduleClause(
10557 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
10558 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
10559 SourceLocation EndLoc) {
10560 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
10561 std::string Values;
10562 Values += "'";
10563 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
10564 Values += "'";
10565 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
10566 << Values << getOpenMPClauseName(OMPC_dist_schedule);
10567 return nullptr;
10568 }
10569 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000010570 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000010571 if (ChunkSize) {
10572 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
10573 !ChunkSize->isInstantiationDependent() &&
10574 !ChunkSize->containsUnexpandedParameterPack()) {
10575 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
10576 ExprResult Val =
10577 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
10578 if (Val.isInvalid())
10579 return nullptr;
10580
10581 ValExpr = Val.get();
10582
10583 // OpenMP [2.7.1, Restrictions]
10584 // chunk_size must be a loop invariant integer expression with a positive
10585 // value.
10586 llvm::APSInt Result;
10587 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
10588 if (Result.isSigned() && !Result.isStrictlyPositive()) {
10589 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
10590 << "dist_schedule" << ChunkSize->getSourceRange();
10591 return nullptr;
10592 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +000010593 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
10594 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +000010595 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
10596 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
10597 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000010598 }
10599 }
10600 }
10601
10602 return new (Context)
10603 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000010604 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000010605}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010606
10607OMPClause *Sema::ActOnOpenMPDefaultmapClause(
10608 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
10609 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
10610 SourceLocation KindLoc, SourceLocation EndLoc) {
10611 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000010612 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010613 std::string Value;
10614 SourceLocation Loc;
10615 Value += "'";
10616 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
10617 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000010618 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010619 Loc = MLoc;
10620 } else {
10621 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000010622 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010623 Loc = KindLoc;
10624 }
10625 Value += "'";
10626 Diag(Loc, diag::err_omp_unexpected_clause_value)
10627 << Value << getOpenMPClauseName(OMPC_defaultmap);
10628 return nullptr;
10629 }
10630
10631 return new (Context)
10632 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
10633}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010634
10635bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
10636 DeclContext *CurLexicalContext = getCurLexicalContext();
10637 if (!CurLexicalContext->isFileContext() &&
10638 !CurLexicalContext->isExternCContext() &&
10639 !CurLexicalContext->isExternCXXContext()) {
10640 Diag(Loc, diag::err_omp_region_not_file_context);
10641 return false;
10642 }
10643 if (IsInOpenMPDeclareTargetContext) {
10644 Diag(Loc, diag::err_omp_enclosed_declare_target);
10645 return false;
10646 }
10647
10648 IsInOpenMPDeclareTargetContext = true;
10649 return true;
10650}
10651
10652void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
10653 assert(IsInOpenMPDeclareTargetContext &&
10654 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
10655
10656 IsInOpenMPDeclareTargetContext = false;
10657}
10658
David Majnemer9d168222016-08-05 17:44:54 +000010659void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
10660 CXXScopeSpec &ScopeSpec,
10661 const DeclarationNameInfo &Id,
10662 OMPDeclareTargetDeclAttr::MapTypeTy MT,
10663 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010664 LookupResult Lookup(*this, Id, LookupOrdinaryName);
10665 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
10666
10667 if (Lookup.isAmbiguous())
10668 return;
10669 Lookup.suppressDiagnostics();
10670
10671 if (!Lookup.isSingleResult()) {
10672 if (TypoCorrection Corrected =
10673 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
10674 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
10675 CTK_ErrorRecovery)) {
10676 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
10677 << Id.getName());
10678 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
10679 return;
10680 }
10681
10682 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
10683 return;
10684 }
10685
10686 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
10687 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
10688 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
10689 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
10690
10691 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
10692 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
10693 ND->addAttr(A);
10694 if (ASTMutationListener *ML = Context.getASTMutationListener())
10695 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
10696 checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
10697 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
10698 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
10699 << Id.getName();
10700 }
10701 } else
10702 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
10703}
10704
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010705static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
10706 Sema &SemaRef, Decl *D) {
10707 if (!D)
10708 return;
10709 Decl *LD = nullptr;
10710 if (isa<TagDecl>(D)) {
10711 LD = cast<TagDecl>(D)->getDefinition();
10712 } else if (isa<VarDecl>(D)) {
10713 LD = cast<VarDecl>(D)->getDefinition();
10714
10715 // If this is an implicit variable that is legal and we do not need to do
10716 // anything.
10717 if (cast<VarDecl>(D)->isImplicit()) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010718 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10719 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10720 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010721 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010722 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010723 return;
10724 }
10725
10726 } else if (isa<FunctionDecl>(D)) {
10727 const FunctionDecl *FD = nullptr;
10728 if (cast<FunctionDecl>(D)->hasBody(FD))
10729 LD = const_cast<FunctionDecl *>(FD);
10730
10731 // If the definition is associated with the current declaration in the
10732 // target region (it can be e.g. a lambda) that is legal and we do not need
10733 // to do anything else.
10734 if (LD == D) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010735 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10736 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10737 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010738 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010739 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010740 return;
10741 }
10742 }
10743 if (!LD)
10744 LD = D;
10745 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
10746 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
10747 // Outlined declaration is not declared target.
10748 if (LD->isOutOfLine()) {
10749 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
10750 SemaRef.Diag(SL, diag::note_used_here) << SR;
10751 } else {
10752 DeclContext *DC = LD->getDeclContext();
10753 while (DC) {
10754 if (isa<FunctionDecl>(DC) &&
10755 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
10756 break;
10757 DC = DC->getParent();
10758 }
10759 if (DC)
10760 return;
10761
10762 // Is not declared in target context.
10763 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
10764 SemaRef.Diag(SL, diag::note_used_here) << SR;
10765 }
10766 // Mark decl as declared target to prevent further diagnostic.
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010767 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10768 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10769 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010770 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010771 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010772 }
10773}
10774
10775static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
10776 Sema &SemaRef, DSAStackTy *Stack,
10777 ValueDecl *VD) {
10778 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
10779 return true;
10780 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
10781 return false;
10782 return true;
10783}
10784
10785void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
10786 if (!D || D->isInvalidDecl())
10787 return;
10788 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
10789 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
10790 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
10791 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10792 if (DSAStack->isThreadPrivate(VD)) {
10793 Diag(SL, diag::err_omp_threadprivate_in_target);
10794 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
10795 return;
10796 }
10797 }
10798 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
10799 // Problem if any with var declared with incomplete type will be reported
10800 // as normal, so no need to check it here.
10801 if ((E || !VD->getType()->isIncompleteType()) &&
10802 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
10803 // Mark decl as declared target to prevent further diagnostic.
10804 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010805 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10806 Context, OMPDeclareTargetDeclAttr::MT_To);
10807 VD->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010808 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010809 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010810 }
10811 return;
10812 }
10813 }
10814 if (!E) {
10815 // Checking declaration inside declare target region.
10816 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
10817 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010818 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10819 Context, OMPDeclareTargetDeclAttr::MT_To);
10820 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010821 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010822 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010823 }
10824 return;
10825 }
10826 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
10827}
Samuel Antao661c0902016-05-26 17:39:58 +000010828
10829OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
10830 SourceLocation StartLoc,
10831 SourceLocation LParenLoc,
10832 SourceLocation EndLoc) {
10833 MappableVarListInfo MVLI(VarList);
10834 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
10835 if (MVLI.ProcessedVarList.empty())
10836 return nullptr;
10837
10838 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10839 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10840 MVLI.VarComponents);
10841}
Samuel Antaoec172c62016-05-26 17:49:04 +000010842
10843OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
10844 SourceLocation StartLoc,
10845 SourceLocation LParenLoc,
10846 SourceLocation EndLoc) {
10847 MappableVarListInfo MVLI(VarList);
10848 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
10849 if (MVLI.ProcessedVarList.empty())
10850 return nullptr;
10851
10852 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10853 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10854 MVLI.VarComponents);
10855}
Carlo Bertolli2404b172016-07-13 15:37:16 +000010856
10857OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
10858 SourceLocation StartLoc,
10859 SourceLocation LParenLoc,
10860 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000010861 MappableVarListInfo MVLI(VarList);
10862 SmallVector<Expr *, 8> PrivateCopies;
10863 SmallVector<Expr *, 8> Inits;
10864
Carlo Bertolli2404b172016-07-13 15:37:16 +000010865 for (auto &RefExpr : VarList) {
10866 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
10867 SourceLocation ELoc;
10868 SourceRange ERange;
10869 Expr *SimpleRefExpr = RefExpr;
10870 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10871 if (Res.second) {
10872 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000010873 MVLI.ProcessedVarList.push_back(RefExpr);
10874 PrivateCopies.push_back(nullptr);
10875 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000010876 }
10877 ValueDecl *D = Res.first;
10878 if (!D)
10879 continue;
10880
10881 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000010882 Type = Type.getNonReferenceType().getUnqualifiedType();
10883
10884 auto *VD = dyn_cast<VarDecl>(D);
10885
10886 // Item should be a pointer or reference to pointer.
10887 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000010888 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
10889 << 0 << RefExpr->getSourceRange();
10890 continue;
10891 }
Samuel Antaocc10b852016-07-28 14:23:26 +000010892
10893 // Build the private variable and the expression that refers to it.
10894 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
10895 D->hasAttrs() ? &D->getAttrs() : nullptr);
10896 if (VDPrivate->isInvalidDecl())
10897 continue;
10898
10899 CurContext->addDecl(VDPrivate);
10900 auto VDPrivateRefExpr = buildDeclRefExpr(
10901 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
10902
10903 // Add temporary variable to initialize the private copy of the pointer.
10904 auto *VDInit =
10905 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
10906 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
10907 RefExpr->getExprLoc());
10908 AddInitializerToDecl(VDPrivate,
10909 DefaultLvalueConversion(VDInitRefExpr).get(),
10910 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
10911
10912 // If required, build a capture to implement the privatization initialized
10913 // with the current list item value.
10914 DeclRefExpr *Ref = nullptr;
10915 if (!VD)
10916 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
10917 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
10918 PrivateCopies.push_back(VDPrivateRefExpr);
10919 Inits.push_back(VDInitRefExpr);
10920
10921 // We need to add a data sharing attribute for this variable to make sure it
10922 // is correctly captured. A variable that shows up in a use_device_ptr has
10923 // similar properties of a first private variable.
10924 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
10925
10926 // Create a mappable component for the list item. List items in this clause
10927 // only need a component.
10928 MVLI.VarBaseDeclarations.push_back(D);
10929 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
10930 MVLI.VarComponents.back().push_back(
10931 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000010932 }
10933
Samuel Antaocc10b852016-07-28 14:23:26 +000010934 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000010935 return nullptr;
10936
Samuel Antaocc10b852016-07-28 14:23:26 +000010937 return OMPUseDevicePtrClause::Create(
10938 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
10939 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000010940}
Carlo Bertolli70594e92016-07-13 17:16:49 +000010941
10942OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
10943 SourceLocation StartLoc,
10944 SourceLocation LParenLoc,
10945 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000010946 MappableVarListInfo MVLI(VarList);
Carlo Bertolli70594e92016-07-13 17:16:49 +000010947 for (auto &RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000010948 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000010949 SourceLocation ELoc;
10950 SourceRange ERange;
10951 Expr *SimpleRefExpr = RefExpr;
10952 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10953 if (Res.second) {
10954 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000010955 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000010956 }
10957 ValueDecl *D = Res.first;
10958 if (!D)
10959 continue;
10960
10961 QualType Type = D->getType();
10962 // item should be a pointer or array or reference to pointer or array
10963 if (!Type.getNonReferenceType()->isPointerType() &&
10964 !Type.getNonReferenceType()->isArrayType()) {
10965 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
10966 << 0 << RefExpr->getSourceRange();
10967 continue;
10968 }
Samuel Antao6890b092016-07-28 14:25:09 +000010969
10970 // Check if the declaration in the clause does not show up in any data
10971 // sharing attribute.
10972 auto DVar = DSAStack->getTopDSA(D, false);
10973 if (isOpenMPPrivate(DVar.CKind)) {
10974 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
10975 << getOpenMPClauseName(DVar.CKind)
10976 << getOpenMPClauseName(OMPC_is_device_ptr)
10977 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
10978 ReportOriginalDSA(*this, DSAStack, D, DVar);
10979 continue;
10980 }
10981
10982 Expr *ConflictExpr;
10983 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000010984 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000010985 [&ConflictExpr](
10986 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
10987 OpenMPClauseKind) -> bool {
10988 ConflictExpr = R.front().getAssociatedExpression();
10989 return true;
10990 })) {
10991 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
10992 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
10993 << ConflictExpr->getSourceRange();
10994 continue;
10995 }
10996
10997 // Store the components in the stack so that they can be used to check
10998 // against other clauses later on.
10999 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
11000 DSAStack->addMappableExpressionComponents(
11001 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
11002
11003 // Record the expression we've just processed.
11004 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
11005
11006 // Create a mappable component for the list item. List items in this clause
11007 // only need a component. We use a null declaration to signal fields in
11008 // 'this'.
11009 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
11010 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
11011 "Unexpected device pointer expression!");
11012 MVLI.VarBaseDeclarations.push_back(
11013 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
11014 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11015 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011016 }
11017
Samuel Antao6890b092016-07-28 14:25:09 +000011018 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000011019 return nullptr;
11020
Samuel Antao6890b092016-07-28 14:25:09 +000011021 return OMPIsDevicePtrClause::Create(
11022 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
11023 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011024}