]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaOpenMP.cpp
Update lldb to trunk r290819 and resolve conflicts.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Sema / SemaOpenMP.cpp
1 //===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
2 //
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
11 /// clauses.
12 ///
13 //===----------------------------------------------------------------------===//
14
15 #include "TreeTransform.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclOpenMP.h"
22 #include "clang/AST/StmtCXX.h"
23 #include "clang/AST/StmtOpenMP.h"
24 #include "clang/AST/StmtVisitor.h"
25 #include "clang/AST/TypeOrdering.h"
26 #include "clang/Basic/OpenMPKinds.h"
27 #include "clang/Basic/TargetInfo.h"
28 #include "clang/Lex/Preprocessor.h"
29 #include "clang/Sema/Initialization.h"
30 #include "clang/Sema/Lookup.h"
31 #include "clang/Sema/Scope.h"
32 #include "clang/Sema/ScopeInfo.h"
33 #include "clang/Sema/SemaInternal.h"
34 using namespace clang;
35
36 //===----------------------------------------------------------------------===//
37 // Stack of data-sharing attributes for variables
38 //===----------------------------------------------------------------------===//
39
40 namespace {
41 /// \brief Default data sharing attributes, which can be applied to directive.
42 enum DefaultDataSharingAttributes {
43   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'.
46 };
47
48 /// \brief Stack for tracking declarations used in OpenMP directives and
49 /// clauses and their data-sharing attributes.
50 class DSAStackTy final {
51 public:
52   struct DSAVarData final {
53     OpenMPDirectiveKind DKind = OMPD_unknown;
54     OpenMPClauseKind CKind = OMPC_unknown;
55     Expr *RefExpr = nullptr;
56     DeclRefExpr *PrivateCopy = nullptr;
57     SourceLocation ImplicitDSALoc;
58     DSAVarData() {}
59   };
60   typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>
61       OperatorOffsetTy;
62
63 private:
64   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;
70   };
71   typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy;
72   typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy;
73   typedef std::pair<unsigned, VarDecl *> LCDeclInfo;
74   typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy;
75   /// 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>
82       MappedExprComponentsTy;
83   typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
84       CriticalsWithHintsTy;
85   typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>
86       DoacrossDependMapTy;
87
88   struct SharingMapTy final {
89     DeclSAMapTy SharingMap;
90     AlignedMapTy AlignedMap;
91     MappedExprComponentsTy MappedExprComponents;
92     LoopControlVariablesMapTy LCVMap;
93     DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
94     SourceLocation DefaultAttrLoc;
95     OpenMPDirectiveKind Directive = OMPD_unknown;
96     DeclarationNameInfo DirectiveName;
97     Scope *CurScope = nullptr;
98     SourceLocation ConstructLoc;
99     /// 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;
103     /// \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;
107     bool NowaitRegion = false;
108     bool CancelRegion = false;
109     unsigned AssociatedLoops = 1;
110     SourceLocation InnerTeamsRegionLoc;
111     SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
112                  Scope *CurScope, SourceLocation Loc)
113         : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
114           ConstructLoc(Loc) {}
115     SharingMapTy() {}
116   };
117
118   typedef SmallVector<SharingMapTy, 4> StackTy;
119
120   /// \brief Stack of used declaration and their data-sharing attributes.
121   StackTy Stack;
122   /// \brief true, if check for DSA must be from parent directive, false, if
123   /// from current directive.
124   OpenMPClauseKind ClauseKindMode = OMPC_unknown;
125   Sema &SemaRef;
126   bool ForceCapturing = false;
127   CriticalsWithHintsTy Criticals;
128
129   typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
130
131   DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D);
132
133   /// \brief Checks if the variable is a local for OpenMP region.
134   bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
135
136 public:
137   explicit DSAStackTy(Sema &S) : Stack(1), SemaRef(S) {}
138
139   bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
140   void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
141
142   bool isForceVarCapturing() const { return ForceCapturing; }
143   void setForceVarCapturing(bool V) { ForceCapturing = V; }
144
145   void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
146             Scope *CurScope, SourceLocation Loc) {
147     Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
148     Stack.back().DefaultAttrLoc = Loc;
149   }
150
151   void pop() {
152     assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
153     Stack.pop_back();
154   }
155
156   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   }
166   /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
167   /// add it and return NULL; otherwise return previous occurrence's expression
168   /// for diagnostics.
169   Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
170
171   /// \brief Register specified variable as loop control variable.
172   void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
173   /// \brief Check if the specified variable is a loop control variable for
174   /// current region.
175   /// \return The index of the loop control variable in the list of associated
176   /// for-loops (from outer to inner).
177   LCDeclInfo isLoopControlVariable(ValueDecl *D);
178   /// \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).
182   LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
183   /// \brief Get the loop control variable for the I-th loop (or nullptr) in
184   /// parent directive.
185   ValueDecl *getParentLoopControlVariable(unsigned I);
186
187   /// \brief Adds explicit data sharing attribute to the specified declaration.
188   void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
189               DeclRefExpr *PrivateCopy = nullptr);
190
191   /// \brief Returns data sharing attributes from top of the stack for the
192   /// specified declaration.
193   DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
194   /// \brief Returns data-sharing attributes for the specified declaration.
195   DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
196   /// \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.
199   DSAVarData hasDSA(ValueDecl *D,
200                     const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
201                     const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
202                     bool FromParent);
203   /// \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.
206   DSAVarData
207   hasInnermostDSA(ValueDecl *D,
208                   const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
209                   const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
210                   bool FromParent);
211   /// \brief Checks if the specified variables has explicit data-sharing
212   /// attributes which match specified \a CPred predicate at the specified
213   /// OpenMP region.
214   bool hasExplicitDSA(ValueDecl *D,
215                       const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
216                       unsigned Level, bool NotLastprivate = false);
217
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
224   /// \brief Finds a directive which matches specified \a DPred predicate.
225   bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind,
226                                                   const DeclarationNameInfo &,
227                                                   SourceLocation)> &DPred,
228                     bool FromParent);
229
230   /// \brief Returns currently analyzed directive.
231   OpenMPDirectiveKind getCurrentDirective() const {
232     return Stack.back().Directive;
233   }
234   /// \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   }
240
241   /// \brief Set default data sharing attribute to none.
242   void setDefaultDSANone(SourceLocation Loc) {
243     Stack.back().DefaultAttr = DSA_none;
244     Stack.back().DefaultAttrLoc = Loc;
245   }
246   /// \brief Set default data sharing attribute to shared.
247   void setDefaultDSAShared(SourceLocation Loc) {
248     Stack.back().DefaultAttr = DSA_shared;
249     Stack.back().DefaultAttrLoc = Loc;
250   }
251
252   DefaultDataSharingAttributes getDefaultDSA() const {
253     return Stack.back().DefaultAttr;
254   }
255   SourceLocation getDefaultDSALocation() const {
256     return Stack.back().DefaultAttrLoc;
257   }
258
259   /// \brief Checks if the specified variable is a threadprivate.
260   bool isThreadPrivate(VarDecl *D) {
261     DSAVarData DVar = getTopDSA(D, false);
262     return isOpenMPThreadPrivate(DVar.CKind);
263   }
264
265   /// \brief Marks current region as ordered (it has an 'ordered' clause).
266   void setOrderedRegion(bool IsOrdered, Expr *Param) {
267     Stack.back().OrderedRegion.setInt(IsOrdered);
268     Stack.back().OrderedRegion.setPointer(Param);
269   }
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)
274       return Stack[Stack.size() - 2].OrderedRegion.getInt();
275     return false;
276   }
277   /// \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   }
283   /// \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   }
294   /// \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.
301   bool isCancelRegion() const { return Stack.back().CancelRegion; }
302
303   /// \brief Set collapse value for the region.
304   void setAssociatedLoops(unsigned Val) { Stack.back().AssociatedLoops = Val; }
305   /// \brief Return collapse value for region.
306   unsigned getAssociatedLoops() const { return Stack.back().AssociatedLoops; }
307
308   /// \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
325   Scope *getCurScope() const { return Stack.back().CurScope; }
326   Scope *getCurScope() { return Stack.back().CurScope; }
327   SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
328
329   /// Do the check specified in \a Check to all component lists and return true
330   /// if any issue is found.
331   bool checkMappableExprComponentListsForDecl(
332       ValueDecl *VD, bool CurrentRegionOnly,
333       const llvm::function_ref<
334           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
335                OpenMPClauseKind)> &Check) {
336     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) {
349       auto MI = SI->MappedExprComponents.find(VD);
350       if (MI != SI->MappedExprComponents.end())
351         for (auto &L : MI->second.Components)
352           if (Check(L, MI->second.Kind))
353             return true;
354     }
355     return false;
356   }
357
358   /// Create a new mappable expression component list associated with a given
359   /// declaration and initialize it with the provided list of components.
360   void addMappableExpressionComponents(
361       ValueDecl *VD,
362       OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
363       OpenMPClauseKind WhereFoundClauseKind) {
364     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.
368     MEC.Components.resize(MEC.Components.size() + 1);
369     MEC.Components.back().append(Components.begin(), Components.end());
370     MEC.Kind = WhereFoundClauseKind;
371   }
372
373   unsigned getNestingLevel() const {
374     assert(Stack.size() > 1);
375     return Stack.size() - 2;
376   }
377   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   }
392 };
393 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
394   return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
395          isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
396 }
397 } // namespace
398
399 static ValueDecl *getCanonicalDecl(ValueDecl *D) {
400   auto *VD = dyn_cast<VarDecl>(D);
401   auto *FD = dyn_cast<FieldDecl>(D);
402   if (VD != nullptr) {
403     VD = VD->getCanonicalDecl();
404     D = VD;
405   } else {
406     assert(FD);
407     FD = FD->getCanonicalDecl();
408     D = FD;
409   }
410   return D;
411 }
412
413 DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter,
414                                           ValueDecl *D) {
415   D = getCanonicalDecl(D);
416   auto *VD = dyn_cast<VarDecl>(D);
417   auto *FD = dyn_cast<FieldDecl>(D);
418   DSAVarData DVar;
419   if (Iter == std::prev(Stack.rend())) {
420     // 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.
425     if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
426       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.
432     if (VD && VD->hasGlobalStorage())
433       DVar.CKind = OMPC_shared;
434
435     // Non-static data members are shared by default.
436     if (FD)
437       DVar.CKind = OMPC_shared;
438
439     return DVar;
440   }
441
442   DVar.DKind = Iter->Directive;
443   // 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.
447   if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
448       (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
449     DVar.CKind = OMPC_private;
450     return DVar;
451   }
452
453   // Explicitly specified attributes and local variables with predetermined
454   // attributes.
455   if (Iter->SharingMap.count(D)) {
456     DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
457     DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
458     DVar.CKind = Iter->SharingMap[D].Attributes;
459     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
460     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;
470     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
471     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.
479     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
480     if (isOpenMPParallelDirective(DVar.DKind) ||
481         isOpenMPTeamsDirective(DVar.DKind)) {
482       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.
491     if (isOpenMPTaskingDirective(DVar.DKind)) {
492       DSAVarData DVarTemp;
493       for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
494            I != EE; ++I) {
495         // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
496         // Referenced in a Construct, implicitly determined, p.6]
497         //  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) {
502           DVar.RefExpr = nullptr;
503           DVar.CKind = OMPC_firstprivate;
504           return DVar;
505         }
506         if (isParallelOrTaskRegion(I->Directive))
507           break;
508       }
509       DVar.CKind =
510           (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
511       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.
519   return getDSA(++Iter, D);
520 }
521
522 Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
523   assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
524   D = getCanonicalDecl(D);
525   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
537 void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
538   assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
539   D = getCanonicalDecl(D);
540   Stack.back().LCVMap.insert(
541       std::make_pair(D, LCDeclInfo(Stack.back().LCVMap.size() + 1, Capture)));
542 }
543
544 DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
545   assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
546   D = getCanonicalDecl(D);
547   return Stack.back().LCVMap.count(D) > 0 ? Stack.back().LCVMap[D]
548                                           : LCDeclInfo(0, nullptr);
549 }
550
551 DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
552   assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
553   D = getCanonicalDecl(D);
554   return Stack[Stack.size() - 2].LCVMap.count(D) > 0
555              ? Stack[Stack.size() - 2].LCVMap[D]
556              : LCDeclInfo(0, nullptr);
557 }
558
559 ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
560   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) {
564     if (Pair.second.first == I)
565       return Pair.first;
566   }
567   return nullptr;
568 }
569
570 void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
571                         DeclRefExpr *PrivateCopy) {
572   D = getCanonicalDecl(D);
573   if (A == OMPC_threadprivate) {
574     auto &Data = Stack[0].SharingMap[D];
575     Data.Attributes = A;
576     Data.RefExpr.setPointer(E);
577     Data.PrivateCopy = nullptr;
578   } else {
579     assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
580     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     }
600   }
601 }
602
603 bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
604   D = D->getCanonicalDecl();
605   if (Stack.size() > 2) {
606     reverse_iterator I = Iter, E = std::prev(Stack.rend());
607     Scope *TopScope = nullptr;
608     while (I != E && !isParallelOrTaskRegion(I->Directive)) {
609       ++I;
610     }
611     if (I == E)
612       return false;
613     TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
614     Scope *CurScope = getCurScope();
615     while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
616       CurScope = CurScope->getParent();
617     }
618     return CurScope != TopScope;
619   }
620   return false;
621 }
622
623 /// \brief Build a variable declaration for OpenMP loop iteration variable.
624 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
625                              StringRef Name, const AttrVec *Attrs = nullptr) {
626   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);
631   if (Attrs) {
632     for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
633          I != E; ++I)
634       Decl->addAttr(*I);
635   }
636   Decl->setImplicit();
637   return Decl;
638 }
639
640 static 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
650 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
651   D = getCanonicalDecl(D);
652   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.
657   auto *VD = dyn_cast<VarDecl>(D);
658   if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
659        !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
660          SemaRef.getLangOpts().OpenMPUseTLS &&
661          SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
662       (VD && VD->getStorageClass() == SC_Register &&
663        VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
664     addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
665                                D->getLocation()),
666            OMPC_threadprivate);
667   }
668   if (Stack[0].SharingMap.count(D)) {
669     DVar.RefExpr = Stack[0].SharingMap[D].RefExpr.getPointer();
670     DVar.CKind = OMPC_threadprivate;
671     return DVar;
672   }
673
674   if (Stack.size() == 1) {
675     // Not in OpenMP execution region and top scope was already checked.
676     return DVar;
677   }
678
679   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
680   // 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.
686   auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
687   if (VD && VD->isStaticDataMember()) {
688     DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
689     if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
690       return DVar;
691
692     DVar.CKind = OMPC_shared;
693     return DVar;
694   }
695
696   QualType Type = D->getType().getNonReferenceType().getCanonicalType();
697   bool IsConstant = Type.isConstant(SemaRef.getASTContext());
698   Type = SemaRef.getASTContext().getBaseElementType(Type);
699   // 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.
703   CXXRecordDecl *RD =
704       SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
705   if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
706     if (auto *CTD = CTSD->getSpecializedTemplate())
707       RD = CTD->getTemplatedDecl();
708   if (IsConstant &&
709       !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
710         RD->hasMutableFields())) {
711     // Variables with const-qualified type having no mutable member may be
712     // listed in a firstprivate clause, even if they are static data members.
713     DSAVarData DVarTemp = hasDSA(
714         D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
715         MatchesAlways, FromParent);
716     if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
717       return DVar;
718
719     DVar.CKind = OMPC_shared;
720     return DVar;
721   }
722
723   // Explicitly specified attributes and local variables with predetermined
724   // attributes.
725   auto StartI = std::next(Stack.rbegin());
726   auto EndI = std::prev(Stack.rend());
727   if (FromParent && StartI != EndI) {
728     StartI = std::next(StartI);
729   }
730   auto I = std::prev(StartI);
731   if (I->SharingMap.count(D)) {
732     DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
733     DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
734     DVar.CKind = I->SharingMap[D].Attributes;
735     DVar.ImplicitDSALoc = I->DefaultAttrLoc;
736   }
737
738   return DVar;
739 }
740
741 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
742                                                   bool FromParent) {
743   D = getCanonicalDecl(D);
744   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);
750 }
751
752 DSAStackTy::DSAVarData
753 DSAStackTy::hasDSA(ValueDecl *D,
754                    const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
755                    const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
756                    bool FromParent) {
757   D = getCanonicalDecl(D);
758   auto StartI = std::next(Stack.rbegin());
759   auto EndI = Stack.rend();
760   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))
765       continue;
766     DSAVarData DVar = getDSA(I, D);
767     if (CPred(DVar.CKind))
768       return DVar;
769   }
770   return DSAVarData();
771 }
772
773 DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
774     ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
775     const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
776     bool FromParent) {
777   D = getCanonicalDecl(D);
778   auto StartI = std::next(Stack.rbegin());
779   auto EndI = Stack.rend();
780   if (FromParent && StartI != EndI)
781     StartI = std::next(StartI);
782   if (StartI == EndI || !DPred(StartI->Directive))
783     return DSAVarData();
784   DSAVarData DVar = getDSA(StartI, D);
785   return CPred(DVar.CKind) ? DVar : DSAVarData();
786 }
787
788 bool DSAStackTy::hasExplicitDSA(
789     ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
790     unsigned Level, bool NotLastprivate) {
791   if (CPred(ClauseKindMode))
792     return true;
793   D = getCanonicalDecl(D);
794   auto StartI = std::next(Stack.begin());
795   auto EndI = Stack.end();
796   if (std::distance(StartI, EndI) <= (int)Level)
797     return false;
798   std::advance(StartI, Level);
799   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());
803 }
804
805 bool DSAStackTy::hasExplicitDirective(
806     const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
807     unsigned Level) {
808   auto StartI = std::next(Stack.begin());
809   auto EndI = Stack.end();
810   if (std::distance(StartI, EndI) <= (int)Level)
811     return false;
812   std::advance(StartI, Level);
813   return DPred(StartI->Directive);
814 }
815
816 bool DSAStackTy::hasDirective(
817     const llvm::function_ref<bool(OpenMPDirectiveKind,
818                                   const DeclarationNameInfo &, SourceLocation)>
819         &DPred,
820     bool FromParent) {
821   // We look only in the enclosing region.
822   if (Stack.size() < 2)
823     return false;
824   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
836 void Sema::InitDataSharingAttributesStack() {
837   VarDataSharingAttributesStack = new DSAStackTy(*this);
838 }
839
840 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
841
842 bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
843   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.
849   auto Ty = D->getType();
850
851   if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
852     // 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
906     if (Ty->isReferenceType())
907       Ty = Ty->castAs<ReferenceType>()->getPointeeType();
908
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
918                 MapExprComponents,
919             OpenMPClauseKind WhereFoundClauseKind) {
920           // Only the map clause information influences how a variable is
921           // captured. E.g. is_device_ptr does not require changing the default
922           // behavior.
923           if (WhereFoundClauseKind != OMPC_map)
924             return false;
925
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     }
958   }
959
960   if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
961     IsByRef = !DSAStack->hasExplicitDSA(
962         D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
963         Level, /*NotLastprivate=*/true);
964   }
965
966   // When passing data by copy, we need to make sure it fits the uintptr size
967   // 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()) ||
973        Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
974     IsByRef = true;
975   }
976
977   return IsByRef;
978 }
979
980 unsigned Sema::getOpenMPNestingLevel() const {
981   assert(getLangOpts().OpenMP);
982   return DSAStack->getNestingLevel();
983 }
984
985 VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
986   assert(LangOpts.OpenMP && "OpenMP is not allowed");
987   D = getCanonicalDecl(D);
988
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   //
996   auto *VD = dyn_cast<VarDecl>(D);
997   if (VD && !VD->hasLocalStorage()) {
998     if (DSAStack->getCurrentDirective() == OMPD_target &&
999         !DSAStack->isClauseParsingMode())
1000       return VD;
1001     if (DSAStack->hasDirective(
1002             [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1003                SourceLocation) -> bool {
1004               return isOpenMPTargetExecutionDirective(K);
1005             },
1006             false))
1007       return VD;
1008   }
1009
1010   if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1011       (!DSAStack->isClauseParsingMode() ||
1012        DSAStack->getParentDirective() != OMPD_unknown)) {
1013     auto &&Info = DSAStack->isLoopControlVariable(D);
1014     if (Info.first ||
1015         (VD && VD->hasLocalStorage() &&
1016          isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
1017         (VD && DSAStack->isForceVarCapturing()))
1018       return VD ? VD : Info.second;
1019     auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
1020     if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
1021       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
1022     DVarPrivate = DSAStack->hasDSA(
1023         D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1024         DSAStack->isClauseParsingMode());
1025     if (DVarPrivate.CKind != OMPC_unknown)
1026       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
1027   }
1028   return nullptr;
1029 }
1030
1031 bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
1032   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1033   return DSAStack->hasExplicitDSA(
1034       D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
1035 }
1036
1037 bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
1038   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1039   // Return true if the current level is no longer enclosed in a target region.
1040
1041   auto *VD = dyn_cast<VarDecl>(D);
1042   return VD && !VD->hasLocalStorage() &&
1043          DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1044                                         Level);
1045 }
1046
1047 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
1048
1049 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1050                                const DeclarationNameInfo &DirName,
1051                                Scope *CurScope, SourceLocation Loc) {
1052   DSAStack->push(DKind, DirName, CurScope, Loc);
1053   PushExpressionEvaluationContext(PotentiallyEvaluated);
1054 }
1055
1056 void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1057   DSAStack->setClauseParsingMode(K);
1058 }
1059
1060 void Sema::EndOpenMPClause() {
1061   DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
1062 }
1063
1064 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
1065   // 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.
1070   if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
1071     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);
1077             continue;
1078           }
1079           auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
1080           VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1081           QualType Type = VD->getType().getNonReferenceType();
1082           auto DVar = DSAStack->getTopDSA(VD, false);
1083           if (DVar.CKind == OMPC_lastprivate) {
1084             // 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.
1089             auto *VDPrivate = buildVarDecl(
1090                 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
1091                 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
1092             ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
1093             if (VDPrivate->isInvalidDecl())
1094               continue;
1095             PrivateCopies.push_back(buildDeclRefExpr(
1096                 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
1097           } else {
1098             // The variable is also a firstprivate, so initialization sequence
1099             // for private copy is generated already.
1100             PrivateCopies.push_back(nullptr);
1101           }
1102         }
1103         // Set initializers to private copies if no errors were found.
1104         if (PrivateCopies.size() == Clause->varlist_size())
1105           Clause->setPrivateCopies(PrivateCopies);
1106       }
1107     }
1108   }
1109
1110   DSAStack->pop();
1111   DiscardCleanupsInEvaluationContext();
1112   PopExpressionEvaluationContext();
1113 }
1114
1115 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1116                                      Expr *NumIterations, Sema &SemaRef,
1117                                      Scope *S, DSAStackTy *Stack);
1118
1119 namespace {
1120
1121 class VarDeclFilterCCC : public CorrectionCandidateCallback {
1122 private:
1123   Sema &SemaRef;
1124
1125 public:
1126   explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
1127   bool ValidateCandidate(const TypoCorrection &Candidate) override {
1128     NamedDecl *ND = Candidate.getCorrectionDecl();
1129     if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
1130       return VD->hasGlobalStorage() &&
1131              SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1132                                    SemaRef.getCurScope());
1133     }
1134     return false;
1135   }
1136 };
1137
1138 class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1139 private:
1140   Sema &SemaRef;
1141
1142 public:
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
1154 } // namespace
1155
1156 ExprResult 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()) {
1167     if (TypoCorrection Corrected = CorrectTypo(
1168             Id, LookupOrdinaryName, CurScope, nullptr,
1169             llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
1170       diagnoseTypo(Corrected,
1171                    PDiag(Lookup.empty()
1172                              ? diag::err_undeclared_var_use_suggest
1173                              : diag::err_omp_expected_var_arg_suggest)
1174                        << Id.getName());
1175       VD = Corrected.getCorrectionDeclAs<VarDecl>();
1176     } else {
1177       Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1178                                        : diag::err_omp_expected_var_arg)
1179           << Id.getName();
1180       return ExprError();
1181     }
1182   } else {
1183     if (!(VD = Lookup.getAsSingle<VarDecl>())) {
1184       Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
1185       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)
1195         << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1196     bool IsDecl =
1197         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1198     Diag(VD->getLocation(),
1199          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1200         << VD;
1201     return ExprError();
1202   }
1203
1204   VarDecl *CanonicalVD = VD->getCanonicalDecl();
1205   NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
1206   // 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.
1209   if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1210       !getCurLexicalContext()->isTranslationUnit()) {
1211     Diag(Id.getLoc(), diag::err_omp_var_scope)
1212         << 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;
1218     return ExprError();
1219   }
1220   // 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.
1224   if (CanonicalVD->isStaticDataMember() &&
1225       !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1226     Diag(Id.getLoc(), diag::err_omp_var_scope)
1227         << 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;
1233     return ExprError();
1234   }
1235   // 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.
1239   if (CanonicalVD->getDeclContext()->isNamespace() &&
1240       (!getCurLexicalContext()->isFileContext() ||
1241        !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1242     Diag(Id.getLoc(), diag::err_omp_var_scope)
1243         << 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;
1249     return ExprError();
1250   }
1251   // 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.
1254   if (CanonicalVD->isStaticLocal() && CurScope &&
1255       !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
1256     Diag(Id.getLoc(), diag::err_omp_var_scope)
1257         << 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;
1263     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.
1269   if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
1270     Diag(Id.getLoc(), diag::err_omp_var_used)
1271         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1272     return ExprError();
1273   }
1274
1275   QualType ExprType = VD->getType().getNonReferenceType();
1276   return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1277                              SourceLocation(), VD,
1278                              /*RefersToEnclosingVariableOrCapture=*/false,
1279                              Id.getLoc(), ExprType, VK_LValue);
1280 }
1281
1282 Sema::DeclGroupPtrTy
1283 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1284                                         ArrayRef<Expr *> VarList) {
1285   if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
1286     CurContext->addDecl(D);
1287     return DeclGroupPtrTy::make(DeclGroupRef(D));
1288   }
1289   return nullptr;
1290 }
1291
1292 namespace {
1293 class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1294   Sema &SemaRef;
1295
1296 public:
1297   bool VisitDeclRefExpr(const DeclRefExpr *E) {
1298     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
1299       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   }
1317   explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
1318 };
1319 } // namespace
1320
1321 OMPThreadPrivateDecl *
1322 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
1323   SmallVector<Expr *, 8> Vars;
1324   for (auto &RefExpr : VarList) {
1325     DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
1326     VarDecl *VD = cast<VarDecl>(DE->getDecl());
1327     SourceLocation ILoc = DE->getExprLoc();
1328
1329     // Mark variable as used.
1330     VD->setReferenced();
1331     VD->markUsed(Context);
1332
1333     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
1340     // 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(),
1343                             diag::err_omp_threadprivate_incomplete_type)) {
1344       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)
1351           << 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;
1357       continue;
1358     }
1359
1360     // 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())) ||
1366         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1367          !VD->isLocalVarDecl())) {
1368       Diag(ILoc, diag::err_omp_var_thread_local)
1369           << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
1370       bool IsDecl =
1371           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1372       Diag(VD->getLocation(),
1373            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1374           << VD;
1375       continue;
1376     }
1377
1378     // 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);
1382       if (Checker.Visit(Init))
1383         continue;
1384     }
1385
1386     Vars.push_back(RefExpr);
1387     DSAStack->addDSA(VD, DE, OMPC_threadprivate);
1388     VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1389         Context, SourceRange(Loc, Loc)));
1390     if (auto *ML = Context.getASTMutationListener())
1391       ML->DeclarationMarkedOpenMPThreadPrivate(VD);
1392   }
1393   OMPThreadPrivateDecl *D = nullptr;
1394   if (!Vars.empty()) {
1395     D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1396                                      Vars);
1397     D->setAccess(AS_public);
1398   }
1399   return D;
1400 }
1401
1402 static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
1403                               const ValueDecl *D, DSAStackTy::DSAVarData DVar,
1404                               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,
1418     PDSA_TaskVarFirstprivate,
1419     PDSA_LocalVarPrivate,
1420     PDSA_Implicit
1421   } Reason = PDSA_Implicit;
1422   bool ReportHint = false;
1423   auto ReportLoc = D->getLocation();
1424   auto *VD = dyn_cast<VarDecl>(D);
1425   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;
1432   } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1433              DVar.CKind == OMPC_firstprivate) {
1434     Reason = PDSA_TaskVarFirstprivate;
1435     ReportLoc = DVar.ImplicitDSALoc;
1436   } else if (VD && VD->isStaticLocal())
1437     Reason = PDSA_StaticLocalVarShared;
1438   else if (VD && VD->isStaticDataMember())
1439     Reason = PDSA_StaticMemberShared;
1440   else if (VD && VD->isFileVarDecl())
1441     Reason = PDSA_GlobalVarShared;
1442   else if (D->getType().isConstant(SemaRef.getASTContext()))
1443     Reason = PDSA_ConstVarShared;
1444   else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
1445     ReportHint = true;
1446     Reason = PDSA_LocalVarPrivate;
1447   }
1448   if (Reason != PDSA_Implicit) {
1449     SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
1450         << 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   }
1456 }
1457
1458 namespace {
1459 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1460   DSAStackTy *Stack;
1461   Sema &SemaRef;
1462   bool ErrorFound;
1463   CapturedStmt *CS;
1464   llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
1465   llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
1466
1467 public:
1468   void VisitDeclRefExpr(DeclRefExpr *E) {
1469     if (E->isTypeDependent() || E->isValueDependent() ||
1470         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1471       return;
1472     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
1473       // Skip internally declared variables.
1474       if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1475         return;
1476
1477       auto DVar = Stack->getTopDSA(VD, false);
1478       // Check if the variable has explicit DSA set and stop analysis if it so.
1479       if (DVar.RefExpr)
1480         return;
1481
1482       auto ELoc = E->getExprLoc();
1483       auto DKind = Stack->getCurrentDirective();
1484       // 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 &&
1489           isParallelOrTaskRegion(DKind) &&
1490           VarsWithInheritedDSA.count(VD) == 0) {
1491         VarsWithInheritedDSA[VD] = E;
1492         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.
1499       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);
1506       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
1507         ErrorFound = true;
1508         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1509         ReportOriginalDSA(SemaRef, Stack, VD, DVar);
1510         return;
1511       }
1512
1513       // Define implicit data-sharing attributes for task.
1514       DVar = Stack->getImplicitDSA(VD, false);
1515       if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1516           !Stack->isLoopControlVariable(VD).first)
1517         ImplicitFirstprivate.push_back(E);
1518     }
1519   }
1520   void VisitMemberExpr(MemberExpr *E) {
1521     if (E->isTypeDependent() || E->isValueDependent() ||
1522         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1523       return;
1524     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
1537         //  an  explicit task.
1538         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);
1546         if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
1547           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);
1555         if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1556             !Stack->isLoopControlVariable(FD).first)
1557           ImplicitFirstprivate.push_back(E);
1558       }
1559     } else
1560       Visit(E->getBase());
1561   }
1562   void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
1563     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     }
1572   }
1573   void VisitStmt(Stmt *S) {
1574     for (auto *C : S->children()) {
1575       if (C && !isa<OMPExecutableDirective>(C))
1576         Visit(C);
1577     }
1578   }
1579
1580   bool isErrorFound() { return ErrorFound; }
1581   ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
1582   llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
1583     return VarsWithInheritedDSA;
1584   }
1585
1586   DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1587       : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
1588 };
1589 } // namespace
1590
1591 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
1592   switch (DKind) {
1593   case OMPD_parallel:
1594   case OMPD_parallel_for:
1595   case OMPD_parallel_for_simd:
1596   case OMPD_parallel_sections:
1597   case OMPD_teams:
1598   case OMPD_target_teams: {
1599     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1600     QualType KmpInt32PtrTy =
1601         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1602     Sema::CapturedParamNameType Params[] = {
1603         std::make_pair(".global_tid.", KmpInt32PtrTy),
1604         std::make_pair(".bound_tid.", KmpInt32PtrTy),
1605         std::make_pair(StringRef(), QualType()) // __context with shared vars
1606     };
1607     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1608                              Params);
1609     break;
1610   }
1611   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:
1619   case OMPD_taskgroup:
1620   case OMPD_distribute:
1621   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:
1627   case OMPD_target_parallel_for_simd:
1628   case OMPD_target_simd: {
1629     Sema::CapturedParamNameType Params[] = {
1630         std::make_pair(StringRef(), QualType()) // __context with shared vars
1631     };
1632     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1633                              Params);
1634     break;
1635   }
1636   case OMPD_task: {
1637     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1638     QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1639     FunctionProtoType::ExtProtoInfo EPI;
1640     EPI.Variadic = true;
1641     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
1642     Sema::CapturedParamNameType Params[] = {
1643         std::make_pair(".global_tid.", KmpInt32Ty),
1644         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()),
1649         std::make_pair(StringRef(), QualType()) // __context with shared vars
1650     };
1651     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1652                              Params);
1653     // 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()));
1658     break;
1659   }
1660   case OMPD_taskloop:
1661   case OMPD_taskloop_simd: {
1662     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);
1672     Sema::CapturedParamNameType Params[] = {
1673         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),
1684         std::make_pair(StringRef(), QualType()) // __context with shared vars
1685     };
1686     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1687                              Params);
1688     // 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()));
1693     break;
1694   }
1695   case OMPD_distribute_parallel_for_simd:
1696   case OMPD_distribute_simd:
1697   case OMPD_distribute_parallel_for:
1698   case OMPD_teams_distribute:
1699   case OMPD_teams_distribute_simd:
1700   case OMPD_teams_distribute_parallel_for_simd:
1701   case OMPD_teams_distribute_parallel_for:
1702   case OMPD_target_teams_distribute:
1703   case OMPD_target_teams_distribute_parallel_for: {
1704     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   }
1718   case OMPD_threadprivate:
1719   case OMPD_taskyield:
1720   case OMPD_barrier:
1721   case OMPD_taskwait:
1722   case OMPD_cancellation_point:
1723   case OMPD_cancel:
1724   case OMPD_flush:
1725   case OMPD_target_enter_data:
1726   case OMPD_target_exit_data:
1727   case OMPD_declare_reduction:
1728   case OMPD_declare_simd:
1729   case OMPD_declare_target:
1730   case OMPD_end_declare_target:
1731   case OMPD_target_update:
1732     llvm_unreachable("OpenMP Directive is not allowed");
1733   case OMPD_unknown:
1734     llvm_unreachable("Unknown OpenMP directive");
1735   }
1736 }
1737
1738 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
1739                                              Expr *CaptureExpr, bool WithInit,
1740                                              bool AsExpression) {
1741   assert(CaptureExpr);
1742   ASTContext &C = S.getASTContext();
1743   Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
1744   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     }
1756     WithInit = true;
1757   }
1758   auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
1759                                           CaptureExpr->getLocStart());
1760   if (!WithInit)
1761     CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
1762   S.CurContext->addHiddenDecl(CED);
1763   S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false,
1764                          /*TypeMayContainAuto=*/true);
1765   return CED;
1766 }
1767
1768 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
1769                                  bool WithInit) {
1770   OMPCapturedExprDecl *CD;
1771   if (auto *VD = S.IsOpenMPCapturedDecl(D))
1772     CD = cast<OMPCapturedExprDecl>(VD);
1773   else
1774     CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
1775                           /*AsExpression=*/false);
1776   return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
1777                           CaptureExpr->getExprLoc());
1778 }
1779
1780 static 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());
1796 }
1797
1798 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1799                                       ArrayRef<OMPClause *> Clauses) {
1800   if (!S.isUsable()) {
1801     ActOnCapturedRegionError();
1802     return StmtError();
1803   }
1804
1805   OMPOrderedClause *OC = nullptr;
1806   OMPScheduleClause *SC = nullptr;
1807   SmallVector<OMPLinearClause *, 4> LCs;
1808   // This is required for proper codegen.
1809   for (auto *Clause : Clauses) {
1810     if (isOpenMPPrivate(Clause->getClauseKind()) ||
1811         Clause->getClauseKind() == OMPC_copyprivate ||
1812         (getLangOpts().OpenMPUseTLS &&
1813          getASTContext().getTargetInfo().isTLSSupported() &&
1814          Clause->getClauseKind() == OMPC_copyin)) {
1815       DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
1816       // Mark all variables in private list clauses as used in inner region.
1817       for (auto *VarRef : Clause->children()) {
1818         if (auto *E = cast_or_null<Expr>(VarRef)) {
1819           MarkDeclarationsReferencedInExpr(E);
1820         }
1821       }
1822       DSAStack->setForceVarCapturing(/*V=*/false);
1823     } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
1824       // 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.
1827       if (auto *C = OMPClauseWithPreInit::get(Clause)) {
1828         if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
1829           for (auto *D : DS->decls())
1830             MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
1831         }
1832       }
1833       if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
1834         if (auto *E = C->getPostUpdateExpr())
1835           MarkDeclarationsReferencedInExpr(E);
1836       }
1837     }
1838     if (Clause->getClauseKind() == OMPC_schedule)
1839       SC = cast<OMPScheduleClause>(Clause);
1840     else if (Clause->getClauseKind() == OMPC_ordered)
1841       OC = cast<OMPOrderedClause>(Clause);
1842     else if (Clause->getClauseKind() == OMPC_linear)
1843       LCs.push_back(cast<OMPLinearClause>(Clause));
1844   }
1845   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   }
1861   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     }
1866     ErrorFound = true;
1867   }
1868   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   }
1875   if (ErrorFound) {
1876     ActOnCapturedRegionError();
1877     return StmtError();
1878   }
1879   return ActOnCapturedRegionEnd(S.get());
1880 }
1881
1882 static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1883                                   OpenMPDirectiveKind CurrentRegion,
1884                                   const DeclarationNameInfo &CurrentName,
1885                                   OpenMPDirectiveKind CancelRegion,
1886                                   SourceLocation StartLoc) {
1887   if (Stack->getCurScope()) {
1888     auto ParentRegion = Stack->getParentDirective();
1889     auto OffendingRegion = ParentRegion;
1890     bool NestingProhibited = false;
1891     bool CloseNesting = true;
1892     bool OrphanSeen = false;
1893     enum {
1894       NoRecommend,
1895       ShouldBeInParallelRegion,
1896       ShouldBeInOrderedRegion,
1897       ShouldBeInTargetRegion,
1898       ShouldBeInTeamsRegion
1899     } Recommend = NoRecommend;
1900     if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
1901       // OpenMP [2.16, Nesting of Regions]
1902       // OpenMP constructs may not be nested inside a simd region.
1903       // OpenMP [2.8.1,simd Construct, Restrictions]
1904       // An ordered construct with the simd clause is the only OpenMP
1905       // construct that can appear in the simd region.
1906       // Allowing a SIMD construct nested in another SIMD construct is an
1907       // 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;
1913     }
1914     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     }
1920     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.
1925       if (ParentRegion != OMPD_sections &&
1926           ParentRegion != OMPD_parallel_sections) {
1927         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
1928             << (ParentRegion != OMPD_unknown)
1929             << getOpenMPDirectiveName(ParentRegion);
1930         return true;
1931       }
1932       return false;
1933     }
1934     // Allow some constructs (except teams) to be orphaned (they could be
1935     // used in functions, called from OpenMP regions with the required
1936     // preconditions).
1937     if (ParentRegion == OMPD_unknown &&
1938         !isOpenMPNestingTeamsDirective(CurrentRegion))
1939       return false;
1940     if (CurrentRegion == OMPD_cancellation_point ||
1941         CurrentRegion == OMPD_cancel) {
1942       // 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.
1948       // 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.
1953       NestingProhibited =
1954           !((CancelRegion == OMPD_parallel &&
1955              (ParentRegion == OMPD_parallel ||
1956               ParentRegion == OMPD_target_parallel)) ||
1957             (CancelRegion == OMPD_for &&
1958              (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
1959               ParentRegion == OMPD_target_parallel_for)) ||
1960             (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
1961             (CancelRegion == OMPD_sections &&
1962              (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
1963               ParentRegion == OMPD_parallel_sections)));
1964     } else if (CurrentRegion == OMPD_master) {
1965       // OpenMP [2.16, Nesting of Regions]
1966       // A master region may not be closely nested inside a worksharing,
1967       // atomic, or explicit task region.
1968       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
1969                           isOpenMPTaskingDirective(ParentRegion);
1970     } 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;
1976       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 */);
1987       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       }
1996     } else if (CurrentRegion == OMPD_barrier) {
1997       // OpenMP [2.16, Nesting of Regions]
1998       // A barrier region may not be closely nested inside a worksharing,
1999       // explicit task, critical, ordered, atomic, or master region.
2000       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2001                           isOpenMPTaskingDirective(ParentRegion) ||
2002                           ParentRegion == OMPD_master ||
2003                           ParentRegion == OMPD_critical ||
2004                           ParentRegion == OMPD_ordered;
2005     } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
2006                !isOpenMPParallelDirective(CurrentRegion) &&
2007                !isOpenMPTeamsDirective(CurrentRegion)) {
2008       // 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.
2011       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2012                           isOpenMPTaskingDirective(ParentRegion) ||
2013                           ParentRegion == OMPD_master ||
2014                           ParentRegion == OMPD_critical ||
2015                           ParentRegion == OMPD_ordered;
2016       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,
2020       // atomic, or explicit task region.
2021       // An ordered region must be closely nested inside a loop region (or
2022       // parallel loop region) with an ordered clause.
2023       // 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.
2026       NestingProhibited = ParentRegion == OMPD_critical ||
2027                           isOpenMPTaskingDirective(ParentRegion) ||
2028                           !(isOpenMPSimdDirective(ParentRegion) ||
2029                             Stack->isParentOrderedRegion());
2030       Recommend = ShouldBeInOrderedRegion;
2031     } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
2032       // 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;
2036       OrphanSeen = ParentRegion == OMPD_unknown;
2037       Recommend = ShouldBeInTargetRegion;
2038       Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2039     }
2040     if (!NestingProhibited &&
2041         !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2042         !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2043         (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
2044       // 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.
2048       NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2049                           !isOpenMPDistributeDirective(CurrentRegion);
2050       Recommend = ShouldBeInParallelRegion;
2051     }
2052     if (!NestingProhibited &&
2053         isOpenMPNestingDistributeDirective(CurrentRegion)) {
2054       // 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
2057       NestingProhibited =
2058           (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
2059       Recommend = ShouldBeInTeamsRegion;
2060     }
2061     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(
2069           [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2070                              SourceLocation) -> bool {
2071             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     }
2080     if (NestingProhibited) {
2081       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       }
2089       return true;
2090     }
2091   }
2092   return false;
2093 }
2094
2095 static 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);
2102   SmallVector<SourceLocation, 4> NameModifierLoc;
2103   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;
2113       } else if (CurNM != OMPD_unknown) {
2114         NameModifierLoc.push_back(IC->getNameModifierLoc());
2115         ++NamedModifiersNumber;
2116       }
2117       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     }
2169     for (auto Loc : NameModifierLoc) {
2170       S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2171     }
2172     ErrorFound = true;
2173   }
2174   return ErrorFound;
2175 }
2176
2177 StmtResult Sema::ActOnOpenMPExecutableDirective(
2178     OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2179     OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2180     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
2181   StmtResult Res = StmtError();
2182   if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
2183                             StartLoc))
2184     return StmtError();
2185
2186   llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
2187   llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
2188   bool ErrorFound = false;
2189   ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
2190   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();
2200
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     }
2211   }
2212
2213   llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
2214   switch (Kind) {
2215   case OMPD_parallel:
2216     Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2217                                        EndLoc);
2218     AllowedNameModifiers.push_back(OMPD_parallel);
2219     break;
2220   case OMPD_simd:
2221     Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2222                                    VarsWithInheritedDSA);
2223     break;
2224   case OMPD_for:
2225     Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2226                                   VarsWithInheritedDSA);
2227     break;
2228   case OMPD_for_simd:
2229     Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2230                                       EndLoc, VarsWithInheritedDSA);
2231     break;
2232   case OMPD_sections:
2233     Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2234                                        EndLoc);
2235     break;
2236   case OMPD_section:
2237     assert(ClausesWithImplicit.empty() &&
2238            "No clauses are allowed for 'omp section' directive");
2239     Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2240     break;
2241   case OMPD_single:
2242     Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2243                                      EndLoc);
2244     break;
2245   case OMPD_master:
2246     assert(ClausesWithImplicit.empty() &&
2247            "No clauses are allowed for 'omp master' directive");
2248     Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2249     break;
2250   case OMPD_critical:
2251     Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2252                                        StartLoc, EndLoc);
2253     break;
2254   case OMPD_parallel_for:
2255     Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2256                                           EndLoc, VarsWithInheritedDSA);
2257     AllowedNameModifiers.push_back(OMPD_parallel);
2258     break;
2259   case OMPD_parallel_for_simd:
2260     Res = ActOnOpenMPParallelForSimdDirective(
2261         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2262     AllowedNameModifiers.push_back(OMPD_parallel);
2263     break;
2264   case OMPD_parallel_sections:
2265     Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2266                                                StartLoc, EndLoc);
2267     AllowedNameModifiers.push_back(OMPD_parallel);
2268     break;
2269   case OMPD_task:
2270     Res =
2271         ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2272     AllowedNameModifiers.push_back(OMPD_task);
2273     break;
2274   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;
2281   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;
2288   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;
2295   case OMPD_taskgroup:
2296     assert(ClausesWithImplicit.empty() &&
2297            "No clauses are allowed for 'omp taskgroup' directive");
2298     Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
2299     break;
2300   case OMPD_flush:
2301     assert(AStmt == nullptr &&
2302            "No associated statement allowed for 'omp flush' directive");
2303     Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2304     break;
2305   case OMPD_ordered:
2306     Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2307                                       EndLoc);
2308     break;
2309   case OMPD_atomic:
2310     Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2311                                      EndLoc);
2312     break;
2313   case OMPD_teams:
2314     Res =
2315         ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2316     break;
2317   case OMPD_target:
2318     Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2319                                      EndLoc);
2320     AllowedNameModifiers.push_back(OMPD_target);
2321     break;
2322   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;
2328   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;
2334   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;
2341   case OMPD_cancel:
2342     assert(AStmt == nullptr &&
2343            "No associated statement allowed for 'omp cancel' directive");
2344     Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2345                                      CancelRegion);
2346     AllowedNameModifiers.push_back(OMPD_cancel);
2347     break;
2348   case OMPD_target_data:
2349     Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2350                                          EndLoc);
2351     AllowedNameModifiers.push_back(OMPD_target_data);
2352     break;
2353   case OMPD_target_enter_data:
2354     Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
2355                                               EndLoc);
2356     AllowedNameModifiers.push_back(OMPD_target_enter_data);
2357     break;
2358   case OMPD_target_exit_data:
2359     Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
2360                                              EndLoc);
2361     AllowedNameModifiers.push_back(OMPD_target_exit_data);
2362     break;
2363   case OMPD_taskloop:
2364     Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
2365                                        EndLoc, VarsWithInheritedDSA);
2366     AllowedNameModifiers.push_back(OMPD_taskloop);
2367     break;
2368   case OMPD_taskloop_simd:
2369     Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2370                                            EndLoc, VarsWithInheritedDSA);
2371     AllowedNameModifiers.push_back(OMPD_taskloop);
2372     break;
2373   case OMPD_distribute:
2374     Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
2375                                          EndLoc, VarsWithInheritedDSA);
2376     break;
2377   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;
2383   case OMPD_distribute_parallel_for:
2384     Res = ActOnOpenMPDistributeParallelForDirective(
2385         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2386     AllowedNameModifiers.push_back(OMPD_parallel);
2387     break;
2388   case OMPD_distribute_parallel_for_simd:
2389     Res = ActOnOpenMPDistributeParallelForSimdDirective(
2390         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2391     AllowedNameModifiers.push_back(OMPD_parallel);
2392     break;
2393   case OMPD_distribute_simd:
2394     Res = ActOnOpenMPDistributeSimdDirective(
2395         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2396     break;
2397   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;
2403   case OMPD_target_simd:
2404     Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2405                                          EndLoc, VarsWithInheritedDSA);
2406     AllowedNameModifiers.push_back(OMPD_target);
2407     break;
2408   case OMPD_teams_distribute:
2409     Res = ActOnOpenMPTeamsDistributeDirective(
2410         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2411     break;
2412   case OMPD_teams_distribute_simd:
2413     Res = ActOnOpenMPTeamsDistributeSimdDirective(
2414         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2415     break;
2416   case OMPD_teams_distribute_parallel_for_simd:
2417     Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
2418         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2419     AllowedNameModifiers.push_back(OMPD_parallel);
2420     break;
2421   case OMPD_teams_distribute_parallel_for:
2422     Res = ActOnOpenMPTeamsDistributeParallelForDirective(
2423         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2424     AllowedNameModifiers.push_back(OMPD_parallel);
2425     break;
2426   case OMPD_target_teams:
2427     Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
2428                                           EndLoc);
2429     AllowedNameModifiers.push_back(OMPD_target);
2430     break;
2431   case OMPD_target_teams_distribute:
2432     Res = ActOnOpenMPTargetTeamsDistributeDirective(
2433         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2434     AllowedNameModifiers.push_back(OMPD_target);
2435     break;
2436   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;
2442   case OMPD_declare_target:
2443   case OMPD_end_declare_target:
2444   case OMPD_threadprivate:
2445   case OMPD_declare_reduction:
2446   case OMPD_declare_simd:
2447     llvm_unreachable("OpenMP Directive is not allowed");
2448   case OMPD_unknown:
2449     llvm_unreachable("Unknown OpenMP directive");
2450   }
2451
2452   for (auto P : VarsWithInheritedDSA) {
2453     Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2454         << P.first << P.second->getSourceRange();
2455   }
2456   ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
2457
2458   if (!AllowedNameModifiers.empty())
2459     ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
2460                  ErrorFound;
2461
2462   if (ErrorFound)
2463     return StmtError();
2464   return Res;
2465 }
2466
2467 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
2468     DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
2469     ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
2470     ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
2471     ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
2472   assert(Aligneds.size() == Alignments.size());
2473   assert(Linears.size() == LinModifiers.size());
2474   assert(Linears.size() == Steps.size());
2475   if (!DG || DG.get().isNull())
2476     return DeclGroupPtrTy();
2477
2478   if (!DG.get().isSingleDecl()) {
2479     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
2480     return DG;
2481   }
2482   auto *ADecl = DG.get().getSingleDecl();
2483   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
2484     ADecl = FTD->getTemplatedDecl();
2485
2486   auto *FD = dyn_cast<FunctionDecl>(ADecl);
2487   if (!FD) {
2488     Diag(ADecl->getLocation(), diag::err_omp_function_expected);
2489     return DeclGroupPtrTy();
2490   }
2491
2492   // 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;
2496   if (Simdlen)
2497     SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
2498   // 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.
2504   llvm::DenseMap<Decl *, Expr *> UniformedArgs;
2505   Expr *UniformedLinearThis = nullptr;
2506   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())
2512                     ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
2513           UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
2514           continue;
2515         }
2516     if (isa<CXXThisExpr>(E)) {
2517       UniformedLinearThis = E;
2518       continue;
2519     }
2520     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2521         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2522   }
2523   // 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   }
2589   // 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   }
2702   auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
2703       Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
2704       Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
2705       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);
2709   ADecl->addAttr(NewAttr);
2710   return ConvertDeclToDeclGroup(ADecl);
2711 }
2712
2713 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2714                                               Stmt *AStmt,
2715                                               SourceLocation StartLoc,
2716                                               SourceLocation EndLoc) {
2717   if (!AStmt)
2718     return StmtError();
2719
2720   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
2728   getCurFunction()->setHasBranchProtectedScope();
2729
2730   return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
2731                                       DSAStack->isCancelRegion());
2732 }
2733
2734 namespace {
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.
2738 class 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;
2745   /// \brief A source location for referring to loop init later.
2746   SourceRange InitSrcRange;
2747   /// \brief A source location for referring to condition later.
2748   SourceRange ConditionSrcRange;
2749   /// \brief A source location for referring to increment later.
2750   SourceRange IncrementSrcRange;
2751   /// \brief Loop variable.
2752   ValueDecl *LCDecl = nullptr;
2753   /// \brief Reference to loop variable.
2754   Expr *LCRef = nullptr;
2755   /// \brief Lower bound (initializer for the var).
2756   Expr *LB = nullptr;
2757   /// \brief Upper bound.
2758   Expr *UB = nullptr;
2759   /// \brief Loop step (increment).
2760   Expr *Step = nullptr;
2761   /// \brief This flag is true when condition is one of:
2762   ///   Var <  UB
2763   ///   Var <= UB
2764   ///   UB  >  Var
2765   ///   UB  >= Var
2766   bool TestIsLessOp = false;
2767   /// \brief This flag is true when condition is strict ( < or > ).
2768   bool TestIsStrictOp = false;
2769   /// \brief This flag is true when step is subtracted on each iteration.
2770   bool SubtractStep = false;
2771
2772 public:
2773   OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
2774       : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
2775   /// \brief Check init-expr for canonical loop form and save loop counter
2776   /// variable - #Var and its initialization value - #LB.
2777   bool CheckInit(Stmt *S, bool EmitDiags = true);
2778   /// \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.
2785   ValueDecl *GetLoopDecl() const { return LCDecl; }
2786   /// \brief Return the reference expression to loop counter variable.
2787   Expr *GetLoopDeclRefExpr() const { return LCRef; }
2788   /// \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.
2797   Expr *
2798   BuildNumIterations(Scope *S, const bool LimitedType,
2799                      llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
2800   /// \brief Build the precondition expression for the loops.
2801   Expr *BuildPreCond(Scope *S, Expr *Cond,
2802                      llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
2803   /// \brief Build reference expression to the counter be used for codegen.
2804   DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
2805                                DSAStackTy &DSA) const;
2806   /// \brief Build reference expression to the private counter be used for
2807   /// codegen.
2808   Expr *BuildPrivateCounterVar() const;
2809   /// \brief Build initialization of the counter be used for codegen.
2810   Expr *BuildCounterInit() const;
2811   /// \brief Build step of the counter be used for codegen.
2812   Expr *BuildCounterStep() const;
2813   /// \brief Return true if any expression is dependent.
2814   bool Dependent() const;
2815
2816 private:
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.
2821   bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
2822   /// \brief Helper to set upper bound.
2823   bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
2824              SourceLocation SL);
2825   /// \brief Helper to set loop increment.
2826   bool SetStep(Expr *NewStep, bool Subtract);
2827 };
2828
2829 bool OpenMPIterationSpaceChecker::Dependent() const {
2830   if (!LCDecl) {
2831     assert(!LB && !UB && !Step);
2832     return false;
2833   }
2834   return LCDecl->getType()->isDependentType() ||
2835          (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
2836          (Step && Step->isValueDependent());
2837 }
2838
2839 static Expr *getExprAsWritten(Expr *E) {
2840   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
2854 bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
2855                                                  Expr *NewLCRefExpr,
2856                                                  Expr *NewLB) {
2857   // State consistency checking to ensure correct usage.
2858   assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
2859          UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
2860   if (!NewLCDecl || !NewLB)
2861     return true;
2862   LCDecl = getCanonicalDecl(NewLCDecl);
2863   LCRef = NewLCRefExpr;
2864   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
2865     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
2866       if ((Ctor->isCopyOrMoveConstructor() ||
2867            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2868           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
2869         NewLB = CE->getArg(0)->IgnoreParenImpCasts();
2870   LB = NewLB;
2871   return false;
2872 }
2873
2874 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
2875                                         SourceRange SR, SourceLocation SL) {
2876   // State consistency checking to ensure correct usage.
2877   assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
2878          Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
2879   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
2889 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2890   // State consistency checking to ensure correct usage.
2891   assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
2892   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());
2919     bool IsConstPos =
2920         IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
2921     bool IsConstZero = IsConstant && !Result.getBoolValue();
2922     if (UB && (IsConstZero ||
2923                (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
2924                              : (IsConstPos || (IsUnsigned && !Subtract))))) {
2925       SemaRef.Diag(NewStep->getExprLoc(),
2926                    diag::err_omp_loop_incr_not_compatible)
2927           << LCDecl << TestIsLessOp << NewStep->getSourceRange();
2928       SemaRef.Diag(ConditionLoc,
2929                    diag::note_omp_loop_cond_requres_compatible_incr)
2930           << TestIsLessOp << ConditionSrcRange;
2931       return true;
2932     }
2933     if (TestIsLessOp == Subtract) {
2934       NewStep =
2935           SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
2936               .get();
2937       Subtract = !Subtract;
2938     }
2939   }
2940
2941   Step = NewStep;
2942   SubtractStep = Subtract;
2943   return false;
2944 }
2945
2946 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
2947   // 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) {
2956     if (EmitDiags) {
2957       SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
2958     }
2959     return true;
2960   }
2961   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
2962     if (!ExprTemp->cleanupsHaveSideEffects())
2963       S = ExprTemp->getSubExpr();
2964
2965   InitSrcRange = S->getSourceRange();
2966   if (Expr *E = dyn_cast<Expr>(S))
2967     S = E->IgnoreParens();
2968   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
2969     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     }
2983   } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
2984     if (DS->isSingleDecl()) {
2985       if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
2986         if (Var->hasInit() && !Var->getType()->isReferenceType()) {
2987           // Accept non-canonical init form here but emit ext. warning.
2988           if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
2989             SemaRef.Diag(S->getLocStart(),
2990                          diag::ext_omp_loop_not_canonical_init)
2991                 << S->getSourceRange();
2992           return SetLCDeclAndLB(Var, nullptr, Var->getInit());
2993         }
2994       }
2995     }
2996   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2997     if (CE->getOperator() == OO_Equal) {
2998       auto *LHS = CE->getArg(0);
2999       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3000         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   }
3012
3013   if (Dependent() || SemaRef.CurContext->isDependentContext())
3014     return false;
3015   if (EmitDiags) {
3016     SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3017         << S->getSourceRange();
3018   }
3019   return true;
3020 }
3021
3022 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
3023 /// variable (which may be the loop variable) if possible.
3024 static const ValueDecl *GetInitLCDecl(Expr *E) {
3025   if (!E)
3026     return nullptr;
3027   E = getExprAsWritten(E);
3028   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3029     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
3030       if ((Ctor->isCopyOrMoveConstructor() ||
3031            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3032           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
3033         E = CE->getArg(0)->IgnoreParenImpCasts();
3034   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;
3046 }
3047
3048 bool 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) {
3056     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
3057     return true;
3058   }
3059   S = getExprAsWritten(S);
3060   SourceLocation CondLoc = S->getLocStart();
3061   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
3062     if (BO->isRelationalOp()) {
3063       if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3064         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());
3068       if (GetInitLCDecl(BO->getRHS()) == LCDecl)
3069         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     }
3074   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3075     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:
3082         if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3083           return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3084                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3085                        CE->getOperatorLoc());
3086         if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
3087           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   }
3096   if (Dependent() || SemaRef.CurContext->isDependentContext())
3097     return false;
3098   SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
3099       << S->getSourceRange() << LCDecl;
3100   return true;
3101 }
3102
3103 bool 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();
3110   if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
3111     if (BO->isAdditiveOp()) {
3112       bool IsAdd = BO->getOpcode() == BO_Add;
3113       if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3114         return SetStep(BO->getRHS(), !IsAdd);
3115       if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
3116         return SetStep(BO->getLHS(), false);
3117     }
3118   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
3119     bool IsAdd = CE->getOperator() == OO_Plus;
3120     if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
3121       if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3122         return SetStep(CE->getArg(1), !IsAdd);
3123       if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
3124         return SetStep(CE->getArg(0), false);
3125     }
3126   }
3127   if (Dependent() || SemaRef.CurContext->isDependentContext())
3128     return false;
3129   SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
3130       << RHS->getSourceRange() << LCDecl;
3131   return true;
3132 }
3133
3134 bool 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) {
3149     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
3150     return true;
3151   }
3152   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3153     if (!ExprTemp->cleanupsHaveSideEffects())
3154       S = ExprTemp->getSubExpr();
3155
3156   IncrementSrcRange = S->getSourceRange();
3157   S = S->IgnoreParens();
3158   if (auto *UO = dyn_cast<UnaryOperator>(S)) {
3159     if (UO->isIncrementDecrementOp() &&
3160         GetInitLCDecl(UO->getSubExpr()) == LCDecl)
3161       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)) {
3167     switch (BO->getOpcode()) {
3168     case BO_AddAssign:
3169     case BO_SubAssign:
3170       if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3171         return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3172       break;
3173     case BO_Assign:
3174       if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3175         return CheckIncRHS(BO->getRHS());
3176       break;
3177     default:
3178       break;
3179     }
3180   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3181     switch (CE->getOperator()) {
3182     case OO_PlusPlus:
3183     case OO_MinusMinus:
3184       if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3185         return SetStep(SemaRef
3186                            .ActOnIntegerConstant(
3187                                CE->getLocStart(),
3188                                ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3189                            .get(),
3190                        false);
3191       break;
3192     case OO_PlusEqual:
3193     case OO_MinusEqual:
3194       if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3195         return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3196       break;
3197     case OO_Equal:
3198       if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3199         return CheckIncRHS(CE->getArg(1));
3200       break;
3201     default:
3202       break;
3203     }
3204   }
3205   if (Dependent() || SemaRef.CurContext->isDependentContext())
3206     return false;
3207   SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
3208       << S->getSourceRange() << LCDecl;
3209   return true;
3210 }
3211
3212 static ExprResult
3213 tryBuildCapture(Sema &SemaRef, Expr *Capture,
3214                 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3215   if (SemaRef.CurContext->isDependentContext())
3216     return ExprResult(Capture);
3217   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;
3228 }
3229
3230 /// \brief Build the expression to calculate the number of iterations.
3231 Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3232     Scope *S, const bool LimitedType,
3233     llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
3234   ExprResult Diff;
3235   auto VarType = LCDecl->getType().getNonReferenceType();
3236   if (VarType->isIntegerType() || VarType->isPointerType() ||
3237       SemaRef.getLangOpts().CPlusPlus) {
3238     // Upper - Lower
3239     auto *UBExpr = TestIsLessOp ? UB : LB;
3240     auto *LBExpr = TestIsLessOp ? LB : UB;
3241     Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3242     Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
3243     if (!Upper || !Lower)
3244       return nullptr;
3245
3246     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3247
3248     if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
3249       // 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
3269   auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3270   if (!NewStep.isUsable())
3271     return nullptr;
3272   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
3273   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
3282   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
3283   if (!Diff.isUsable())
3284     return nullptr;
3285
3286   // OpenMP runtime requires 32-bit or 64-bit loop variables.
3287   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);
3297     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     }
3303   }
3304   if (LimitedType) {
3305     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(
3313           NewSize, Type->hasSignedIntegerRepresentation() ||
3314                        C.getTypeSize(Type) < NewSize);
3315       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       }
3321     }
3322   }
3323
3324   return Diff.get();
3325 }
3326
3327 Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3328     Scope *S, Expr *Cond,
3329     llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
3330   // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3331   bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3332   SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3333
3334   auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3335   auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3336   if (!NewLB.isUsable() || !NewUB.isUsable())
3337     return nullptr;
3338
3339   auto CondExpr = SemaRef.BuildBinOp(
3340       S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3341                                   : (TestIsStrictOp ? BO_GT : BO_GE),
3342       NewLB.get(), NewUB.get());
3343   if (CondExpr.isUsable()) {
3344     if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
3345                                                 SemaRef.Context.BoolTy))
3346       CondExpr = SemaRef.PerformImplicitConversion(
3347           CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3348           /*AllowExplicit=*/true);
3349   }
3350   SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3351   // Otherwise use original loop conditon and evaluate it in runtime.
3352   return CondExpr.isUsable() ? CondExpr.get() : Cond;
3353 }
3354
3355 /// \brief Build reference expression to the counter be used for codegen.
3356 DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
3357     llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
3358   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);
3363     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));
3368     return Ref;
3369   }
3370   return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
3371                           DefaultLoc);
3372 }
3373
3374 Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
3375   if (LCDecl && !LCDecl->isInvalidDecl()) {
3376     auto Type = LCDecl->getType().getNonReferenceType();
3377     auto *PrivateVar =
3378         buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
3379                      LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
3380     if (PrivateVar->isInvalidDecl())
3381       return nullptr;
3382     return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3383   }
3384   return nullptr;
3385 }
3386
3387 /// \brief Build initialization of the counter to be used for codegen.
3388 Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3389
3390 /// \brief Build step of the counter be used for codegen.
3391 Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3392
3393 /// \brief Iteration space of a single for loop.
3394 struct LoopIterationSpace final {
3395   /// \brief Condition of the loop.
3396   Expr *PreCond = nullptr;
3397   /// \brief This expression calculates the number of iterations in the loop.
3398   /// It is always possible to calculate it before starting the loop.
3399   Expr *NumIterations = nullptr;
3400   /// \brief The loop counter variable.
3401   Expr *CounterVar = nullptr;
3402   /// \brief Private loop counter variable.
3403   Expr *PrivateCounterVar = nullptr;
3404   /// \brief This is initializer for the initial value of #CounterVar.
3405   Expr *CounterInit = nullptr;
3406   /// \brief This is step for the #CounterVar used to generate its update:
3407   /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
3408   Expr *CounterStep = nullptr;
3409   /// \brief Should step be subtracted?
3410   bool Subtract = false;
3411   /// \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
3419 } // namespace
3420
3421 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
3422   assert(getLangOpts().OpenMP && "OpenMP is not active.");
3423   assert(Init && "Expected loop in canonical form.");
3424   unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
3425   if (AssociatedLoops > 0 &&
3426       isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
3427     OpenMPIterationSpaceChecker ISC(*this, ForLoc);
3428     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     }
3443     DSAStack->setAssociatedLoops(AssociatedLoops - 1);
3444   }
3445 }
3446
3447 /// \brief Called on a for stmt to check and extract its iteration space
3448 /// for further processing (such as collapsing).
3449 static bool CheckOpenMPIterationSpace(
3450     OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3451     unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
3452     Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
3453     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
3454     LoopIterationSpace &ResultIterSpace,
3455     llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3456   // OpenMP [2.6, Canonical Loop Form]
3457   //   for (init-expr; test-expr; incr-expr) structured-block
3458   auto *For = dyn_cast_or_null<ForStmt>(S);
3459   if (!For) {
3460     SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
3461         << (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     }
3479     return true;
3480   }
3481   assert(For->getBody());
3482
3483   OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3484
3485   // Check init.
3486   auto Init = For->getInit();
3487   if (ISC.CheckInit(Init))
3488     return true;
3489
3490   bool HasErrors = false;
3491
3492   // Check loop variable's type.
3493   if (auto *LCDecl = ISC.GetLoopDecl()) {
3494     auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
3495
3496     // 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)
3556         DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
3557                           [](OpenMPDirectiveKind) -> bool { return true; },
3558                           /*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());
3569   }
3570
3571   if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
3572     return HasErrors;
3573
3574   // Build the loop's iteration space representation.
3575   ResultIterSpace.PreCond =
3576       ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
3577   ResultIterSpace.NumIterations = ISC.BuildNumIterations(
3578       DSA.getCurScope(),
3579       (isOpenMPWorksharingDirective(DKind) ||
3580        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
3581       Captures);
3582   ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
3583   ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
3584   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
3591   HasErrors |= (ResultIterSpace.PreCond == nullptr ||
3592                 ResultIterSpace.NumIterations == nullptr ||
3593                 ResultIterSpace.CounterVar == nullptr ||
3594                 ResultIterSpace.PrivateCounterVar == nullptr ||
3595                 ResultIterSpace.CounterInit == nullptr ||
3596                 ResultIterSpace.CounterStep == nullptr);
3597
3598   return HasErrors;
3599 }
3600
3601 /// \brief Build 'VarRef = Start.
3602 static ExprResult
3603 BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
3604                  ExprResult Start,
3605                  llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3606   // Build 'VarRef = Start.
3607   auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
3608   if (!NewStart.isUsable())
3609     return ExprError();
3610   if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
3611                                    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   }
3618
3619   auto Init =
3620       SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3621   return Init;
3622 }
3623
3624 /// \brief Build 'VarRef = Start + Iter * Step'.
3625 static ExprResult
3626 BuildCounterUpdate(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) {
3630   // 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
3636   ExprResult NewStep = Step;
3637   if (Captures)
3638     NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
3639   if (NewStep.isInvalid())
3640     return ExprError();
3641   ExprResult Update =
3642       SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
3643   if (!Update.isUsable())
3644     return ExprError();
3645
3646   // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
3647   // 'VarRef = Start (+|-) Iter * Step'.
3648   ExprResult NewStart = Start;
3649   if (Captures)
3650     NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
3651   if (NewStart.isInvalid())
3652     return ExprError();
3653
3654   // 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   }
3675
3676   // 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
3683     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     }
3690
3691     Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
3692   }
3693   return Update;
3694 }
3695
3696 /// \brief Convert integer expression \a E to make it have at least \a Bits
3697 /// bits.
3698 static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
3699   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.
3714 static 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;
3721 }
3722
3723 /// Build preinits statement for the given declarations.
3724 static 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.
3735 static 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.
3747 static 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
3766 /// \brief Called on a for stmt to check itself and nested loops (if any).
3767 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
3768 /// number of collapsed loops otherwise.
3769 static unsigned
3770 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
3771                 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
3772                 DSAStackTy &DSA,
3773                 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
3774                 OMPLoopDirective::HelperExprs &Built) {
3775   unsigned NestedLoopCount = 1;
3776   if (CollapseLoopCountExpr) {
3777     // Found 'collapse' clause - calculate collapse number.
3778     llvm::APSInt Result;
3779     if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
3780       NestedLoopCount = Result.getLimitedValue();
3781   }
3782   if (OrderedLoopCountExpr) {
3783     // Found 'ordered' clause - calculate collapse number.
3784     llvm::APSInt Result;
3785     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     }
3796   }
3797   // This is helper routine for loop directives (e.g., 'for', 'simd',
3798   // 'for simd', etc.).
3799   llvm::MapVector<Expr *, DeclRefExpr *> Captures;
3800   SmallVector<LoopIterationSpace, 4> IterSpaces;
3801   IterSpaces.resize(NestedLoopCount);
3802   Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
3803   for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
3804     if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
3805                                   NestedLoopCount, CollapseLoopCountExpr,
3806                                   OrderedLoopCountExpr, VarsWithImplicitDSA,
3807                                   IterSpaces[Cnt], Captures))
3808       return 0;
3809     // Move on to the next nested for loop, or to the loop body.
3810     // 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();
3815   }
3816
3817   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   //
3824   //   #pragma omp simd collapse(2) ordered(2)
3825   //   for (i = 0; i < NI; ++i)
3826   //     for (k = 0; k < NK; ++k)
3827   //       for (j = J0; j < NJ; j+=2) {
3828   //         <loop body>
3829   //       }
3830   //
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.
3851   // Precondition tests if there is at least one iteration (all conditions are
3852   // true).
3853   auto PreCond = ExprResult(IterSpaces[0].PreCond);
3854   auto N0 = IterSpaces[0].NumIterations;
3855   ExprResult LastIteration32 = WidenIterationCount(
3856       32 /* Bits */, SemaRef
3857                          .PerformImplicitConversion(
3858                              N0->IgnoreImpCasts(), N0->getType(),
3859                              Sema::AA_Converting, /*AllowExplicit=*/true)
3860                          .get(),
3861       SemaRef);
3862   ExprResult LastIteration64 = WidenIterationCount(
3863       64 /* Bits */, SemaRef
3864                          .PerformImplicitConversion(
3865                              N0->IgnoreImpCasts(), N0->getType(),
3866                              Sema::AA_Converting, /*AllowExplicit=*/true)
3867                          .get(),
3868       SemaRef);
3869
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) {
3878     if (PreCond.isUsable()) {
3879       PreCond =
3880           SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
3881                              PreCond.get(), IterSpaces[Cnt].PreCond);
3882     }
3883     auto N = IterSpaces[Cnt].NumIterations;
3884     SourceLocation Loc = N->getExprLoc();
3885     AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
3886     if (LastIteration32.isUsable())
3887       LastIteration32 = SemaRef.BuildBinOp(
3888           CurScope, Loc, BO_Mul, LastIteration32.get(),
3889           SemaRef
3890               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3891                                          Sema::AA_Converting,
3892                                          /*AllowExplicit=*/true)
3893               .get());
3894     if (LastIteration64.isUsable())
3895       LastIteration64 = SemaRef.BuildBinOp(
3896           CurScope, Loc, BO_Mul, LastIteration64.get(),
3897           SemaRef
3898               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3899                                          Sema::AA_Converting,
3900                                          /*AllowExplicit=*/true)
3901               .get());
3902   }
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;
3914   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   }
3923
3924   if (!LastIteration.isUsable())
3925     return 0;
3926
3927   // Save the number of iterations.
3928   ExprResult NumIterations = LastIteration;
3929   {
3930     LastIteration = SemaRef.BuildBinOp(
3931         CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
3932         LastIteration.get(),
3933         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) {
3945     ExprResult SaveRef =
3946         tryBuildCapture(SemaRef, LastIteration.get(), Captures);
3947     LastIteration = SaveRef;
3948
3949     // Prepare SaveRef + 1.
3950     NumIterations = SemaRef.BuildBinOp(
3951         CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
3952         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3953     if (!NumIterations.isUsable())
3954       return 0;
3955   }
3956
3957   SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
3958
3959   // Build variables passed into runtime, necessary for worksharing directives.
3960   ExprResult LB, UB, IL, ST, EUB, PrevLB, PrevUB;
3961   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
3962       isOpenMPDistributeDirective(DKind)) {
3963     // Lower bound variable, initialized with zero.
3964     VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
3965     LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
3966     SemaRef.AddInitializerToDecl(
3967         LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3968         /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3969
3970     // Upper bound variable, initialized with last iteration number.
3971     VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
3972     UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
3973     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);
3980     VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
3981     IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
3982     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).
3987     VarDecl *STDecl =
3988         buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
3989     ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
3990     SemaRef.AddInitializerToDecl(
3991         STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
3992         /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3993
3994     // Build expression: UB = min(UB, LastIteration)
3995     // It is necessary for CodeGen of directives with static scheduling.
3996     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());
4003
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     }
4028   }
4029
4030   // Build the iteration variable and its initialization before loop.
4031   ExprResult IV;
4032   ExprResult Init;
4033   {
4034     VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4035     IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
4036     Expr *RHS =
4037         (isOpenMPWorksharingDirective(DKind) ||
4038          isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4039             ? LB.get()
4040             : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4041     Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4042     Init = SemaRef.ActOnFinishFullExpr(Init.get());
4043   }
4044
4045   // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
4046   SourceLocation CondLoc;
4047   ExprResult Cond =
4048       (isOpenMPWorksharingDirective(DKind) ||
4049        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4050           ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4051           : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4052                                NumIterations.get());
4053
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());
4062   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;
4069   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4070       isOpenMPDistributeDirective(DKind)) {
4071     // 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   }
4092
4093   // Build updates and final values of the loop counters.
4094   bool HasErrors = false;
4095   Built.Counters.resize(NestedLoopCount);
4096   Built.Inits.resize(NestedLoopCount);
4097   Built.Updates.resize(NestedLoopCount);
4098   Built.Finals.resize(NestedLoopCount);
4099   SmallVector<Expr *, 4> LoopMultipliers;
4100   {
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
4126       // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
4127       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);
4131       ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
4132                                          IS.CounterInit, Captures);
4133       if (!Init.isUsable()) {
4134         HasErrors = true;
4135         break;
4136       }
4137       ExprResult Update = BuildCounterUpdate(
4138           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4139           IS.CounterStep, IS.Subtract, &Captures);
4140       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(
4147           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
4148           IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
4149       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())
4164           Div = tryBuildCapture(SemaRef, Div.get(), Captures);
4165         if (!Div.isUsable()) {
4166           HasErrors = true;
4167           break;
4168         }
4169         LoopMultipliers.push_back(Div.get());
4170       }
4171       if (!Update.isUsable() || !Final.isUsable()) {
4172         HasErrors = true;
4173         break;
4174       }
4175       // Save results
4176       Built.Counters[Cnt] = IS.CounterVar;
4177       Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
4178       Built.Inits[Cnt] = Init.get();
4179       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();
4190   Built.NumIterations = NumIterations.get();
4191   Built.CalcLastIteration =
4192       SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
4193   Built.PreCond = PreCond.get();
4194   Built.PreInits = buildPreInits(C, Captures);
4195   Built.Cond = Cond.get();
4196   Built.Init = Init.get();
4197   Built.Inc = Inc.get();
4198   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();
4205   Built.PrevLB = PrevLB.get();
4206   Built.PrevUB = PrevUB.get();
4207
4208   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;
4243           UpCounterVal = SemaRef
4244                              .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
4245                                          UpCounterVal, NormalizedOffset)
4246                              .get();
4247         }
4248         Multiplier = *ILM;
4249         ++I;
4250         ++IS;
4251         ++ILM;
4252       }
4253       Pair.first->setCounterValue(UpCounterVal);
4254     }
4255   }
4256
4257   return NestedLoopCount;
4258 }
4259
4260 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
4261   auto CollapseClauses =
4262       OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4263   if (CollapseClauses.begin() != CollapseClauses.end())
4264     return (*CollapseClauses.begin())->getNumForLoops();
4265   return nullptr;
4266 }
4267
4268 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
4269   auto OrderedClauses =
4270       OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4271   if (OrderedClauses.begin() != OrderedClauses.end())
4272     return (*OrderedClauses.begin())->getNumForLoops();
4273   return nullptr;
4274 }
4275
4276 static 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     }
4314   }
4315   return false;
4316 }
4317
4318 StmtResult Sema::ActOnOpenMPSimdDirective(
4319     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4320     SourceLocation EndLoc,
4321     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4322   if (!AStmt)
4323     return StmtError();
4324
4325   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4326   OMPLoopDirective::HelperExprs B;
4327   // 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);
4332   if (NestedLoopCount == 0)
4333     return StmtError();
4334
4335   assert((CurContext->isDependentContext() || B.builtAll()) &&
4336          "omp simd loop exprs were not built");
4337
4338   if (!CurContext->isDependentContext()) {
4339     // Finalize the clauses that need pre-built expressions for CodeGen.
4340     for (auto C : Clauses) {
4341       if (auto *LC = dyn_cast<OMPLinearClause>(C))
4342         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4343                                      B.NumIterations, *this, CurScope,
4344                                      DSAStack))
4345           return StmtError();
4346     }
4347   }
4348
4349   if (checkSimdlenSafelenSpecified(*this, Clauses))
4350     return StmtError();
4351
4352   getCurFunction()->setHasBranchProtectedScope();
4353   return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4354                                   Clauses, AStmt, B);
4355 }
4356
4357 StmtResult Sema::ActOnOpenMPForDirective(
4358     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4359     SourceLocation EndLoc,
4360     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4361   if (!AStmt)
4362     return StmtError();
4363
4364   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4365   OMPLoopDirective::HelperExprs B;
4366   // 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);
4371   if (NestedLoopCount == 0)
4372     return StmtError();
4373
4374   assert((CurContext->isDependentContext() || B.builtAll()) &&
4375          "omp for loop exprs were not built");
4376
4377   if (!CurContext->isDependentContext()) {
4378     // Finalize the clauses that need pre-built expressions for CodeGen.
4379     for (auto C : Clauses) {
4380       if (auto *LC = dyn_cast<OMPLinearClause>(C))
4381         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4382                                      B.NumIterations, *this, CurScope,
4383                                      DSAStack))
4384           return StmtError();
4385     }
4386   }
4387
4388   getCurFunction()->setHasBranchProtectedScope();
4389   return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4390                                  Clauses, AStmt, B, DSAStack->isCancelRegion());
4391 }
4392
4393 StmtResult Sema::ActOnOpenMPForSimdDirective(
4394     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4395     SourceLocation EndLoc,
4396     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4397   if (!AStmt)
4398     return StmtError();
4399
4400   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4401   OMPLoopDirective::HelperExprs B;
4402   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4403   // define the nested loops number.
4404   unsigned NestedLoopCount =
4405       CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
4406                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4407                       VarsWithImplicitDSA, B);
4408   if (NestedLoopCount == 0)
4409     return StmtError();
4410
4411   assert((CurContext->isDependentContext() || B.builtAll()) &&
4412          "omp for simd loop exprs were not built");
4413
4414   if (!CurContext->isDependentContext()) {
4415     // Finalize the clauses that need pre-built expressions for CodeGen.
4416     for (auto C : Clauses) {
4417       if (auto *LC = dyn_cast<OMPLinearClause>(C))
4418         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4419                                      B.NumIterations, *this, CurScope,
4420                                      DSAStack))
4421           return StmtError();
4422     }
4423   }
4424
4425   if (checkSimdlenSafelenSpecified(*this, Clauses))
4426     return StmtError();
4427
4428   getCurFunction()->setHasBranchProtectedScope();
4429   return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4430                                      Clauses, AStmt, B);
4431 }
4432
4433 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
4434                                               Stmt *AStmt,
4435                                               SourceLocation StartLoc,
4436                                               SourceLocation EndLoc) {
4437   if (!AStmt)
4438     return StmtError();
4439
4440   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4441   auto BaseStmt = AStmt;
4442   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
4443     BaseStmt = CS->getCapturedStmt();
4444   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
4445     auto S = C->children();
4446     if (S.begin() == S.end())
4447       return StmtError();
4448     // All associated statements must be '#pragma omp section' except for
4449     // the first one.
4450     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
4451       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4452         if (SectionStmt)
4453           Diag(SectionStmt->getLocStart(),
4454                diag::err_omp_sections_substmt_not_section);
4455         return StmtError();
4456       }
4457       cast<OMPSectionDirective>(SectionStmt)
4458           ->setHasCancel(DSAStack->isCancelRegion());
4459     }
4460   } else {
4461     Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
4462     return StmtError();
4463   }
4464
4465   getCurFunction()->setHasBranchProtectedScope();
4466
4467   return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4468                                       DSAStack->isCancelRegion());
4469 }
4470
4471 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
4472                                              SourceLocation StartLoc,
4473                                              SourceLocation EndLoc) {
4474   if (!AStmt)
4475     return StmtError();
4476
4477   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4478
4479   getCurFunction()->setHasBranchProtectedScope();
4480   DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
4481
4482   return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
4483                                      DSAStack->isCancelRegion());
4484 }
4485
4486 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
4487                                             Stmt *AStmt,
4488                                             SourceLocation StartLoc,
4489                                             SourceLocation EndLoc) {
4490   if (!AStmt)
4491     return StmtError();
4492
4493   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4494
4495   getCurFunction()->setHasBranchProtectedScope();
4496
4497   // 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
4514   return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4515 }
4516
4517 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
4518                                             SourceLocation StartLoc,
4519                                             SourceLocation EndLoc) {
4520   if (!AStmt)
4521     return StmtError();
4522
4523   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4524
4525   getCurFunction()->setHasBranchProtectedScope();
4526
4527   return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
4528 }
4529
4530 StmtResult Sema::ActOnOpenMPCriticalDirective(
4531     const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
4532     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
4533   if (!AStmt)
4534     return StmtError();
4535
4536   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4537
4538   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
4579   getCurFunction()->setHasBranchProtectedScope();
4580
4581   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;
4586 }
4587
4588 StmtResult Sema::ActOnOpenMPParallelForDirective(
4589     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4590     SourceLocation EndLoc,
4591     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4592   if (!AStmt)
4593     return StmtError();
4594
4595   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
4603   OMPLoopDirective::HelperExprs B;
4604   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4605   // define the nested loops number.
4606   unsigned NestedLoopCount =
4607       CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
4608                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4609                       VarsWithImplicitDSA, B);
4610   if (NestedLoopCount == 0)
4611     return StmtError();
4612
4613   assert((CurContext->isDependentContext() || B.builtAll()) &&
4614          "omp parallel for loop exprs were not built");
4615
4616   if (!CurContext->isDependentContext()) {
4617     // Finalize the clauses that need pre-built expressions for CodeGen.
4618     for (auto C : Clauses) {
4619       if (auto *LC = dyn_cast<OMPLinearClause>(C))
4620         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4621                                      B.NumIterations, *this, CurScope,
4622                                      DSAStack))
4623           return StmtError();
4624     }
4625   }
4626
4627   getCurFunction()->setHasBranchProtectedScope();
4628   return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
4629                                          NestedLoopCount, Clauses, AStmt, B,
4630                                          DSAStack->isCancelRegion());
4631 }
4632
4633 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
4634     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4635     SourceLocation EndLoc,
4636     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4637   if (!AStmt)
4638     return StmtError();
4639
4640   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
4648   OMPLoopDirective::HelperExprs B;
4649   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4650   // define the nested loops number.
4651   unsigned NestedLoopCount =
4652       CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
4653                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4654                       VarsWithImplicitDSA, B);
4655   if (NestedLoopCount == 0)
4656     return StmtError();
4657
4658   if (!CurContext->isDependentContext()) {
4659     // Finalize the clauses that need pre-built expressions for CodeGen.
4660     for (auto C : Clauses) {
4661       if (auto *LC = dyn_cast<OMPLinearClause>(C))
4662         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4663                                      B.NumIterations, *this, CurScope,
4664                                      DSAStack))
4665           return StmtError();
4666     }
4667   }
4668
4669   if (checkSimdlenSafelenSpecified(*this, Clauses))
4670     return StmtError();
4671
4672   getCurFunction()->setHasBranchProtectedScope();
4673   return OMPParallelForSimdDirective::Create(
4674       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
4675 }
4676
4677 StmtResult
4678 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
4679                                            Stmt *AStmt, SourceLocation StartLoc,
4680                                            SourceLocation EndLoc) {
4681   if (!AStmt)
4682     return StmtError();
4683
4684   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4685   auto BaseStmt = AStmt;
4686   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
4687     BaseStmt = CS->getCapturedStmt();
4688   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
4689     auto S = C->children();
4690     if (S.begin() == S.end())
4691       return StmtError();
4692     // All associated statements must be '#pragma omp section' except for
4693     // the first one.
4694     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
4695       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       }
4701       cast<OMPSectionDirective>(SectionStmt)
4702           ->setHasCancel(DSAStack->isCancelRegion());
4703     }
4704   } else {
4705     Diag(AStmt->getLocStart(),
4706          diag::err_omp_parallel_sections_not_compound_stmt);
4707     return StmtError();
4708   }
4709
4710   getCurFunction()->setHasBranchProtectedScope();
4711
4712   return OMPParallelSectionsDirective::Create(
4713       Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
4714 }
4715
4716 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
4717                                           Stmt *AStmt, SourceLocation StartLoc,
4718                                           SourceLocation EndLoc) {
4719   if (!AStmt)
4720     return StmtError();
4721
4722   auto *CS = cast<CapturedStmt>(AStmt);
4723   // 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
4732   return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4733                                   DSAStack->isCancelRegion());
4734 }
4735
4736 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
4737                                                SourceLocation EndLoc) {
4738   return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
4739 }
4740
4741 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
4742                                              SourceLocation EndLoc) {
4743   return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
4744 }
4745
4746 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
4747                                               SourceLocation EndLoc) {
4748   return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
4749 }
4750
4751 StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
4752                                                SourceLocation StartLoc,
4753                                                SourceLocation EndLoc) {
4754   if (!AStmt)
4755     return StmtError();
4756
4757   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4758
4759   getCurFunction()->setHasBranchProtectedScope();
4760
4761   return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
4762 }
4763
4764 StmtResult 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
4771 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
4772                                              Stmt *AStmt,
4773                                              SourceLocation StartLoc,
4774                                              SourceLocation EndLoc) {
4775   OMPClause *DependFound = nullptr;
4776   OMPClause *DependSourceClause = nullptr;
4777   OMPClause *DependSinkClause = nullptr;
4778   bool ErrorFound = false;
4779   OMPThreadsClause *TC = nullptr;
4780   OMPSIMDClause *SC = nullptr;
4781   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;
4792         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;
4804       }
4805     } else if (C->getClauseKind() == OMPC_threads)
4806       TC = cast<OMPThreadsClause>(C);
4807     else if (C->getClauseKind() == OMPC_simd)
4808       SC = cast<OMPSIMDClause>(C);
4809   }
4810   if (!ErrorFound && !SC &&
4811       isOpenMPSimdDirective(DSAStack->getParentDirective())) {
4812     // 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);
4816     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)
4835     return StmtError();
4836
4837   if (AStmt) {
4838     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4839
4840     getCurFunction()->setHasBranchProtectedScope();
4841   }
4842
4843   return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4844 }
4845
4846 namespace {
4847 /// \brief Helper class for checking expression in 'omp atomic [update]'
4848 /// construct.
4849 class 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;
4877   /// \brief 'x' lvalue part of the source atomic expression.
4878   Expr *X;
4879   /// \brief 'expr' rvalue part of the source atomic expression.
4880   Expr *E;
4881   /// \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;
4890   /// \brief true if the source expression is a postfix unary operation, false
4891   /// if it is a prefix unary operation.
4892   bool IsPostfixUpdate;
4893
4894 public:
4895   OpenMPAtomicUpdateChecker(Sema &SemaRef)
4896       : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
4897         IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
4898   /// \brief Check specified statement that it is suitable for 'atomic update'
4899   /// constructs and extract 'x', 'expr' and Operation from the original
4900   /// expression. If DiagId and NoteId == 0, then only check is performed
4901   /// without error notification.
4902   /// \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.
4905   bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
4906   /// \brief Return the 'x' lvalue part of the source atomic expression.
4907   Expr *getX() const { return X; }
4908   /// \brief Return the 'expr' rvalue part of the source atomic expression.
4909   Expr *getExpr() const { return E; }
4910   /// \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
4918   /// \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
4922 private:
4923   bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
4924                             unsigned NoteId = 0);
4925 };
4926 } // namespace
4927
4928 bool 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()) {
4943         Op = AtomicInnerBinOp->getOpcode();
4944         OpLoc = AtomicInnerBinOp->getOperatorLoc();
4945         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;
4956           IsXLHSInRHSPart = true;
4957         } else if (XId == RHSId) {
4958           E = LHS;
4959           IsXLHSInRHSPart = false;
4960         } 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   }
4986   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
4987     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
4988     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
4989     return true;
4990   } else if (SemaRef.CurContext->isDependentContext())
4991     E = X = UpdateExpr = nullptr;
4992   return ErrorFound != NoError;
4993 }
4994
4995 bool 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
5015         Op = BinaryOperator::getOpForCompoundAssignment(
5016             AtomicCompAssignOp->getOpcode());
5017         OpLoc = AtomicCompAssignOp->getOperatorLoc();
5018         E = AtomicCompAssignOp->getRHS();
5019         X = AtomicCompAssignOp->getLHS()->IgnoreParens();
5020         IsXLHSInRHSPart = true;
5021       } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5022                      AtomicBody->IgnoreParenImpCasts())) {
5023         // Check for Binary Operation
5024         if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
5025           return true;
5026       } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5027                      AtomicBody->IgnoreParenImpCasts())) {
5028         // Check for Unary Operation
5029         if (AtomicUnaryOp->isIncrementDecrementOp()) {
5030           IsPostfixUpdate = AtomicUnaryOp->isPostfix();
5031           Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5032           OpLoc = AtomicUnaryOp->getOperatorLoc();
5033           X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
5034           E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5035           IsXLHSInRHSPart = true;
5036         } else {
5037           ErrorFound = NotAnUnaryIncDecExpression;
5038           ErrorLoc = AtomicUnaryOp->getExprLoc();
5039           ErrorRange = AtomicUnaryOp->getSourceRange();
5040           NoteLoc = AtomicUnaryOp->getOperatorLoc();
5041           NoteRange = SourceRange(NoteLoc, NoteLoc);
5042         }
5043       } else if (!AtomicBody->isInstantiationDependent()) {
5044         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   }
5058   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
5059     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5060     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5061     return true;
5062   } else if (SemaRef.CurContext->isDependentContext())
5063     E = X = UpdateExpr = nullptr;
5064   if (ErrorFound == NoError && E && X) {
5065     // 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   }
5083   return ErrorFound != NoError;
5084 }
5085
5086 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5087                                             Stmt *AStmt,
5088                                             SourceLocation StartLoc,
5089                                             SourceLocation EndLoc) {
5090   if (!AStmt)
5091     return StmtError();
5092
5093   auto *CS = cast<CapturedStmt>(AStmt);
5094   // 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.
5099   OpenMPClauseKind AtomicKind = OMPC_unknown;
5100   SourceLocation AtomicKindLoc;
5101   for (auto *C : Clauses) {
5102     if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
5103         C->getClauseKind() == OMPC_update ||
5104         C->getClauseKind() == OMPC_capture) {
5105       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();
5113       }
5114     }
5115   }
5116
5117   auto Body = CS->getCapturedStmt();
5118   if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5119     Body = EWC->getSubExpr();
5120
5121   Expr *X = nullptr;
5122   Expr *V = nullptr;
5123   Expr *E = nullptr;
5124   Expr *UE = nullptr;
5125   bool IsXLHSInRHSPart = false;
5126   bool IsPostfixUpdate = false;
5127   // 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.
5149   if (AtomicKind == OMPC_read) {
5150     enum {
5151       NotAnExpression,
5152       NotAnAssignmentOp,
5153       NotAScalarType,
5154       NotAnLValue,
5155       NoError
5156     } ErrorFound = NoError;
5157     SourceLocation ErrorLoc, NoteLoc;
5158     SourceRange ErrorRange, NoteRange;
5159     // If clause is read:
5160     //  v = x;
5161     if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5162       auto *AtomicBinOp =
5163           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         }
5189       } else if (!AtomicBody->isInstantiationDependent()) {
5190         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);
5202     }
5203     if (ErrorFound != NoError) {
5204       Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5205           << ErrorRange;
5206       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5207                                                       << NoteRange;
5208       return StmtError();
5209     } else if (CurContext->isDependentContext())
5210       V = X = nullptr;
5211   } else if (AtomicKind == OMPC_write) {
5212     enum {
5213       NotAnExpression,
5214       NotAnAssignmentOp,
5215       NotAScalarType,
5216       NotAnLValue,
5217       NoError
5218     } ErrorFound = NoError;
5219     SourceLocation ErrorLoc, NoteLoc;
5220     SourceRange ErrorRange, NoteRange;
5221     // If clause is write:
5222     //  x = expr;
5223     if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5224       auto *AtomicBinOp =
5225           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5226       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5227         X = AtomicBinOp->getLHS();
5228         E = AtomicBinOp->getRHS();
5229         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         }
5250       } else if (!AtomicBody->isInstantiationDependent()) {
5251         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);
5263     }
5264     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;
5272   } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
5273     // 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))
5287       return StmtError();
5288     if (!CurContext->isDependentContext()) {
5289       E = Checker.getExpr();
5290       X = Checker.getX();
5291       UE = Checker.getUpdateExpr();
5292       IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5293     }
5294   } else if (AtomicKind == OMPC_capture) {
5295     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();
5328       } else if (!AtomicBody->isInstantiationDependent()) {
5329         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();
5399               IsPostfixUpdate = true;
5400             }
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();
5429                 IsPostfixUpdate = false;
5430               }
5431             }
5432           }
5433           if (!IsUpdateExprFound) {
5434             //  { v = x; x = expr; }
5435             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) {
5442                 ErrorFound = NotAnAssignmentOp;
5443                 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
5444                                                 : First->getLocStart();
5445                 NoteRange = ErrorRange = FirstBinOp
5446                                              ? FirstBinOp->getSourceRange()
5447                                              : SourceRange(ErrorLoc, ErrorLoc);
5448               } else {
5449                 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);
5458                 } else {
5459                   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                   }
5483                 }
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       }
5507     }
5508   }
5509
5510   getCurFunction()->setHasBranchProtectedScope();
5511
5512   return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5513                                     X, V, E, UE, IsXLHSInRHSPart,
5514                                     IsPostfixUpdate);
5515 }
5516
5517 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
5518                                             Stmt *AStmt,
5519                                             SourceLocation StartLoc,
5520                                             SourceLocation EndLoc) {
5521   if (!AStmt)
5522     return StmtError();
5523
5524   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();
5531
5532   // 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()) {
5542         auto *OED = dyn_cast<OMPExecutableDirective>(*I);
5543         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;
5551     } else {
5552       auto *OED = dyn_cast<OMPExecutableDirective>(S);
5553       OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
5554     }
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
5565   getCurFunction()->setHasBranchProtectedScope();
5566
5567   return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5568 }
5569
5570 StmtResult
5571 Sema::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
5591 StmtResult 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) {
5622       if (auto *LC = dyn_cast<OMPLinearClause>(C))
5623         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5624                                      B.NumIterations, *this, CurScope,
5625                                      DSAStack))
5626           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
5636 /// \brief Check for existence of a map clause in the list of clauses.
5637 static 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
5648 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
5649                                                 Stmt *AStmt,
5650                                                 SourceLocation StartLoc,
5651                                                 SourceLocation EndLoc) {
5652   if (!AStmt)
5653     return StmtError();
5654
5655   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5656
5657   // OpenMP [2.10.1, Restrictions, p. 97]
5658   // At least one map clause must appear on the directive.
5659   if (!HasMapClause(Clauses)) {
5660     Diag(StartLoc, diag::err_omp_no_map_for_directive)
5661         << getOpenMPDirectiveName(OMPD_target_data);
5662     return StmtError();
5663   }
5664
5665   getCurFunction()->setHasBranchProtectedScope();
5666
5667   return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
5668                                         AStmt);
5669 }
5670
5671 StmtResult
5672 Sema::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
5687 StmtResult
5688 Sema::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
5702 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
5703                                                   SourceLocation StartLoc,
5704                                                   SourceLocation EndLoc) {
5705   bool seenMotionClause = false;
5706   for (auto *C : Clauses) {
5707     if (C->getClauseKind() == OMPC_to || C->getClauseKind() == OMPC_from)
5708       seenMotionClause = true;
5709   }
5710   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
5717 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
5718                                            Stmt *AStmt, SourceLocation StartLoc,
5719                                            SourceLocation EndLoc) {
5720   if (!AStmt)
5721     return StmtError();
5722
5723   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
5736 StmtResult
5737 Sema::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
5758 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
5759                                             SourceLocation StartLoc,
5760                                             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   }
5776   DSAStack->setParentCancelRegion(/*Cancel=*/true);
5777   return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5778                                     CancelRegion);
5779 }
5780
5781 static 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
5805 StmtResult Sema::ActOnOpenMPTaskLoopDirective(
5806     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5807     SourceLocation EndLoc,
5808     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5809   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),
5818                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
5819                       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
5826   // 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
5832   getCurFunction()->setHasBranchProtectedScope();
5833   return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
5834                                       NestedLoopCount, Clauses, AStmt, B);
5835 }
5836
5837 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
5838     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5839     SourceLocation EndLoc,
5840     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5841   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
5858   if (!CurContext->isDependentContext()) {
5859     // Finalize the clauses that need pre-built expressions for CodeGen.
5860     for (auto C : Clauses) {
5861       if (auto *LC = dyn_cast<OMPLinearClause>(C))
5862         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5863                                      B.NumIterations, *this, CurScope,
5864                                      DSAStack))
5865           return StmtError();
5866     }
5867   }
5868
5869   // 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
5875   getCurFunction()->setHasBranchProtectedScope();
5876   return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
5877                                           NestedLoopCount, Clauses, AStmt, B);
5878 }
5879
5880 StmtResult Sema::ActOnOpenMPDistributeDirective(
5881     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5882     SourceLocation EndLoc,
5883     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5884   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
5906 StmtResult 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
5939 StmtResult 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
5967   if (checkSimdlenSafelenSpecified(*this, Clauses))
5968     return StmtError();
5969
5970   getCurFunction()->setHasBranchProtectedScope();
5971   return OMPDistributeParallelForSimdDirective::Create(
5972       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
5973 }
5974
5975 StmtResult 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
6003   if (checkSimdlenSafelenSpecified(*this, Clauses))
6004     return StmtError();
6005
6006   getCurFunction()->setHasBranchProtectedScope();
6007   return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
6008                                             NestedLoopCount, Clauses, AStmt, B);
6009 }
6010
6011 StmtResult 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) {
6042       if (auto *LC = dyn_cast<OMPLinearClause>(C))
6043         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6044                                      B.NumIterations, *this, CurScope,
6045                                      DSAStack))
6046           return StmtError();
6047     }
6048   }
6049   if (checkSimdlenSafelenSpecified(*this, Clauses))
6050     return StmtError();
6051
6052   getCurFunction()->setHasBranchProtectedScope();
6053   return OMPTargetParallelForSimdDirective::Create(
6054       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6055 }
6056
6057 StmtResult 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.
6075   unsigned NestedLoopCount =
6076       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) {
6088       if (auto *LC = dyn_cast<OMPLinearClause>(C))
6089         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
6104 StmtResult 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();
6133   return OMPTeamsDistributeDirective::Create(
6134       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6135 }
6136
6137 StmtResult 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.
6155   unsigned NestedLoopCount = CheckOpenMPLoop(
6156       OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6157       nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6158       VarsWithImplicitDSA, B);
6159
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
6185 StmtResult 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
6233 StmtResult 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
6278 StmtResult 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
6299 StmtResult 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
6333 StmtResult 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
6378 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
6379                                              SourceLocation StartLoc,
6380                                              SourceLocation LParenLoc,
6381                                              SourceLocation EndLoc) {
6382   OMPClause *Res = nullptr;
6383   switch (Kind) {
6384   case OMPC_final:
6385     Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
6386     break;
6387   case OMPC_num_threads:
6388     Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
6389     break;
6390   case OMPC_safelen:
6391     Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
6392     break;
6393   case OMPC_simdlen:
6394     Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
6395     break;
6396   case OMPC_collapse:
6397     Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
6398     break;
6399   case OMPC_ordered:
6400     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
6401     break;
6402   case OMPC_device:
6403     Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
6404     break;
6405   case OMPC_num_teams:
6406     Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
6407     break;
6408   case OMPC_thread_limit:
6409     Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
6410     break;
6411   case OMPC_priority:
6412     Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
6413     break;
6414   case OMPC_grainsize:
6415     Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
6416     break;
6417   case OMPC_num_tasks:
6418     Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
6419     break;
6420   case OMPC_hint:
6421     Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
6422     break;
6423   case OMPC_if:
6424   case OMPC_default:
6425   case OMPC_proc_bind:
6426   case OMPC_schedule:
6427   case OMPC_private:
6428   case OMPC_firstprivate:
6429   case OMPC_lastprivate:
6430   case OMPC_shared:
6431   case OMPC_reduction:
6432   case OMPC_linear:
6433   case OMPC_aligned:
6434   case OMPC_copyin:
6435   case OMPC_copyprivate:
6436   case OMPC_nowait:
6437   case OMPC_untied:
6438   case OMPC_mergeable:
6439   case OMPC_threadprivate:
6440   case OMPC_flush:
6441   case OMPC_read:
6442   case OMPC_write:
6443   case OMPC_update:
6444   case OMPC_capture:
6445   case OMPC_seq_cst:
6446   case OMPC_depend:
6447   case OMPC_threads:
6448   case OMPC_simd:
6449   case OMPC_map:
6450   case OMPC_nogroup:
6451   case OMPC_dist_schedule:
6452   case OMPC_defaultmap:
6453   case OMPC_unknown:
6454   case OMPC_uniform:
6455   case OMPC_to:
6456   case OMPC_from:
6457   case OMPC_use_device_ptr:
6458   case OMPC_is_device_ptr:
6459     llvm_unreachable("Clause is not allowed.");
6460   }
6461   return Res;
6462 }
6463
6464 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
6465                                      Expr *Condition, SourceLocation StartLoc,
6466                                      SourceLocation LParenLoc,
6467                                      SourceLocation NameModifierLoc,
6468                                      SourceLocation ColonLoc,
6469                                      SourceLocation EndLoc) {
6470   Expr *ValExpr = Condition;
6471   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6472       !Condition->isInstantiationDependent() &&
6473       !Condition->containsUnexpandedParameterPack()) {
6474     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
6475     if (Val.isInvalid())
6476       return nullptr;
6477
6478     ValExpr = MakeFullExpr(Val.get()).get();
6479   }
6480
6481   return new (Context) OMPIfClause(NameModifier, ValExpr, StartLoc, LParenLoc,
6482                                    NameModifierLoc, ColonLoc, EndLoc);
6483 }
6484
6485 OMPClause *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()) {
6493     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
6494     if (Val.isInvalid())
6495       return nullptr;
6496
6497     ValExpr = MakeFullExpr(Val.get()).get();
6498   }
6499
6500   return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
6501 }
6502 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
6503                                                         Expr *Op) {
6504   if (!Op)
6505     return ExprError();
6506
6507   class IntConvertDiagnoser : public ICEConvertDiagnoser {
6508   public:
6509     IntConvertDiagnoser()
6510         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
6511     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
6512                                          QualType T) override {
6513       return S.Diag(Loc, diag::err_omp_not_integral) << T;
6514     }
6515     SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
6516                                              QualType T) override {
6517       return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
6518     }
6519     SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
6520                                                QualType T,
6521                                                QualType ConvTy) override {
6522       return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
6523     }
6524     SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
6525                                            QualType ConvTy) override {
6526       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
6527              << ConvTy->isEnumeralType() << ConvTy;
6528     }
6529     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
6530                                             QualType T) override {
6531       return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
6532     }
6533     SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
6534                                         QualType ConvTy) override {
6535       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
6536              << ConvTy->isEnumeralType() << ConvTy;
6537     }
6538     SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
6539                                              QualType) override {
6540       llvm_unreachable("conversion functions are permitted");
6541     }
6542   } ConvertDiagnoser;
6543   return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
6544 }
6545
6546 static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
6547                                       OpenMPClauseKind CKind,
6548                                       bool StrictlyPositive) {
6549   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) &&
6561         Result.isSigned() &&
6562         !((!StrictlyPositive && Result.isNonNegative()) ||
6563           (StrictlyPositive && Result.isStrictlyPositive()))) {
6564       SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
6565           << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
6566           << ValExpr->getSourceRange();
6567       return false;
6568     }
6569   }
6570   return true;
6571 }
6572
6573 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
6574                                              SourceLocation StartLoc,
6575                                              SourceLocation LParenLoc,
6576                                              SourceLocation EndLoc) {
6577   Expr *ValExpr = NumThreads;
6578
6579   // OpenMP [2.5, Restrictions]
6580   //  The num_threads expression must evaluate to a positive integer value.
6581   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
6582                                  /*StrictlyPositive=*/true))
6583     return nullptr;
6584
6585   return new (Context)
6586       OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
6587 }
6588
6589 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
6590                                                        OpenMPClauseKind CKind,
6591                                                        bool StrictlyPositive) {
6592   if (!E)
6593     return ExprError();
6594   if (E->isValueDependent() || E->isTypeDependent() ||
6595       E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
6596     return E;
6597   llvm::APSInt Result;
6598   ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
6599   if (ICE.isInvalid())
6600     return ExprError();
6601   if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
6602       (!StrictlyPositive && !Result.isNonNegative())) {
6603     Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
6604         << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
6605         << E->getSourceRange();
6606     return ExprError();
6607   }
6608   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   }
6613   if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
6614     DSAStack->setAssociatedLoops(Result.getExtValue());
6615   else if (CKind == OMPC_ordered)
6616     DSAStack->setAssociatedLoops(Result.getExtValue());
6617   return ICE;
6618 }
6619
6620 OMPClause *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())
6628     return nullptr;
6629   return new (Context)
6630       OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
6631 }
6632
6633 OMPClause *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
6646 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
6647                                            SourceLocation StartLoc,
6648                                            SourceLocation LParenLoc,
6649                                            SourceLocation EndLoc) {
6650   // OpenMP [2.7.1, loop construct, Description]
6651   // OpenMP [2.8.1, simd construct, Description]
6652   // OpenMP [2.9.6, distribute construct, Description]
6653   // The parameter of the collapse clause must be a constant
6654   // positive integer expression.
6655   ExprResult NumForLoopsResult =
6656       VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
6657   if (NumForLoopsResult.isInvalid())
6658     return nullptr;
6659   return new (Context)
6660       OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
6661 }
6662
6663 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
6664                                           SourceLocation EndLoc,
6665                                           SourceLocation LParenLoc,
6666                                           Expr *NumForLoops) {
6667   // 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();
6678   } else
6679     NumForLoops = nullptr;
6680   DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
6681   return new (Context)
6682       OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
6683 }
6684
6685 OMPClause *Sema::ActOnOpenMPSimpleClause(
6686     OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
6687     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
6688   OMPClause *Res = nullptr;
6689   switch (Kind) {
6690   case OMPC_default:
6691     Res =
6692         ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
6693                                  ArgumentLoc, StartLoc, LParenLoc, EndLoc);
6694     break;
6695   case OMPC_proc_bind:
6696     Res = ActOnOpenMPProcBindClause(
6697         static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
6698         LParenLoc, EndLoc);
6699     break;
6700   case OMPC_if:
6701   case OMPC_final:
6702   case OMPC_num_threads:
6703   case OMPC_safelen:
6704   case OMPC_simdlen:
6705   case OMPC_collapse:
6706   case OMPC_schedule:
6707   case OMPC_private:
6708   case OMPC_firstprivate:
6709   case OMPC_lastprivate:
6710   case OMPC_shared:
6711   case OMPC_reduction:
6712   case OMPC_linear:
6713   case OMPC_aligned:
6714   case OMPC_copyin:
6715   case OMPC_copyprivate:
6716   case OMPC_ordered:
6717   case OMPC_nowait:
6718   case OMPC_untied:
6719   case OMPC_mergeable:
6720   case OMPC_threadprivate:
6721   case OMPC_flush:
6722   case OMPC_read:
6723   case OMPC_write:
6724   case OMPC_update:
6725   case OMPC_capture:
6726   case OMPC_seq_cst:
6727   case OMPC_depend:
6728   case OMPC_device:
6729   case OMPC_threads:
6730   case OMPC_simd:
6731   case OMPC_map:
6732   case OMPC_num_teams:
6733   case OMPC_thread_limit:
6734   case OMPC_priority:
6735   case OMPC_grainsize:
6736   case OMPC_nogroup:
6737   case OMPC_num_tasks:
6738   case OMPC_hint:
6739   case OMPC_dist_schedule:
6740   case OMPC_defaultmap:
6741   case OMPC_unknown:
6742   case OMPC_uniform:
6743   case OMPC_to:
6744   case OMPC_from:
6745   case OMPC_use_device_ptr:
6746   case OMPC_is_device_ptr:
6747     llvm_unreachable("Clause is not allowed.");
6748   }
6749   return Res;
6750 }
6751
6752 static std::string
6753 getListOfPossibleValues(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
6775 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
6776                                           SourceLocation KindKwLoc,
6777                                           SourceLocation StartLoc,
6778                                           SourceLocation LParenLoc,
6779                                           SourceLocation EndLoc) {
6780   if (Kind == OMPC_DEFAULT_unknown) {
6781     static_assert(OMPC_DEFAULT_unknown > 0,
6782                   "OMPC_DEFAULT_unknown not greater than 0");
6783     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
6784         << getListOfPossibleValues(OMPC_default, /*First=*/0,
6785                                    /*Last=*/OMPC_DEFAULT_unknown)
6786         << getOpenMPClauseName(OMPC_default);
6787     return nullptr;
6788   }
6789   switch (Kind) {
6790   case OMPC_DEFAULT_none:
6791     DSAStack->setDefaultDSANone(KindKwLoc);
6792     break;
6793   case OMPC_DEFAULT_shared:
6794     DSAStack->setDefaultDSAShared(KindKwLoc);
6795     break;
6796   case OMPC_DEFAULT_unknown:
6797     llvm_unreachable("Clause kind is not allowed.");
6798     break;
6799   }
6800   return new (Context)
6801       OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
6802 }
6803
6804 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
6805                                            SourceLocation KindKwLoc,
6806                                            SourceLocation StartLoc,
6807                                            SourceLocation LParenLoc,
6808                                            SourceLocation EndLoc) {
6809   if (Kind == OMPC_PROC_BIND_unknown) {
6810     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
6811         << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
6812                                    /*Last=*/OMPC_PROC_BIND_unknown)
6813         << getOpenMPClauseName(OMPC_proc_bind);
6814     return nullptr;
6815   }
6816   return new (Context)
6817       OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
6818 }
6819
6820 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
6821     OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
6822     SourceLocation StartLoc, SourceLocation LParenLoc,
6823     ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
6824     SourceLocation EndLoc) {
6825   OMPClause *Res = nullptr;
6826   switch (Kind) {
6827   case OMPC_schedule:
6828     enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
6829     assert(Argument.size() == NumberOfElements &&
6830            ArgumentLoc.size() == NumberOfElements);
6831     Res = ActOnOpenMPScheduleClause(
6832         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);
6837     break;
6838   case OMPC_if:
6839     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
6840     Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
6841                               Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
6842                               DelimLoc, EndLoc);
6843     break;
6844   case OMPC_dist_schedule:
6845     Res = ActOnOpenMPDistScheduleClause(
6846         static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
6847         StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
6848     break;
6849   case OMPC_defaultmap:
6850     enum { Modifier, DefaultmapKind };
6851     Res = ActOnOpenMPDefaultmapClause(
6852         static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
6853         static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
6854         StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
6855         EndLoc);
6856     break;
6857   case OMPC_final:
6858   case OMPC_num_threads:
6859   case OMPC_safelen:
6860   case OMPC_simdlen:
6861   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:
6872   case OMPC_copyprivate:
6873   case OMPC_ordered:
6874   case OMPC_nowait:
6875   case OMPC_untied:
6876   case OMPC_mergeable:
6877   case OMPC_threadprivate:
6878   case OMPC_flush:
6879   case OMPC_read:
6880   case OMPC_write:
6881   case OMPC_update:
6882   case OMPC_capture:
6883   case OMPC_seq_cst:
6884   case OMPC_depend:
6885   case OMPC_device:
6886   case OMPC_threads:
6887   case OMPC_simd:
6888   case OMPC_map:
6889   case OMPC_num_teams:
6890   case OMPC_thread_limit:
6891   case OMPC_priority:
6892   case OMPC_grainsize:
6893   case OMPC_nogroup:
6894   case OMPC_num_tasks:
6895   case OMPC_hint:
6896   case OMPC_unknown:
6897   case OMPC_uniform:
6898   case OMPC_to:
6899   case OMPC_from:
6900   case OMPC_use_device_ptr:
6901   case OMPC_is_device_ptr:
6902     llvm_unreachable("Clause is not allowed.");
6903   }
6904   return Res;
6905 }
6906
6907 static 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
6929 OMPClause *Sema::ActOnOpenMPScheduleClause(
6930     OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
6931     OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
6932     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   }
6950   if (Kind == OMPC_SCHEDULE_unknown) {
6951     std::string Values;
6952     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);
6960     }
6961     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
6962         << Values << getOpenMPClauseName(OMPC_schedule);
6963     return nullptr;
6964   }
6965   // 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   }
6975   Expr *ValExpr = ChunkSize;
6976   Stmt *HelperValStmt = nullptr;
6977   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;
6993       if (ValExpr->isIntegerConstantExpr(Result, Context)) {
6994         if (Result.isSigned() && !Result.isStrictlyPositive()) {
6995           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
6996               << "schedule" << 1 << ChunkSize->getSourceRange();
6997           return nullptr;
6998         }
6999       } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
7000                  !CurContext->isDependentContext()) {
7001         llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7002         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7003         HelperValStmt = buildPreInits(Context, Captures);
7004       }
7005     }
7006   }
7007
7008   return new (Context)
7009       OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
7010                         ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
7011 }
7012
7013 OMPClause *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;
7021   case OMPC_nowait:
7022     Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
7023     break;
7024   case OMPC_untied:
7025     Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
7026     break;
7027   case OMPC_mergeable:
7028     Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
7029     break;
7030   case OMPC_read:
7031     Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
7032     break;
7033   case OMPC_write:
7034     Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
7035     break;
7036   case OMPC_update:
7037     Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
7038     break;
7039   case OMPC_capture:
7040     Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
7041     break;
7042   case OMPC_seq_cst:
7043     Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
7044     break;
7045   case OMPC_threads:
7046     Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
7047     break;
7048   case OMPC_simd:
7049     Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
7050     break;
7051   case OMPC_nogroup:
7052     Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
7053     break;
7054   case OMPC_if:
7055   case OMPC_final:
7056   case OMPC_num_threads:
7057   case OMPC_safelen:
7058   case OMPC_simdlen:
7059   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:
7069   case OMPC_copyprivate:
7070   case OMPC_default:
7071   case OMPC_proc_bind:
7072   case OMPC_threadprivate:
7073   case OMPC_flush:
7074   case OMPC_depend:
7075   case OMPC_device:
7076   case OMPC_map:
7077   case OMPC_num_teams:
7078   case OMPC_thread_limit:
7079   case OMPC_priority:
7080   case OMPC_grainsize:
7081   case OMPC_num_tasks:
7082   case OMPC_hint:
7083   case OMPC_dist_schedule:
7084   case OMPC_defaultmap:
7085   case OMPC_unknown:
7086   case OMPC_uniform:
7087   case OMPC_to:
7088   case OMPC_from:
7089   case OMPC_use_device_ptr:
7090   case OMPC_is_device_ptr:
7091     llvm_unreachable("Clause is not allowed.");
7092   }
7093   return Res;
7094 }
7095
7096 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
7097                                          SourceLocation EndLoc) {
7098   DSAStack->setNowaitRegion();
7099   return new (Context) OMPNowaitClause(StartLoc, EndLoc);
7100 }
7101
7102 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
7103                                          SourceLocation EndLoc) {
7104   return new (Context) OMPUntiedClause(StartLoc, EndLoc);
7105 }
7106
7107 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
7108                                             SourceLocation EndLoc) {
7109   return new (Context) OMPMergeableClause(StartLoc, EndLoc);
7110 }
7111
7112 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
7113                                        SourceLocation EndLoc) {
7114   return new (Context) OMPReadClause(StartLoc, EndLoc);
7115 }
7116
7117 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
7118                                         SourceLocation EndLoc) {
7119   return new (Context) OMPWriteClause(StartLoc, EndLoc);
7120 }
7121
7122 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
7123                                          SourceLocation EndLoc) {
7124   return new (Context) OMPUpdateClause(StartLoc, EndLoc);
7125 }
7126
7127 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
7128                                           SourceLocation EndLoc) {
7129   return new (Context) OMPCaptureClause(StartLoc, EndLoc);
7130 }
7131
7132 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
7133                                          SourceLocation EndLoc) {
7134   return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
7135 }
7136
7137 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
7138                                           SourceLocation EndLoc) {
7139   return new (Context) OMPThreadsClause(StartLoc, EndLoc);
7140 }
7141
7142 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
7143                                        SourceLocation EndLoc) {
7144   return new (Context) OMPSIMDClause(StartLoc, EndLoc);
7145 }
7146
7147 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
7148                                           SourceLocation EndLoc) {
7149   return new (Context) OMPNogroupClause(StartLoc, EndLoc);
7150 }
7151
7152 OMPClause *Sema::ActOnOpenMPVarListClause(
7153     OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
7154     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
7155     SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
7156     const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
7157     OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
7158     OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
7159     SourceLocation DepLinMapLoc) {
7160   OMPClause *Res = nullptr;
7161   switch (Kind) {
7162   case OMPC_private:
7163     Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7164     break;
7165   case OMPC_firstprivate:
7166     Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7167     break;
7168   case OMPC_lastprivate:
7169     Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7170     break;
7171   case OMPC_shared:
7172     Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
7173     break;
7174   case OMPC_reduction:
7175     Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
7176                                      EndLoc, ReductionIdScopeSpec, ReductionId);
7177     break;
7178   case OMPC_linear:
7179     Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
7180                                   LinKind, DepLinMapLoc, ColonLoc, EndLoc);
7181     break;
7182   case OMPC_aligned:
7183     Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
7184                                    ColonLoc, EndLoc);
7185     break;
7186   case OMPC_copyin:
7187     Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
7188     break;
7189   case OMPC_copyprivate:
7190     Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7191     break;
7192   case OMPC_flush:
7193     Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
7194     break;
7195   case OMPC_depend:
7196     Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
7197                                   StartLoc, LParenLoc, EndLoc);
7198     break;
7199   case OMPC_map:
7200     Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
7201                                DepLinMapLoc, ColonLoc, VarList, StartLoc,
7202                                LParenLoc, EndLoc);
7203     break;
7204   case OMPC_to:
7205     Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
7206     break;
7207   case OMPC_from:
7208     Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
7209     break;
7210   case OMPC_use_device_ptr:
7211     Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7212     break;
7213   case OMPC_is_device_ptr:
7214     Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7215     break;
7216   case OMPC_if:
7217   case OMPC_final:
7218   case OMPC_num_threads:
7219   case OMPC_safelen:
7220   case OMPC_simdlen:
7221   case OMPC_collapse:
7222   case OMPC_default:
7223   case OMPC_proc_bind:
7224   case OMPC_schedule:
7225   case OMPC_ordered:
7226   case OMPC_nowait:
7227   case OMPC_untied:
7228   case OMPC_mergeable:
7229   case OMPC_threadprivate:
7230   case OMPC_read:
7231   case OMPC_write:
7232   case OMPC_update:
7233   case OMPC_capture:
7234   case OMPC_seq_cst:
7235   case OMPC_device:
7236   case OMPC_threads:
7237   case OMPC_simd:
7238   case OMPC_num_teams:
7239   case OMPC_thread_limit:
7240   case OMPC_priority:
7241   case OMPC_grainsize:
7242   case OMPC_nogroup:
7243   case OMPC_num_tasks:
7244   case OMPC_hint:
7245   case OMPC_dist_schedule:
7246   case OMPC_defaultmap:
7247   case OMPC_unknown:
7248   case OMPC_uniform:
7249     llvm_unreachable("Clause is not allowed.");
7250   }
7251   return Res;
7252 }
7253
7254 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
7255                                        ExprObjectKind OK, SourceLocation Loc) {
7256   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
7273 static std::pair<ValueDecl *, bool>
7274 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
7275                SourceRange &ERange, bool AllowArraySection = false) {
7276   if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
7277       RefExpr->containsUnexpandedParameterPack())
7278     return std::make_pair(nullptr, true);
7279
7280   // 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();
7286   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();
7311   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()))) {
7317     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     }
7327     return std::make_pair(nullptr, false);
7328   }
7329   return std::make_pair(DE ? DE->getDecl() : ME->getMemberDecl(), false);
7330 }
7331
7332 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
7333                                           SourceLocation StartLoc,
7334                                           SourceLocation LParenLoc,
7335                                           SourceLocation EndLoc) {
7336   SmallVector<Expr *, 8> Vars;
7337   SmallVector<Expr *, 8> PrivateCopies;
7338   for (auto &RefExpr : VarList) {
7339     assert(RefExpr && "NULL expr in OpenMP private clause.");
7340     SourceLocation ELoc;
7341     SourceRange ERange;
7342     Expr *SimpleRefExpr = RefExpr;
7343     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
7344     if (Res.second) {
7345       // It will be analyzed later.
7346       Vars.push_back(RefExpr);
7347       PrivateCopies.push_back(nullptr);
7348     }
7349     ValueDecl *D = Res.first;
7350     if (!D)
7351       continue;
7352
7353     QualType Type = D->getType();
7354     auto *VD = dyn_cast<VarDecl>(D);
7355
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.
7359     if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
7360       continue;
7361     Type = Type.getNonReferenceType();
7362
7363     // 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.
7370     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
7371     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
7372       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7373                                           << getOpenMPClauseName(OMPC_private);
7374       ReportOriginalDSA(*this, DSAStack, D, DVar);
7375       continue;
7376     }
7377
7378     auto CurrDir = DSAStack->getCurrentDirective();
7379     // Variably modified types are not supported for tasks.
7380     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
7381         isOpenMPTaskingDirective(CurrDir)) {
7382       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7383           << getOpenMPClauseName(OMPC_private) << Type
7384           << getOpenMPDirectiveName(CurrDir);
7385       bool IsDecl =
7386           !VD ||
7387           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
7388       Diag(D->getLocation(),
7389            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7390           << D;
7391       continue;
7392     }
7393
7394     // 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
7397     if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
7398         CurrDir == OMPD_target_teams ||
7399         CurrDir == OMPD_target_teams_distribute ||
7400         CurrDir == OMPD_target_teams_distribute_parallel_for) {
7401       OpenMPClauseKind ConflictKind;
7402       if (DSAStack->checkMappableExprComponentListsForDecl(
7403               VD, /*CurrentRegionOnly=*/true,
7404               [&](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)
7410             << getOpenMPClauseName(OMPC_private)
7411             << getOpenMPClauseName(ConflictKind)
7412             << getOpenMPDirectiveName(CurrDir);
7413         ReportOriginalDSA(*this, DSAStack, D, DVar);
7414         continue;
7415       }
7416     }
7417
7418     // 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.
7422     // 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.
7427     Type = Type.getUnqualifiedType();
7428     auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7429                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
7430     ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
7431     if (VDPrivate->isInvalidDecl())
7432       continue;
7433     auto VDPrivateRefExpr = buildDeclRefExpr(
7434         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
7435
7436     DeclRefExpr *Ref = nullptr;
7437     if (!VD && !CurContext->isDependentContext())
7438       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
7439     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
7440     Vars.push_back((VD || CurContext->isDependentContext())
7441                        ? RefExpr->IgnoreParens()
7442                        : Ref);
7443     PrivateCopies.push_back(VDPrivateRefExpr);
7444   }
7445
7446   if (Vars.empty())
7447     return nullptr;
7448
7449   return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
7450                                   PrivateCopies);
7451 }
7452
7453 namespace {
7454 class DiagsUninitializedSeveretyRAII {
7455 private:
7456   DiagnosticsEngine &Diags;
7457   SourceLocation SavedLoc;
7458   bool IsIgnored;
7459
7460 public:
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 };
7474 }
7475
7476 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
7477                                                SourceLocation StartLoc,
7478                                                SourceLocation LParenLoc,
7479                                                SourceLocation EndLoc) {
7480   SmallVector<Expr *, 8> Vars;
7481   SmallVector<Expr *, 8> PrivateCopies;
7482   SmallVector<Expr *, 8> Inits;
7483   SmallVector<Decl *, 4> ExprCaptures;
7484   bool IsImplicitClause =
7485       StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
7486   auto ImplicitClauseLoc = DSAStack->getConstructLoc();
7487
7488   for (auto &RefExpr : VarList) {
7489     assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
7490     SourceLocation ELoc;
7491     SourceRange ERange;
7492     Expr *SimpleRefExpr = RefExpr;
7493     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
7494     if (Res.second) {
7495       // It will be analyzed later.
7496       Vars.push_back(RefExpr);
7497       PrivateCopies.push_back(nullptr);
7498       Inits.push_back(nullptr);
7499     }
7500     ValueDecl *D = Res.first;
7501     if (!D)
7502       continue;
7503
7504     ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
7505     QualType Type = D->getType();
7506     auto *VD = dyn_cast<VarDecl>(D);
7507
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,
7512                             diag::err_omp_firstprivate_incomplete_type))
7513       continue;
7514     Type = Type.getNonReferenceType();
7515
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
7518     //  clause requires an accessible, unambiguous copy constructor for the
7519     //  class type.
7520     auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
7521
7522     // If an implicit firstprivate variable found it was checked already.
7523     DSAStackTy::DSAVarData TopDVar;
7524     if (!IsImplicitClause) {
7525       DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
7526       TopDVar = DVar;
7527       bool IsConstant = ElemType.isConstant(Context);
7528       // 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.
7532       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
7533           DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
7534         Diag(ELoc, diag::err_omp_wrong_dsa)
7535             << getOpenMPClauseName(DVar.CKind)
7536             << getOpenMPClauseName(OMPC_firstprivate);
7537         ReportOriginalDSA(*this, DSAStack, D, DVar);
7538         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.
7552       if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
7553           DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
7554         Diag(ELoc, diag::err_omp_wrong_dsa)
7555             << getOpenMPClauseName(DVar.CKind)
7556             << getOpenMPClauseName(OMPC_firstprivate);
7557         ReportOriginalDSA(*this, DSAStack, D, DVar);
7558         continue;
7559       }
7560
7561       OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
7562       // 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.
7567       if (isOpenMPWorksharingDirective(CurrDir) &&
7568           !isOpenMPParallelDirective(CurrDir) &&
7569           !isOpenMPTeamsDirective(CurrDir)) {
7570         DVar = DSAStack->getImplicitDSA(D, true);
7571         if (DVar.CKind != OMPC_shared &&
7572             (isOpenMPParallelDirective(DVar.DKind) ||
7573              DVar.DKind == OMPD_unknown)) {
7574           Diag(ELoc, diag::err_omp_required_access)
7575               << getOpenMPClauseName(OMPC_firstprivate)
7576               << getOpenMPClauseName(OMPC_shared);
7577           ReportOriginalDSA(*this, DSAStack, D, DVar);
7578           continue;
7579         }
7580       }
7581       // 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.
7592       if (isOpenMPTaskingDirective(CurrDir)) {
7593         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);
7600         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);
7605           ReportOriginalDSA(*this, DSAStack, D, DVar);
7606           continue;
7607         }
7608       }
7609
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) {
7624         DVar = DSAStack->hasInnermostDSA(
7625             D, [](OpenMPClauseKind C) -> bool { return C == OMPC_private; },
7626             [](OpenMPDirectiveKind K) -> bool {
7627               return isOpenMPTeamsDirective(K);
7628             },
7629             false);
7630         if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) {
7631           Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams);
7632           ReportOriginalDSA(*this, DSAStack, D, DVar);
7633           continue;
7634         }
7635         DVar = DSAStack->hasInnermostDSA(
7636             D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
7637             [](OpenMPDirectiveKind K) -> bool {
7638               return isOpenMPTeamsDirective(K);
7639             },
7640             false);
7641         if (DVar.CKind == OMPC_reduction &&
7642             isOpenMPTeamsDirective(DVar.DKind)) {
7643           Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction);
7644           ReportOriginalDSA(*this, DSAStack, D, DVar);
7645           continue;
7646         }
7647         DVar = DSAStack->getTopDSA(D, false);
7648         if (DVar.CKind == OMPC_lastprivate) {
7649           Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
7650           ReportOriginalDSA(*this, DSAStack, D, DVar);
7651           continue;
7652         }
7653       }
7654       // 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
7657       if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
7658           CurrDir == OMPD_target_teams ||
7659           CurrDir == OMPD_target_teams_distribute ||
7660           CurrDir == OMPD_target_teams_distribute_parallel_for) {
7661         OpenMPClauseKind ConflictKind;
7662         if (DSAStack->checkMappableExprComponentListsForDecl(
7663                 VD, /*CurrentRegionOnly=*/true,
7664                 [&](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)
7670               << getOpenMPClauseName(OMPC_firstprivate)
7671               << getOpenMPClauseName(ConflictKind)
7672               << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7673           ReportOriginalDSA(*this, DSAStack, D, DVar);
7674           continue;
7675         }
7676       }
7677     }
7678
7679     // Variably modified types are not supported for tasks.
7680     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
7681         isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
7682       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7683           << getOpenMPClauseName(OMPC_firstprivate) << Type
7684           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7685       bool IsDecl =
7686           !VD ||
7687           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
7688       Diag(D->getLocation(),
7689            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7690           << D;
7691       continue;
7692     }
7693
7694     Type = Type.getUnqualifiedType();
7695     auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7696                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
7697     // 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.
7705     if (Type->isArrayType()) {
7706       auto VDInit =
7707           buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
7708       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
7709       auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
7710       ElemType = ElemType.getUnqualifiedType();
7711       auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
7712                                       ".firstprivate.temp");
7713       InitializedEntity Entity =
7714           InitializedEntity::InitializeVariable(VDInitTemp);
7715       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>());
7723       // Remove temp variable declaration.
7724       Context.Deallocate(VDInitTemp);
7725     } else {
7726       auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
7727                                   ".firstprivate.temp");
7728       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
7729                                        RefExpr->getExprLoc());
7730       AddInitializerToDecl(VDPrivate,
7731                            DefaultLvalueConversion(VDInitRefExpr).get(),
7732                            /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
7733     }
7734     if (VDPrivate->isInvalidDecl()) {
7735       if (IsImplicitClause) {
7736         Diag(RefExpr->getExprLoc(),
7737              diag::note_omp_task_predetermined_firstprivate_here);
7738       }
7739       continue;
7740     }
7741     CurContext->addDecl(VDPrivate);
7742     auto VDPrivateRefExpr = buildDeclRefExpr(
7743         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
7744         RefExpr->getExprLoc());
7745     DeclRefExpr *Ref = nullptr;
7746     if (!VD && !CurContext->isDependentContext()) {
7747       if (TopDVar.CKind == OMPC_lastprivate)
7748         Ref = TopDVar.PrivateCopy;
7749       else {
7750         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
7751         if (!IsOpenMPCapturedDecl(D))
7752           ExprCaptures.push_back(Ref->getDecl());
7753       }
7754     }
7755     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
7756     Vars.push_back((VD || CurContext->isDependentContext())
7757                        ? RefExpr->IgnoreParens()
7758                        : Ref);
7759     PrivateCopies.push_back(VDPrivateRefExpr);
7760     Inits.push_back(VDInitRefExpr);
7761   }
7762
7763   if (Vars.empty())
7764     return nullptr;
7765
7766   return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
7767                                        Vars, PrivateCopies, Inits,
7768                                        buildPreInits(Context, ExprCaptures));
7769 }
7770
7771 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
7772                                               SourceLocation StartLoc,
7773                                               SourceLocation LParenLoc,
7774                                               SourceLocation EndLoc) {
7775   SmallVector<Expr *, 8> Vars;
7776   SmallVector<Expr *, 8> SrcExprs;
7777   SmallVector<Expr *, 8> DstExprs;
7778   SmallVector<Expr *, 8> AssignmentOps;
7779   SmallVector<Decl *, 4> ExprCaptures;
7780   SmallVector<Expr *, 4> ExprPostUpdates;
7781   for (auto &RefExpr : VarList) {
7782     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
7783     SourceLocation ELoc;
7784     SourceRange ERange;
7785     Expr *SimpleRefExpr = RefExpr;
7786     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
7787     if (Res.second) {
7788       // It will be analyzed later.
7789       Vars.push_back(RefExpr);
7790       SrcExprs.push_back(nullptr);
7791       DstExprs.push_back(nullptr);
7792       AssignmentOps.push_back(nullptr);
7793     }
7794     ValueDecl *D = Res.first;
7795     if (!D)
7796       continue;
7797
7798     QualType Type = D->getType();
7799     auto *VD = dyn_cast<VarDecl>(D);
7800
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,
7805                             diag::err_omp_lastprivate_incomplete_type))
7806       continue;
7807     Type = Type.getNonReferenceType();
7808
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.
7814     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
7815     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);
7821       ReportOriginalDSA(*this, DSAStack, D, DVar);
7822       continue;
7823     }
7824
7825     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.
7832     DSAStackTy::DSAVarData TopDVar = DVar;
7833     if (isOpenMPWorksharingDirective(CurrDir) &&
7834         !isOpenMPParallelDirective(CurrDir) &&
7835         !isOpenMPTeamsDirective(CurrDir)) {
7836       DVar = DSAStack->getImplicitDSA(D, true);
7837       if (DVar.CKind != OMPC_shared) {
7838         Diag(ELoc, diag::err_omp_required_access)
7839             << getOpenMPClauseName(OMPC_lastprivate)
7840             << getOpenMPClauseName(OMPC_shared);
7841         ReportOriginalDSA(*this, DSAStack, D, DVar);
7842         continue;
7843       }
7844     }
7845
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
7858     // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
7859     //  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.
7863     //  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.
7866     Type = Context.getBaseElementType(Type).getNonReferenceType();
7867     auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
7868                                Type.getUnqualifiedType(), ".lastprivate.src",
7869                                D->hasAttrs() ? &D->getAttrs() : nullptr);
7870     auto *PseudoSrcExpr =
7871         buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
7872     auto *DstVD =
7873         buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
7874                      D->hasAttrs() ? &D->getAttrs() : nullptr);
7875     auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
7876     // For arrays generate assignment operation for single element and replace
7877     // it by the original array element in CodeGen.
7878     auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
7879                                    PseudoDstExpr, PseudoSrcExpr);
7880     if (AssignmentOp.isInvalid())
7881       continue;
7882     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
7883                                        /*DiscardedValue=*/true);
7884     if (AssignmentOp.isInvalid())
7885       continue;
7886
7887     DeclRefExpr *Ref = nullptr;
7888     if (!VD && !CurContext->isDependentContext()) {
7889       if (TopDVar.CKind == OMPC_firstprivate)
7890         Ref = TopDVar.PrivateCopy;
7891       else {
7892         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
7893         if (!IsOpenMPCapturedDecl(D))
7894           ExprCaptures.push_back(Ref->getDecl());
7895       }
7896       if (TopDVar.CKind == OMPC_firstprivate ||
7897           (!IsOpenMPCapturedDecl(D) &&
7898            Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
7899         ExprResult RefRes = DefaultLvalueConversion(Ref);
7900         if (!RefRes.isUsable())
7901           continue;
7902         ExprResult PostUpdateRes =
7903             BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
7904                        RefRes.get());
7905         if (!PostUpdateRes.isUsable())
7906           continue;
7907         ExprPostUpdates.push_back(
7908             IgnoredValueConversions(PostUpdateRes.get()).get());
7909       }
7910     }
7911     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
7912     Vars.push_back((VD || CurContext->isDependentContext())
7913                        ? RefExpr->IgnoreParens()
7914                        : Ref);
7915     SrcExprs.push_back(PseudoSrcExpr);
7916     DstExprs.push_back(PseudoDstExpr);
7917     AssignmentOps.push_back(AssignmentOp.get());
7918   }
7919
7920   if (Vars.empty())
7921     return nullptr;
7922
7923   return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
7924                                       Vars, SrcExprs, DstExprs, AssignmentOps,
7925                                       buildPreInits(Context, ExprCaptures),
7926                                       buildPostUpdate(*this, ExprPostUpdates));
7927 }
7928
7929 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
7930                                          SourceLocation StartLoc,
7931                                          SourceLocation LParenLoc,
7932                                          SourceLocation EndLoc) {
7933   SmallVector<Expr *, 8> Vars;
7934   for (auto &RefExpr : VarList) {
7935     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
7936     SourceLocation ELoc;
7937     SourceRange ERange;
7938     Expr *SimpleRefExpr = RefExpr;
7939     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
7940     if (Res.second) {
7941       // It will be analyzed later.
7942       Vars.push_back(RefExpr);
7943     }
7944     ValueDecl *D = Res.first;
7945     if (!D)
7946       continue;
7947
7948     auto *VD = dyn_cast<VarDecl>(D);
7949     // 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.
7956     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
7957     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);
7961       ReportOriginalDSA(*this, DSAStack, D, DVar);
7962       continue;
7963     }
7964
7965     DeclRefExpr *Ref = nullptr;
7966     if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
7967       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
7968     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
7969     Vars.push_back((VD || !Ref || CurContext->isDependentContext())
7970                        ? RefExpr->IgnoreParens()
7971                        : Ref);
7972   }
7973
7974   if (Vars.empty())
7975     return nullptr;
7976
7977   return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
7978 }
7979
7980 namespace {
7981 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
7982   DSAStackTy *Stack;
7983
7984 public:
7985   bool VisitDeclRefExpr(DeclRefExpr *E) {
7986     if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
7987       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
7988       if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
7989         return false;
7990       if (DVar.CKind != OMPC_unknown)
7991         return true;
7992       DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
7993           VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
7994           false);
7995       if (DVarPrivate.CKind != OMPC_unknown)
7996         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   }
8008   explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
8009 };
8010 } // namespace
8011
8012 namespace {
8013 // Transform MemberExpression for specified FieldDecl of current class to
8014 // DeclRefExpr to specified OMPCapturedExprDecl.
8015 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
8016   typedef TreeTransform<TransformExprToCaptures> BaseTransform;
8017   ValueDecl *Field;
8018   DeclRefExpr *CapturedExpr;
8019
8020 public:
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) {
8027       CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
8028       return CapturedExpr;
8029     }
8030     return BaseTransform::TransformMemberExpr(E);
8031   }
8032   DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
8033 };
8034 } // namespace
8035
8036 template <typename T>
8037 static 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
8048 static ExprResult
8049 buildDeclareReductionRef(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;
8074     for (auto *D : ULE->decls()) {
8075       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
8138 OMPClause *Sema::ActOnOpenMPReductionClause(
8139     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
8140     SourceLocation ColonLoc, SourceLocation EndLoc,
8141     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
8142     ArrayRef<Expr *> UnresolvedReductions) {
8143   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:
8158     BOK = BO_Add;
8159     break;
8160   case OO_Star:
8161     BOK = BO_Mul;
8162     break;
8163   case OO_Amp:
8164     BOK = BO_And;
8165     break;
8166   case OO_Pipe:
8167     BOK = BO_Or;
8168     break;
8169   case OO_Caret:
8170     BOK = BO_Xor;
8171     break;
8172   case OO_AmpAmp:
8173     BOK = BO_LAnd;
8174     break;
8175   case OO_PipePipe:
8176     BOK = BO_LOr;
8177     break;
8178   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:
8213   case OO_Coawait:
8214   case NUM_OVERLOADED_OPERATORS:
8215     llvm_unreachable("Unexpected reduction identifier");
8216   case OO_None:
8217     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;
8226   if (ReductionIdScopeSpec.isValid())
8227     ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
8228   ReductionIdRange.setEnd(ReductionId.getEndLoc());
8229
8230   SmallVector<Expr *, 8> Vars;
8231   SmallVector<Expr *, 8> Privates;
8232   SmallVector<Expr *, 8> LHSs;
8233   SmallVector<Expr *, 8> RHSs;
8234   SmallVector<Expr *, 8> ReductionOps;
8235   SmallVector<Decl *, 4> ExprCaptures;
8236   SmallVector<Expr *, 4> ExprPostUpdates;
8237   auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
8238   bool FirstIter = true;
8239   for (auto RefExpr : VarList) {
8240     assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
8241     // 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.
8248     if (!FirstIter && IR != ER)
8249       ++IR;
8250     FirstIter = false;
8251     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);
8262       // 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);
8275     }
8276     ValueDecl *D = Res.first;
8277     if (!D)
8278       continue;
8279
8280     QualType Type;
8281     auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
8282     auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
8283     if (ASE)
8284       Type = ASE->getType().getNonReferenceType();
8285     else if (OASE) {
8286       auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
8287       if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
8288         Type = ATy->getElementType();
8289       else
8290         Type = BaseType->getPointeeType();
8291       Type = Type.getNonReferenceType();
8292     } else
8293       Type = Context.getBaseElementType(D->getType().getNonReferenceType());
8294     auto *VD = dyn_cast<VarDecl>(D);
8295
8296     // 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]
8303     // A list item that appears in a reduction clause must not be
8304     // const-qualified.
8305     if (Type.getNonReferenceType().isConstant(Context)) {
8306       Diag(ELoc, diag::err_omp_const_reduction_list_item)
8307           << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
8308       if (!ASE && !OASE) {
8309         bool IsDecl = !VD ||
8310                       VD->isThisDeclarationADefinition(Context) ==
8311                           VarDecl::DeclarationOnly;
8312         Diag(D->getLocation(),
8313              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8314             << D;
8315       }
8316       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.
8321     if (!ASE && !OASE && VD) {
8322       VarDecl *VDDef = VD->getDefinition();
8323       if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
8324         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         }
8330       }
8331     }
8332
8333     // 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.
8344     DSAStackTy::DSAVarData DVar;
8345     DVar = DSAStack->getTopDSA(D, false);
8346     if (DVar.CKind == OMPC_reduction) {
8347       Diag(ELoc, diag::err_omp_once_referenced)
8348           << getOpenMPClauseName(OMPC_reduction);
8349       if (DVar.RefExpr)
8350         Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
8351     } else if (DVar.CKind != OMPC_unknown) {
8352       Diag(ELoc, diag::err_omp_wrong_dsa)
8353           << getOpenMPClauseName(DVar.CKind)
8354           << getOpenMPClauseName(OMPC_reduction);
8355       ReportOriginalDSA(*this, DSAStack, D, DVar);
8356       continue;
8357     }
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.
8363     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8364     if (isOpenMPWorksharingDirective(CurrDir) &&
8365         !isOpenMPParallelDirective(CurrDir) &&
8366         !isOpenMPTeamsDirective(CurrDir)) {
8367       DVar = DSAStack->getImplicitDSA(D, true);
8368       if (DVar.CKind != OMPC_shared) {
8369         Diag(ELoc, diag::err_omp_required_access)
8370             << getOpenMPClauseName(OMPC_reduction)
8371             << getOpenMPClauseName(OMPC_shared);
8372         ReportOriginalDSA(*this, DSAStack, D, DVar);
8373         continue;
8374       }
8375     }
8376
8377     // 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
8442     Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
8443     auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
8444                                D->hasAttrs() ? &D->getAttrs() : nullptr);
8445     auto *RHSVD = buildVarDecl(*this, ELoc, Type, D->getName(),
8446                                D->hasAttrs() ? &D->getAttrs() : nullptr);
8447     auto PrivateTy = Type;
8448     if (OASE ||
8449         (!ASE &&
8450          D->getType().getNonReferenceType()->isVariablyModifiedType())) {
8451       // For arrays/array sections only:
8452       // 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());
8460     } else if (!ASE && !OASE &&
8461                Context.getAsArrayType(D->getType().getNonReferenceType()))
8462       PrivateTy = D->getType().getNonReferenceType();
8463     // Private copy.
8464     auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, D->getName(),
8465                                    D->hasAttrs() ? &D->getAttrs() : nullptr);
8466     // Add initializer for private variable.
8467     Expr *Init = nullptr;
8468     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);
8477       }
8478     } 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();
8493         }
8494         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;
8519       }
8520       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       }
8580     }
8581     if (Init && DeclareReductionRef.isUnset()) {
8582       AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
8583                            /*TypeMayContainAuto=*/false);
8584     } else if (!Init)
8585       ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
8586     if (RHSVD->isInvalidDecl())
8587       continue;
8588     if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
8589       Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
8590                                                             << ReductionIdRange;
8591       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;
8597       continue;
8598     }
8599     // Store initializer for single element in private copy. Will be used during
8600     // codegen.
8601     PrivateVD->setInit(RHSVD->getInit());
8602     PrivateVD->setInitStyle(RHSVD->getInitStyle());
8603     auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc);
8604     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());
8619       }
8620       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;
8649     }
8650
8651     DeclRefExpr *Ref = nullptr;
8652     Expr *VarsExpr = RefExpr->IgnoreParens();
8653     if (!VD && !CurContext->isDependentContext()) {
8654       if (ASE || OASE) {
8655         TransformExprToCaptures RebuildToCapture(*this, D);
8656         VarsExpr =
8657             RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
8658         Ref = RebuildToCapture.getCapturedExpr();
8659       } else {
8660         VarsExpr = Ref =
8661             buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
8662       }
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());
8676         }
8677       }
8678     }
8679     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
8680     Vars.push_back(VarsExpr);
8681     Privates.push_back(PrivateDRE);
8682     LHSs.push_back(LHSDRE);
8683     RHSs.push_back(RHSDRE);
8684     ReductionOps.push_back(ReductionOp.get());
8685   }
8686
8687   if (Vars.empty())
8688     return nullptr;
8689
8690   return OMPReductionClause::Create(
8691       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
8692       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates,
8693       LHSs, RHSs, ReductionOps, buildPreInits(Context, ExprCaptures),
8694       buildPostUpdate(*this, ExprPostUpdates));
8695 }
8696
8697 bool 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
8707 bool 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
8756 OMPClause *Sema::ActOnOpenMPLinearClause(
8757     ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
8758     SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
8759     SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
8760   SmallVector<Expr *, 8> Vars;
8761   SmallVector<Expr *, 8> Privates;
8762   SmallVector<Expr *, 8> Inits;
8763   SmallVector<Decl *, 4> ExprCaptures;
8764   SmallVector<Expr *, 4> ExprPostUpdates;
8765   if (CheckOpenMPLinearModifier(LinKind, LinLoc))
8766     LinKind = OMPC_LINEAR_val;
8767   for (auto &RefExpr : VarList) {
8768     assert(RefExpr && "NULL expr in OpenMP linear clause.");
8769     SourceLocation ELoc;
8770     SourceRange ERange;
8771     Expr *SimpleRefExpr = RefExpr;
8772     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8773                               /*AllowArraySection=*/false);
8774     if (Res.second) {
8775       // It will be analyzed later.
8776       Vars.push_back(RefExpr);
8777       Privates.push_back(nullptr);
8778       Inits.push_back(nullptr);
8779     }
8780     ValueDecl *D = Res.first;
8781     if (!D)
8782       continue;
8783
8784     QualType Type = D->getType();
8785     auto *VD = dyn_cast<VarDecl>(D);
8786
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.
8791     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
8792     if (DVar.RefExpr) {
8793       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8794                                           << getOpenMPClauseName(OMPC_linear);
8795       ReportOriginalDSA(*this, DSAStack, D, DVar);
8796       continue;
8797     }
8798
8799     if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
8800       continue;
8801     Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
8802
8803     // Build private copy of original var.
8804     auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
8805                                  D->hasAttrs() ? &D->getAttrs() : nullptr);
8806     auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
8807     // Build var to save initial value.
8808     VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
8809     Expr *InitExpr;
8810     DeclRefExpr *Ref = nullptr;
8811     if (!VD && !CurContext->isDependentContext()) {
8812       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     }
8829     if (LinKind == OMPC_LINEAR_uval)
8830       InitExpr = VD ? VD->getInit() : SimpleRefExpr;
8831     else
8832       InitExpr = VD ? SimpleRefExpr : Ref;
8833     AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
8834                          /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
8835     auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
8836
8837     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
8838     Vars.push_back((VD || CurContext->isDependentContext())
8839                        ? RefExpr->IgnoreParens()
8840                        : Ref);
8841     Privates.push_back(PrivateRef);
8842     Inits.push_back(InitRef);
8843   }
8844
8845   if (Vars.empty())
8846     return nullptr;
8847
8848   Expr *StepExpr = Step;
8849   Expr *CalcStepExpr = nullptr;
8850   if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
8851       !Step->isInstantiationDependent() &&
8852       !Step->containsUnexpandedParameterPack()) {
8853     SourceLocation StepLoc = Step->getLocStart();
8854     ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
8855     if (Val.isInvalid())
8856       return nullptr;
8857     StepExpr = Val.get();
8858
8859     // Build var to save the step value.
8860     VarDecl *SaveVar =
8861         buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
8862     ExprResult SaveRef =
8863         buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
8864     ExprResult CalcStep =
8865         BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
8866     CalcStep = ActOnFinishFullExpr(CalcStep.get());
8867
8868     // Warn about zero linear step (it would be probably better specified as
8869     // making corresponding variables 'const').
8870     llvm::APSInt Result;
8871     bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
8872     if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
8873       Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
8874                                                      << (Vars.size() > 1);
8875     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     }
8880   }
8881
8882   return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
8883                                  ColonLoc, EndLoc, Vars, Privates, Inits,
8884                                  StepExpr, CalcStepExpr,
8885                                  buildPreInits(Context, ExprCaptures),
8886                                  buildPostUpdate(*this, ExprPostUpdates));
8887 }
8888
8889 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
8890                                      Expr *NumIterations, Sema &SemaRef,
8891                                      Scope *S, DSAStackTy *Stack) {
8892   // 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();
8901   else if (CalcStep) {
8902     Step = cast<BinaryOperator>(CalcStep)->getLHS();
8903   }
8904   bool HasErrors = false;
8905   auto CurInit = Clause.inits().begin();
8906   auto CurPrivate = Clause.privates().begin();
8907   auto LinKind = Clause.getModifier();
8908   for (auto &RefExpr : Clause.varlists()) {
8909     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);
8926     Expr *InitExpr = *CurInit;
8927
8928     // Build privatized reference to the current linear var.
8929     auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
8930     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);
8938
8939     // Build update: Var = InitExpr + IV * Step
8940     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;
8947     Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
8948                                          /*DiscardedValue=*/true);
8949
8950     // Build final: Var = InitExpr + NumIterations * Step
8951     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;
8958     Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
8959                                         /*DiscardedValue=*/true);
8960
8961     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     }
8969     ++CurInit;
8970     ++CurPrivate;
8971   }
8972   Clause.setUpdates(Updates);
8973   Clause.setFinals(Finals);
8974   return HasErrors;
8975 }
8976
8977 OMPClause *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) {
8983     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) {
8990       // It will be analyzed later.
8991       Vars.push_back(RefExpr);
8992     }
8993     ValueDecl *D = Res.first;
8994     if (!D)
8995       continue;
8996
8997     QualType QType = D->getType();
8998     auto *VD = dyn_cast<VarDecl>(D);
8999
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.
9003     QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
9004     const Type *Ty = QType.getTypePtrOrNull();
9005     if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
9006       Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
9007           << QType << getLangOpts().CPlusPlus << ERange;
9008       bool IsDecl =
9009           !VD ||
9010           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9011       Diag(D->getLocation(),
9012            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9013           << D;
9014       continue;
9015     }
9016
9017     // OpenMP  [2.8.1, simd construct, Restrictions]
9018     // A list-item cannot appear in more than one aligned clause.
9019     if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
9020       Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
9021       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
9022           << getOpenMPClauseName(OMPC_aligned);
9023       continue;
9024     }
9025
9026     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());
9032   }
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
9053 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
9054                                          SourceLocation StartLoc,
9055                                          SourceLocation LParenLoc,
9056                                          SourceLocation EndLoc) {
9057   SmallVector<Expr *, 8> Vars;
9058   SmallVector<Expr *, 8> SrcExprs;
9059   SmallVector<Expr *, 8> DstExprs;
9060   SmallVector<Expr *, 8> AssignmentOps;
9061   for (auto &RefExpr : VarList) {
9062     assert(RefExpr && "NULL expr in OpenMP copyin clause.");
9063     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
9064       // It will be analyzed later.
9065       Vars.push_back(RefExpr);
9066       SrcExprs.push_back(nullptr);
9067       DstExprs.push_back(nullptr);
9068       AssignmentOps.push_back(nullptr);
9069       continue;
9070     }
9071
9072     SourceLocation ELoc = RefExpr->getExprLoc();
9073     // 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.
9077     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
9078     if (!DE || !isa<VarDecl>(DE->getDecl())) {
9079       Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
9080           << 0 << RefExpr->getSourceRange();
9081       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);
9091       SrcExprs.push_back(nullptr);
9092       DstExprs.push_back(nullptr);
9093       AssignmentOps.push_back(nullptr);
9094       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)
9101           << getOpenMPClauseName(OMPC_copyin)
9102           << getOpenMPDirectiveName(OMPD_threadprivate);
9103       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
9108     //  copyin clause requires an accessible, unambiguous copy assignment
9109     //  operator for the class type.
9110     auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
9111     auto *SrcVD =
9112         buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
9113                      ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
9114     auto *PseudoSrcExpr = buildDeclRefExpr(
9115         *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
9116     auto *DstVD =
9117         buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
9118                      VD->hasAttrs() ? &VD->getAttrs() : nullptr);
9119     auto *PseudoDstExpr =
9120         buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
9121     // 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;
9131
9132     DSAStack->addDSA(VD, DE, OMPC_copyin);
9133     Vars.push_back(DE);
9134     SrcExprs.push_back(PseudoSrcExpr);
9135     DstExprs.push_back(PseudoDstExpr);
9136     AssignmentOps.push_back(AssignmentOp.get());
9137   }
9138
9139   if (Vars.empty())
9140     return nullptr;
9141
9142   return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9143                                  SrcExprs, DstExprs, AssignmentOps);
9144 }
9145
9146 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
9147                                               SourceLocation StartLoc,
9148                                               SourceLocation LParenLoc,
9149                                               SourceLocation EndLoc) {
9150   SmallVector<Expr *, 8> Vars;
9151   SmallVector<Expr *, 8> SrcExprs;
9152   SmallVector<Expr *, 8> DstExprs;
9153   SmallVector<Expr *, 8> AssignmentOps;
9154   for (auto &RefExpr : VarList) {
9155     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) {
9162       // It will be analyzed later.
9163       Vars.push_back(RefExpr);
9164       SrcExprs.push_back(nullptr);
9165       DstExprs.push_back(nullptr);
9166       AssignmentOps.push_back(nullptr);
9167     }
9168     ValueDecl *D = Res.first;
9169     if (!D)
9170       continue;
9171
9172     QualType Type = D->getType();
9173     auto *VD = dyn_cast<VarDecl>(D);
9174
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.
9178     if (!VD || !DSAStack->isThreadPrivate(VD)) {
9179       auto DVar = DSAStack->getTopDSA(D, false);
9180       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
9181           DVar.RefExpr) {
9182         Diag(ELoc, diag::err_omp_wrong_dsa)
9183             << getOpenMPClauseName(DVar.CKind)
9184             << getOpenMPClauseName(OMPC_copyprivate);
9185         ReportOriginalDSA(*this, DSAStack, D, DVar);
9186         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) {
9193         DVar = DSAStack->getImplicitDSA(D, false);
9194         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";
9198           ReportOriginalDSA(*this, DSAStack, D, DVar);
9199           continue;
9200         }
9201       }
9202     }
9203
9204     // Variably modified types are not supported.
9205     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
9206       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9207           << getOpenMPClauseName(OMPC_copyprivate) << Type
9208           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9209       bool IsDecl =
9210           !VD ||
9211           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9212       Diag(D->getLocation(),
9213            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9214           << D;
9215       continue;
9216     }
9217
9218     // 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.
9222     Type = Context.getBaseElementType(Type.getNonReferenceType())
9223                .getUnqualifiedType();
9224     auto *SrcVD =
9225         buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
9226                      D->hasAttrs() ? &D->getAttrs() : nullptr);
9227     auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
9228     auto *DstVD =
9229         buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
9230                      D->hasAttrs() ? &D->getAttrs() : nullptr);
9231     auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
9232     auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
9233                                    PseudoDstExpr, PseudoSrcExpr);
9234     if (AssignmentOp.isInvalid())
9235       continue;
9236     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
9237                                        /*DiscardedValue=*/true);
9238     if (AssignmentOp.isInvalid())
9239       continue;
9240
9241     // No need to mark vars as copyprivate, they are already threadprivate or
9242     // implicitly private.
9243     assert(VD || IsOpenMPCapturedDecl(D));
9244     Vars.push_back(
9245         VD ? RefExpr->IgnoreParens()
9246            : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
9247     SrcExprs.push_back(PseudoSrcExpr);
9248     DstExprs.push_back(PseudoDstExpr);
9249     AssignmentOps.push_back(AssignmentOp.get());
9250   }
9251
9252   if (Vars.empty())
9253     return nullptr;
9254
9255   return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9256                                       Vars, SrcExprs, DstExprs, AssignmentOps);
9257 }
9258
9259 OMPClause *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 }
9268
9269 OMPClause *
9270 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
9271                               SourceLocation DepLoc, SourceLocation ColonLoc,
9272                               ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9273                               SourceLocation LParenLoc, SourceLocation EndLoc) {
9274   if (DSAStack->getCurrentDirective() == OMPD_ordered &&
9275       DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
9276     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
9277         << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
9278     return nullptr;
9279   }
9280   if (DSAStack->getCurrentDirective() != OMPD_ordered &&
9281       (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
9282        DepKind == OMPC_DEPEND_sink)) {
9283     unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
9284     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
9285         << getListOfPossibleValues(OMPC_depend, /*First=*/0,
9286                                    /*Last=*/OMPC_DEPEND_unknown, Except)
9287         << getOpenMPClauseName(OMPC_depend);
9288     return nullptr;
9289   }
9290   SmallVector<Expr *, 8> Vars;
9291   DSAStackTy::OperatorOffsetTy OpsOffs;
9292   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);
9298     }
9299   }
9300   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.");
9304       if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
9305         // It will be analyzed later.
9306         Vars.push_back(RefExpr);
9307         continue;
9308       }
9309
9310       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.
9326         if (CurContext->isDependentContext()) {
9327           // It will be analyzed later.
9328           Vars.push_back(RefExpr);
9329           continue;
9330         }
9331         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});
9386       } 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())) ||
9396             (ASE &&
9397              !ASE->getBase()
9398                   ->getType()
9399                   .getNonReferenceType()
9400                   ->isPointerType() &&
9401              !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
9402           Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item)
9403               << 0 << RefExpr->getSourceRange();
9404           continue;
9405         }
9406       }
9407       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   }
9420   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;
9425 }
9426
9427 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
9428                                          SourceLocation LParenLoc,
9429                                          SourceLocation EndLoc) {
9430   Expr *ValExpr = Device;
9431
9432   // OpenMP [2.9.1, Restrictions]
9433   // The device expression must evaluate to a non-negative integer value.
9434   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
9435                                  /*StrictlyPositive=*/false))
9436     return nullptr;
9437
9438   return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9439 }
9440
9441 static 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
9482 static 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)) {
9489     if (!RD->isInvalidDecl() && !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
9490       return false;
9491   }
9492   return true;
9493 }
9494
9495 /// \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.
9498 static 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
9518   // covering the whole dimension.
9519   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.
9552 static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
9553                                                         const Expr *E,
9554                                                         QualType BaseQTy) {
9555   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
9583 // 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
9586 // components of the expression.
9587 static Expr *CheckMapClauseExpressionBase(
9588     Sema &SemaRef, Expr *E,
9589     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
9590     OpenMPClauseKind CKind) {
9591   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
9615   // 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
9620   // exist except in the rightmost expression (unless they cover the whole
9621   // dimension of the array). E.g. these would be invalid:
9622   //
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
9632   bool AllowUnitySizeArraySection = true;
9633   bool AllowWholeSizeArraySection = true;
9634
9635   while (!RelevantExpr) {
9636     E = E->IgnoreParenImpCasts();
9637
9638     if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
9639       if (!isa<VarDecl>(CurE->getDecl()))
9640         break;
9641
9642       RelevantExpr = CurE;
9643
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;
9648
9649       // Record the component.
9650       CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
9651           CurE, CurE->getDecl()));
9652       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()) {
9676         SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
9677             << CurE->getSourceRange() << getOpenMPClauseName(CKind);
9678         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.
9684       QualType CurType = BaseE->getType().getNonReferenceType();
9685
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
9697       // 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;
9706
9707       // Record the component.
9708       CurComponents.push_back(
9709           OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
9710       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       }
9721
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;
9728
9729       // Record the component - we don't have any declaration associated.
9730       CurComponents.push_back(
9731           OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
9732       continue;
9733     }
9734
9735     if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
9736       E = CurE->getBase()->IgnoreParenImpCasts();
9737
9738       auto CurType =
9739           OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
9740
9741       // 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.
9744       if (CurType->isReferenceType())
9745         CurType = CurType->getPointeeType();
9746
9747       bool IsPointer = CurType->isAnyPointerType();
9748
9749       if (!IsPointer && !CurType->isArrayType()) {
9750         SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
9751             << 0 << CurE->getSourceRange();
9752         break;
9753       }
9754
9755       bool NotWhole =
9756           CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
9757       bool NotUnity =
9758           CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
9759
9760       if (AllowWholeSizeArraySection) {
9761         // Any array section is currently allowed. Allowing a whole size array
9762         // section implies allowing a unity array section as well.
9763         //
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;
9769       } else if (AllowUnitySizeArraySection && NotUnity) {
9770         // 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       }
9777
9778       // Record the component - we don't have any declaration associated.
9779       CurComponents.push_back(
9780           OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
9781       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.
9796 static bool CheckMapConflicts(
9797     Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
9798     bool CurrentRegionOnly,
9799     OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
9800     OpenMPClauseKind CKind) {
9801   assert(VD && E);
9802   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
9809   assert(!CurComponents.empty() && "Map clause expression with no components!");
9810   assert(CurComponents.back().getAssociatedDeclaration() == VD &&
9811          "Map clause expression with unexpected base!");
9812
9813   // Variables to help detecting enclosing problems in data environment nests.
9814   bool IsEnclosedByDataEnvironmentExpr = false;
9815   const Expr *EnclosingExpr = nullptr;
9816
9817   bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
9818       VD, CurrentRegionOnly,
9819       [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
9820               StackComponents,
9821           OpenMPClauseKind) -> bool {
9822
9823         assert(!StackComponents.empty() &&
9824                "Map clause expression with no components!");
9825         assert(StackComponents.back().getAssociatedDeclaration() == VD &&
9826                "Map clause expression with unexpected base!");
9827
9828         // The whole expression in the stack.
9829         auto *RE = StackComponents.front().getAssociatedExpression();
9830
9831         // 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.
9844           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(),
9850                          diag::err_omp_multiple_array_items_in_map_clause)
9851                 << CI->getAssociatedExpression()->getSourceRange();
9852             SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
9853                          diag::note_used_here)
9854                 << SI->getAssociatedExpression()->getSourceRange();
9855             return true;
9856           }
9857
9858           // Do both expressions have the same kind?
9859           if (CI->getAssociatedExpression()->getStmtClass() !=
9860               SI->getAssociatedExpression()->getStmtClass())
9861             break;
9862
9863           // Are we dealing with different variables/fields?
9864           if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
9865             break;
9866         }
9867         // 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 =
9873                   dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
9874             Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
9875           } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
9876                          SI->getAssociatedExpression())) {
9877             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         }
9886
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) {
9895             if (CKind == OMPC_map)
9896               SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
9897             else {
9898               assert(CKind == OMPC_to || CKind == OMPC_from);
9899               SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
9900                   << ERange;
9901             }
9902             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
9913         QualType DerivedType =
9914             std::prev(CI)->getAssociatedDeclaration()->getType();
9915         SourceLocation DerivedLoc =
9916             std::prev(CI)->getAssociatedExpression()->getExprLoc();
9917
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.
9921         DerivedType = DerivedType.getNonReferenceType();
9922
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)) {
9956           if (CKind == OMPC_map)
9957             SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
9958           else {
9959             assert(CKind == OMPC_to || CKind == OMPC_from);
9960             SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
9961                 << ERange;
9962           }
9963           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
9969         // data environment but does not contain it completely.
9970         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,
9992   //  then the list item must also have a corresponding list item in the device
9993   //  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
10007 namespace {
10008 // Utility struct that gathers all the related lists associated with a mappable
10009 // expression.
10010 struct 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'.
10034 static void
10035 checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
10036                             OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
10037                             SourceLocation StartLoc,
10038                             OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
10039                             bool IsMapTypeImplicit = false) {
10040   // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
10041   assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
10042          "Unexpected clause kind with mappable expressions!");
10043
10044   // 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.
10049
10050   for (auto &RE : MVLI.VarList) {
10051     assert(RE && "Null expr in omp to/from/map clause");
10052     SourceLocation ELoc = RE->getExprLoc();
10053
10054     auto *VE = RE->IgnoreParenLValueCasts();
10055
10056     if (VE->isValueDependent() || VE->isTypeDependent() ||
10057         VE->isInstantiationDependent() ||
10058         VE->containsUnexpandedParameterPack()) {
10059       // We can only analyze this information once the missing information is
10060       // resolved.
10061       MVLI.ProcessedVarList.push_back(RE);
10062       continue;
10063     }
10064
10065     auto *SimpleExpr = RE->IgnoreParenCasts();
10066
10067     if (!RE->IgnoreParenImpCasts()->isLValue()) {
10068       SemaRef.Diag(ELoc,
10069                    diag::err_omp_expected_named_var_member_or_array_expression)
10070           << RE->getSourceRange();
10071       continue;
10072     }
10073
10074     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.
10079     auto *BE =
10080         CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
10081     if (!BE)
10082       continue;
10083
10084     assert(!CurComponents.empty() &&
10085            "Invalid mappable expression information.");
10086
10087     // 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);
10098
10099     assert((VD || FD) && "Only variables or fields are expected here!");
10100     (void)FD;
10101
10102     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
10103     // 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);
10111       continue;
10112     }
10113
10114     // 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.
10117
10118     // Check conflicts with other map clause expressions. We check the conflicts
10119     // with the current construct separately from the enclosing data
10120     // 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))
10124       break;
10125     if (CKind == OMPC_map &&
10126         CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10127                           /*CurrentRegionOnly=*/false, CurComponents, CKind))
10128       break;
10129
10130     // OpenMP 4.5 [2.10.5, target update Construct]
10131     // 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.
10134     QualType Type = CurDeclaration->getType().getNonReferenceType();
10135
10136     // 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.
10138     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
10139     //  A list item must have a mappable type.
10140     if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
10141                            DSAS, Type))
10142       continue;
10143
10144     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);
10156         continue;
10157       }
10158
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
10176       if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
10177            DKind == OMPD_target_teams_distribute ||
10178            DKind == OMPD_target_teams_distribute_parallel_for) && VD) {
10179         auto DVar = DSAS->getTopDSA(VD, false);
10180         if (isOpenMPPrivate(DVar.CKind)) {
10181           SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
10182               << getOpenMPClauseName(DVar.CKind)
10183               << getOpenMPClauseName(OMPC_map)
10184               << getOpenMPDirectiveName(DSAS->getCurrentDirective());
10185           ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
10186           continue;
10187         }
10188       }
10189     }
10190
10191     // Save the current expression.
10192     MVLI.ProcessedVarList.push_back(RE);
10193
10194     // Store the components in the stack so that they can be used to check
10195     // against other clauses later on.
10196     DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
10197                                           /*WhereFoundClauseKind=*/OMPC_map);
10198
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
10201     // null as base declaration.
10202     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);
10207   }
10208 }
10209
10210 OMPClause *
10211 Sema::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);
10219
10220   // 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.
10222   return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10223                               MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10224                               MVLI.VarComponents, MapTypeModifier, MapType,
10225                               IsMapTypeImplicit, MapLoc);
10226 }
10227
10228 QualType 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
10260 Sema::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
10342 void 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();
10358   // 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.
10364   auto *OmpInParm =
10365       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
10366   // 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
10383 void 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
10397 void 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();
10412   // 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");
10420   // 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");
10428   if (S != nullptr) {
10429     PushOnScopeChains(OmpPrivParm, S);
10430     PushOnScopeChains(OmpOrigParm, S);
10431   } else {
10432     DRD->addDecl(OmpPrivParm);
10433     DRD->addDecl(OmpOrigParm);
10434   }
10435 }
10436
10437 void 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
10452 Sema::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
10465 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
10466                                            SourceLocation StartLoc,
10467                                            SourceLocation LParenLoc,
10468                                            SourceLocation EndLoc) {
10469   Expr *ValExpr = NumTeams;
10470
10471   // OpenMP [teams Constrcut, Restrictions]
10472   // The num_teams expression must evaluate to a positive integer value.
10473   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
10474                                  /*StrictlyPositive=*/true))
10475     return nullptr;
10476
10477   return new (Context) OMPNumTeamsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10478 }
10479
10480 OMPClause *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.
10488   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
10489                                  /*StrictlyPositive=*/true))
10490     return nullptr;
10491
10492   return new (Context)
10493       OMPThreadLimitClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10494 }
10495
10496 OMPClause *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 }
10510
10511 OMPClause *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 }
10526
10527 OMPClause *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
10543 OMPClause *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
10556 OMPClause *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;
10570   Stmt *HelperValStmt = nullptr;
10571   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         }
10593       } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
10594                  !CurContext->isDependentContext()) {
10595         llvm::MapVector<Expr *, DeclRefExpr *> Captures;
10596         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
10597         HelperValStmt = buildPreInits(Context, Captures);
10598       }
10599     }
10600   }
10601
10602   return new (Context)
10603       OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
10604                             Kind, ValExpr, HelperValStmt);
10605 }
10606
10607 OMPClause *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)'
10612   if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
10613     std::string Value;
10614     SourceLocation Loc;
10615     Value += "'";
10616     if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
10617       Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
10618                                              OMPC_DEFAULTMAP_MODIFIER_tofrom);
10619       Loc = MLoc;
10620     } else {
10621       Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
10622                                              OMPC_DEFAULTMAP_scalar);
10623       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 }
10634
10635 bool 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
10652 void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
10653   assert(IsInOpenMPDeclareTargetContext &&
10654          "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
10655
10656   IsInOpenMPDeclareTargetContext = false;
10657 }
10658
10659 void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
10660                                         CXXScopeSpec &ScopeSpec,
10661                                         const DeclarationNameInfo &Id,
10662                                         OMPDeclareTargetDeclAttr::MapTypeTy MT,
10663                                         NamedDeclSetType &SameDirectiveDecls) {
10664   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
10705 static 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()) {
10718       Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10719           SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10720       D->addAttr(A);
10721       if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
10722         ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
10723       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) {
10735       Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10736           SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10737       D->addAttr(A);
10738       if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
10739         ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
10740       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.
10767     Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10768         SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10769     D->addAttr(A);
10770     if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
10771       ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
10772   }
10773 }
10774
10775 static 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
10785 void 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)) {
10805         Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10806             Context, OMPDeclareTargetDeclAttr::MT_To);
10807         VD->addAttr(A);
10808         if (ASTMutationListener *ML = Context.getASTMutationListener())
10809           ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
10810       }
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))) {
10818       Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10819           Context, OMPDeclareTargetDeclAttr::MT_To);
10820       D->addAttr(A);
10821       if (ASTMutationListener *ML = Context.getASTMutationListener())
10822         ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
10823     }
10824     return;
10825   }
10826   checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
10827 }
10828
10829 OMPClause *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 }
10842
10843 OMPClause *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 }
10856
10857 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
10858                                                SourceLocation StartLoc,
10859                                                SourceLocation LParenLoc,
10860                                                SourceLocation EndLoc) {
10861   MappableVarListInfo MVLI(VarList);
10862   SmallVector<Expr *, 8> PrivateCopies;
10863   SmallVector<Expr *, 8> Inits;
10864
10865   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.
10873       MVLI.ProcessedVarList.push_back(RefExpr);
10874       PrivateCopies.push_back(nullptr);
10875       Inits.push_back(nullptr);
10876     }
10877     ValueDecl *D = Res.first;
10878     if (!D)
10879       continue;
10880
10881     QualType Type = D->getType();
10882     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()) {
10888       Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
10889           << 0 << RefExpr->getSourceRange();
10890       continue;
10891     }
10892
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));
10932   }
10933
10934   if (MVLI.ProcessedVarList.empty())
10935     return nullptr;
10936
10937   return OMPUseDevicePtrClause::Create(
10938       Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
10939       PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
10940 }
10941
10942 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
10943                                               SourceLocation StartLoc,
10944                                               SourceLocation LParenLoc,
10945                                               SourceLocation EndLoc) {
10946   MappableVarListInfo MVLI(VarList);
10947   for (auto &RefExpr : VarList) {
10948     assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
10949     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.
10955       MVLI.ProcessedVarList.push_back(RefExpr);
10956     }
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     }
10969
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(
10984             D, /*CurrentRegionOnly=*/true,
10985             [&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);
11016   }
11017
11018   if (MVLI.ProcessedVarList.empty())
11019     return nullptr;
11020
11021   return OMPIsDevicePtrClause::Create(
11022       Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
11023       MVLI.VarBaseDeclarations, MVLI.VarComponents);
11024 }