1 //===--- CGStmtOpenMP.cpp - Emit LLVM Code from Statements ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This contains code to emit OpenMP nodes as LLVM code.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CGCleanup.h"
14 #include "CGOpenMPRuntime.h"
15 #include "CodeGenFunction.h"
16 #include "CodeGenModule.h"
17 #include "TargetInfo.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/Attr.h"
20 #include "clang/AST/DeclOpenMP.h"
21 #include "clang/AST/OpenMPClause.h"
22 #include "clang/AST/Stmt.h"
23 #include "clang/AST/StmtOpenMP.h"
24 #include "clang/Basic/PrettyStackTrace.h"
25 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
26 using namespace clang;
27 using namespace CodeGen;
28 using namespace llvm::omp;
29 
30 namespace {
31 /// Lexical scope for OpenMP executable constructs, that handles correct codegen
32 /// for captured expressions.
33 class OMPLexicalScope : public CodeGenFunction::LexicalScope {
34   void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
35     for (const auto *C : S.clauses()) {
36       if (const auto *CPI = OMPClauseWithPreInit::get(C)) {
37         if (const auto *PreInit =
38                 cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
39           for (const auto *I : PreInit->decls()) {
40             if (!I->hasAttr<OMPCaptureNoInitAttr>()) {
41               CGF.EmitVarDecl(cast<VarDecl>(*I));
42             } else {
43               CodeGenFunction::AutoVarEmission Emission =
44                   CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
45               CGF.EmitAutoVarCleanups(Emission);
46             }
47           }
48         }
49       }
50     }
51   }
52   CodeGenFunction::OMPPrivateScope InlinedShareds;
53 
54   static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
55     return CGF.LambdaCaptureFields.lookup(VD) ||
56            (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
57            (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl));
58   }
59 
60 public:
61   OMPLexicalScope(
62       CodeGenFunction &CGF, const OMPExecutableDirective &S,
63       const llvm::Optional<OpenMPDirectiveKind> CapturedRegion = llvm::None,
64       const bool EmitPreInitStmt = true)
65       : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
66         InlinedShareds(CGF) {
67     if (EmitPreInitStmt)
68       emitPreInitStmt(CGF, S);
69     if (!CapturedRegion.hasValue())
70       return;
71     assert(S.hasAssociatedStmt() &&
72            "Expected associated statement for inlined directive.");
73     const CapturedStmt *CS = S.getCapturedStmt(*CapturedRegion);
74     for (const auto &C : CS->captures()) {
75       if (C.capturesVariable() || C.capturesVariableByCopy()) {
76         auto *VD = C.getCapturedVar();
77         assert(VD == VD->getCanonicalDecl() &&
78                "Canonical decl must be captured.");
79         DeclRefExpr DRE(
80             CGF.getContext(), const_cast<VarDecl *>(VD),
81             isCapturedVar(CGF, VD) || (CGF.CapturedStmtInfo &&
82                                        InlinedShareds.isGlobalVarCaptured(VD)),
83             VD->getType().getNonReferenceType(), VK_LValue, C.getLocation());
84         InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
85           return CGF.EmitLValue(&DRE).getAddress(CGF);
86         });
87       }
88     }
89     (void)InlinedShareds.Privatize();
90   }
91 };
92 
93 /// Lexical scope for OpenMP parallel construct, that handles correct codegen
94 /// for captured expressions.
95 class OMPParallelScope final : public OMPLexicalScope {
96   bool EmitPreInitStmt(const OMPExecutableDirective &S) {
97     OpenMPDirectiveKind Kind = S.getDirectiveKind();
98     return !(isOpenMPTargetExecutionDirective(Kind) ||
99              isOpenMPLoopBoundSharingDirective(Kind)) &&
100            isOpenMPParallelDirective(Kind);
101   }
102 
103 public:
104   OMPParallelScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
105       : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None,
106                         EmitPreInitStmt(S)) {}
107 };
108 
109 /// Lexical scope for OpenMP teams construct, that handles correct codegen
110 /// for captured expressions.
111 class OMPTeamsScope final : public OMPLexicalScope {
112   bool EmitPreInitStmt(const OMPExecutableDirective &S) {
113     OpenMPDirectiveKind Kind = S.getDirectiveKind();
114     return !isOpenMPTargetExecutionDirective(Kind) &&
115            isOpenMPTeamsDirective(Kind);
116   }
117 
118 public:
119   OMPTeamsScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
120       : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None,
121                         EmitPreInitStmt(S)) {}
122 };
123 
124 /// Private scope for OpenMP loop-based directives, that supports capturing
125 /// of used expression from loop statement.
126 class OMPLoopScope : public CodeGenFunction::RunCleanupsScope {
127   void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopDirective &S) {
128     CodeGenFunction::OMPMapVars PreCondVars;
129     llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
130     for (const auto *E : S.counters()) {
131       const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
132       EmittedAsPrivate.insert(VD->getCanonicalDecl());
133       (void)PreCondVars.setVarAddr(
134           CGF, VD, CGF.CreateMemTemp(VD->getType().getNonReferenceType()));
135     }
136     // Mark private vars as undefs.
137     for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
138       for (const Expr *IRef : C->varlists()) {
139         const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
140         if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
141           (void)PreCondVars.setVarAddr(
142               CGF, OrigVD,
143               Address(llvm::UndefValue::get(
144                           CGF.ConvertTypeForMem(CGF.getContext().getPointerType(
145                               OrigVD->getType().getNonReferenceType()))),
146                       CGF.getContext().getDeclAlign(OrigVD)));
147         }
148       }
149     }
150     (void)PreCondVars.apply(CGF);
151     // Emit init, __range and __end variables for C++ range loops.
152     const Stmt *Body =
153         S.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers();
154     for (unsigned Cnt = 0; Cnt < S.getCollapsedNumber(); ++Cnt) {
155       Body = OMPLoopDirective::tryToFindNextInnerLoop(
156           Body, /*TryImperfectlyNestedLoops=*/true);
157       if (auto *For = dyn_cast<ForStmt>(Body)) {
158         Body = For->getBody();
159       } else {
160         assert(isa<CXXForRangeStmt>(Body) &&
161                "Expected canonical for loop or range-based for loop.");
162         auto *CXXFor = cast<CXXForRangeStmt>(Body);
163         if (const Stmt *Init = CXXFor->getInit())
164           CGF.EmitStmt(Init);
165         CGF.EmitStmt(CXXFor->getRangeStmt());
166         CGF.EmitStmt(CXXFor->getEndStmt());
167         Body = CXXFor->getBody();
168       }
169     }
170     if (const auto *PreInits = cast_or_null<DeclStmt>(S.getPreInits())) {
171       for (const auto *I : PreInits->decls())
172         CGF.EmitVarDecl(cast<VarDecl>(*I));
173     }
174     PreCondVars.restore(CGF);
175   }
176 
177 public:
178   OMPLoopScope(CodeGenFunction &CGF, const OMPLoopDirective &S)
179       : CodeGenFunction::RunCleanupsScope(CGF) {
180     emitPreInitStmt(CGF, S);
181   }
182 };
183 
184 class OMPSimdLexicalScope : public CodeGenFunction::LexicalScope {
185   CodeGenFunction::OMPPrivateScope InlinedShareds;
186 
187   static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
188     return CGF.LambdaCaptureFields.lookup(VD) ||
189            (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
190            (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl) &&
191             cast<BlockDecl>(CGF.CurCodeDecl)->capturesVariable(VD));
192   }
193 
194 public:
195   OMPSimdLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
196       : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
197         InlinedShareds(CGF) {
198     for (const auto *C : S.clauses()) {
199       if (const auto *CPI = OMPClauseWithPreInit::get(C)) {
200         if (const auto *PreInit =
201                 cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
202           for (const auto *I : PreInit->decls()) {
203             if (!I->hasAttr<OMPCaptureNoInitAttr>()) {
204               CGF.EmitVarDecl(cast<VarDecl>(*I));
205             } else {
206               CodeGenFunction::AutoVarEmission Emission =
207                   CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
208               CGF.EmitAutoVarCleanups(Emission);
209             }
210           }
211         }
212       } else if (const auto *UDP = dyn_cast<OMPUseDevicePtrClause>(C)) {
213         for (const Expr *E : UDP->varlists()) {
214           const Decl *D = cast<DeclRefExpr>(E)->getDecl();
215           if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(D))
216             CGF.EmitVarDecl(*OED);
217         }
218       }
219     }
220     if (!isOpenMPSimdDirective(S.getDirectiveKind()))
221       CGF.EmitOMPPrivateClause(S, InlinedShareds);
222     if (const auto *TG = dyn_cast<OMPTaskgroupDirective>(&S)) {
223       if (const Expr *E = TG->getReductionRef())
224         CGF.EmitVarDecl(*cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()));
225     }
226     const auto *CS = cast_or_null<CapturedStmt>(S.getAssociatedStmt());
227     while (CS) {
228       for (auto &C : CS->captures()) {
229         if (C.capturesVariable() || C.capturesVariableByCopy()) {
230           auto *VD = C.getCapturedVar();
231           assert(VD == VD->getCanonicalDecl() &&
232                  "Canonical decl must be captured.");
233           DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(VD),
234                           isCapturedVar(CGF, VD) ||
235                               (CGF.CapturedStmtInfo &&
236                                InlinedShareds.isGlobalVarCaptured(VD)),
237                           VD->getType().getNonReferenceType(), VK_LValue,
238                           C.getLocation());
239           InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
240             return CGF.EmitLValue(&DRE).getAddress(CGF);
241           });
242         }
243       }
244       CS = dyn_cast<CapturedStmt>(CS->getCapturedStmt());
245     }
246     (void)InlinedShareds.Privatize();
247   }
248 };
249 
250 } // namespace
251 
252 static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
253                                          const OMPExecutableDirective &S,
254                                          const RegionCodeGenTy &CodeGen);
255 
256 LValue CodeGenFunction::EmitOMPSharedLValue(const Expr *E) {
257   if (const auto *OrigDRE = dyn_cast<DeclRefExpr>(E)) {
258     if (const auto *OrigVD = dyn_cast<VarDecl>(OrigDRE->getDecl())) {
259       OrigVD = OrigVD->getCanonicalDecl();
260       bool IsCaptured =
261           LambdaCaptureFields.lookup(OrigVD) ||
262           (CapturedStmtInfo && CapturedStmtInfo->lookup(OrigVD)) ||
263           (CurCodeDecl && isa<BlockDecl>(CurCodeDecl));
264       DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD), IsCaptured,
265                       OrigDRE->getType(), VK_LValue, OrigDRE->getExprLoc());
266       return EmitLValue(&DRE);
267     }
268   }
269   return EmitLValue(E);
270 }
271 
272 llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
273   ASTContext &C = getContext();
274   llvm::Value *Size = nullptr;
275   auto SizeInChars = C.getTypeSizeInChars(Ty);
276   if (SizeInChars.isZero()) {
277     // getTypeSizeInChars() returns 0 for a VLA.
278     while (const VariableArrayType *VAT = C.getAsVariableArrayType(Ty)) {
279       VlaSizePair VlaSize = getVLASize(VAT);
280       Ty = VlaSize.Type;
281       Size = Size ? Builder.CreateNUWMul(Size, VlaSize.NumElts)
282                   : VlaSize.NumElts;
283     }
284     SizeInChars = C.getTypeSizeInChars(Ty);
285     if (SizeInChars.isZero())
286       return llvm::ConstantInt::get(SizeTy, /*V=*/0);
287     return Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
288   }
289   return CGM.getSize(SizeInChars);
290 }
291 
292 void CodeGenFunction::GenerateOpenMPCapturedVars(
293     const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
294   const RecordDecl *RD = S.getCapturedRecordDecl();
295   auto CurField = RD->field_begin();
296   auto CurCap = S.captures().begin();
297   for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
298                                                  E = S.capture_init_end();
299        I != E; ++I, ++CurField, ++CurCap) {
300     if (CurField->hasCapturedVLAType()) {
301       const VariableArrayType *VAT = CurField->getCapturedVLAType();
302       llvm::Value *Val = VLASizeMap[VAT->getSizeExpr()];
303       CapturedVars.push_back(Val);
304     } else if (CurCap->capturesThis()) {
305       CapturedVars.push_back(CXXThisValue);
306     } else if (CurCap->capturesVariableByCopy()) {
307       llvm::Value *CV = EmitLoadOfScalar(EmitLValue(*I), CurCap->getLocation());
308 
309       // If the field is not a pointer, we need to save the actual value
310       // and load it as a void pointer.
311       if (!CurField->getType()->isAnyPointerType()) {
312         ASTContext &Ctx = getContext();
313         Address DstAddr = CreateMemTemp(
314             Ctx.getUIntPtrType(),
315             Twine(CurCap->getCapturedVar()->getName(), ".casted"));
316         LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
317 
318         llvm::Value *SrcAddrVal = EmitScalarConversion(
319             DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
320             Ctx.getPointerType(CurField->getType()), CurCap->getLocation());
321         LValue SrcLV =
322             MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType());
323 
324         // Store the value using the source type pointer.
325         EmitStoreThroughLValue(RValue::get(CV), SrcLV);
326 
327         // Load the value using the destination type pointer.
328         CV = EmitLoadOfScalar(DstLV, CurCap->getLocation());
329       }
330       CapturedVars.push_back(CV);
331     } else {
332       assert(CurCap->capturesVariable() && "Expected capture by reference.");
333       CapturedVars.push_back(EmitLValue(*I).getAddress(*this).getPointer());
334     }
335   }
336 }
337 
338 static Address castValueFromUintptr(CodeGenFunction &CGF, SourceLocation Loc,
339                                     QualType DstType, StringRef Name,
340                                     LValue AddrLV) {
341   ASTContext &Ctx = CGF.getContext();
342 
343   llvm::Value *CastedPtr = CGF.EmitScalarConversion(
344       AddrLV.getAddress(CGF).getPointer(), Ctx.getUIntPtrType(),
345       Ctx.getPointerType(DstType), Loc);
346   Address TmpAddr =
347       CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
348           .getAddress(CGF);
349   return TmpAddr;
350 }
351 
352 static QualType getCanonicalParamType(ASTContext &C, QualType T) {
353   if (T->isLValueReferenceType())
354     return C.getLValueReferenceType(
355         getCanonicalParamType(C, T.getNonReferenceType()),
356         /*SpelledAsLValue=*/false);
357   if (T->isPointerType())
358     return C.getPointerType(getCanonicalParamType(C, T->getPointeeType()));
359   if (const ArrayType *A = T->getAsArrayTypeUnsafe()) {
360     if (const auto *VLA = dyn_cast<VariableArrayType>(A))
361       return getCanonicalParamType(C, VLA->getElementType());
362     if (!A->isVariablyModifiedType())
363       return C.getCanonicalType(T);
364   }
365   return C.getCanonicalParamType(T);
366 }
367 
368 namespace {
369 /// Contains required data for proper outlined function codegen.
370 struct FunctionOptions {
371   /// Captured statement for which the function is generated.
372   const CapturedStmt *S = nullptr;
373   /// true if cast to/from  UIntPtr is required for variables captured by
374   /// value.
375   const bool UIntPtrCastRequired = true;
376   /// true if only casted arguments must be registered as local args or VLA
377   /// sizes.
378   const bool RegisterCastedArgsOnly = false;
379   /// Name of the generated function.
380   const StringRef FunctionName;
381   /// Location of the non-debug version of the outlined function.
382   SourceLocation Loc;
383   explicit FunctionOptions(const CapturedStmt *S, bool UIntPtrCastRequired,
384                            bool RegisterCastedArgsOnly, StringRef FunctionName,
385                            SourceLocation Loc)
386       : S(S), UIntPtrCastRequired(UIntPtrCastRequired),
387         RegisterCastedArgsOnly(UIntPtrCastRequired && RegisterCastedArgsOnly),
388         FunctionName(FunctionName), Loc(Loc) {}
389 };
390 } // namespace
391 
392 static llvm::Function *emitOutlinedFunctionPrologue(
393     CodeGenFunction &CGF, FunctionArgList &Args,
394     llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>>
395         &LocalAddrs,
396     llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>>
397         &VLASizes,
398     llvm::Value *&CXXThisValue, const FunctionOptions &FO) {
399   const CapturedDecl *CD = FO.S->getCapturedDecl();
400   const RecordDecl *RD = FO.S->getCapturedRecordDecl();
401   assert(CD->hasBody() && "missing CapturedDecl body");
402 
403   CXXThisValue = nullptr;
404   // Build the argument list.
405   CodeGenModule &CGM = CGF.CGM;
406   ASTContext &Ctx = CGM.getContext();
407   FunctionArgList TargetArgs;
408   Args.append(CD->param_begin(),
409               std::next(CD->param_begin(), CD->getContextParamPosition()));
410   TargetArgs.append(
411       CD->param_begin(),
412       std::next(CD->param_begin(), CD->getContextParamPosition()));
413   auto I = FO.S->captures().begin();
414   FunctionDecl *DebugFunctionDecl = nullptr;
415   if (!FO.UIntPtrCastRequired) {
416     FunctionProtoType::ExtProtoInfo EPI;
417     QualType FunctionTy = Ctx.getFunctionType(Ctx.VoidTy, llvm::None, EPI);
418     DebugFunctionDecl = FunctionDecl::Create(
419         Ctx, Ctx.getTranslationUnitDecl(), FO.S->getBeginLoc(),
420         SourceLocation(), DeclarationName(), FunctionTy,
421         Ctx.getTrivialTypeSourceInfo(FunctionTy), SC_Static,
422         /*isInlineSpecified=*/false, /*hasWrittenPrototype=*/false);
423   }
424   for (const FieldDecl *FD : RD->fields()) {
425     QualType ArgType = FD->getType();
426     IdentifierInfo *II = nullptr;
427     VarDecl *CapVar = nullptr;
428 
429     // If this is a capture by copy and the type is not a pointer, the outlined
430     // function argument type should be uintptr and the value properly casted to
431     // uintptr. This is necessary given that the runtime library is only able to
432     // deal with pointers. We can pass in the same way the VLA type sizes to the
433     // outlined function.
434     if (FO.UIntPtrCastRequired &&
435         ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
436          I->capturesVariableArrayType()))
437       ArgType = Ctx.getUIntPtrType();
438 
439     if (I->capturesVariable() || I->capturesVariableByCopy()) {
440       CapVar = I->getCapturedVar();
441       II = CapVar->getIdentifier();
442     } else if (I->capturesThis()) {
443       II = &Ctx.Idents.get("this");
444     } else {
445       assert(I->capturesVariableArrayType());
446       II = &Ctx.Idents.get("vla");
447     }
448     if (ArgType->isVariablyModifiedType())
449       ArgType = getCanonicalParamType(Ctx, ArgType);
450     VarDecl *Arg;
451     if (DebugFunctionDecl && (CapVar || I->capturesThis())) {
452       Arg = ParmVarDecl::Create(
453           Ctx, DebugFunctionDecl,
454           CapVar ? CapVar->getBeginLoc() : FD->getBeginLoc(),
455           CapVar ? CapVar->getLocation() : FD->getLocation(), II, ArgType,
456           /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
457     } else {
458       Arg = ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(),
459                                       II, ArgType, ImplicitParamDecl::Other);
460     }
461     Args.emplace_back(Arg);
462     // Do not cast arguments if we emit function with non-original types.
463     TargetArgs.emplace_back(
464         FO.UIntPtrCastRequired
465             ? Arg
466             : CGM.getOpenMPRuntime().translateParameter(FD, Arg));
467     ++I;
468   }
469   Args.append(
470       std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
471       CD->param_end());
472   TargetArgs.append(
473       std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
474       CD->param_end());
475 
476   // Create the function declaration.
477   const CGFunctionInfo &FuncInfo =
478       CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, TargetArgs);
479   llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
480 
481   auto *F =
482       llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
483                              FO.FunctionName, &CGM.getModule());
484   CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
485   if (CD->isNothrow())
486     F->setDoesNotThrow();
487   F->setDoesNotRecurse();
488 
489   // Generate the function.
490   CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, TargetArgs,
491                     FO.UIntPtrCastRequired ? FO.Loc : FO.S->getBeginLoc(),
492                     FO.UIntPtrCastRequired ? FO.Loc
493                                            : CD->getBody()->getBeginLoc());
494   unsigned Cnt = CD->getContextParamPosition();
495   I = FO.S->captures().begin();
496   for (const FieldDecl *FD : RD->fields()) {
497     // Do not map arguments if we emit function with non-original types.
498     Address LocalAddr(Address::invalid());
499     if (!FO.UIntPtrCastRequired && Args[Cnt] != TargetArgs[Cnt]) {
500       LocalAddr = CGM.getOpenMPRuntime().getParameterAddress(CGF, Args[Cnt],
501                                                              TargetArgs[Cnt]);
502     } else {
503       LocalAddr = CGF.GetAddrOfLocalVar(Args[Cnt]);
504     }
505     // If we are capturing a pointer by copy we don't need to do anything, just
506     // use the value that we get from the arguments.
507     if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
508       const VarDecl *CurVD = I->getCapturedVar();
509       if (!FO.RegisterCastedArgsOnly)
510         LocalAddrs.insert({Args[Cnt], {CurVD, LocalAddr}});
511       ++Cnt;
512       ++I;
513       continue;
514     }
515 
516     LValue ArgLVal = CGF.MakeAddrLValue(LocalAddr, Args[Cnt]->getType(),
517                                         AlignmentSource::Decl);
518     if (FD->hasCapturedVLAType()) {
519       if (FO.UIntPtrCastRequired) {
520         ArgLVal = CGF.MakeAddrLValue(
521             castValueFromUintptr(CGF, I->getLocation(), FD->getType(),
522                                  Args[Cnt]->getName(), ArgLVal),
523             FD->getType(), AlignmentSource::Decl);
524       }
525       llvm::Value *ExprArg = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation());
526       const VariableArrayType *VAT = FD->getCapturedVLAType();
527       VLASizes.try_emplace(Args[Cnt], VAT->getSizeExpr(), ExprArg);
528     } else if (I->capturesVariable()) {
529       const VarDecl *Var = I->getCapturedVar();
530       QualType VarTy = Var->getType();
531       Address ArgAddr = ArgLVal.getAddress(CGF);
532       if (ArgLVal.getType()->isLValueReferenceType()) {
533         ArgAddr = CGF.EmitLoadOfReference(ArgLVal);
534       } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) {
535         assert(ArgLVal.getType()->isPointerType());
536         ArgAddr = CGF.EmitLoadOfPointer(
537             ArgAddr, ArgLVal.getType()->castAs<PointerType>());
538       }
539       if (!FO.RegisterCastedArgsOnly) {
540         LocalAddrs.insert(
541             {Args[Cnt],
542              {Var, Address(ArgAddr.getPointer(), Ctx.getDeclAlign(Var))}});
543       }
544     } else if (I->capturesVariableByCopy()) {
545       assert(!FD->getType()->isAnyPointerType() &&
546              "Not expecting a captured pointer.");
547       const VarDecl *Var = I->getCapturedVar();
548       LocalAddrs.insert({Args[Cnt],
549                          {Var, FO.UIntPtrCastRequired
550                                    ? castValueFromUintptr(
551                                          CGF, I->getLocation(), FD->getType(),
552                                          Args[Cnt]->getName(), ArgLVal)
553                                    : ArgLVal.getAddress(CGF)}});
554     } else {
555       // If 'this' is captured, load it into CXXThisValue.
556       assert(I->capturesThis());
557       CXXThisValue = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation());
558       LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress(CGF)}});
559     }
560     ++Cnt;
561     ++I;
562   }
563 
564   return F;
565 }
566 
567 llvm::Function *
568 CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S,
569                                                     SourceLocation Loc) {
570   assert(
571       CapturedStmtInfo &&
572       "CapturedStmtInfo should be set when generating the captured function");
573   const CapturedDecl *CD = S.getCapturedDecl();
574   // Build the argument list.
575   bool NeedWrapperFunction =
576       getDebugInfo() && CGM.getCodeGenOpts().hasReducedDebugInfo();
577   FunctionArgList Args;
578   llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs;
579   llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes;
580   SmallString<256> Buffer;
581   llvm::raw_svector_ostream Out(Buffer);
582   Out << CapturedStmtInfo->getHelperName();
583   if (NeedWrapperFunction)
584     Out << "_debug__";
585   FunctionOptions FO(&S, !NeedWrapperFunction, /*RegisterCastedArgsOnly=*/false,
586                      Out.str(), Loc);
587   llvm::Function *F = emitOutlinedFunctionPrologue(*this, Args, LocalAddrs,
588                                                    VLASizes, CXXThisValue, FO);
589   CodeGenFunction::OMPPrivateScope LocalScope(*this);
590   for (const auto &LocalAddrPair : LocalAddrs) {
591     if (LocalAddrPair.second.first) {
592       LocalScope.addPrivate(LocalAddrPair.second.first, [&LocalAddrPair]() {
593         return LocalAddrPair.second.second;
594       });
595     }
596   }
597   (void)LocalScope.Privatize();
598   for (const auto &VLASizePair : VLASizes)
599     VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second;
600   PGO.assignRegionCounters(GlobalDecl(CD), F);
601   CapturedStmtInfo->EmitBody(*this, CD->getBody());
602   (void)LocalScope.ForceCleanup();
603   FinishFunction(CD->getBodyRBrace());
604   if (!NeedWrapperFunction)
605     return F;
606 
607   FunctionOptions WrapperFO(&S, /*UIntPtrCastRequired=*/true,
608                             /*RegisterCastedArgsOnly=*/true,
609                             CapturedStmtInfo->getHelperName(), Loc);
610   CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true);
611   WrapperCGF.CapturedStmtInfo = CapturedStmtInfo;
612   Args.clear();
613   LocalAddrs.clear();
614   VLASizes.clear();
615   llvm::Function *WrapperF =
616       emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes,
617                                    WrapperCGF.CXXThisValue, WrapperFO);
618   llvm::SmallVector<llvm::Value *, 4> CallArgs;
619   for (const auto *Arg : Args) {
620     llvm::Value *CallArg;
621     auto I = LocalAddrs.find(Arg);
622     if (I != LocalAddrs.end()) {
623       LValue LV = WrapperCGF.MakeAddrLValue(
624           I->second.second,
625           I->second.first ? I->second.first->getType() : Arg->getType(),
626           AlignmentSource::Decl);
627       CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getBeginLoc());
628     } else {
629       auto EI = VLASizes.find(Arg);
630       if (EI != VLASizes.end()) {
631         CallArg = EI->second.second;
632       } else {
633         LValue LV = WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg),
634                                               Arg->getType(),
635                                               AlignmentSource::Decl);
636         CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getBeginLoc());
637       }
638     }
639     CallArgs.emplace_back(WrapperCGF.EmitFromMemory(CallArg, Arg->getType()));
640   }
641   CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, Loc, F, CallArgs);
642   WrapperCGF.FinishFunction();
643   return WrapperF;
644 }
645 
646 //===----------------------------------------------------------------------===//
647 //                              OpenMP Directive Emission
648 //===----------------------------------------------------------------------===//
649 void CodeGenFunction::EmitOMPAggregateAssign(
650     Address DestAddr, Address SrcAddr, QualType OriginalType,
651     const llvm::function_ref<void(Address, Address)> CopyGen) {
652   // Perform element-by-element initialization.
653   QualType ElementTy;
654 
655   // Drill down to the base element type on both arrays.
656   const ArrayType *ArrayTy = OriginalType->getAsArrayTypeUnsafe();
657   llvm::Value *NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
658   SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
659 
660   llvm::Value *SrcBegin = SrcAddr.getPointer();
661   llvm::Value *DestBegin = DestAddr.getPointer();
662   // Cast from pointer to array type to pointer to single element.
663   llvm::Value *DestEnd = Builder.CreateGEP(DestBegin, NumElements);
664   // The basic structure here is a while-do loop.
665   llvm::BasicBlock *BodyBB = createBasicBlock("omp.arraycpy.body");
666   llvm::BasicBlock *DoneBB = createBasicBlock("omp.arraycpy.done");
667   llvm::Value *IsEmpty =
668       Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
669   Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
670 
671   // Enter the loop body, making that address the current address.
672   llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
673   EmitBlock(BodyBB);
674 
675   CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
676 
677   llvm::PHINode *SrcElementPHI =
678     Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
679   SrcElementPHI->addIncoming(SrcBegin, EntryBB);
680   Address SrcElementCurrent =
681       Address(SrcElementPHI,
682               SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
683 
684   llvm::PHINode *DestElementPHI =
685     Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
686   DestElementPHI->addIncoming(DestBegin, EntryBB);
687   Address DestElementCurrent =
688     Address(DestElementPHI,
689             DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
690 
691   // Emit copy.
692   CopyGen(DestElementCurrent, SrcElementCurrent);
693 
694   // Shift the address forward by one element.
695   llvm::Value *DestElementNext = Builder.CreateConstGEP1_32(
696       DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
697   llvm::Value *SrcElementNext = Builder.CreateConstGEP1_32(
698       SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
699   // Check whether we've reached the end.
700   llvm::Value *Done =
701       Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
702   Builder.CreateCondBr(Done, DoneBB, BodyBB);
703   DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
704   SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
705 
706   // Done.
707   EmitBlock(DoneBB, /*IsFinished=*/true);
708 }
709 
710 void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
711                                   Address SrcAddr, const VarDecl *DestVD,
712                                   const VarDecl *SrcVD, const Expr *Copy) {
713   if (OriginalType->isArrayType()) {
714     const auto *BO = dyn_cast<BinaryOperator>(Copy);
715     if (BO && BO->getOpcode() == BO_Assign) {
716       // Perform simple memcpy for simple copying.
717       LValue Dest = MakeAddrLValue(DestAddr, OriginalType);
718       LValue Src = MakeAddrLValue(SrcAddr, OriginalType);
719       EmitAggregateAssign(Dest, Src, OriginalType);
720     } else {
721       // For arrays with complex element types perform element by element
722       // copying.
723       EmitOMPAggregateAssign(
724           DestAddr, SrcAddr, OriginalType,
725           [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
726             // Working with the single array element, so have to remap
727             // destination and source variables to corresponding array
728             // elements.
729             CodeGenFunction::OMPPrivateScope Remap(*this);
730             Remap.addPrivate(DestVD, [DestElement]() { return DestElement; });
731             Remap.addPrivate(SrcVD, [SrcElement]() { return SrcElement; });
732             (void)Remap.Privatize();
733             EmitIgnoredExpr(Copy);
734           });
735     }
736   } else {
737     // Remap pseudo source variable to private copy.
738     CodeGenFunction::OMPPrivateScope Remap(*this);
739     Remap.addPrivate(SrcVD, [SrcAddr]() { return SrcAddr; });
740     Remap.addPrivate(DestVD, [DestAddr]() { return DestAddr; });
741     (void)Remap.Privatize();
742     // Emit copying of the whole variable.
743     EmitIgnoredExpr(Copy);
744   }
745 }
746 
747 bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
748                                                 OMPPrivateScope &PrivateScope) {
749   if (!HaveInsertPoint())
750     return false;
751   bool DeviceConstTarget =
752       getLangOpts().OpenMPIsDevice &&
753       isOpenMPTargetExecutionDirective(D.getDirectiveKind());
754   bool FirstprivateIsLastprivate = false;
755   llvm::DenseMap<const VarDecl *, OpenMPLastprivateModifier> Lastprivates;
756   for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
757     for (const auto *D : C->varlists())
758       Lastprivates.try_emplace(
759           cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl(),
760           C->getKind());
761   }
762   llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
763   llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
764   getOpenMPCaptureRegions(CaptureRegions, D.getDirectiveKind());
765   // Force emission of the firstprivate copy if the directive does not emit
766   // outlined function, like omp for, omp simd, omp distribute etc.
767   bool MustEmitFirstprivateCopy =
768       CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown;
769   for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
770     const auto *IRef = C->varlist_begin();
771     const auto *InitsRef = C->inits().begin();
772     for (const Expr *IInit : C->private_copies()) {
773       const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
774       bool ThisFirstprivateIsLastprivate =
775           Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
776       const FieldDecl *FD = CapturedStmtInfo->lookup(OrigVD);
777       const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
778       if (!MustEmitFirstprivateCopy && !ThisFirstprivateIsLastprivate && FD &&
779           !FD->getType()->isReferenceType() &&
780           (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())) {
781         EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
782         ++IRef;
783         ++InitsRef;
784         continue;
785       }
786       // Do not emit copy for firstprivate constant variables in target regions,
787       // captured by reference.
788       if (DeviceConstTarget && OrigVD->getType().isConstant(getContext()) &&
789           FD && FD->getType()->isReferenceType() &&
790           (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())) {
791         (void)CGM.getOpenMPRuntime().registerTargetFirstprivateCopy(*this,
792                                                                     OrigVD);
793         ++IRef;
794         ++InitsRef;
795         continue;
796       }
797       FirstprivateIsLastprivate =
798           FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
799       if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
800         const auto *VDInit =
801             cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
802         bool IsRegistered;
803         DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
804                         /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
805                         (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
806         LValue OriginalLVal;
807         if (!FD) {
808           // Check if the firstprivate variable is just a constant value.
809           ConstantEmission CE = tryEmitAsConstant(&DRE);
810           if (CE && !CE.isReference()) {
811             // Constant value, no need to create a copy.
812             ++IRef;
813             ++InitsRef;
814             continue;
815           }
816           if (CE && CE.isReference()) {
817             OriginalLVal = CE.getReferenceLValue(*this, &DRE);
818           } else {
819             assert(!CE && "Expected non-constant firstprivate.");
820             OriginalLVal = EmitLValue(&DRE);
821           }
822         } else {
823           OriginalLVal = EmitLValue(&DRE);
824         }
825         QualType Type = VD->getType();
826         if (Type->isArrayType()) {
827           // Emit VarDecl with copy init for arrays.
828           // Get the address of the original variable captured in current
829           // captured region.
830           IsRegistered = PrivateScope.addPrivate(
831               OrigVD, [this, VD, Type, OriginalLVal, VDInit]() {
832                 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
833                 const Expr *Init = VD->getInit();
834                 if (!isa<CXXConstructExpr>(Init) ||
835                     isTrivialInitializer(Init)) {
836                   // Perform simple memcpy.
837                   LValue Dest =
838                       MakeAddrLValue(Emission.getAllocatedAddress(), Type);
839                   EmitAggregateAssign(Dest, OriginalLVal, Type);
840                 } else {
841                   EmitOMPAggregateAssign(
842                       Emission.getAllocatedAddress(),
843                       OriginalLVal.getAddress(*this), Type,
844                       [this, VDInit, Init](Address DestElement,
845                                            Address SrcElement) {
846                         // Clean up any temporaries needed by the
847                         // initialization.
848                         RunCleanupsScope InitScope(*this);
849                         // Emit initialization for single element.
850                         setAddrOfLocalVar(VDInit, SrcElement);
851                         EmitAnyExprToMem(Init, DestElement,
852                                          Init->getType().getQualifiers(),
853                                          /*IsInitializer*/ false);
854                         LocalDeclMap.erase(VDInit);
855                       });
856                 }
857                 EmitAutoVarCleanups(Emission);
858                 return Emission.getAllocatedAddress();
859               });
860         } else {
861           Address OriginalAddr = OriginalLVal.getAddress(*this);
862           IsRegistered =
863               PrivateScope.addPrivate(OrigVD, [this, VDInit, OriginalAddr, VD,
864                                                ThisFirstprivateIsLastprivate,
865                                                OrigVD, &Lastprivates, IRef]() {
866                 // Emit private VarDecl with copy init.
867                 // Remap temp VDInit variable to the address of the original
868                 // variable (for proper handling of captured global variables).
869                 setAddrOfLocalVar(VDInit, OriginalAddr);
870                 EmitDecl(*VD);
871                 LocalDeclMap.erase(VDInit);
872                 if (ThisFirstprivateIsLastprivate &&
873                     Lastprivates[OrigVD->getCanonicalDecl()] ==
874                         OMPC_LASTPRIVATE_conditional) {
875                   // Create/init special variable for lastprivate conditionals.
876                   Address VDAddr =
877                       CGM.getOpenMPRuntime().emitLastprivateConditionalInit(
878                           *this, OrigVD);
879                   llvm::Value *V = EmitLoadOfScalar(
880                       MakeAddrLValue(GetAddrOfLocalVar(VD), (*IRef)->getType(),
881                                      AlignmentSource::Decl),
882                       (*IRef)->getExprLoc());
883                   EmitStoreOfScalar(V,
884                                     MakeAddrLValue(VDAddr, (*IRef)->getType(),
885                                                    AlignmentSource::Decl));
886                   LocalDeclMap.erase(VD);
887                   setAddrOfLocalVar(VD, VDAddr);
888                   return VDAddr;
889                 }
890                 return GetAddrOfLocalVar(VD);
891               });
892         }
893         assert(IsRegistered &&
894                "firstprivate var already registered as private");
895         // Silence the warning about unused variable.
896         (void)IsRegistered;
897       }
898       ++IRef;
899       ++InitsRef;
900     }
901   }
902   return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
903 }
904 
905 void CodeGenFunction::EmitOMPPrivateClause(
906     const OMPExecutableDirective &D,
907     CodeGenFunction::OMPPrivateScope &PrivateScope) {
908   if (!HaveInsertPoint())
909     return;
910   llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
911   for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
912     auto IRef = C->varlist_begin();
913     for (const Expr *IInit : C->private_copies()) {
914       const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
915       if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
916         const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
917         bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, VD]() {
918           // Emit private VarDecl with copy init.
919           EmitDecl(*VD);
920           return GetAddrOfLocalVar(VD);
921         });
922         assert(IsRegistered && "private var already registered as private");
923         // Silence the warning about unused variable.
924         (void)IsRegistered;
925       }
926       ++IRef;
927     }
928   }
929 }
930 
931 bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
932   if (!HaveInsertPoint())
933     return false;
934   // threadprivate_var1 = master_threadprivate_var1;
935   // operator=(threadprivate_var2, master_threadprivate_var2);
936   // ...
937   // __kmpc_barrier(&loc, global_tid);
938   llvm::DenseSet<const VarDecl *> CopiedVars;
939   llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
940   for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
941     auto IRef = C->varlist_begin();
942     auto ISrcRef = C->source_exprs().begin();
943     auto IDestRef = C->destination_exprs().begin();
944     for (const Expr *AssignOp : C->assignment_ops()) {
945       const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
946       QualType Type = VD->getType();
947       if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
948         // Get the address of the master variable. If we are emitting code with
949         // TLS support, the address is passed from the master as field in the
950         // captured declaration.
951         Address MasterAddr = Address::invalid();
952         if (getLangOpts().OpenMPUseTLS &&
953             getContext().getTargetInfo().isTLSSupported()) {
954           assert(CapturedStmtInfo->lookup(VD) &&
955                  "Copyin threadprivates should have been captured!");
956           DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(VD), true,
957                           (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
958           MasterAddr = EmitLValue(&DRE).getAddress(*this);
959           LocalDeclMap.erase(VD);
960         } else {
961           MasterAddr =
962             Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
963                                         : CGM.GetAddrOfGlobal(VD),
964                     getContext().getDeclAlign(VD));
965         }
966         // Get the address of the threadprivate variable.
967         Address PrivateAddr = EmitLValue(*IRef).getAddress(*this);
968         if (CopiedVars.size() == 1) {
969           // At first check if current thread is a master thread. If it is, no
970           // need to copy data.
971           CopyBegin = createBasicBlock("copyin.not.master");
972           CopyEnd = createBasicBlock("copyin.not.master.end");
973           Builder.CreateCondBr(
974               Builder.CreateICmpNE(
975                   Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
976                   Builder.CreatePtrToInt(PrivateAddr.getPointer(),
977                                          CGM.IntPtrTy)),
978               CopyBegin, CopyEnd);
979           EmitBlock(CopyBegin);
980         }
981         const auto *SrcVD =
982             cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
983         const auto *DestVD =
984             cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
985         EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
986       }
987       ++IRef;
988       ++ISrcRef;
989       ++IDestRef;
990     }
991   }
992   if (CopyEnd) {
993     // Exit out of copying procedure for non-master thread.
994     EmitBlock(CopyEnd, /*IsFinished=*/true);
995     return true;
996   }
997   return false;
998 }
999 
1000 bool CodeGenFunction::EmitOMPLastprivateClauseInit(
1001     const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
1002   if (!HaveInsertPoint())
1003     return false;
1004   bool HasAtLeastOneLastprivate = false;
1005   llvm::DenseSet<const VarDecl *> SIMDLCVs;
1006   if (isOpenMPSimdDirective(D.getDirectiveKind())) {
1007     const auto *LoopDirective = cast<OMPLoopDirective>(&D);
1008     for (const Expr *C : LoopDirective->counters()) {
1009       SIMDLCVs.insert(
1010           cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1011     }
1012   }
1013   llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
1014   for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
1015     HasAtLeastOneLastprivate = true;
1016     if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
1017         !getLangOpts().OpenMPSimd)
1018       break;
1019     const auto *IRef = C->varlist_begin();
1020     const auto *IDestRef = C->destination_exprs().begin();
1021     for (const Expr *IInit : C->private_copies()) {
1022       // Keep the address of the original variable for future update at the end
1023       // of the loop.
1024       const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1025       // Taskloops do not require additional initialization, it is done in
1026       // runtime support library.
1027       if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
1028         const auto *DestVD =
1029             cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
1030         PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() {
1031           DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
1032                           /*RefersToEnclosingVariableOrCapture=*/
1033                               CapturedStmtInfo->lookup(OrigVD) != nullptr,
1034                           (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
1035           return EmitLValue(&DRE).getAddress(*this);
1036         });
1037         // Check if the variable is also a firstprivate: in this case IInit is
1038         // not generated. Initialization of this variable will happen in codegen
1039         // for 'firstprivate' clause.
1040         if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
1041           const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
1042           bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, VD, C,
1043                                                                OrigVD]() {
1044             if (C->getKind() == OMPC_LASTPRIVATE_conditional) {
1045               Address VDAddr =
1046                   CGM.getOpenMPRuntime().emitLastprivateConditionalInit(*this,
1047                                                                         OrigVD);
1048               setAddrOfLocalVar(VD, VDAddr);
1049               return VDAddr;
1050             }
1051             // Emit private VarDecl with copy init.
1052             EmitDecl(*VD);
1053             return GetAddrOfLocalVar(VD);
1054           });
1055           assert(IsRegistered &&
1056                  "lastprivate var already registered as private");
1057           (void)IsRegistered;
1058         }
1059       }
1060       ++IRef;
1061       ++IDestRef;
1062     }
1063   }
1064   return HasAtLeastOneLastprivate;
1065 }
1066 
1067 void CodeGenFunction::EmitOMPLastprivateClauseFinal(
1068     const OMPExecutableDirective &D, bool NoFinals,
1069     llvm::Value *IsLastIterCond) {
1070   if (!HaveInsertPoint())
1071     return;
1072   // Emit following code:
1073   // if (<IsLastIterCond>) {
1074   //   orig_var1 = private_orig_var1;
1075   //   ...
1076   //   orig_varn = private_orig_varn;
1077   // }
1078   llvm::BasicBlock *ThenBB = nullptr;
1079   llvm::BasicBlock *DoneBB = nullptr;
1080   if (IsLastIterCond) {
1081     // Emit implicit barrier if at least one lastprivate conditional is found
1082     // and this is not a simd mode.
1083     if (!getLangOpts().OpenMPSimd &&
1084         llvm::any_of(D.getClausesOfKind<OMPLastprivateClause>(),
1085                      [](const OMPLastprivateClause *C) {
1086                        return C->getKind() == OMPC_LASTPRIVATE_conditional;
1087                      })) {
1088       CGM.getOpenMPRuntime().emitBarrierCall(*this, D.getBeginLoc(),
1089                                              OMPD_unknown,
1090                                              /*EmitChecks=*/false,
1091                                              /*ForceSimpleCall=*/true);
1092     }
1093     ThenBB = createBasicBlock(".omp.lastprivate.then");
1094     DoneBB = createBasicBlock(".omp.lastprivate.done");
1095     Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
1096     EmitBlock(ThenBB);
1097   }
1098   llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
1099   llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
1100   if (const auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
1101     auto IC = LoopDirective->counters().begin();
1102     for (const Expr *F : LoopDirective->finals()) {
1103       const auto *D =
1104           cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
1105       if (NoFinals)
1106         AlreadyEmittedVars.insert(D);
1107       else
1108         LoopCountersAndUpdates[D] = F;
1109       ++IC;
1110     }
1111   }
1112   for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
1113     auto IRef = C->varlist_begin();
1114     auto ISrcRef = C->source_exprs().begin();
1115     auto IDestRef = C->destination_exprs().begin();
1116     for (const Expr *AssignOp : C->assignment_ops()) {
1117       const auto *PrivateVD =
1118           cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1119       QualType Type = PrivateVD->getType();
1120       const auto *CanonicalVD = PrivateVD->getCanonicalDecl();
1121       if (AlreadyEmittedVars.insert(CanonicalVD).second) {
1122         // If lastprivate variable is a loop control variable for loop-based
1123         // directive, update its value before copyin back to original
1124         // variable.
1125         if (const Expr *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
1126           EmitIgnoredExpr(FinalExpr);
1127         const auto *SrcVD =
1128             cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
1129         const auto *DestVD =
1130             cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
1131         // Get the address of the private variable.
1132         Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
1133         if (const auto *RefTy = PrivateVD->getType()->getAs<ReferenceType>())
1134           PrivateAddr =
1135               Address(Builder.CreateLoad(PrivateAddr),
1136                       getNaturalTypeAlignment(RefTy->getPointeeType()));
1137         // Store the last value to the private copy in the last iteration.
1138         if (C->getKind() == OMPC_LASTPRIVATE_conditional)
1139           CGM.getOpenMPRuntime().emitLastprivateConditionalFinalUpdate(
1140               *this, MakeAddrLValue(PrivateAddr, (*IRef)->getType()), PrivateVD,
1141               (*IRef)->getExprLoc());
1142         // Get the address of the original variable.
1143         Address OriginalAddr = GetAddrOfLocalVar(DestVD);
1144         EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
1145       }
1146       ++IRef;
1147       ++ISrcRef;
1148       ++IDestRef;
1149     }
1150     if (const Expr *PostUpdate = C->getPostUpdateExpr())
1151       EmitIgnoredExpr(PostUpdate);
1152   }
1153   if (IsLastIterCond)
1154     EmitBlock(DoneBB, /*IsFinished=*/true);
1155 }
1156 
1157 void CodeGenFunction::EmitOMPReductionClauseInit(
1158     const OMPExecutableDirective &D,
1159     CodeGenFunction::OMPPrivateScope &PrivateScope) {
1160   if (!HaveInsertPoint())
1161     return;
1162   SmallVector<const Expr *, 4> Shareds;
1163   SmallVector<const Expr *, 4> Privates;
1164   SmallVector<const Expr *, 4> ReductionOps;
1165   SmallVector<const Expr *, 4> LHSs;
1166   SmallVector<const Expr *, 4> RHSs;
1167   for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1168     auto IPriv = C->privates().begin();
1169     auto IRed = C->reduction_ops().begin();
1170     auto ILHS = C->lhs_exprs().begin();
1171     auto IRHS = C->rhs_exprs().begin();
1172     for (const Expr *Ref : C->varlists()) {
1173       Shareds.emplace_back(Ref);
1174       Privates.emplace_back(*IPriv);
1175       ReductionOps.emplace_back(*IRed);
1176       LHSs.emplace_back(*ILHS);
1177       RHSs.emplace_back(*IRHS);
1178       std::advance(IPriv, 1);
1179       std::advance(IRed, 1);
1180       std::advance(ILHS, 1);
1181       std::advance(IRHS, 1);
1182     }
1183   }
1184   ReductionCodeGen RedCG(Shareds, Privates, ReductionOps);
1185   unsigned Count = 0;
1186   auto ILHS = LHSs.begin();
1187   auto IRHS = RHSs.begin();
1188   auto IPriv = Privates.begin();
1189   for (const Expr *IRef : Shareds) {
1190     const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
1191     // Emit private VarDecl with reduction init.
1192     RedCG.emitSharedLValue(*this, Count);
1193     RedCG.emitAggregateType(*this, Count);
1194     AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
1195     RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(),
1196                              RedCG.getSharedLValue(Count),
1197                              [&Emission](CodeGenFunction &CGF) {
1198                                CGF.EmitAutoVarInit(Emission);
1199                                return true;
1200                              });
1201     EmitAutoVarCleanups(Emission);
1202     Address BaseAddr = RedCG.adjustPrivateAddress(
1203         *this, Count, Emission.getAllocatedAddress());
1204     bool IsRegistered = PrivateScope.addPrivate(
1205         RedCG.getBaseDecl(Count), [BaseAddr]() { return BaseAddr; });
1206     assert(IsRegistered && "private var already registered as private");
1207     // Silence the warning about unused variable.
1208     (void)IsRegistered;
1209 
1210     const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
1211     const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
1212     QualType Type = PrivateVD->getType();
1213     bool isaOMPArraySectionExpr = isa<OMPArraySectionExpr>(IRef);
1214     if (isaOMPArraySectionExpr && Type->isVariablyModifiedType()) {
1215       // Store the address of the original variable associated with the LHS
1216       // implicit variable.
1217       PrivateScope.addPrivate(LHSVD, [&RedCG, Count, this]() {
1218         return RedCG.getSharedLValue(Count).getAddress(*this);
1219       });
1220       PrivateScope.addPrivate(
1221           RHSVD, [this, PrivateVD]() { return GetAddrOfLocalVar(PrivateVD); });
1222     } else if ((isaOMPArraySectionExpr && Type->isScalarType()) ||
1223                isa<ArraySubscriptExpr>(IRef)) {
1224       // Store the address of the original variable associated with the LHS
1225       // implicit variable.
1226       PrivateScope.addPrivate(LHSVD, [&RedCG, Count, this]() {
1227         return RedCG.getSharedLValue(Count).getAddress(*this);
1228       });
1229       PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() {
1230         return Builder.CreateElementBitCast(GetAddrOfLocalVar(PrivateVD),
1231                                             ConvertTypeForMem(RHSVD->getType()),
1232                                             "rhs.begin");
1233       });
1234     } else {
1235       QualType Type = PrivateVD->getType();
1236       bool IsArray = getContext().getAsArrayType(Type) != nullptr;
1237       Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress(*this);
1238       // Store the address of the original variable associated with the LHS
1239       // implicit variable.
1240       if (IsArray) {
1241         OriginalAddr = Builder.CreateElementBitCast(
1242             OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
1243       }
1244       PrivateScope.addPrivate(LHSVD, [OriginalAddr]() { return OriginalAddr; });
1245       PrivateScope.addPrivate(
1246           RHSVD, [this, PrivateVD, RHSVD, IsArray]() {
1247             return IsArray
1248                        ? Builder.CreateElementBitCast(
1249                              GetAddrOfLocalVar(PrivateVD),
1250                              ConvertTypeForMem(RHSVD->getType()), "rhs.begin")
1251                        : GetAddrOfLocalVar(PrivateVD);
1252           });
1253     }
1254     ++ILHS;
1255     ++IRHS;
1256     ++IPriv;
1257     ++Count;
1258   }
1259 }
1260 
1261 void CodeGenFunction::EmitOMPReductionClauseFinal(
1262     const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
1263   if (!HaveInsertPoint())
1264     return;
1265   llvm::SmallVector<const Expr *, 8> Privates;
1266   llvm::SmallVector<const Expr *, 8> LHSExprs;
1267   llvm::SmallVector<const Expr *, 8> RHSExprs;
1268   llvm::SmallVector<const Expr *, 8> ReductionOps;
1269   bool HasAtLeastOneReduction = false;
1270   for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1271     HasAtLeastOneReduction = true;
1272     Privates.append(C->privates().begin(), C->privates().end());
1273     LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1274     RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1275     ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1276   }
1277   if (HasAtLeastOneReduction) {
1278     bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
1279                       isOpenMPParallelDirective(D.getDirectiveKind()) ||
1280                       ReductionKind == OMPD_simd;
1281     bool SimpleReduction = ReductionKind == OMPD_simd;
1282     // Emit nowait reduction if nowait clause is present or directive is a
1283     // parallel directive (it always has implicit barrier).
1284     CGM.getOpenMPRuntime().emitReduction(
1285         *this, D.getEndLoc(), Privates, LHSExprs, RHSExprs, ReductionOps,
1286         {WithNowait, SimpleReduction, ReductionKind});
1287   }
1288 }
1289 
1290 static void emitPostUpdateForReductionClause(
1291     CodeGenFunction &CGF, const OMPExecutableDirective &D,
1292     const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
1293   if (!CGF.HaveInsertPoint())
1294     return;
1295   llvm::BasicBlock *DoneBB = nullptr;
1296   for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1297     if (const Expr *PostUpdate = C->getPostUpdateExpr()) {
1298       if (!DoneBB) {
1299         if (llvm::Value *Cond = CondGen(CGF)) {
1300           // If the first post-update expression is found, emit conditional
1301           // block if it was requested.
1302           llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
1303           DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1304           CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1305           CGF.EmitBlock(ThenBB);
1306         }
1307       }
1308       CGF.EmitIgnoredExpr(PostUpdate);
1309     }
1310   }
1311   if (DoneBB)
1312     CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1313 }
1314 
1315 namespace {
1316 /// Codegen lambda for appending distribute lower and upper bounds to outlined
1317 /// parallel function. This is necessary for combined constructs such as
1318 /// 'distribute parallel for'
1319 typedef llvm::function_ref<void(CodeGenFunction &,
1320                                 const OMPExecutableDirective &,
1321                                 llvm::SmallVectorImpl<llvm::Value *> &)>
1322     CodeGenBoundParametersTy;
1323 } // anonymous namespace
1324 
1325 static void
1326 checkForLastprivateConditionalUpdate(CodeGenFunction &CGF,
1327                                      const OMPExecutableDirective &S) {
1328   if (CGF.getLangOpts().OpenMP < 50)
1329     return;
1330   llvm::DenseSet<CanonicalDeclPtr<const VarDecl>> PrivateDecls;
1331   for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
1332     for (const Expr *Ref : C->varlists()) {
1333       if (!Ref->getType()->isScalarType())
1334         continue;
1335       const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts());
1336       if (!DRE)
1337         continue;
1338       PrivateDecls.insert(cast<VarDecl>(DRE->getDecl()));
1339       CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, Ref);
1340     }
1341   }
1342   for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
1343     for (const Expr *Ref : C->varlists()) {
1344       if (!Ref->getType()->isScalarType())
1345         continue;
1346       const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts());
1347       if (!DRE)
1348         continue;
1349       PrivateDecls.insert(cast<VarDecl>(DRE->getDecl()));
1350       CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, Ref);
1351     }
1352   }
1353   for (const auto *C : S.getClausesOfKind<OMPLinearClause>()) {
1354     for (const Expr *Ref : C->varlists()) {
1355       if (!Ref->getType()->isScalarType())
1356         continue;
1357       const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts());
1358       if (!DRE)
1359         continue;
1360       PrivateDecls.insert(cast<VarDecl>(DRE->getDecl()));
1361       CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, Ref);
1362     }
1363   }
1364   // Privates should ne analyzed since they are not captured at all.
1365   // Task reductions may be skipped - tasks are ignored.
1366   // Firstprivates do not return value but may be passed by reference - no need
1367   // to check for updated lastprivate conditional.
1368   for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
1369     for (const Expr *Ref : C->varlists()) {
1370       if (!Ref->getType()->isScalarType())
1371         continue;
1372       const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts());
1373       if (!DRE)
1374         continue;
1375       PrivateDecls.insert(cast<VarDecl>(DRE->getDecl()));
1376     }
1377   }
1378   CGF.CGM.getOpenMPRuntime().checkAndEmitSharedLastprivateConditional(
1379       CGF, S, PrivateDecls);
1380 }
1381 
1382 static void emitCommonOMPParallelDirective(
1383     CodeGenFunction &CGF, const OMPExecutableDirective &S,
1384     OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1385     const CodeGenBoundParametersTy &CodeGenBoundParameters) {
1386   const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
1387   llvm::Function *OutlinedFn =
1388       CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
1389           S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
1390   if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
1391     CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
1392     llvm::Value *NumThreads =
1393         CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1394                            /*IgnoreResultAssign=*/true);
1395     CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
1396         CGF, NumThreads, NumThreadsClause->getBeginLoc());
1397   }
1398   if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
1399     CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
1400     CGF.CGM.getOpenMPRuntime().emitProcBindClause(
1401         CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getBeginLoc());
1402   }
1403   const Expr *IfCond = nullptr;
1404   for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1405     if (C->getNameModifier() == OMPD_unknown ||
1406         C->getNameModifier() == OMPD_parallel) {
1407       IfCond = C->getCondition();
1408       break;
1409     }
1410   }
1411 
1412   OMPParallelScope Scope(CGF, S);
1413   llvm::SmallVector<llvm::Value *, 16> CapturedVars;
1414   // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk
1415   // lower and upper bounds with the pragma 'for' chunking mechanism.
1416   // The following lambda takes care of appending the lower and upper bound
1417   // parameters when necessary
1418   CodeGenBoundParameters(CGF, S, CapturedVars);
1419   CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
1420   CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getBeginLoc(), OutlinedFn,
1421                                               CapturedVars, IfCond);
1422 }
1423 
1424 static void emitEmptyBoundParameters(CodeGenFunction &,
1425                                      const OMPExecutableDirective &,
1426                                      llvm::SmallVectorImpl<llvm::Value *> &) {}
1427 
1428 void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
1429   if (llvm::OpenMPIRBuilder *OMPBuilder = CGM.getOpenMPIRBuilder()) {
1430     // Check if we have any if clause associated with the directive.
1431     llvm::Value *IfCond = nullptr;
1432     if (const auto *C = S.getSingleClause<OMPIfClause>())
1433       IfCond = EmitScalarExpr(C->getCondition(),
1434                               /*IgnoreResultAssign=*/true);
1435 
1436     llvm::Value *NumThreads = nullptr;
1437     if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>())
1438       NumThreads = EmitScalarExpr(NumThreadsClause->getNumThreads(),
1439                                   /*IgnoreResultAssign=*/true);
1440 
1441     ProcBindKind ProcBind = OMP_PROC_BIND_default;
1442     if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>())
1443       ProcBind = ProcBindClause->getProcBindKind();
1444 
1445     using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
1446 
1447     // The cleanup callback that finalizes all variabels at the given location,
1448     // thus calls destructors etc.
1449     auto FiniCB = [this](InsertPointTy IP) {
1450       CGBuilderTy::InsertPointGuard IPG(Builder);
1451       assert(IP.getBlock()->end() != IP.getPoint() &&
1452              "OpenMP IR Builder should cause terminated block!");
1453       llvm::BasicBlock *IPBB = IP.getBlock();
1454       llvm::BasicBlock *DestBB = IPBB->splitBasicBlock(IP.getPoint());
1455       IPBB->getTerminator()->eraseFromParent();
1456       Builder.SetInsertPoint(IPBB);
1457       CodeGenFunction::JumpDest Dest = getJumpDestInCurrentScope(DestBB);
1458       EmitBranchThroughCleanup(Dest);
1459     };
1460 
1461     // Privatization callback that performs appropriate action for
1462     // shared/private/firstprivate/lastprivate/copyin/... variables.
1463     //
1464     // TODO: This defaults to shared right now.
1465     auto PrivCB = [](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
1466                      llvm::Value &Val, llvm::Value *&ReplVal) {
1467       // The next line is appropriate only for variables (Val) with the
1468       // data-sharing attribute "shared".
1469       ReplVal = &Val;
1470 
1471       return CodeGenIP;
1472     };
1473 
1474     const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
1475     const Stmt *ParallelRegionBodyStmt = CS->getCapturedStmt();
1476 
1477     auto BodyGenCB = [ParallelRegionBodyStmt,
1478                       this](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
1479                             llvm::BasicBlock &ContinuationBB) {
1480       auto OldAllocaIP = AllocaInsertPt;
1481       AllocaInsertPt = &*AllocaIP.getPoint();
1482 
1483       auto OldReturnBlock = ReturnBlock;
1484       ReturnBlock = getJumpDestInCurrentScope(&ContinuationBB);
1485 
1486       llvm::BasicBlock *CodeGenIPBB = CodeGenIP.getBlock();
1487       CodeGenIPBB->splitBasicBlock(CodeGenIP.getPoint());
1488       llvm::Instruction *CodeGenIPBBTI = CodeGenIPBB->getTerminator();
1489       CodeGenIPBBTI->removeFromParent();
1490 
1491       Builder.SetInsertPoint(CodeGenIPBB);
1492 
1493       EmitStmt(ParallelRegionBodyStmt);
1494 
1495       Builder.Insert(CodeGenIPBBTI);
1496 
1497       AllocaInsertPt = OldAllocaIP;
1498       ReturnBlock = OldReturnBlock;
1499     };
1500 
1501     CGCapturedStmtInfo CGSI(*CS, CR_OpenMP);
1502     CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(*this, &CGSI);
1503     Builder.restoreIP(OMPBuilder->CreateParallel(Builder, BodyGenCB, PrivCB,
1504                                                  FiniCB, IfCond, NumThreads,
1505                                                  ProcBind, S.hasCancel()));
1506     return;
1507   }
1508 
1509   // Emit parallel region as a standalone region.
1510   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
1511     Action.Enter(CGF);
1512     OMPPrivateScope PrivateScope(CGF);
1513     bool Copyins = CGF.EmitOMPCopyinClause(S);
1514     (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1515     if (Copyins) {
1516       // Emit implicit barrier to synchronize threads and avoid data races on
1517       // propagation master's thread values of threadprivate variables to local
1518       // instances of that variables of all other implicit threads.
1519       CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1520           CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
1521           /*ForceSimpleCall=*/true);
1522     }
1523     CGF.EmitOMPPrivateClause(S, PrivateScope);
1524     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1525     (void)PrivateScope.Privatize();
1526     CGF.EmitStmt(S.getCapturedStmt(OMPD_parallel)->getCapturedStmt());
1527     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
1528   };
1529   {
1530     auto LPCRegion =
1531         CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
1532     emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen,
1533                                    emitEmptyBoundParameters);
1534     emitPostUpdateForReductionClause(*this, S,
1535                                      [](CodeGenFunction &) { return nullptr; });
1536   }
1537   // Check for outer lastprivate conditional update.
1538   checkForLastprivateConditionalUpdate(*this, S);
1539 }
1540 
1541 static void emitBody(CodeGenFunction &CGF, const Stmt *S, const Stmt *NextLoop,
1542                      int MaxLevel, int Level = 0) {
1543   assert(Level < MaxLevel && "Too deep lookup during loop body codegen.");
1544   const Stmt *SimplifiedS = S->IgnoreContainers();
1545   if (const auto *CS = dyn_cast<CompoundStmt>(SimplifiedS)) {
1546     PrettyStackTraceLoc CrashInfo(
1547         CGF.getContext().getSourceManager(), CS->getLBracLoc(),
1548         "LLVM IR generation of compound statement ('{}')");
1549 
1550     // Keep track of the current cleanup stack depth, including debug scopes.
1551     CodeGenFunction::LexicalScope Scope(CGF, S->getSourceRange());
1552     for (const Stmt *CurStmt : CS->body())
1553       emitBody(CGF, CurStmt, NextLoop, MaxLevel, Level);
1554     return;
1555   }
1556   if (SimplifiedS == NextLoop) {
1557     if (const auto *For = dyn_cast<ForStmt>(SimplifiedS)) {
1558       S = For->getBody();
1559     } else {
1560       assert(isa<CXXForRangeStmt>(SimplifiedS) &&
1561              "Expected canonical for loop or range-based for loop.");
1562       const auto *CXXFor = cast<CXXForRangeStmt>(SimplifiedS);
1563       CGF.EmitStmt(CXXFor->getLoopVarStmt());
1564       S = CXXFor->getBody();
1565     }
1566     if (Level + 1 < MaxLevel) {
1567       NextLoop = OMPLoopDirective::tryToFindNextInnerLoop(
1568           S, /*TryImperfectlyNestedLoops=*/true);
1569       emitBody(CGF, S, NextLoop, MaxLevel, Level + 1);
1570       return;
1571     }
1572   }
1573   CGF.EmitStmt(S);
1574 }
1575 
1576 void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1577                                       JumpDest LoopExit) {
1578   RunCleanupsScope BodyScope(*this);
1579   // Update counters values on current iteration.
1580   for (const Expr *UE : D.updates())
1581     EmitIgnoredExpr(UE);
1582   // Update the linear variables.
1583   // In distribute directives only loop counters may be marked as linear, no
1584   // need to generate the code for them.
1585   if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
1586     for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
1587       for (const Expr *UE : C->updates())
1588         EmitIgnoredExpr(UE);
1589     }
1590   }
1591 
1592   // On a continue in the body, jump to the end.
1593   JumpDest Continue = getJumpDestInCurrentScope("omp.body.continue");
1594   BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1595   for (const Expr *E : D.finals_conditions()) {
1596     if (!E)
1597       continue;
1598     // Check that loop counter in non-rectangular nest fits into the iteration
1599     // space.
1600     llvm::BasicBlock *NextBB = createBasicBlock("omp.body.next");
1601     EmitBranchOnBoolExpr(E, NextBB, Continue.getBlock(),
1602                          getProfileCount(D.getBody()));
1603     EmitBlock(NextBB);
1604   }
1605   // Emit loop variables for C++ range loops.
1606   const Stmt *Body =
1607       D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers();
1608   // Emit loop body.
1609   emitBody(*this, Body,
1610            OMPLoopDirective::tryToFindNextInnerLoop(
1611                Body, /*TryImperfectlyNestedLoops=*/true),
1612            D.getCollapsedNumber());
1613 
1614   // The end (updates/cleanups).
1615   EmitBlock(Continue.getBlock());
1616   BreakContinueStack.pop_back();
1617 }
1618 
1619 void CodeGenFunction::EmitOMPInnerLoop(
1620     const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1621     const Expr *IncExpr,
1622     const llvm::function_ref<void(CodeGenFunction &)> BodyGen,
1623     const llvm::function_ref<void(CodeGenFunction &)> PostIncGen) {
1624   auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
1625 
1626   // Start the loop with a block that tests the condition.
1627   auto CondBlock = createBasicBlock("omp.inner.for.cond");
1628   EmitBlock(CondBlock);
1629   const SourceRange R = S.getSourceRange();
1630   LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1631                  SourceLocToDebugLoc(R.getEnd()));
1632 
1633   // If there are any cleanups between here and the loop-exit scope,
1634   // create a block to stage a loop exit along.
1635   llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
1636   if (RequiresCleanup)
1637     ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
1638 
1639   llvm::BasicBlock *LoopBody = createBasicBlock("omp.inner.for.body");
1640 
1641   // Emit condition.
1642   EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
1643   if (ExitBlock != LoopExit.getBlock()) {
1644     EmitBlock(ExitBlock);
1645     EmitBranchThroughCleanup(LoopExit);
1646   }
1647 
1648   EmitBlock(LoopBody);
1649   incrementProfileCounter(&S);
1650 
1651   // Create a block for the increment.
1652   JumpDest Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
1653   BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1654 
1655   BodyGen(*this);
1656 
1657   // Emit "IV = IV + 1" and a back-edge to the condition block.
1658   EmitBlock(Continue.getBlock());
1659   EmitIgnoredExpr(IncExpr);
1660   PostIncGen(*this);
1661   BreakContinueStack.pop_back();
1662   EmitBranch(CondBlock);
1663   LoopStack.pop();
1664   // Emit the fall-through block.
1665   EmitBlock(LoopExit.getBlock());
1666 }
1667 
1668 bool CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
1669   if (!HaveInsertPoint())
1670     return false;
1671   // Emit inits for the linear variables.
1672   bool HasLinears = false;
1673   for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
1674     for (const Expr *Init : C->inits()) {
1675       HasLinears = true;
1676       const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
1677       if (const auto *Ref =
1678               dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
1679         AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1680         const auto *OrigVD = cast<VarDecl>(Ref->getDecl());
1681         DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
1682                         CapturedStmtInfo->lookup(OrigVD) != nullptr,
1683                         VD->getInit()->getType(), VK_LValue,
1684                         VD->getInit()->getExprLoc());
1685         EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1686                                                 VD->getType()),
1687                        /*capturedByInit=*/false);
1688         EmitAutoVarCleanups(Emission);
1689       } else {
1690         EmitVarDecl(*VD);
1691       }
1692     }
1693     // Emit the linear steps for the linear clauses.
1694     // If a step is not constant, it is pre-calculated before the loop.
1695     if (const auto *CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1696       if (const auto *SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
1697         EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
1698         // Emit calculation of the linear step.
1699         EmitIgnoredExpr(CS);
1700       }
1701   }
1702   return HasLinears;
1703 }
1704 
1705 void CodeGenFunction::EmitOMPLinearClauseFinal(
1706     const OMPLoopDirective &D,
1707     const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
1708   if (!HaveInsertPoint())
1709     return;
1710   llvm::BasicBlock *DoneBB = nullptr;
1711   // Emit the final values of the linear variables.
1712   for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
1713     auto IC = C->varlist_begin();
1714     for (const Expr *F : C->finals()) {
1715       if (!DoneBB) {
1716         if (llvm::Value *Cond = CondGen(*this)) {
1717           // If the first post-update expression is found, emit conditional
1718           // block if it was requested.
1719           llvm::BasicBlock *ThenBB = createBasicBlock(".omp.linear.pu");
1720           DoneBB = createBasicBlock(".omp.linear.pu.done");
1721           Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1722           EmitBlock(ThenBB);
1723         }
1724       }
1725       const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1726       DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
1727                       CapturedStmtInfo->lookup(OrigVD) != nullptr,
1728                       (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
1729       Address OrigAddr = EmitLValue(&DRE).getAddress(*this);
1730       CodeGenFunction::OMPPrivateScope VarScope(*this);
1731       VarScope.addPrivate(OrigVD, [OrigAddr]() { return OrigAddr; });
1732       (void)VarScope.Privatize();
1733       EmitIgnoredExpr(F);
1734       ++IC;
1735     }
1736     if (const Expr *PostUpdate = C->getPostUpdateExpr())
1737       EmitIgnoredExpr(PostUpdate);
1738   }
1739   if (DoneBB)
1740     EmitBlock(DoneBB, /*IsFinished=*/true);
1741 }
1742 
1743 static void emitAlignedClause(CodeGenFunction &CGF,
1744                               const OMPExecutableDirective &D) {
1745   if (!CGF.HaveInsertPoint())
1746     return;
1747   for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
1748     llvm::APInt ClauseAlignment(64, 0);
1749     if (const Expr *AlignmentExpr = Clause->getAlignment()) {
1750       auto *AlignmentCI =
1751           cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1752       ClauseAlignment = AlignmentCI->getValue();
1753     }
1754     for (const Expr *E : Clause->varlists()) {
1755       llvm::APInt Alignment(ClauseAlignment);
1756       if (Alignment == 0) {
1757         // OpenMP [2.8.1, Description]
1758         // If no optional parameter is specified, implementation-defined default
1759         // alignments for SIMD instructions on the target platforms are assumed.
1760         Alignment =
1761             CGF.getContext()
1762                 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1763                     E->getType()->getPointeeType()))
1764                 .getQuantity();
1765       }
1766       assert((Alignment == 0 || Alignment.isPowerOf2()) &&
1767              "alignment is not power of 2");
1768       if (Alignment != 0) {
1769         llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1770         CGF.EmitAlignmentAssumption(
1771             PtrValue, E, /*No second loc needed*/ SourceLocation(),
1772             llvm::ConstantInt::get(CGF.getLLVMContext(), Alignment));
1773       }
1774     }
1775   }
1776 }
1777 
1778 void CodeGenFunction::EmitOMPPrivateLoopCounters(
1779     const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1780   if (!HaveInsertPoint())
1781     return;
1782   auto I = S.private_counters().begin();
1783   for (const Expr *E : S.counters()) {
1784     const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1785     const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
1786     // Emit var without initialization.
1787     AutoVarEmission VarEmission = EmitAutoVarAlloca(*PrivateVD);
1788     EmitAutoVarCleanups(VarEmission);
1789     LocalDeclMap.erase(PrivateVD);
1790     (void)LoopScope.addPrivate(VD, [&VarEmission]() {
1791       return VarEmission.getAllocatedAddress();
1792     });
1793     if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1794         VD->hasGlobalStorage()) {
1795       (void)LoopScope.addPrivate(PrivateVD, [this, VD, E]() {
1796         DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(VD),
1797                         LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1798                         E->getType(), VK_LValue, E->getExprLoc());
1799         return EmitLValue(&DRE).getAddress(*this);
1800       });
1801     } else {
1802       (void)LoopScope.addPrivate(PrivateVD, [&VarEmission]() {
1803         return VarEmission.getAllocatedAddress();
1804       });
1805     }
1806     ++I;
1807   }
1808   // Privatize extra loop counters used in loops for ordered(n) clauses.
1809   for (const auto *C : S.getClausesOfKind<OMPOrderedClause>()) {
1810     if (!C->getNumForLoops())
1811       continue;
1812     for (unsigned I = S.getCollapsedNumber(),
1813                   E = C->getLoopNumIterations().size();
1814          I < E; ++I) {
1815       const auto *DRE = cast<DeclRefExpr>(C->getLoopCounter(I));
1816       const auto *VD = cast<VarDecl>(DRE->getDecl());
1817       // Override only those variables that can be captured to avoid re-emission
1818       // of the variables declared within the loops.
1819       if (DRE->refersToEnclosingVariableOrCapture()) {
1820         (void)LoopScope.addPrivate(VD, [this, DRE, VD]() {
1821           return CreateMemTemp(DRE->getType(), VD->getName());
1822         });
1823       }
1824     }
1825   }
1826 }
1827 
1828 static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1829                         const Expr *Cond, llvm::BasicBlock *TrueBlock,
1830                         llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
1831   if (!CGF.HaveInsertPoint())
1832     return;
1833   {
1834     CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
1835     CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
1836     (void)PreCondScope.Privatize();
1837     // Get initial values of real counters.
1838     for (const Expr *I : S.inits()) {
1839       CGF.EmitIgnoredExpr(I);
1840     }
1841   }
1842   // Create temp loop control variables with their init values to support
1843   // non-rectangular loops.
1844   CodeGenFunction::OMPMapVars PreCondVars;
1845   for (const Expr * E: S.dependent_counters()) {
1846     if (!E)
1847       continue;
1848     assert(!E->getType().getNonReferenceType()->isRecordType() &&
1849            "dependent counter must not be an iterator.");
1850     const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1851     Address CounterAddr =
1852         CGF.CreateMemTemp(VD->getType().getNonReferenceType());
1853     (void)PreCondVars.setVarAddr(CGF, VD, CounterAddr);
1854   }
1855   (void)PreCondVars.apply(CGF);
1856   for (const Expr *E : S.dependent_inits()) {
1857     if (!E)
1858       continue;
1859     CGF.EmitIgnoredExpr(E);
1860   }
1861   // Check that loop is executed at least one time.
1862   CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1863   PreCondVars.restore(CGF);
1864 }
1865 
1866 void CodeGenFunction::EmitOMPLinearClause(
1867     const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1868   if (!HaveInsertPoint())
1869     return;
1870   llvm::DenseSet<const VarDecl *> SIMDLCVs;
1871   if (isOpenMPSimdDirective(D.getDirectiveKind())) {
1872     const auto *LoopDirective = cast<OMPLoopDirective>(&D);
1873     for (const Expr *C : LoopDirective->counters()) {
1874       SIMDLCVs.insert(
1875           cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1876     }
1877   }
1878   for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
1879     auto CurPrivate = C->privates().begin();
1880     for (const Expr *E : C->varlists()) {
1881       const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1882       const auto *PrivateVD =
1883           cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
1884       if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
1885         bool IsRegistered = PrivateScope.addPrivate(VD, [this, PrivateVD]() {
1886           // Emit private VarDecl with copy init.
1887           EmitVarDecl(*PrivateVD);
1888           return GetAddrOfLocalVar(PrivateVD);
1889         });
1890         assert(IsRegistered && "linear var already registered as private");
1891         // Silence the warning about unused variable.
1892         (void)IsRegistered;
1893       } else {
1894         EmitVarDecl(*PrivateVD);
1895       }
1896       ++CurPrivate;
1897     }
1898   }
1899 }
1900 
1901 static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
1902                                      const OMPExecutableDirective &D,
1903                                      bool IsMonotonic) {
1904   if (!CGF.HaveInsertPoint())
1905     return;
1906   if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
1907     RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1908                                  /*ignoreResult=*/true);
1909     auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1910     CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1911     // In presence of finite 'safelen', it may be unsafe to mark all
1912     // the memory instructions parallel, because loop-carried
1913     // dependences of 'safelen' iterations are possible.
1914     if (!IsMonotonic)
1915       CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
1916   } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
1917     RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1918                                  /*ignoreResult=*/true);
1919     auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1920     CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1921     // In presence of finite 'safelen', it may be unsafe to mark all
1922     // the memory instructions parallel, because loop-carried
1923     // dependences of 'safelen' iterations are possible.
1924     CGF.LoopStack.setParallel(/*Enable=*/false);
1925   }
1926 }
1927 
1928 void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1929                                       bool IsMonotonic) {
1930   // Walk clauses and process safelen/lastprivate.
1931   LoopStack.setParallel(!IsMonotonic);
1932   LoopStack.setVectorizeEnable();
1933   emitSimdlenSafelenClause(*this, D, IsMonotonic);
1934   if (const auto *C = D.getSingleClause<OMPOrderClause>())
1935     if (C->getKind() == OMPC_ORDER_concurrent)
1936       LoopStack.setParallel(/*Enable=*/true);
1937 }
1938 
1939 void CodeGenFunction::EmitOMPSimdFinal(
1940     const OMPLoopDirective &D,
1941     const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
1942   if (!HaveInsertPoint())
1943     return;
1944   llvm::BasicBlock *DoneBB = nullptr;
1945   auto IC = D.counters().begin();
1946   auto IPC = D.private_counters().begin();
1947   for (const Expr *F : D.finals()) {
1948     const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
1949     const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1950     const auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
1951     if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1952         OrigVD->hasGlobalStorage() || CED) {
1953       if (!DoneBB) {
1954         if (llvm::Value *Cond = CondGen(*this)) {
1955           // If the first post-update expression is found, emit conditional
1956           // block if it was requested.
1957           llvm::BasicBlock *ThenBB = createBasicBlock(".omp.final.then");
1958           DoneBB = createBasicBlock(".omp.final.done");
1959           Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1960           EmitBlock(ThenBB);
1961         }
1962       }
1963       Address OrigAddr = Address::invalid();
1964       if (CED) {
1965         OrigAddr =
1966             EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress(*this);
1967       } else {
1968         DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(PrivateVD),
1969                         /*RefersToEnclosingVariableOrCapture=*/false,
1970                         (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
1971         OrigAddr = EmitLValue(&DRE).getAddress(*this);
1972       }
1973       OMPPrivateScope VarScope(*this);
1974       VarScope.addPrivate(OrigVD, [OrigAddr]() { return OrigAddr; });
1975       (void)VarScope.Privatize();
1976       EmitIgnoredExpr(F);
1977     }
1978     ++IC;
1979     ++IPC;
1980   }
1981   if (DoneBB)
1982     EmitBlock(DoneBB, /*IsFinished=*/true);
1983 }
1984 
1985 static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF,
1986                                          const OMPLoopDirective &S,
1987                                          CodeGenFunction::JumpDest LoopExit) {
1988   CGF.EmitOMPLoopBody(S, LoopExit);
1989   CGF.EmitStopPoint(&S);
1990 }
1991 
1992 /// Emit a helper variable and return corresponding lvalue.
1993 static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1994                                const DeclRefExpr *Helper) {
1995   auto VDecl = cast<VarDecl>(Helper->getDecl());
1996   CGF.EmitVarDecl(*VDecl);
1997   return CGF.EmitLValue(Helper);
1998 }
1999 
2000 static void emitCommonSimdLoop(CodeGenFunction &CGF, const OMPLoopDirective &S,
2001                                const RegionCodeGenTy &SimdInitGen,
2002                                const RegionCodeGenTy &BodyCodeGen) {
2003   auto &&ThenGen = [&S, &SimdInitGen, &BodyCodeGen](CodeGenFunction &CGF,
2004                                                     PrePostActionTy &) {
2005     CGOpenMPRuntime::NontemporalDeclsRAII NontemporalsRegion(CGF.CGM, S);
2006     CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF);
2007     SimdInitGen(CGF);
2008 
2009     BodyCodeGen(CGF);
2010   };
2011   auto &&ElseGen = [&BodyCodeGen](CodeGenFunction &CGF, PrePostActionTy &) {
2012     CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF);
2013     CGF.LoopStack.setVectorizeEnable(/*Enable=*/false);
2014 
2015     BodyCodeGen(CGF);
2016   };
2017   const Expr *IfCond = nullptr;
2018   for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2019     if (CGF.getLangOpts().OpenMP >= 50 &&
2020         (C->getNameModifier() == OMPD_unknown ||
2021          C->getNameModifier() == OMPD_simd)) {
2022       IfCond = C->getCondition();
2023       break;
2024     }
2025   }
2026   if (IfCond) {
2027     CGF.CGM.getOpenMPRuntime().emitIfClause(CGF, IfCond, ThenGen, ElseGen);
2028   } else {
2029     RegionCodeGenTy ThenRCG(ThenGen);
2030     ThenRCG(CGF);
2031   }
2032 }
2033 
2034 static void emitOMPSimdRegion(CodeGenFunction &CGF, const OMPLoopDirective &S,
2035                               PrePostActionTy &Action) {
2036   Action.Enter(CGF);
2037   assert(isOpenMPSimdDirective(S.getDirectiveKind()) &&
2038          "Expected simd directive");
2039   OMPLoopScope PreInitScope(CGF, S);
2040   // if (PreCond) {
2041   //   for (IV in 0..LastIteration) BODY;
2042   //   <Final counter/linear vars updates>;
2043   // }
2044   //
2045   if (isOpenMPDistributeDirective(S.getDirectiveKind()) ||
2046       isOpenMPWorksharingDirective(S.getDirectiveKind()) ||
2047       isOpenMPTaskLoopDirective(S.getDirectiveKind())) {
2048     (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()));
2049     (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()));
2050   }
2051 
2052   // Emit: if (PreCond) - begin.
2053   // If the condition constant folds and can be elided, avoid emitting the
2054   // whole loop.
2055   bool CondConstant;
2056   llvm::BasicBlock *ContBlock = nullptr;
2057   if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2058     if (!CondConstant)
2059       return;
2060   } else {
2061     llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("simd.if.then");
2062     ContBlock = CGF.createBasicBlock("simd.if.end");
2063     emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
2064                 CGF.getProfileCount(&S));
2065     CGF.EmitBlock(ThenBlock);
2066     CGF.incrementProfileCounter(&S);
2067   }
2068 
2069   // Emit the loop iteration variable.
2070   const Expr *IVExpr = S.getIterationVariable();
2071   const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
2072   CGF.EmitVarDecl(*IVDecl);
2073   CGF.EmitIgnoredExpr(S.getInit());
2074 
2075   // Emit the iterations count variable.
2076   // If it is not a variable, Sema decided to calculate iterations count on
2077   // each iteration (e.g., it is foldable into a constant).
2078   if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2079     CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2080     // Emit calculation of the iterations count.
2081     CGF.EmitIgnoredExpr(S.getCalcLastIteration());
2082   }
2083 
2084   emitAlignedClause(CGF, S);
2085   (void)CGF.EmitOMPLinearClauseInit(S);
2086   {
2087     CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2088     CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
2089     CGF.EmitOMPLinearClause(S, LoopScope);
2090     CGF.EmitOMPPrivateClause(S, LoopScope);
2091     CGF.EmitOMPReductionClauseInit(S, LoopScope);
2092     CGOpenMPRuntime::LastprivateConditionalRAII LPCRegion(
2093         CGF, S, CGF.EmitLValue(S.getIterationVariable()));
2094     bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2095     (void)LoopScope.Privatize();
2096     if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
2097       CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
2098 
2099     emitCommonSimdLoop(
2100         CGF, S,
2101         [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2102           CGF.EmitOMPSimdInit(S);
2103         },
2104         [&S, &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) {
2105           CGF.EmitOMPInnerLoop(
2106               S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
2107               [&S](CodeGenFunction &CGF) {
2108                 CGF.EmitOMPLoopBody(S, CodeGenFunction::JumpDest());
2109                 CGF.EmitStopPoint(&S);
2110               },
2111               [](CodeGenFunction &) {});
2112         });
2113     CGF.EmitOMPSimdFinal(S, [](CodeGenFunction &) { return nullptr; });
2114     // Emit final copy of the lastprivate variables at the end of loops.
2115     if (HasLastprivateClause)
2116       CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
2117     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
2118     emitPostUpdateForReductionClause(CGF, S,
2119                                      [](CodeGenFunction &) { return nullptr; });
2120   }
2121   CGF.EmitOMPLinearClauseFinal(S, [](CodeGenFunction &) { return nullptr; });
2122   // Emit: if (PreCond) - end.
2123   if (ContBlock) {
2124     CGF.EmitBranch(ContBlock);
2125     CGF.EmitBlock(ContBlock, true);
2126   }
2127 }
2128 
2129 void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
2130   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2131     emitOMPSimdRegion(CGF, S, Action);
2132   };
2133   {
2134     auto LPCRegion =
2135         CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
2136     OMPLexicalScope Scope(*this, S, OMPD_unknown);
2137     CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2138   }
2139   // Check for outer lastprivate conditional update.
2140   checkForLastprivateConditionalUpdate(*this, S);
2141 }
2142 
2143 void CodeGenFunction::EmitOMPOuterLoop(
2144     bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S,
2145     CodeGenFunction::OMPPrivateScope &LoopScope,
2146     const CodeGenFunction::OMPLoopArguments &LoopArgs,
2147     const CodeGenFunction::CodeGenLoopTy &CodeGenLoop,
2148     const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) {
2149   CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
2150 
2151   const Expr *IVExpr = S.getIterationVariable();
2152   const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2153   const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2154 
2155   JumpDest LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
2156 
2157   // Start the loop with a block that tests the condition.
2158   llvm::BasicBlock *CondBlock = createBasicBlock("omp.dispatch.cond");
2159   EmitBlock(CondBlock);
2160   const SourceRange R = S.getSourceRange();
2161   LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
2162                  SourceLocToDebugLoc(R.getEnd()));
2163 
2164   llvm::Value *BoolCondVal = nullptr;
2165   if (!DynamicOrOrdered) {
2166     // UB = min(UB, GlobalUB) or
2167     // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g.
2168     // 'distribute parallel for')
2169     EmitIgnoredExpr(LoopArgs.EUB);
2170     // IV = LB
2171     EmitIgnoredExpr(LoopArgs.Init);
2172     // IV < UB
2173     BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond);
2174   } else {
2175     BoolCondVal =
2176         RT.emitForNext(*this, S.getBeginLoc(), IVSize, IVSigned, LoopArgs.IL,
2177                        LoopArgs.LB, LoopArgs.UB, LoopArgs.ST);
2178   }
2179 
2180   // If there are any cleanups between here and the loop-exit scope,
2181   // create a block to stage a loop exit along.
2182   llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
2183   if (LoopScope.requiresCleanups())
2184     ExitBlock = createBasicBlock("omp.dispatch.cleanup");
2185 
2186   llvm::BasicBlock *LoopBody = createBasicBlock("omp.dispatch.body");
2187   Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
2188   if (ExitBlock != LoopExit.getBlock()) {
2189     EmitBlock(ExitBlock);
2190     EmitBranchThroughCleanup(LoopExit);
2191   }
2192   EmitBlock(LoopBody);
2193 
2194   // Emit "IV = LB" (in case of static schedule, we have already calculated new
2195   // LB for loop condition and emitted it above).
2196   if (DynamicOrOrdered)
2197     EmitIgnoredExpr(LoopArgs.Init);
2198 
2199   // Create a block for the increment.
2200   JumpDest Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
2201   BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
2202 
2203   emitCommonSimdLoop(
2204       *this, S,
2205       [&S, IsMonotonic](CodeGenFunction &CGF, PrePostActionTy &) {
2206         // Generate !llvm.loop.parallel metadata for loads and stores for loops
2207         // with dynamic/guided scheduling and without ordered clause.
2208         if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
2209           CGF.LoopStack.setParallel(!IsMonotonic);
2210           if (const auto *C = S.getSingleClause<OMPOrderClause>())
2211             if (C->getKind() == OMPC_ORDER_concurrent)
2212               CGF.LoopStack.setParallel(/*Enable=*/true);
2213         } else {
2214           CGF.EmitOMPSimdInit(S, IsMonotonic);
2215         }
2216       },
2217       [&S, &LoopArgs, LoopExit, &CodeGenLoop, IVSize, IVSigned, &CodeGenOrdered,
2218        &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) {
2219         SourceLocation Loc = S.getBeginLoc();
2220         // when 'distribute' is not combined with a 'for':
2221         // while (idx <= UB) { BODY; ++idx; }
2222         // when 'distribute' is combined with a 'for'
2223         // (e.g. 'distribute parallel for')
2224         // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
2225         CGF.EmitOMPInnerLoop(
2226             S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr,
2227             [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
2228               CodeGenLoop(CGF, S, LoopExit);
2229             },
2230             [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) {
2231               CodeGenOrdered(CGF, Loc, IVSize, IVSigned);
2232             });
2233       });
2234 
2235   EmitBlock(Continue.getBlock());
2236   BreakContinueStack.pop_back();
2237   if (!DynamicOrOrdered) {
2238     // Emit "LB = LB + Stride", "UB = UB + Stride".
2239     EmitIgnoredExpr(LoopArgs.NextLB);
2240     EmitIgnoredExpr(LoopArgs.NextUB);
2241   }
2242 
2243   EmitBranch(CondBlock);
2244   LoopStack.pop();
2245   // Emit the fall-through block.
2246   EmitBlock(LoopExit.getBlock());
2247 
2248   // Tell the runtime we are done.
2249   auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
2250     if (!DynamicOrOrdered)
2251       CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
2252                                                      S.getDirectiveKind());
2253   };
2254   OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
2255 }
2256 
2257 void CodeGenFunction::EmitOMPForOuterLoop(
2258     const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
2259     const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
2260     const OMPLoopArguments &LoopArgs,
2261     const CodeGenDispatchBoundsTy &CGDispatchBounds) {
2262   CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
2263 
2264   // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
2265   const bool DynamicOrOrdered =
2266       Ordered || RT.isDynamic(ScheduleKind.Schedule);
2267 
2268   assert((Ordered ||
2269           !RT.isStaticNonchunked(ScheduleKind.Schedule,
2270                                  LoopArgs.Chunk != nullptr)) &&
2271          "static non-chunked schedule does not need outer loop");
2272 
2273   // Emit outer loop.
2274   //
2275   // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2276   // When schedule(dynamic,chunk_size) is specified, the iterations are
2277   // distributed to threads in the team in chunks as the threads request them.
2278   // Each thread executes a chunk of iterations, then requests another chunk,
2279   // until no chunks remain to be distributed. Each chunk contains chunk_size
2280   // iterations, except for the last chunk to be distributed, which may have
2281   // fewer iterations. When no chunk_size is specified, it defaults to 1.
2282   //
2283   // When schedule(guided,chunk_size) is specified, the iterations are assigned
2284   // to threads in the team in chunks as the executing threads request them.
2285   // Each thread executes a chunk of iterations, then requests another chunk,
2286   // until no chunks remain to be assigned. For a chunk_size of 1, the size of
2287   // each chunk is proportional to the number of unassigned iterations divided
2288   // by the number of threads in the team, decreasing to 1. For a chunk_size
2289   // with value k (greater than 1), the size of each chunk is determined in the
2290   // same way, with the restriction that the chunks do not contain fewer than k
2291   // iterations (except for the last chunk to be assigned, which may have fewer
2292   // than k iterations).
2293   //
2294   // When schedule(auto) is specified, the decision regarding scheduling is
2295   // delegated to the compiler and/or runtime system. The programmer gives the
2296   // implementation the freedom to choose any possible mapping of iterations to
2297   // threads in the team.
2298   //
2299   // When schedule(runtime) is specified, the decision regarding scheduling is
2300   // deferred until run time, and the schedule and chunk size are taken from the
2301   // run-sched-var ICV. If the ICV is set to auto, the schedule is
2302   // implementation defined
2303   //
2304   // while(__kmpc_dispatch_next(&LB, &UB)) {
2305   //   idx = LB;
2306   //   while (idx <= UB) { BODY; ++idx;
2307   //   __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
2308   //   } // inner loop
2309   // }
2310   //
2311   // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2312   // When schedule(static, chunk_size) is specified, iterations are divided into
2313   // chunks of size chunk_size, and the chunks are assigned to the threads in
2314   // the team in a round-robin fashion in the order of the thread number.
2315   //
2316   // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
2317   //   while (idx <= UB) { BODY; ++idx; } // inner loop
2318   //   LB = LB + ST;
2319   //   UB = UB + ST;
2320   // }
2321   //
2322 
2323   const Expr *IVExpr = S.getIterationVariable();
2324   const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2325   const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2326 
2327   if (DynamicOrOrdered) {
2328     const std::pair<llvm::Value *, llvm::Value *> DispatchBounds =
2329         CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB);
2330     llvm::Value *LBVal = DispatchBounds.first;
2331     llvm::Value *UBVal = DispatchBounds.second;
2332     CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal,
2333                                                              LoopArgs.Chunk};
2334     RT.emitForDispatchInit(*this, S.getBeginLoc(), ScheduleKind, IVSize,
2335                            IVSigned, Ordered, DipatchRTInputValues);
2336   } else {
2337     CGOpenMPRuntime::StaticRTInput StaticInit(
2338         IVSize, IVSigned, Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB,
2339         LoopArgs.ST, LoopArgs.Chunk);
2340     RT.emitForStaticInit(*this, S.getBeginLoc(), S.getDirectiveKind(),
2341                          ScheduleKind, StaticInit);
2342   }
2343 
2344   auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc,
2345                                     const unsigned IVSize,
2346                                     const bool IVSigned) {
2347     if (Ordered) {
2348       CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize,
2349                                                             IVSigned);
2350     }
2351   };
2352 
2353   OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
2354                                  LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB);
2355   OuterLoopArgs.IncExpr = S.getInc();
2356   OuterLoopArgs.Init = S.getInit();
2357   OuterLoopArgs.Cond = S.getCond();
2358   OuterLoopArgs.NextLB = S.getNextLowerBound();
2359   OuterLoopArgs.NextUB = S.getNextUpperBound();
2360   EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs,
2361                    emitOMPLoopBodyWithStopPoint, CodeGenOrdered);
2362 }
2363 
2364 static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc,
2365                              const unsigned IVSize, const bool IVSigned) {}
2366 
2367 void CodeGenFunction::EmitOMPDistributeOuterLoop(
2368     OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S,
2369     OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs,
2370     const CodeGenLoopTy &CodeGenLoopContent) {
2371 
2372   CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
2373 
2374   // Emit outer loop.
2375   // Same behavior as a OMPForOuterLoop, except that schedule cannot be
2376   // dynamic
2377   //
2378 
2379   const Expr *IVExpr = S.getIterationVariable();
2380   const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2381   const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2382 
2383   CGOpenMPRuntime::StaticRTInput StaticInit(
2384       IVSize, IVSigned, /* Ordered = */ false, LoopArgs.IL, LoopArgs.LB,
2385       LoopArgs.UB, LoopArgs.ST, LoopArgs.Chunk);
2386   RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind, StaticInit);
2387 
2388   // for combined 'distribute' and 'for' the increment expression of distribute
2389   // is stored in DistInc. For 'distribute' alone, it is in Inc.
2390   Expr *IncExpr;
2391   if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()))
2392     IncExpr = S.getDistInc();
2393   else
2394     IncExpr = S.getInc();
2395 
2396   // this routine is shared by 'omp distribute parallel for' and
2397   // 'omp distribute': select the right EUB expression depending on the
2398   // directive
2399   OMPLoopArguments OuterLoopArgs;
2400   OuterLoopArgs.LB = LoopArgs.LB;
2401   OuterLoopArgs.UB = LoopArgs.UB;
2402   OuterLoopArgs.ST = LoopArgs.ST;
2403   OuterLoopArgs.IL = LoopArgs.IL;
2404   OuterLoopArgs.Chunk = LoopArgs.Chunk;
2405   OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2406                           ? S.getCombinedEnsureUpperBound()
2407                           : S.getEnsureUpperBound();
2408   OuterLoopArgs.IncExpr = IncExpr;
2409   OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2410                            ? S.getCombinedInit()
2411                            : S.getInit();
2412   OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2413                            ? S.getCombinedCond()
2414                            : S.getCond();
2415   OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2416                              ? S.getCombinedNextLowerBound()
2417                              : S.getNextLowerBound();
2418   OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2419                              ? S.getCombinedNextUpperBound()
2420                              : S.getNextUpperBound();
2421 
2422   EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S,
2423                    LoopScope, OuterLoopArgs, CodeGenLoopContent,
2424                    emitEmptyOrdered);
2425 }
2426 
2427 static std::pair<LValue, LValue>
2428 emitDistributeParallelForInnerBounds(CodeGenFunction &CGF,
2429                                      const OMPExecutableDirective &S) {
2430   const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2431   LValue LB =
2432       EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2433   LValue UB =
2434       EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2435 
2436   // When composing 'distribute' with 'for' (e.g. as in 'distribute
2437   // parallel for') we need to use the 'distribute'
2438   // chunk lower and upper bounds rather than the whole loop iteration
2439   // space. These are parameters to the outlined function for 'parallel'
2440   // and we copy the bounds of the previous schedule into the
2441   // the current ones.
2442   LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable());
2443   LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable());
2444   llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar(
2445       PrevLB, LS.getPrevLowerBoundVariable()->getExprLoc());
2446   PrevLBVal = CGF.EmitScalarConversion(
2447       PrevLBVal, LS.getPrevLowerBoundVariable()->getType(),
2448       LS.getIterationVariable()->getType(),
2449       LS.getPrevLowerBoundVariable()->getExprLoc());
2450   llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar(
2451       PrevUB, LS.getPrevUpperBoundVariable()->getExprLoc());
2452   PrevUBVal = CGF.EmitScalarConversion(
2453       PrevUBVal, LS.getPrevUpperBoundVariable()->getType(),
2454       LS.getIterationVariable()->getType(),
2455       LS.getPrevUpperBoundVariable()->getExprLoc());
2456 
2457   CGF.EmitStoreOfScalar(PrevLBVal, LB);
2458   CGF.EmitStoreOfScalar(PrevUBVal, UB);
2459 
2460   return {LB, UB};
2461 }
2462 
2463 /// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then
2464 /// we need to use the LB and UB expressions generated by the worksharing
2465 /// code generation support, whereas in non combined situations we would
2466 /// just emit 0 and the LastIteration expression
2467 /// This function is necessary due to the difference of the LB and UB
2468 /// types for the RT emission routines for 'for_static_init' and
2469 /// 'for_dispatch_init'
2470 static std::pair<llvm::Value *, llvm::Value *>
2471 emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF,
2472                                         const OMPExecutableDirective &S,
2473                                         Address LB, Address UB) {
2474   const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2475   const Expr *IVExpr = LS.getIterationVariable();
2476   // when implementing a dynamic schedule for a 'for' combined with a
2477   // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop
2478   // is not normalized as each team only executes its own assigned
2479   // distribute chunk
2480   QualType IteratorTy = IVExpr->getType();
2481   llvm::Value *LBVal =
2482       CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy, S.getBeginLoc());
2483   llvm::Value *UBVal =
2484       CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy, S.getBeginLoc());
2485   return {LBVal, UBVal};
2486 }
2487 
2488 static void emitDistributeParallelForDistributeInnerBoundParams(
2489     CodeGenFunction &CGF, const OMPExecutableDirective &S,
2490     llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) {
2491   const auto &Dir = cast<OMPLoopDirective>(S);
2492   LValue LB =
2493       CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable()));
2494   llvm::Value *LBCast =
2495       CGF.Builder.CreateIntCast(CGF.Builder.CreateLoad(LB.getAddress(CGF)),
2496                                 CGF.SizeTy, /*isSigned=*/false);
2497   CapturedVars.push_back(LBCast);
2498   LValue UB =
2499       CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable()));
2500 
2501   llvm::Value *UBCast =
2502       CGF.Builder.CreateIntCast(CGF.Builder.CreateLoad(UB.getAddress(CGF)),
2503                                 CGF.SizeTy, /*isSigned=*/false);
2504   CapturedVars.push_back(UBCast);
2505 }
2506 
2507 static void
2508 emitInnerParallelForWhenCombined(CodeGenFunction &CGF,
2509                                  const OMPLoopDirective &S,
2510                                  CodeGenFunction::JumpDest LoopExit) {
2511   auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF,
2512                                          PrePostActionTy &Action) {
2513     Action.Enter(CGF);
2514     bool HasCancel = false;
2515     if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
2516       if (const auto *D = dyn_cast<OMPTeamsDistributeParallelForDirective>(&S))
2517         HasCancel = D->hasCancel();
2518       else if (const auto *D = dyn_cast<OMPDistributeParallelForDirective>(&S))
2519         HasCancel = D->hasCancel();
2520       else if (const auto *D =
2521                    dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&S))
2522         HasCancel = D->hasCancel();
2523     }
2524     CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, S.getDirectiveKind(),
2525                                                      HasCancel);
2526     CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(),
2527                                emitDistributeParallelForInnerBounds,
2528                                emitDistributeParallelForDispatchBounds);
2529   };
2530 
2531   emitCommonOMPParallelDirective(
2532       CGF, S,
2533       isOpenMPSimdDirective(S.getDirectiveKind()) ? OMPD_for_simd : OMPD_for,
2534       CGInlinedWorksharingLoop,
2535       emitDistributeParallelForDistributeInnerBoundParams);
2536 }
2537 
2538 void CodeGenFunction::EmitOMPDistributeParallelForDirective(
2539     const OMPDistributeParallelForDirective &S) {
2540   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2541     CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2542                               S.getDistInc());
2543   };
2544   OMPLexicalScope Scope(*this, S, OMPD_parallel);
2545   CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
2546 }
2547 
2548 void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
2549     const OMPDistributeParallelForSimdDirective &S) {
2550   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2551     CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2552                               S.getDistInc());
2553   };
2554   OMPLexicalScope Scope(*this, S, OMPD_parallel);
2555   CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
2556 }
2557 
2558 void CodeGenFunction::EmitOMPDistributeSimdDirective(
2559     const OMPDistributeSimdDirective &S) {
2560   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2561     CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
2562   };
2563   OMPLexicalScope Scope(*this, S, OMPD_unknown);
2564   CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2565 }
2566 
2567 void CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
2568     CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S) {
2569   // Emit SPMD target parallel for region as a standalone region.
2570   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2571     emitOMPSimdRegion(CGF, S, Action);
2572   };
2573   llvm::Function *Fn;
2574   llvm::Constant *Addr;
2575   // Emit target region as a standalone region.
2576   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
2577       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
2578   assert(Fn && Addr && "Target device function emission failed.");
2579 }
2580 
2581 void CodeGenFunction::EmitOMPTargetSimdDirective(
2582     const OMPTargetSimdDirective &S) {
2583   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2584     emitOMPSimdRegion(CGF, S, Action);
2585   };
2586   emitCommonOMPTargetDirective(*this, S, CodeGen);
2587 }
2588 
2589 namespace {
2590   struct ScheduleKindModifiersTy {
2591     OpenMPScheduleClauseKind Kind;
2592     OpenMPScheduleClauseModifier M1;
2593     OpenMPScheduleClauseModifier M2;
2594     ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
2595                             OpenMPScheduleClauseModifier M1,
2596                             OpenMPScheduleClauseModifier M2)
2597         : Kind(Kind), M1(M1), M2(M2) {}
2598   };
2599 } // namespace
2600 
2601 bool CodeGenFunction::EmitOMPWorksharingLoop(
2602     const OMPLoopDirective &S, Expr *EUB,
2603     const CodeGenLoopBoundsTy &CodeGenLoopBounds,
2604     const CodeGenDispatchBoundsTy &CGDispatchBounds) {
2605   // Emit the loop iteration variable.
2606   const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2607   const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl());
2608   EmitVarDecl(*IVDecl);
2609 
2610   // Emit the iterations count variable.
2611   // If it is not a variable, Sema decided to calculate iterations count on each
2612   // iteration (e.g., it is foldable into a constant).
2613   if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2614     EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2615     // Emit calculation of the iterations count.
2616     EmitIgnoredExpr(S.getCalcLastIteration());
2617   }
2618 
2619   CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
2620 
2621   bool HasLastprivateClause;
2622   // Check pre-condition.
2623   {
2624     OMPLoopScope PreInitScope(*this, S);
2625     // Skip the entire loop if we don't meet the precondition.
2626     // If the condition constant folds and can be elided, avoid emitting the
2627     // whole loop.
2628     bool CondConstant;
2629     llvm::BasicBlock *ContBlock = nullptr;
2630     if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2631       if (!CondConstant)
2632         return false;
2633     } else {
2634       llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then");
2635       ContBlock = createBasicBlock("omp.precond.end");
2636       emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
2637                   getProfileCount(&S));
2638       EmitBlock(ThenBlock);
2639       incrementProfileCounter(&S);
2640     }
2641 
2642     RunCleanupsScope DoacrossCleanupScope(*this);
2643     bool Ordered = false;
2644     if (const auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
2645       if (OrderedClause->getNumForLoops())
2646         RT.emitDoacrossInit(*this, S, OrderedClause->getLoopNumIterations());
2647       else
2648         Ordered = true;
2649     }
2650 
2651     llvm::DenseSet<const Expr *> EmittedFinals;
2652     emitAlignedClause(*this, S);
2653     bool HasLinears = EmitOMPLinearClauseInit(S);
2654     // Emit helper vars inits.
2655 
2656     std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S);
2657     LValue LB = Bounds.first;
2658     LValue UB = Bounds.second;
2659     LValue ST =
2660         EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2661     LValue IL =
2662         EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2663 
2664     // Emit 'then' code.
2665     {
2666       OMPPrivateScope LoopScope(*this);
2667       if (EmitOMPFirstprivateClause(S, LoopScope) || HasLinears) {
2668         // Emit implicit barrier to synchronize threads and avoid data races on
2669         // initialization of firstprivate variables and post-update of
2670         // lastprivate variables.
2671         CGM.getOpenMPRuntime().emitBarrierCall(
2672             *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
2673             /*ForceSimpleCall=*/true);
2674       }
2675       EmitOMPPrivateClause(S, LoopScope);
2676       CGOpenMPRuntime::LastprivateConditionalRAII LPCRegion(
2677           *this, S, EmitLValue(S.getIterationVariable()));
2678       HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
2679       EmitOMPReductionClauseInit(S, LoopScope);
2680       EmitOMPPrivateLoopCounters(S, LoopScope);
2681       EmitOMPLinearClause(S, LoopScope);
2682       (void)LoopScope.Privatize();
2683       if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
2684         CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(*this, S);
2685 
2686       // Detect the loop schedule kind and chunk.
2687       const Expr *ChunkExpr = nullptr;
2688       OpenMPScheduleTy ScheduleKind;
2689       if (const auto *C = S.getSingleClause<OMPScheduleClause>()) {
2690         ScheduleKind.Schedule = C->getScheduleKind();
2691         ScheduleKind.M1 = C->getFirstScheduleModifier();
2692         ScheduleKind.M2 = C->getSecondScheduleModifier();
2693         ChunkExpr = C->getChunkSize();
2694       } else {
2695         // Default behaviour for schedule clause.
2696         CGM.getOpenMPRuntime().getDefaultScheduleAndChunk(
2697             *this, S, ScheduleKind.Schedule, ChunkExpr);
2698       }
2699       bool HasChunkSizeOne = false;
2700       llvm::Value *Chunk = nullptr;
2701       if (ChunkExpr) {
2702         Chunk = EmitScalarExpr(ChunkExpr);
2703         Chunk = EmitScalarConversion(Chunk, ChunkExpr->getType(),
2704                                      S.getIterationVariable()->getType(),
2705                                      S.getBeginLoc());
2706         Expr::EvalResult Result;
2707         if (ChunkExpr->EvaluateAsInt(Result, getContext())) {
2708           llvm::APSInt EvaluatedChunk = Result.Val.getInt();
2709           HasChunkSizeOne = (EvaluatedChunk.getLimitedValue() == 1);
2710         }
2711       }
2712       const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2713       const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2714       // OpenMP 4.5, 2.7.1 Loop Construct, Description.
2715       // If the static schedule kind is specified or if the ordered clause is
2716       // specified, and if no monotonic modifier is specified, the effect will
2717       // be as if the monotonic modifier was specified.
2718       bool StaticChunkedOne = RT.isStaticChunked(ScheduleKind.Schedule,
2719           /* Chunked */ Chunk != nullptr) && HasChunkSizeOne &&
2720           isOpenMPLoopBoundSharingDirective(S.getDirectiveKind());
2721       if ((RT.isStaticNonchunked(ScheduleKind.Schedule,
2722                                  /* Chunked */ Chunk != nullptr) ||
2723            StaticChunkedOne) &&
2724           !Ordered) {
2725         JumpDest LoopExit =
2726             getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
2727         emitCommonSimdLoop(
2728             *this, S,
2729             [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2730               if (isOpenMPSimdDirective(S.getDirectiveKind())) {
2731                 CGF.EmitOMPSimdInit(S, /*IsMonotonic=*/true);
2732               } else if (const auto *C = S.getSingleClause<OMPOrderClause>()) {
2733                 if (C->getKind() == OMPC_ORDER_concurrent)
2734                   CGF.LoopStack.setParallel(/*Enable=*/true);
2735               }
2736             },
2737             [IVSize, IVSigned, Ordered, IL, LB, UB, ST, StaticChunkedOne, Chunk,
2738              &S, ScheduleKind, LoopExit,
2739              &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) {
2740               // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2741               // When no chunk_size is specified, the iteration space is divided
2742               // into chunks that are approximately equal in size, and at most
2743               // one chunk is distributed to each thread. Note that the size of
2744               // the chunks is unspecified in this case.
2745               CGOpenMPRuntime::StaticRTInput StaticInit(
2746                   IVSize, IVSigned, Ordered, IL.getAddress(CGF),
2747                   LB.getAddress(CGF), UB.getAddress(CGF), ST.getAddress(CGF),
2748                   StaticChunkedOne ? Chunk : nullptr);
2749               CGF.CGM.getOpenMPRuntime().emitForStaticInit(
2750                   CGF, S.getBeginLoc(), S.getDirectiveKind(), ScheduleKind,
2751                   StaticInit);
2752               // UB = min(UB, GlobalUB);
2753               if (!StaticChunkedOne)
2754                 CGF.EmitIgnoredExpr(S.getEnsureUpperBound());
2755               // IV = LB;
2756               CGF.EmitIgnoredExpr(S.getInit());
2757               // For unchunked static schedule generate:
2758               //
2759               // while (idx <= UB) {
2760               //   BODY;
2761               //   ++idx;
2762               // }
2763               //
2764               // For static schedule with chunk one:
2765               //
2766               // while (IV <= PrevUB) {
2767               //   BODY;
2768               //   IV += ST;
2769               // }
2770               CGF.EmitOMPInnerLoop(
2771                   S, LoopScope.requiresCleanups(),
2772                   StaticChunkedOne ? S.getCombinedParForInDistCond()
2773                                    : S.getCond(),
2774                   StaticChunkedOne ? S.getDistInc() : S.getInc(),
2775                   [&S, LoopExit](CodeGenFunction &CGF) {
2776                     CGF.EmitOMPLoopBody(S, LoopExit);
2777                     CGF.EmitStopPoint(&S);
2778                   },
2779                   [](CodeGenFunction &) {});
2780             });
2781         EmitBlock(LoopExit.getBlock());
2782         // Tell the runtime we are done.
2783         auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2784           CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
2785                                                          S.getDirectiveKind());
2786         };
2787         OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
2788       } else {
2789         const bool IsMonotonic =
2790             Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static ||
2791             ScheduleKind.Schedule == OMPC_SCHEDULE_unknown ||
2792             ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
2793             ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
2794         // Emit the outer loop, which requests its work chunk [LB..UB] from
2795         // runtime and runs the inner loop to process it.
2796         const OMPLoopArguments LoopArguments(
2797             LB.getAddress(*this), UB.getAddress(*this), ST.getAddress(*this),
2798             IL.getAddress(*this), Chunk, EUB);
2799         EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
2800                             LoopArguments, CGDispatchBounds);
2801       }
2802       if (isOpenMPSimdDirective(S.getDirectiveKind())) {
2803         EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) {
2804           return CGF.Builder.CreateIsNotNull(
2805               CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
2806         });
2807       }
2808       EmitOMPReductionClauseFinal(
2809           S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind())
2810                  ? /*Parallel and Simd*/ OMPD_parallel_for_simd
2811                  : /*Parallel only*/ OMPD_parallel);
2812       // Emit post-update of the reduction variables if IsLastIter != 0.
2813       emitPostUpdateForReductionClause(
2814           *this, S, [IL, &S](CodeGenFunction &CGF) {
2815             return CGF.Builder.CreateIsNotNull(
2816                 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
2817           });
2818       // Emit final copy of the lastprivate variables if IsLastIter != 0.
2819       if (HasLastprivateClause)
2820         EmitOMPLastprivateClauseFinal(
2821             S, isOpenMPSimdDirective(S.getDirectiveKind()),
2822             Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc())));
2823     }
2824     EmitOMPLinearClauseFinal(S, [IL, &S](CodeGenFunction &CGF) {
2825       return CGF.Builder.CreateIsNotNull(
2826           CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
2827     });
2828     DoacrossCleanupScope.ForceCleanup();
2829     // We're now done with the loop, so jump to the continuation block.
2830     if (ContBlock) {
2831       EmitBranch(ContBlock);
2832       EmitBlock(ContBlock, /*IsFinished=*/true);
2833     }
2834   }
2835   return HasLastprivateClause;
2836 }
2837 
2838 /// The following two functions generate expressions for the loop lower
2839 /// and upper bounds in case of static and dynamic (dispatch) schedule
2840 /// of the associated 'for' or 'distribute' loop.
2841 static std::pair<LValue, LValue>
2842 emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
2843   const auto &LS = cast<OMPLoopDirective>(S);
2844   LValue LB =
2845       EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2846   LValue UB =
2847       EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2848   return {LB, UB};
2849 }
2850 
2851 /// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
2852 /// consider the lower and upper bound expressions generated by the
2853 /// worksharing loop support, but we use 0 and the iteration space size as
2854 /// constants
2855 static std::pair<llvm::Value *, llvm::Value *>
2856 emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S,
2857                           Address LB, Address UB) {
2858   const auto &LS = cast<OMPLoopDirective>(S);
2859   const Expr *IVExpr = LS.getIterationVariable();
2860   const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
2861   llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
2862   llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
2863   return {LBVal, UBVal};
2864 }
2865 
2866 void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
2867   bool HasLastprivates = false;
2868   auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2869                                           PrePostActionTy &) {
2870     OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
2871     HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2872                                                  emitForLoopBounds,
2873                                                  emitDispatchForLoopBounds);
2874   };
2875   {
2876     auto LPCRegion =
2877         CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
2878     OMPLexicalScope Scope(*this, S, OMPD_unknown);
2879     CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2880                                                 S.hasCancel());
2881   }
2882 
2883   // Emit an implicit barrier at the end.
2884   if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates)
2885     CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for);
2886   // Check for outer lastprivate conditional update.
2887   checkForLastprivateConditionalUpdate(*this, S);
2888 }
2889 
2890 void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
2891   bool HasLastprivates = false;
2892   auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2893                                           PrePostActionTy &) {
2894     HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2895                                                  emitForLoopBounds,
2896                                                  emitDispatchForLoopBounds);
2897   };
2898   {
2899     auto LPCRegion =
2900         CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
2901     OMPLexicalScope Scope(*this, S, OMPD_unknown);
2902     CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2903   }
2904 
2905   // Emit an implicit barrier at the end.
2906   if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates)
2907     CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for);
2908   // Check for outer lastprivate conditional update.
2909   checkForLastprivateConditionalUpdate(*this, S);
2910 }
2911 
2912 static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2913                                 const Twine &Name,
2914                                 llvm::Value *Init = nullptr) {
2915   LValue LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
2916   if (Init)
2917     CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
2918   return LVal;
2919 }
2920 
2921 void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
2922   const Stmt *CapturedStmt = S.getInnermostCapturedStmt()->getCapturedStmt();
2923   const auto *CS = dyn_cast<CompoundStmt>(CapturedStmt);
2924   bool HasLastprivates = false;
2925   auto &&CodeGen = [&S, CapturedStmt, CS,
2926                     &HasLastprivates](CodeGenFunction &CGF, PrePostActionTy &) {
2927     ASTContext &C = CGF.getContext();
2928     QualType KmpInt32Ty =
2929         C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2930     // Emit helper vars inits.
2931     LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2932                                   CGF.Builder.getInt32(0));
2933     llvm::ConstantInt *GlobalUBVal = CS != nullptr
2934                                          ? CGF.Builder.getInt32(CS->size() - 1)
2935                                          : CGF.Builder.getInt32(0);
2936     LValue UB =
2937         createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2938     LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2939                                   CGF.Builder.getInt32(1));
2940     LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2941                                   CGF.Builder.getInt32(0));
2942     // Loop counter.
2943     LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
2944     OpaqueValueExpr IVRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue);
2945     CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
2946     OpaqueValueExpr UBRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue);
2947     CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2948     // Generate condition for loop.
2949     BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
2950                         OK_Ordinary, S.getBeginLoc(), FPOptions());
2951     // Increment for loop counter.
2952     UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
2953                       S.getBeginLoc(), true);
2954     auto &&BodyGen = [CapturedStmt, CS, &S, &IV](CodeGenFunction &CGF) {
2955       // Iterate through all sections and emit a switch construct:
2956       // switch (IV) {
2957       //   case 0:
2958       //     <SectionStmt[0]>;
2959       //     break;
2960       // ...
2961       //   case <NumSection> - 1:
2962       //     <SectionStmt[<NumSection> - 1]>;
2963       //     break;
2964       // }
2965       // .omp.sections.exit:
2966       llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
2967       llvm::SwitchInst *SwitchStmt =
2968           CGF.Builder.CreateSwitch(CGF.EmitLoadOfScalar(IV, S.getBeginLoc()),
2969                                    ExitBB, CS == nullptr ? 1 : CS->size());
2970       if (CS) {
2971         unsigned CaseNumber = 0;
2972         for (const Stmt *SubStmt : CS->children()) {
2973           auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2974           CGF.EmitBlock(CaseBB);
2975           SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
2976           CGF.EmitStmt(SubStmt);
2977           CGF.EmitBranch(ExitBB);
2978           ++CaseNumber;
2979         }
2980       } else {
2981         llvm::BasicBlock *CaseBB = CGF.createBasicBlock(".omp.sections.case");
2982         CGF.EmitBlock(CaseBB);
2983         SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
2984         CGF.EmitStmt(CapturedStmt);
2985         CGF.EmitBranch(ExitBB);
2986       }
2987       CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2988     };
2989 
2990     CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2991     if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
2992       // Emit implicit barrier to synchronize threads and avoid data races on
2993       // initialization of firstprivate variables and post-update of lastprivate
2994       // variables.
2995       CGF.CGM.getOpenMPRuntime().emitBarrierCall(
2996           CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
2997           /*ForceSimpleCall=*/true);
2998     }
2999     CGF.EmitOMPPrivateClause(S, LoopScope);
3000     CGOpenMPRuntime::LastprivateConditionalRAII LPCRegion(CGF, S, IV);
3001     HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
3002     CGF.EmitOMPReductionClauseInit(S, LoopScope);
3003     (void)LoopScope.Privatize();
3004     if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
3005       CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
3006 
3007     // Emit static non-chunked loop.
3008     OpenMPScheduleTy ScheduleKind;
3009     ScheduleKind.Schedule = OMPC_SCHEDULE_static;
3010     CGOpenMPRuntime::StaticRTInput StaticInit(
3011         /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(CGF),
3012         LB.getAddress(CGF), UB.getAddress(CGF), ST.getAddress(CGF));
3013     CGF.CGM.getOpenMPRuntime().emitForStaticInit(
3014         CGF, S.getBeginLoc(), S.getDirectiveKind(), ScheduleKind, StaticInit);
3015     // UB = min(UB, GlobalUB);
3016     llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, S.getBeginLoc());
3017     llvm::Value *MinUBGlobalUB = CGF.Builder.CreateSelect(
3018         CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
3019     CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
3020     // IV = LB;
3021     CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getBeginLoc()), IV);
3022     // while (idx <= UB) { BODY; ++idx; }
3023     CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
3024                          [](CodeGenFunction &) {});
3025     // Tell the runtime we are done.
3026     auto &&CodeGen = [&S](CodeGenFunction &CGF) {
3027       CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
3028                                                      S.getDirectiveKind());
3029     };
3030     CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
3031     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
3032     // Emit post-update of the reduction variables if IsLastIter != 0.
3033     emitPostUpdateForReductionClause(CGF, S, [IL, &S](CodeGenFunction &CGF) {
3034       return CGF.Builder.CreateIsNotNull(
3035           CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
3036     });
3037 
3038     // Emit final copy of the lastprivate variables if IsLastIter != 0.
3039     if (HasLastprivates)
3040       CGF.EmitOMPLastprivateClauseFinal(
3041           S, /*NoFinals=*/false,
3042           CGF.Builder.CreateIsNotNull(
3043               CGF.EmitLoadOfScalar(IL, S.getBeginLoc())));
3044   };
3045 
3046   bool HasCancel = false;
3047   if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
3048     HasCancel = OSD->hasCancel();
3049   else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
3050     HasCancel = OPSD->hasCancel();
3051   OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
3052   CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
3053                                               HasCancel);
3054   // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
3055   // clause. Otherwise the barrier will be generated by the codegen for the
3056   // directive.
3057   if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
3058     // Emit implicit barrier to synchronize threads and avoid data races on
3059     // initialization of firstprivate variables.
3060     CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(),
3061                                            OMPD_unknown);
3062   }
3063 }
3064 
3065 void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
3066   {
3067     auto LPCRegion =
3068         CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
3069     OMPLexicalScope Scope(*this, S, OMPD_unknown);
3070     EmitSections(S);
3071   }
3072   // Emit an implicit barrier at the end.
3073   if (!S.getSingleClause<OMPNowaitClause>()) {
3074     CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(),
3075                                            OMPD_sections);
3076   }
3077   // Check for outer lastprivate conditional update.
3078   checkForLastprivateConditionalUpdate(*this, S);
3079 }
3080 
3081 void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
3082   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3083     CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
3084   };
3085   OMPLexicalScope Scope(*this, S, OMPD_unknown);
3086   CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
3087                                               S.hasCancel());
3088 }
3089 
3090 void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
3091   llvm::SmallVector<const Expr *, 8> CopyprivateVars;
3092   llvm::SmallVector<const Expr *, 8> DestExprs;
3093   llvm::SmallVector<const Expr *, 8> SrcExprs;
3094   llvm::SmallVector<const Expr *, 8> AssignmentOps;
3095   // Check if there are any 'copyprivate' clauses associated with this
3096   // 'single' construct.
3097   // Build a list of copyprivate variables along with helper expressions
3098   // (<source>, <destination>, <destination>=<source> expressions)
3099   for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
3100     CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
3101     DestExprs.append(C->destination_exprs().begin(),
3102                      C->destination_exprs().end());
3103     SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
3104     AssignmentOps.append(C->assignment_ops().begin(),
3105                          C->assignment_ops().end());
3106   }
3107   // Emit code for 'single' region along with 'copyprivate' clauses
3108   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3109     Action.Enter(CGF);
3110     OMPPrivateScope SingleScope(CGF);
3111     (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
3112     CGF.EmitOMPPrivateClause(S, SingleScope);
3113     (void)SingleScope.Privatize();
3114     CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
3115   };
3116   {
3117     auto LPCRegion =
3118         CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
3119     OMPLexicalScope Scope(*this, S, OMPD_unknown);
3120     CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getBeginLoc(),
3121                                             CopyprivateVars, DestExprs,
3122                                             SrcExprs, AssignmentOps);
3123   }
3124   // Emit an implicit barrier at the end (to avoid data race on firstprivate
3125   // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
3126   if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
3127     CGM.getOpenMPRuntime().emitBarrierCall(
3128         *this, S.getBeginLoc(),
3129         S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
3130   }
3131   // Check for outer lastprivate conditional update.
3132   checkForLastprivateConditionalUpdate(*this, S);
3133 }
3134 
3135 static void emitMaster(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
3136   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3137     Action.Enter(CGF);
3138     CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
3139   };
3140   CGF.CGM.getOpenMPRuntime().emitMasterRegion(CGF, CodeGen, S.getBeginLoc());
3141 }
3142 
3143 void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
3144   OMPLexicalScope Scope(*this, S, OMPD_unknown);
3145   emitMaster(*this, S);
3146 }
3147 
3148 void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
3149   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3150     Action.Enter(CGF);
3151     CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
3152   };
3153   const Expr *Hint = nullptr;
3154   if (const auto *HintClause = S.getSingleClause<OMPHintClause>())
3155     Hint = HintClause->getHint();
3156   OMPLexicalScope Scope(*this, S, OMPD_unknown);
3157   CGM.getOpenMPRuntime().emitCriticalRegion(*this,
3158                                             S.getDirectiveName().getAsString(),
3159                                             CodeGen, S.getBeginLoc(), Hint);
3160 }
3161 
3162 void CodeGenFunction::EmitOMPParallelForDirective(
3163     const OMPParallelForDirective &S) {
3164   // Emit directive as a combined directive that consists of two implicit
3165   // directives: 'parallel' with 'for' directive.
3166   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3167     Action.Enter(CGF);
3168     OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
3169     CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
3170                                emitDispatchForLoopBounds);
3171   };
3172   {
3173     auto LPCRegion =
3174         CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
3175     emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
3176                                    emitEmptyBoundParameters);
3177   }
3178   // Check for outer lastprivate conditional update.
3179   checkForLastprivateConditionalUpdate(*this, S);
3180 }
3181 
3182 void CodeGenFunction::EmitOMPParallelForSimdDirective(
3183     const OMPParallelForSimdDirective &S) {
3184   // Emit directive as a combined directive that consists of two implicit
3185   // directives: 'parallel' with 'for' directive.
3186   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3187     Action.Enter(CGF);
3188     CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
3189                                emitDispatchForLoopBounds);
3190   };
3191   {
3192     auto LPCRegion =
3193         CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
3194     emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen,
3195                                    emitEmptyBoundParameters);
3196   }
3197   // Check for outer lastprivate conditional update.
3198   checkForLastprivateConditionalUpdate(*this, S);
3199 }
3200 
3201 void CodeGenFunction::EmitOMPParallelMasterDirective(
3202     const OMPParallelMasterDirective &S) {
3203   // Emit directive as a combined directive that consists of two implicit
3204   // directives: 'parallel' with 'master' directive.
3205   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3206     Action.Enter(CGF);
3207     OMPPrivateScope PrivateScope(CGF);
3208     bool Copyins = CGF.EmitOMPCopyinClause(S);
3209     (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3210     if (Copyins) {
3211       // Emit implicit barrier to synchronize threads and avoid data races on
3212       // propagation master's thread values of threadprivate variables to local
3213       // instances of that variables of all other implicit threads.
3214       CGF.CGM.getOpenMPRuntime().emitBarrierCall(
3215           CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
3216           /*ForceSimpleCall=*/true);
3217     }
3218     CGF.EmitOMPPrivateClause(S, PrivateScope);
3219     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
3220     (void)PrivateScope.Privatize();
3221     emitMaster(CGF, S);
3222     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
3223   };
3224   {
3225     auto LPCRegion =
3226         CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
3227     emitCommonOMPParallelDirective(*this, S, OMPD_master, CodeGen,
3228                                    emitEmptyBoundParameters);
3229     emitPostUpdateForReductionClause(*this, S,
3230                                      [](CodeGenFunction &) { return nullptr; });
3231   }
3232   // Check for outer lastprivate conditional update.
3233   checkForLastprivateConditionalUpdate(*this, S);
3234 }
3235 
3236 void CodeGenFunction::EmitOMPParallelSectionsDirective(
3237     const OMPParallelSectionsDirective &S) {
3238   // Emit directive as a combined directive that consists of two implicit
3239   // directives: 'parallel' with 'sections' directive.
3240   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3241     Action.Enter(CGF);
3242     CGF.EmitSections(S);
3243   };
3244   {
3245     auto LPCRegion =
3246         CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
3247     emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
3248                                    emitEmptyBoundParameters);
3249   }
3250   // Check for outer lastprivate conditional update.
3251   checkForLastprivateConditionalUpdate(*this, S);
3252 }
3253 
3254 void CodeGenFunction::EmitOMPTaskBasedDirective(
3255     const OMPExecutableDirective &S, const OpenMPDirectiveKind CapturedRegion,
3256     const RegionCodeGenTy &BodyGen, const TaskGenTy &TaskGen,
3257     OMPTaskDataTy &Data) {
3258   // Emit outlined function for task construct.
3259   const CapturedStmt *CS = S.getCapturedStmt(CapturedRegion);
3260   auto I = CS->getCapturedDecl()->param_begin();
3261   auto PartId = std::next(I);
3262   auto TaskT = std::next(I, 4);
3263   // Check if the task is final
3264   if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
3265     // If the condition constant folds and can be elided, try to avoid emitting
3266     // the condition and the dead arm of the if/else.
3267     const Expr *Cond = Clause->getCondition();
3268     bool CondConstant;
3269     if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
3270       Data.Final.setInt(CondConstant);
3271     else
3272       Data.Final.setPointer(EvaluateExprAsBool(Cond));
3273   } else {
3274     // By default the task is not final.
3275     Data.Final.setInt(/*IntVal=*/false);
3276   }
3277   // Check if the task has 'priority' clause.
3278   if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
3279     const Expr *Prio = Clause->getPriority();
3280     Data.Priority.setInt(/*IntVal=*/true);
3281     Data.Priority.setPointer(EmitScalarConversion(
3282         EmitScalarExpr(Prio), Prio->getType(),
3283         getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
3284         Prio->getExprLoc()));
3285   }
3286   // The first function argument for tasks is a thread id, the second one is a
3287   // part id (0 for tied tasks, >=0 for untied task).
3288   llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
3289   // Get list of private variables.
3290   for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
3291     auto IRef = C->varlist_begin();
3292     for (const Expr *IInit : C->private_copies()) {
3293       const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
3294       if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
3295         Data.PrivateVars.push_back(*IRef);
3296         Data.PrivateCopies.push_back(IInit);
3297       }
3298       ++IRef;
3299     }
3300   }
3301   EmittedAsPrivate.clear();
3302   // Get list of firstprivate variables.
3303   for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
3304     auto IRef = C->varlist_begin();
3305     auto IElemInitRef = C->inits().begin();
3306     for (const Expr *IInit : C->private_copies()) {
3307       const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
3308       if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
3309         Data.FirstprivateVars.push_back(*IRef);
3310         Data.FirstprivateCopies.push_back(IInit);
3311         Data.FirstprivateInits.push_back(*IElemInitRef);
3312       }
3313       ++IRef;
3314       ++IElemInitRef;
3315     }
3316   }
3317   // Get list of lastprivate variables (for taskloops).
3318   llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
3319   for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
3320     auto IRef = C->varlist_begin();
3321     auto ID = C->destination_exprs().begin();
3322     for (const Expr *IInit : C->private_copies()) {
3323       const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
3324       if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
3325         Data.LastprivateVars.push_back(*IRef);
3326         Data.LastprivateCopies.push_back(IInit);
3327       }
3328       LastprivateDstsOrigs.insert(
3329           {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
3330            cast<DeclRefExpr>(*IRef)});
3331       ++IRef;
3332       ++ID;
3333     }
3334   }
3335   SmallVector<const Expr *, 4> LHSs;
3336   SmallVector<const Expr *, 4> RHSs;
3337   for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
3338     auto IPriv = C->privates().begin();
3339     auto IRed = C->reduction_ops().begin();
3340     auto ILHS = C->lhs_exprs().begin();
3341     auto IRHS = C->rhs_exprs().begin();
3342     for (const Expr *Ref : C->varlists()) {
3343       Data.ReductionVars.emplace_back(Ref);
3344       Data.ReductionCopies.emplace_back(*IPriv);
3345       Data.ReductionOps.emplace_back(*IRed);
3346       LHSs.emplace_back(*ILHS);
3347       RHSs.emplace_back(*IRHS);
3348       std::advance(IPriv, 1);
3349       std::advance(IRed, 1);
3350       std::advance(ILHS, 1);
3351       std::advance(IRHS, 1);
3352     }
3353   }
3354   Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit(
3355       *this, S.getBeginLoc(), LHSs, RHSs, Data);
3356   // Build list of dependences.
3357   for (const auto *C : S.getClausesOfKind<OMPDependClause>())
3358     for (const Expr *IRef : C->varlists())
3359       Data.Dependences.emplace_back(C->getDependencyKind(), IRef);
3360   auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs,
3361                     CapturedRegion](CodeGenFunction &CGF,
3362                                     PrePostActionTy &Action) {
3363     // Set proper addresses for generated private copies.
3364     OMPPrivateScope Scope(CGF);
3365     if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
3366         !Data.LastprivateVars.empty()) {
3367       llvm::FunctionType *CopyFnTy = llvm::FunctionType::get(
3368           CGF.Builder.getVoidTy(), {CGF.Builder.getInt8PtrTy()}, true);
3369       enum { PrivatesParam = 2, CopyFnParam = 3 };
3370       llvm::Value *CopyFn = CGF.Builder.CreateLoad(
3371           CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam)));
3372       llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(
3373           CS->getCapturedDecl()->getParam(PrivatesParam)));
3374       // Map privates.
3375       llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
3376       llvm::SmallVector<llvm::Value *, 16> CallArgs;
3377       CallArgs.push_back(PrivatesPtr);
3378       for (const Expr *E : Data.PrivateVars) {
3379         const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3380         Address PrivatePtr = CGF.CreateMemTemp(
3381             CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
3382         PrivatePtrs.emplace_back(VD, PrivatePtr);
3383         CallArgs.push_back(PrivatePtr.getPointer());
3384       }
3385       for (const Expr *E : Data.FirstprivateVars) {
3386         const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3387         Address PrivatePtr =
3388             CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
3389                               ".firstpriv.ptr.addr");
3390         PrivatePtrs.emplace_back(VD, PrivatePtr);
3391         CallArgs.push_back(PrivatePtr.getPointer());
3392       }
3393       for (const Expr *E : Data.LastprivateVars) {
3394         const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3395         Address PrivatePtr =
3396             CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
3397                               ".lastpriv.ptr.addr");
3398         PrivatePtrs.emplace_back(VD, PrivatePtr);
3399         CallArgs.push_back(PrivatePtr.getPointer());
3400       }
3401       CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3402           CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs);
3403       for (const auto &Pair : LastprivateDstsOrigs) {
3404         const auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
3405         DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(OrigVD),
3406                         /*RefersToEnclosingVariableOrCapture=*/
3407                             CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
3408                         Pair.second->getType(), VK_LValue,
3409                         Pair.second->getExprLoc());
3410         Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
3411           return CGF.EmitLValue(&DRE).getAddress(CGF);
3412         });
3413       }
3414       for (const auto &Pair : PrivatePtrs) {
3415         Address Replacement(CGF.Builder.CreateLoad(Pair.second),
3416                             CGF.getContext().getDeclAlign(Pair.first));
3417         Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
3418       }
3419     }
3420     if (Data.Reductions) {
3421       OMPLexicalScope LexScope(CGF, S, CapturedRegion);
3422       ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionCopies,
3423                              Data.ReductionOps);
3424       llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
3425           CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9)));
3426       for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
3427         RedCG.emitSharedLValue(CGF, Cnt);
3428         RedCG.emitAggregateType(CGF, Cnt);
3429         // FIXME: This must removed once the runtime library is fixed.
3430         // Emit required threadprivate variables for
3431         // initializer/combiner/finalizer.
3432         CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
3433                                                            RedCG, Cnt);
3434         Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
3435             CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
3436         Replacement =
3437             Address(CGF.EmitScalarConversion(
3438                         Replacement.getPointer(), CGF.getContext().VoidPtrTy,
3439                         CGF.getContext().getPointerType(
3440                             Data.ReductionCopies[Cnt]->getType()),
3441                         Data.ReductionCopies[Cnt]->getExprLoc()),
3442                     Replacement.getAlignment());
3443         Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
3444         Scope.addPrivate(RedCG.getBaseDecl(Cnt),
3445                          [Replacement]() { return Replacement; });
3446       }
3447     }
3448     // Privatize all private variables except for in_reduction items.
3449     (void)Scope.Privatize();
3450     SmallVector<const Expr *, 4> InRedVars;
3451     SmallVector<const Expr *, 4> InRedPrivs;
3452     SmallVector<const Expr *, 4> InRedOps;
3453     SmallVector<const Expr *, 4> TaskgroupDescriptors;
3454     for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
3455       auto IPriv = C->privates().begin();
3456       auto IRed = C->reduction_ops().begin();
3457       auto ITD = C->taskgroup_descriptors().begin();
3458       for (const Expr *Ref : C->varlists()) {
3459         InRedVars.emplace_back(Ref);
3460         InRedPrivs.emplace_back(*IPriv);
3461         InRedOps.emplace_back(*IRed);
3462         TaskgroupDescriptors.emplace_back(*ITD);
3463         std::advance(IPriv, 1);
3464         std::advance(IRed, 1);
3465         std::advance(ITD, 1);
3466       }
3467     }
3468     // Privatize in_reduction items here, because taskgroup descriptors must be
3469     // privatized earlier.
3470     OMPPrivateScope InRedScope(CGF);
3471     if (!InRedVars.empty()) {
3472       ReductionCodeGen RedCG(InRedVars, InRedPrivs, InRedOps);
3473       for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
3474         RedCG.emitSharedLValue(CGF, Cnt);
3475         RedCG.emitAggregateType(CGF, Cnt);
3476         // The taskgroup descriptor variable is always implicit firstprivate and
3477         // privatized already during processing of the firstprivates.
3478         // FIXME: This must removed once the runtime library is fixed.
3479         // Emit required threadprivate variables for
3480         // initializer/combiner/finalizer.
3481         CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
3482                                                            RedCG, Cnt);
3483         llvm::Value *ReductionsPtr =
3484             CGF.EmitLoadOfScalar(CGF.EmitLValue(TaskgroupDescriptors[Cnt]),
3485                                  TaskgroupDescriptors[Cnt]->getExprLoc());
3486         Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
3487             CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
3488         Replacement = Address(
3489             CGF.EmitScalarConversion(
3490                 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
3491                 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
3492                 InRedPrivs[Cnt]->getExprLoc()),
3493             Replacement.getAlignment());
3494         Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
3495         InRedScope.addPrivate(RedCG.getBaseDecl(Cnt),
3496                               [Replacement]() { return Replacement; });
3497       }
3498     }
3499     (void)InRedScope.Privatize();
3500 
3501     Action.Enter(CGF);
3502     BodyGen(CGF);
3503   };
3504   llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
3505       S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
3506       Data.NumberOfParts);
3507   OMPLexicalScope Scope(*this, S, llvm::None,
3508                         !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3509                             !isOpenMPSimdDirective(S.getDirectiveKind()));
3510   TaskGen(*this, OutlinedFn, Data);
3511 }
3512 
3513 static ImplicitParamDecl *
3514 createImplicitFirstprivateForType(ASTContext &C, OMPTaskDataTy &Data,
3515                                   QualType Ty, CapturedDecl *CD,
3516                                   SourceLocation Loc) {
3517   auto *OrigVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
3518                                            ImplicitParamDecl::Other);
3519   auto *OrigRef = DeclRefExpr::Create(
3520       C, NestedNameSpecifierLoc(), SourceLocation(), OrigVD,
3521       /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
3522   auto *PrivateVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
3523                                               ImplicitParamDecl::Other);
3524   auto *PrivateRef = DeclRefExpr::Create(
3525       C, NestedNameSpecifierLoc(), SourceLocation(), PrivateVD,
3526       /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
3527   QualType ElemType = C.getBaseElementType(Ty);
3528   auto *InitVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, ElemType,
3529                                            ImplicitParamDecl::Other);
3530   auto *InitRef = DeclRefExpr::Create(
3531       C, NestedNameSpecifierLoc(), SourceLocation(), InitVD,
3532       /*RefersToEnclosingVariableOrCapture=*/false, Loc, ElemType, VK_LValue);
3533   PrivateVD->setInitStyle(VarDecl::CInit);
3534   PrivateVD->setInit(ImplicitCastExpr::Create(C, ElemType, CK_LValueToRValue,
3535                                               InitRef, /*BasePath=*/nullptr,
3536                                               VK_RValue));
3537   Data.FirstprivateVars.emplace_back(OrigRef);
3538   Data.FirstprivateCopies.emplace_back(PrivateRef);
3539   Data.FirstprivateInits.emplace_back(InitRef);
3540   return OrigVD;
3541 }
3542 
3543 void CodeGenFunction::EmitOMPTargetTaskBasedDirective(
3544     const OMPExecutableDirective &S, const RegionCodeGenTy &BodyGen,
3545     OMPTargetDataInfo &InputInfo) {
3546   // Emit outlined function for task construct.
3547   const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
3548   Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
3549   QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
3550   auto I = CS->getCapturedDecl()->param_begin();
3551   auto PartId = std::next(I);
3552   auto TaskT = std::next(I, 4);
3553   OMPTaskDataTy Data;
3554   // The task is not final.
3555   Data.Final.setInt(/*IntVal=*/false);
3556   // Get list of firstprivate variables.
3557   for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
3558     auto IRef = C->varlist_begin();
3559     auto IElemInitRef = C->inits().begin();
3560     for (auto *IInit : C->private_copies()) {
3561       Data.FirstprivateVars.push_back(*IRef);
3562       Data.FirstprivateCopies.push_back(IInit);
3563       Data.FirstprivateInits.push_back(*IElemInitRef);
3564       ++IRef;
3565       ++IElemInitRef;
3566     }
3567   }
3568   OMPPrivateScope TargetScope(*this);
3569   VarDecl *BPVD = nullptr;
3570   VarDecl *PVD = nullptr;
3571   VarDecl *SVD = nullptr;
3572   if (InputInfo.NumberOfTargetItems > 0) {
3573     auto *CD = CapturedDecl::Create(
3574         getContext(), getContext().getTranslationUnitDecl(), /*NumParams=*/0);
3575     llvm::APInt ArrSize(/*numBits=*/32, InputInfo.NumberOfTargetItems);
3576     QualType BaseAndPointersType = getContext().getConstantArrayType(
3577         getContext().VoidPtrTy, ArrSize, nullptr, ArrayType::Normal,
3578         /*IndexTypeQuals=*/0);
3579     BPVD = createImplicitFirstprivateForType(
3580         getContext(), Data, BaseAndPointersType, CD, S.getBeginLoc());
3581     PVD = createImplicitFirstprivateForType(
3582         getContext(), Data, BaseAndPointersType, CD, S.getBeginLoc());
3583     QualType SizesType = getContext().getConstantArrayType(
3584         getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1),
3585         ArrSize, nullptr, ArrayType::Normal,
3586         /*IndexTypeQuals=*/0);
3587     SVD = createImplicitFirstprivateForType(getContext(), Data, SizesType, CD,
3588                                             S.getBeginLoc());
3589     TargetScope.addPrivate(
3590         BPVD, [&InputInfo]() { return InputInfo.BasePointersArray; });
3591     TargetScope.addPrivate(PVD,
3592                            [&InputInfo]() { return InputInfo.PointersArray; });
3593     TargetScope.addPrivate(SVD,
3594                            [&InputInfo]() { return InputInfo.SizesArray; });
3595   }
3596   (void)TargetScope.Privatize();
3597   // Build list of dependences.
3598   for (const auto *C : S.getClausesOfKind<OMPDependClause>())
3599     for (const Expr *IRef : C->varlists())
3600       Data.Dependences.emplace_back(C->getDependencyKind(), IRef);
3601   auto &&CodeGen = [&Data, &S, CS, &BodyGen, BPVD, PVD, SVD,
3602                     &InputInfo](CodeGenFunction &CGF, PrePostActionTy &Action) {
3603     // Set proper addresses for generated private copies.
3604     OMPPrivateScope Scope(CGF);
3605     if (!Data.FirstprivateVars.empty()) {
3606       llvm::FunctionType *CopyFnTy = llvm::FunctionType::get(
3607           CGF.Builder.getVoidTy(), {CGF.Builder.getInt8PtrTy()}, true);
3608       enum { PrivatesParam = 2, CopyFnParam = 3 };
3609       llvm::Value *CopyFn = CGF.Builder.CreateLoad(
3610           CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam)));
3611       llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(
3612           CS->getCapturedDecl()->getParam(PrivatesParam)));
3613       // Map privates.
3614       llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
3615       llvm::SmallVector<llvm::Value *, 16> CallArgs;
3616       CallArgs.push_back(PrivatesPtr);
3617       for (const Expr *E : Data.FirstprivateVars) {
3618         const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3619         Address PrivatePtr =
3620             CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
3621                               ".firstpriv.ptr.addr");
3622         PrivatePtrs.emplace_back(VD, PrivatePtr);
3623         CallArgs.push_back(PrivatePtr.getPointer());
3624       }
3625       CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3626           CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs);
3627       for (const auto &Pair : PrivatePtrs) {
3628         Address Replacement(CGF.Builder.CreateLoad(Pair.second),
3629                             CGF.getContext().getDeclAlign(Pair.first));
3630         Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
3631       }
3632     }
3633     // Privatize all private variables except for in_reduction items.
3634     (void)Scope.Privatize();
3635     if (InputInfo.NumberOfTargetItems > 0) {
3636       InputInfo.BasePointersArray = CGF.Builder.CreateConstArrayGEP(
3637           CGF.GetAddrOfLocalVar(BPVD), /*Index=*/0);
3638       InputInfo.PointersArray = CGF.Builder.CreateConstArrayGEP(
3639           CGF.GetAddrOfLocalVar(PVD), /*Index=*/0);
3640       InputInfo.SizesArray = CGF.Builder.CreateConstArrayGEP(
3641           CGF.GetAddrOfLocalVar(SVD), /*Index=*/0);
3642     }
3643 
3644     Action.Enter(CGF);
3645     OMPLexicalScope LexScope(CGF, S, OMPD_task, /*EmitPreInitStmt=*/false);
3646     BodyGen(CGF);
3647   };
3648   llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
3649       S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, /*Tied=*/true,
3650       Data.NumberOfParts);
3651   llvm::APInt TrueOrFalse(32, S.hasClausesOfKind<OMPNowaitClause>() ? 1 : 0);
3652   IntegerLiteral IfCond(getContext(), TrueOrFalse,
3653                         getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
3654                         SourceLocation());
3655 
3656   CGM.getOpenMPRuntime().emitTaskCall(*this, S.getBeginLoc(), S, OutlinedFn,
3657                                       SharedsTy, CapturedStruct, &IfCond, Data);
3658 }
3659 
3660 void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
3661   // Emit outlined function for task construct.
3662   const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
3663   Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
3664   QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
3665   const Expr *IfCond = nullptr;
3666   for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3667     if (C->getNameModifier() == OMPD_unknown ||
3668         C->getNameModifier() == OMPD_task) {
3669       IfCond = C->getCondition();
3670       break;
3671     }
3672   }
3673 
3674   OMPTaskDataTy Data;
3675   // Check if we should emit tied or untied task.
3676   Data.Tied = !S.getSingleClause<OMPUntiedClause>();
3677   auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
3678     CGF.EmitStmt(CS->getCapturedStmt());
3679   };
3680   auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
3681                     IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn,
3682                             const OMPTaskDataTy &Data) {
3683     CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getBeginLoc(), S, OutlinedFn,
3684                                             SharedsTy, CapturedStruct, IfCond,
3685                                             Data);
3686   };
3687   auto LPCRegion =
3688       CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
3689   EmitOMPTaskBasedDirective(S, OMPD_task, BodyGen, TaskGen, Data);
3690 }
3691 
3692 void CodeGenFunction::EmitOMPTaskyieldDirective(
3693     const OMPTaskyieldDirective &S) {
3694   CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getBeginLoc());
3695 }
3696 
3697 void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
3698   CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_barrier);
3699 }
3700 
3701 void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
3702   CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getBeginLoc());
3703 }
3704 
3705 void CodeGenFunction::EmitOMPTaskgroupDirective(
3706     const OMPTaskgroupDirective &S) {
3707   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3708     Action.Enter(CGF);
3709     if (const Expr *E = S.getReductionRef()) {
3710       SmallVector<const Expr *, 4> LHSs;
3711       SmallVector<const Expr *, 4> RHSs;
3712       OMPTaskDataTy Data;
3713       for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) {
3714         auto IPriv = C->privates().begin();
3715         auto IRed = C->reduction_ops().begin();
3716         auto ILHS = C->lhs_exprs().begin();
3717         auto IRHS = C->rhs_exprs().begin();
3718         for (const Expr *Ref : C->varlists()) {
3719           Data.ReductionVars.emplace_back(Ref);
3720           Data.ReductionCopies.emplace_back(*IPriv);
3721           Data.ReductionOps.emplace_back(*IRed);
3722           LHSs.emplace_back(*ILHS);
3723           RHSs.emplace_back(*IRHS);
3724           std::advance(IPriv, 1);
3725           std::advance(IRed, 1);
3726           std::advance(ILHS, 1);
3727           std::advance(IRHS, 1);
3728         }
3729       }
3730       llvm::Value *ReductionDesc =
3731           CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getBeginLoc(),
3732                                                            LHSs, RHSs, Data);
3733       const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3734       CGF.EmitVarDecl(*VD);
3735       CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD),
3736                             /*Volatile=*/false, E->getType());
3737     }
3738     CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
3739   };
3740   OMPLexicalScope Scope(*this, S, OMPD_unknown);
3741   CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getBeginLoc());
3742 }
3743 
3744 void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
3745   CGM.getOpenMPRuntime().emitFlush(
3746       *this,
3747       [&S]() -> ArrayRef<const Expr *> {
3748         if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>())
3749           return llvm::makeArrayRef(FlushClause->varlist_begin(),
3750                                     FlushClause->varlist_end());
3751         return llvm::None;
3752       }(),
3753       S.getBeginLoc());
3754 }
3755 
3756 void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S,
3757                                             const CodeGenLoopTy &CodeGenLoop,
3758                                             Expr *IncExpr) {
3759   // Emit the loop iteration variable.
3760   const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
3761   const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl());
3762   EmitVarDecl(*IVDecl);
3763 
3764   // Emit the iterations count variable.
3765   // If it is not a variable, Sema decided to calculate iterations count on each
3766   // iteration (e.g., it is foldable into a constant).
3767   if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
3768     EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3769     // Emit calculation of the iterations count.
3770     EmitIgnoredExpr(S.getCalcLastIteration());
3771   }
3772 
3773   CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
3774 
3775   bool HasLastprivateClause = false;
3776   // Check pre-condition.
3777   {
3778     OMPLoopScope PreInitScope(*this, S);
3779     // Skip the entire loop if we don't meet the precondition.
3780     // If the condition constant folds and can be elided, avoid emitting the
3781     // whole loop.
3782     bool CondConstant;
3783     llvm::BasicBlock *ContBlock = nullptr;
3784     if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3785       if (!CondConstant)
3786         return;
3787     } else {
3788       llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then");
3789       ContBlock = createBasicBlock("omp.precond.end");
3790       emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
3791                   getProfileCount(&S));
3792       EmitBlock(ThenBlock);
3793       incrementProfileCounter(&S);
3794     }
3795 
3796     emitAlignedClause(*this, S);
3797     // Emit 'then' code.
3798     {
3799       // Emit helper vars inits.
3800 
3801       LValue LB = EmitOMPHelperVar(
3802           *this, cast<DeclRefExpr>(
3803                      (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3804                           ? S.getCombinedLowerBoundVariable()
3805                           : S.getLowerBoundVariable())));
3806       LValue UB = EmitOMPHelperVar(
3807           *this, cast<DeclRefExpr>(
3808                      (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3809                           ? S.getCombinedUpperBoundVariable()
3810                           : S.getUpperBoundVariable())));
3811       LValue ST =
3812           EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
3813       LValue IL =
3814           EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
3815 
3816       OMPPrivateScope LoopScope(*this);
3817       if (EmitOMPFirstprivateClause(S, LoopScope)) {
3818         // Emit implicit barrier to synchronize threads and avoid data races
3819         // on initialization of firstprivate variables and post-update of
3820         // lastprivate variables.
3821         CGM.getOpenMPRuntime().emitBarrierCall(
3822             *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
3823             /*ForceSimpleCall=*/true);
3824       }
3825       EmitOMPPrivateClause(S, LoopScope);
3826       if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
3827           !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3828           !isOpenMPTeamsDirective(S.getDirectiveKind()))
3829         EmitOMPReductionClauseInit(S, LoopScope);
3830       HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
3831       EmitOMPPrivateLoopCounters(S, LoopScope);
3832       (void)LoopScope.Privatize();
3833       if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
3834         CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(*this, S);
3835 
3836       // Detect the distribute schedule kind and chunk.
3837       llvm::Value *Chunk = nullptr;
3838       OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
3839       if (const auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
3840         ScheduleKind = C->getDistScheduleKind();
3841         if (const Expr *Ch = C->getChunkSize()) {
3842           Chunk = EmitScalarExpr(Ch);
3843           Chunk = EmitScalarConversion(Chunk, Ch->getType(),
3844                                        S.getIterationVariable()->getType(),
3845                                        S.getBeginLoc());
3846         }
3847       } else {
3848         // Default behaviour for dist_schedule clause.
3849         CGM.getOpenMPRuntime().getDefaultDistScheduleAndChunk(
3850             *this, S, ScheduleKind, Chunk);
3851       }
3852       const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3853       const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3854 
3855       // OpenMP [2.10.8, distribute Construct, Description]
3856       // If dist_schedule is specified, kind must be static. If specified,
3857       // iterations are divided into chunks of size chunk_size, chunks are
3858       // assigned to the teams of the league in a round-robin fashion in the
3859       // order of the team number. When no chunk_size is specified, the
3860       // iteration space is divided into chunks that are approximately equal
3861       // in size, and at most one chunk is distributed to each team of the
3862       // league. The size of the chunks is unspecified in this case.
3863       bool StaticChunked = RT.isStaticChunked(
3864           ScheduleKind, /* Chunked */ Chunk != nullptr) &&
3865           isOpenMPLoopBoundSharingDirective(S.getDirectiveKind());
3866       if (RT.isStaticNonchunked(ScheduleKind,
3867                                 /* Chunked */ Chunk != nullptr) ||
3868           StaticChunked) {
3869         CGOpenMPRuntime::StaticRTInput StaticInit(
3870             IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(*this),
3871             LB.getAddress(*this), UB.getAddress(*this), ST.getAddress(*this),
3872             StaticChunked ? Chunk : nullptr);
3873         RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind,
3874                                     StaticInit);
3875         JumpDest LoopExit =
3876             getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
3877         // UB = min(UB, GlobalUB);
3878         EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3879                             ? S.getCombinedEnsureUpperBound()
3880                             : S.getEnsureUpperBound());
3881         // IV = LB;
3882         EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3883                             ? S.getCombinedInit()
3884                             : S.getInit());
3885 
3886         const Expr *Cond =
3887             isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3888                 ? S.getCombinedCond()
3889                 : S.getCond();
3890 
3891         if (StaticChunked)
3892           Cond = S.getCombinedDistCond();
3893 
3894         // For static unchunked schedules generate:
3895         //
3896         //  1. For distribute alone, codegen
3897         //    while (idx <= UB) {
3898         //      BODY;
3899         //      ++idx;
3900         //    }
3901         //
3902         //  2. When combined with 'for' (e.g. as in 'distribute parallel for')
3903         //    while (idx <= UB) {
3904         //      <CodeGen rest of pragma>(LB, UB);
3905         //      idx += ST;
3906         //    }
3907         //
3908         // For static chunk one schedule generate:
3909         //
3910         // while (IV <= GlobalUB) {
3911         //   <CodeGen rest of pragma>(LB, UB);
3912         //   LB += ST;
3913         //   UB += ST;
3914         //   UB = min(UB, GlobalUB);
3915         //   IV = LB;
3916         // }
3917         //
3918         emitCommonSimdLoop(
3919             *this, S,
3920             [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3921               if (isOpenMPSimdDirective(S.getDirectiveKind()))
3922                 CGF.EmitOMPSimdInit(S, /*IsMonotonic=*/true);
3923             },
3924             [&S, &LoopScope, Cond, IncExpr, LoopExit, &CodeGenLoop,
3925              StaticChunked](CodeGenFunction &CGF, PrePostActionTy &) {
3926               CGF.EmitOMPInnerLoop(
3927                   S, LoopScope.requiresCleanups(), Cond, IncExpr,
3928                   [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
3929                     CodeGenLoop(CGF, S, LoopExit);
3930                   },
3931                   [&S, StaticChunked](CodeGenFunction &CGF) {
3932                     if (StaticChunked) {
3933                       CGF.EmitIgnoredExpr(S.getCombinedNextLowerBound());
3934                       CGF.EmitIgnoredExpr(S.getCombinedNextUpperBound());
3935                       CGF.EmitIgnoredExpr(S.getCombinedEnsureUpperBound());
3936                       CGF.EmitIgnoredExpr(S.getCombinedInit());
3937                     }
3938                   });
3939             });
3940         EmitBlock(LoopExit.getBlock());
3941         // Tell the runtime we are done.
3942         RT.emitForStaticFinish(*this, S.getEndLoc(), S.getDirectiveKind());
3943       } else {
3944         // Emit the outer loop, which requests its work chunk [LB..UB] from
3945         // runtime and runs the inner loop to process it.
3946         const OMPLoopArguments LoopArguments = {
3947             LB.getAddress(*this), UB.getAddress(*this), ST.getAddress(*this),
3948             IL.getAddress(*this), Chunk};
3949         EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
3950                                    CodeGenLoop);
3951       }
3952       if (isOpenMPSimdDirective(S.getDirectiveKind())) {
3953         EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) {
3954           return CGF.Builder.CreateIsNotNull(
3955               CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
3956         });
3957       }
3958       if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
3959           !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3960           !isOpenMPTeamsDirective(S.getDirectiveKind())) {
3961         EmitOMPReductionClauseFinal(S, OMPD_simd);
3962         // Emit post-update of the reduction variables if IsLastIter != 0.
3963         emitPostUpdateForReductionClause(
3964             *this, S, [IL, &S](CodeGenFunction &CGF) {
3965               return CGF.Builder.CreateIsNotNull(
3966                   CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
3967             });
3968       }
3969       // Emit final copy of the lastprivate variables if IsLastIter != 0.
3970       if (HasLastprivateClause) {
3971         EmitOMPLastprivateClauseFinal(
3972             S, /*NoFinals=*/false,
3973             Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc())));
3974       }
3975     }
3976 
3977     // We're now done with the loop, so jump to the continuation block.
3978     if (ContBlock) {
3979       EmitBranch(ContBlock);
3980       EmitBlock(ContBlock, true);
3981     }
3982   }
3983 }
3984 
3985 void CodeGenFunction::EmitOMPDistributeDirective(
3986     const OMPDistributeDirective &S) {
3987   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3988     CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
3989   };
3990   OMPLexicalScope Scope(*this, S, OMPD_unknown);
3991   CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
3992 }
3993 
3994 static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
3995                                                    const CapturedStmt *S,
3996                                                    SourceLocation Loc) {
3997   CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3998   CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
3999   CGF.CapturedStmtInfo = &CapStmtInfo;
4000   llvm::Function *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S, Loc);
4001   Fn->setDoesNotRecurse();
4002   return Fn;
4003 }
4004 
4005 void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
4006   if (S.hasClausesOfKind<OMPDependClause>()) {
4007     assert(!S.getAssociatedStmt() &&
4008            "No associated statement must be in ordered depend construct.");
4009     for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
4010       CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
4011     return;
4012   }
4013   const auto *C = S.getSingleClause<OMPSIMDClause>();
4014   auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
4015                                  PrePostActionTy &Action) {
4016     const CapturedStmt *CS = S.getInnermostCapturedStmt();
4017     if (C) {
4018       llvm::SmallVector<llvm::Value *, 16> CapturedVars;
4019       CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
4020       llvm::Function *OutlinedFn =
4021           emitOutlinedOrderedFunction(CGM, CS, S.getBeginLoc());
4022       CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getBeginLoc(),
4023                                                       OutlinedFn, CapturedVars);
4024     } else {
4025       Action.Enter(CGF);
4026       CGF.EmitStmt(CS->getCapturedStmt());
4027     }
4028   };
4029   OMPLexicalScope Scope(*this, S, OMPD_unknown);
4030   CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getBeginLoc(), !C);
4031 }
4032 
4033 static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
4034                                          QualType SrcType, QualType DestType,
4035                                          SourceLocation Loc) {
4036   assert(CGF.hasScalarEvaluationKind(DestType) &&
4037          "DestType must have scalar evaluation kind.");
4038   assert(!Val.isAggregate() && "Must be a scalar or complex.");
4039   return Val.isScalar() ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
4040                                                    DestType, Loc)
4041                         : CGF.EmitComplexToScalarConversion(
4042                               Val.getComplexVal(), SrcType, DestType, Loc);
4043 }
4044 
4045 static CodeGenFunction::ComplexPairTy
4046 convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
4047                       QualType DestType, SourceLocation Loc) {
4048   assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
4049          "DestType must have complex evaluation kind.");
4050   CodeGenFunction::ComplexPairTy ComplexVal;
4051   if (Val.isScalar()) {
4052     // Convert the input element to the element type of the complex.
4053     QualType DestElementType =
4054         DestType->castAs<ComplexType>()->getElementType();
4055     llvm::Value *ScalarVal = CGF.EmitScalarConversion(
4056         Val.getScalarVal(), SrcType, DestElementType, Loc);
4057     ComplexVal = CodeGenFunction::ComplexPairTy(
4058         ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
4059   } else {
4060     assert(Val.isComplex() && "Must be a scalar or complex.");
4061     QualType SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
4062     QualType DestElementType =
4063         DestType->castAs<ComplexType>()->getElementType();
4064     ComplexVal.first = CGF.EmitScalarConversion(
4065         Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
4066     ComplexVal.second = CGF.EmitScalarConversion(
4067         Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
4068   }
4069   return ComplexVal;
4070 }
4071 
4072 static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
4073                                   LValue LVal, RValue RVal) {
4074   if (LVal.isGlobalReg()) {
4075     CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
4076   } else {
4077     CGF.EmitAtomicStore(RVal, LVal,
4078                         IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
4079                                  : llvm::AtomicOrdering::Monotonic,
4080                         LVal.isVolatile(), /*isInit=*/false);
4081   }
4082 }
4083 
4084 void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
4085                                          QualType RValTy, SourceLocation Loc) {
4086   switch (getEvaluationKind(LVal.getType())) {
4087   case TEK_Scalar:
4088     EmitStoreThroughLValue(RValue::get(convertToScalarValue(
4089                                *this, RVal, RValTy, LVal.getType(), Loc)),
4090                            LVal);
4091     break;
4092   case TEK_Complex:
4093     EmitStoreOfComplex(
4094         convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
4095         /*isInit=*/false);
4096     break;
4097   case TEK_Aggregate:
4098     llvm_unreachable("Must be a scalar or complex.");
4099   }
4100 }
4101 
4102 static void emitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
4103                                   const Expr *X, const Expr *V,
4104                                   SourceLocation Loc) {
4105   // v = x;
4106   assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
4107   assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
4108   LValue XLValue = CGF.EmitLValue(X);
4109   LValue VLValue = CGF.EmitLValue(V);
4110   RValue Res = XLValue.isGlobalReg()
4111                    ? CGF.EmitLoadOfLValue(XLValue, Loc)
4112                    : CGF.EmitAtomicLoad(
4113                          XLValue, Loc,
4114                          IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
4115                                   : llvm::AtomicOrdering::Monotonic,
4116                          XLValue.isVolatile());
4117   // OpenMP, 2.12.6, atomic Construct
4118   // Any atomic construct with a seq_cst clause forces the atomically
4119   // performed operation to include an implicit flush operation without a
4120   // list.
4121   if (IsSeqCst)
4122     CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
4123   CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
4124   CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, V);
4125 }
4126 
4127 static void emitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
4128                                    const Expr *X, const Expr *E,
4129                                    SourceLocation Loc) {
4130   // x = expr;
4131   assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
4132   emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
4133   CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X);
4134   // OpenMP, 2.12.6, atomic Construct
4135   // Any atomic construct with a seq_cst clause forces the atomically
4136   // performed operation to include an implicit flush operation without a
4137   // list.
4138   if (IsSeqCst)
4139     CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
4140 }
4141 
4142 static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
4143                                                 RValue Update,
4144                                                 BinaryOperatorKind BO,
4145                                                 llvm::AtomicOrdering AO,
4146                                                 bool IsXLHSInRHSPart) {
4147   ASTContext &Context = CGF.getContext();
4148   // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
4149   // expression is simple and atomic is allowed for the given type for the
4150   // target platform.
4151   if (BO == BO_Comma || !Update.isScalar() ||
4152       !Update.getScalarVal()->getType()->isIntegerTy() || !X.isSimple() ||
4153       (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
4154        (Update.getScalarVal()->getType() !=
4155         X.getAddress(CGF).getElementType())) ||
4156       !X.getAddress(CGF).getElementType()->isIntegerTy() ||
4157       !Context.getTargetInfo().hasBuiltinAtomic(
4158           Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
4159     return std::make_pair(false, RValue::get(nullptr));
4160 
4161   llvm::AtomicRMWInst::BinOp RMWOp;
4162   switch (BO) {
4163   case BO_Add:
4164     RMWOp = llvm::AtomicRMWInst::Add;
4165     break;
4166   case BO_Sub:
4167     if (!IsXLHSInRHSPart)
4168       return std::make_pair(false, RValue::get(nullptr));
4169     RMWOp = llvm::AtomicRMWInst::Sub;
4170     break;
4171   case BO_And:
4172     RMWOp = llvm::AtomicRMWInst::And;
4173     break;
4174   case BO_Or:
4175     RMWOp = llvm::AtomicRMWInst::Or;
4176     break;
4177   case BO_Xor:
4178     RMWOp = llvm::AtomicRMWInst::Xor;
4179     break;
4180   case BO_LT:
4181     RMWOp = X.getType()->hasSignedIntegerRepresentation()
4182                 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
4183                                    : llvm::AtomicRMWInst::Max)
4184                 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
4185                                    : llvm::AtomicRMWInst::UMax);
4186     break;
4187   case BO_GT:
4188     RMWOp = X.getType()->hasSignedIntegerRepresentation()
4189                 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
4190                                    : llvm::AtomicRMWInst::Min)
4191                 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
4192                                    : llvm::AtomicRMWInst::UMin);
4193     break;
4194   case BO_Assign:
4195     RMWOp = llvm::AtomicRMWInst::Xchg;
4196     break;
4197   case BO_Mul:
4198   case BO_Div:
4199   case BO_Rem:
4200   case BO_Shl:
4201   case BO_Shr:
4202   case BO_LAnd:
4203   case BO_LOr:
4204     return std::make_pair(false, RValue::get(nullptr));
4205   case BO_PtrMemD:
4206   case BO_PtrMemI:
4207   case BO_LE:
4208   case BO_GE:
4209   case BO_EQ:
4210   case BO_NE:
4211   case BO_Cmp:
4212   case BO_AddAssign:
4213   case BO_SubAssign:
4214   case BO_AndAssign:
4215   case BO_OrAssign:
4216   case BO_XorAssign:
4217   case BO_MulAssign:
4218   case BO_DivAssign:
4219   case BO_RemAssign:
4220   case BO_ShlAssign:
4221   case BO_ShrAssign:
4222   case BO_Comma:
4223     llvm_unreachable("Unsupported atomic update operation");
4224   }
4225   llvm::Value *UpdateVal = Update.getScalarVal();
4226   if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
4227     UpdateVal = CGF.Builder.CreateIntCast(
4228         IC, X.getAddress(CGF).getElementType(),
4229         X.getType()->hasSignedIntegerRepresentation());
4230   }
4231   llvm::Value *Res =
4232       CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(CGF), UpdateVal, AO);
4233   return std::make_pair(true, RValue::get(Res));
4234 }
4235 
4236 std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
4237     LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
4238     llvm::AtomicOrdering AO, SourceLocation Loc,
4239     const llvm::function_ref<RValue(RValue)> CommonGen) {
4240   // Update expressions are allowed to have the following forms:
4241   // x binop= expr; -> xrval + expr;
4242   // x++, ++x -> xrval + 1;
4243   // x--, --x -> xrval - 1;
4244   // x = x binop expr; -> xrval binop expr
4245   // x = expr Op x; - > expr binop xrval;
4246   auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
4247   if (!Res.first) {
4248     if (X.isGlobalReg()) {
4249       // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
4250       // 'xrval'.
4251       EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
4252     } else {
4253       // Perform compare-and-swap procedure.
4254       EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
4255     }
4256   }
4257   return Res;
4258 }
4259 
4260 static void emitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
4261                                     const Expr *X, const Expr *E,
4262                                     const Expr *UE, bool IsXLHSInRHSPart,
4263                                     SourceLocation Loc) {
4264   assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
4265          "Update expr in 'atomic update' must be a binary operator.");
4266   const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
4267   // Update expressions are allowed to have the following forms:
4268   // x binop= expr; -> xrval + expr;
4269   // x++, ++x -> xrval + 1;
4270   // x--, --x -> xrval - 1;
4271   // x = x binop expr; -> xrval binop expr
4272   // x = expr Op x; - > expr binop xrval;
4273   assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
4274   LValue XLValue = CGF.EmitLValue(X);
4275   RValue ExprRValue = CGF.EmitAnyExpr(E);
4276   llvm::AtomicOrdering AO = IsSeqCst
4277                                 ? llvm::AtomicOrdering::SequentiallyConsistent
4278                                 : llvm::AtomicOrdering::Monotonic;
4279   const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
4280   const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
4281   const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
4282   const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
4283   auto &&Gen = [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) {
4284     CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
4285     CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
4286     return CGF.EmitAnyExpr(UE);
4287   };
4288   (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
4289       XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
4290   CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X);
4291   // OpenMP, 2.12.6, atomic Construct
4292   // Any atomic construct with a seq_cst clause forces the atomically
4293   // performed operation to include an implicit flush operation without a
4294   // list.
4295   if (IsSeqCst)
4296     CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
4297 }
4298 
4299 static RValue convertToType(CodeGenFunction &CGF, RValue Value,
4300                             QualType SourceType, QualType ResType,
4301                             SourceLocation Loc) {
4302   switch (CGF.getEvaluationKind(ResType)) {
4303   case TEK_Scalar:
4304     return RValue::get(
4305         convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
4306   case TEK_Complex: {
4307     auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
4308     return RValue::getComplex(Res.first, Res.second);
4309   }
4310   case TEK_Aggregate:
4311     break;
4312   }
4313   llvm_unreachable("Must be a scalar or complex.");
4314 }
4315 
4316 static void emitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
4317                                      bool IsPostfixUpdate, const Expr *V,
4318                                      const Expr *X, const Expr *E,
4319                                      const Expr *UE, bool IsXLHSInRHSPart,
4320                                      SourceLocation Loc) {
4321   assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
4322   assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
4323   RValue NewVVal;
4324   LValue VLValue = CGF.EmitLValue(V);
4325   LValue XLValue = CGF.EmitLValue(X);
4326   RValue ExprRValue = CGF.EmitAnyExpr(E);
4327   llvm::AtomicOrdering AO = IsSeqCst
4328                                 ? llvm::AtomicOrdering::SequentiallyConsistent
4329                                 : llvm::AtomicOrdering::Monotonic;
4330   QualType NewVValType;
4331   if (UE) {
4332     // 'x' is updated with some additional value.
4333     assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
4334            "Update expr in 'atomic capture' must be a binary operator.");
4335     const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
4336     // Update expressions are allowed to have the following forms:
4337     // x binop= expr; -> xrval + expr;
4338     // x++, ++x -> xrval + 1;
4339     // x--, --x -> xrval - 1;
4340     // x = x binop expr; -> xrval binop expr
4341     // x = expr Op x; - > expr binop xrval;
4342     const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
4343     const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
4344     const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
4345     NewVValType = XRValExpr->getType();
4346     const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
4347     auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
4348                   IsPostfixUpdate](RValue XRValue) {
4349       CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
4350       CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
4351       RValue Res = CGF.EmitAnyExpr(UE);
4352       NewVVal = IsPostfixUpdate ? XRValue : Res;
4353       return Res;
4354     };
4355     auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
4356         XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
4357     CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X);
4358     if (Res.first) {
4359       // 'atomicrmw' instruction was generated.
4360       if (IsPostfixUpdate) {
4361         // Use old value from 'atomicrmw'.
4362         NewVVal = Res.second;
4363       } else {
4364         // 'atomicrmw' does not provide new value, so evaluate it using old
4365         // value of 'x'.
4366         CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
4367         CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
4368         NewVVal = CGF.EmitAnyExpr(UE);
4369       }
4370     }
4371   } else {
4372     // 'x' is simply rewritten with some 'expr'.
4373     NewVValType = X->getType().getNonReferenceType();
4374     ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
4375                                X->getType().getNonReferenceType(), Loc);
4376     auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) {
4377       NewVVal = XRValue;
4378       return ExprRValue;
4379     };
4380     // Try to perform atomicrmw xchg, otherwise simple exchange.
4381     auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
4382         XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
4383         Loc, Gen);
4384     CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X);
4385     if (Res.first) {
4386       // 'atomicrmw' instruction was generated.
4387       NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
4388     }
4389   }
4390   // Emit post-update store to 'v' of old/new 'x' value.
4391   CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
4392   CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, V);
4393   // OpenMP, 2.12.6, atomic Construct
4394   // Any atomic construct with a seq_cst clause forces the atomically
4395   // performed operation to include an implicit flush operation without a
4396   // list.
4397   if (IsSeqCst)
4398     CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
4399 }
4400 
4401 static void emitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
4402                               bool IsSeqCst, bool IsPostfixUpdate,
4403                               const Expr *X, const Expr *V, const Expr *E,
4404                               const Expr *UE, bool IsXLHSInRHSPart,
4405                               SourceLocation Loc) {
4406   switch (Kind) {
4407   case OMPC_read:
4408     emitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
4409     break;
4410   case OMPC_write:
4411     emitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
4412     break;
4413   case OMPC_unknown:
4414   case OMPC_update:
4415     emitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
4416     break;
4417   case OMPC_capture:
4418     emitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
4419                              IsXLHSInRHSPart, Loc);
4420     break;
4421   case OMPC_if:
4422   case OMPC_final:
4423   case OMPC_num_threads:
4424   case OMPC_private:
4425   case OMPC_firstprivate:
4426   case OMPC_lastprivate:
4427   case OMPC_reduction:
4428   case OMPC_task_reduction:
4429   case OMPC_in_reduction:
4430   case OMPC_safelen:
4431   case OMPC_simdlen:
4432   case OMPC_allocator:
4433   case OMPC_allocate:
4434   case OMPC_collapse:
4435   case OMPC_default:
4436   case OMPC_seq_cst:
4437   case OMPC_shared:
4438   case OMPC_linear:
4439   case OMPC_aligned:
4440   case OMPC_copyin:
4441   case OMPC_copyprivate:
4442   case OMPC_flush:
4443   case OMPC_proc_bind:
4444   case OMPC_schedule:
4445   case OMPC_ordered:
4446   case OMPC_nowait:
4447   case OMPC_untied:
4448   case OMPC_threadprivate:
4449   case OMPC_depend:
4450   case OMPC_mergeable:
4451   case OMPC_device:
4452   case OMPC_threads:
4453   case OMPC_simd:
4454   case OMPC_map:
4455   case OMPC_num_teams:
4456   case OMPC_thread_limit:
4457   case OMPC_priority:
4458   case OMPC_grainsize:
4459   case OMPC_nogroup:
4460   case OMPC_num_tasks:
4461   case OMPC_hint:
4462   case OMPC_dist_schedule:
4463   case OMPC_defaultmap:
4464   case OMPC_uniform:
4465   case OMPC_to:
4466   case OMPC_from:
4467   case OMPC_use_device_ptr:
4468   case OMPC_is_device_ptr:
4469   case OMPC_unified_address:
4470   case OMPC_unified_shared_memory:
4471   case OMPC_reverse_offload:
4472   case OMPC_dynamic_allocators:
4473   case OMPC_atomic_default_mem_order:
4474   case OMPC_device_type:
4475   case OMPC_match:
4476   case OMPC_nontemporal:
4477   case OMPC_order:
4478     llvm_unreachable("Clause is not allowed in 'omp atomic'.");
4479   }
4480 }
4481 
4482 void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
4483   bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
4484   OpenMPClauseKind Kind = OMPC_unknown;
4485   for (const OMPClause *C : S.clauses()) {
4486     // Find first clause (skip seq_cst clause, if it is first).
4487     if (C->getClauseKind() != OMPC_seq_cst) {
4488       Kind = C->getClauseKind();
4489       break;
4490     }
4491   }
4492 
4493   const Stmt *CS = S.getInnermostCapturedStmt()->IgnoreContainers();
4494   if (const auto *FE = dyn_cast<FullExpr>(CS))
4495     enterFullExpression(FE);
4496   // Processing for statements under 'atomic capture'.
4497   if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
4498     for (const Stmt *C : Compound->body()) {
4499       if (const auto *FE = dyn_cast<FullExpr>(C))
4500         enterFullExpression(FE);
4501     }
4502   }
4503 
4504   auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
4505                                             PrePostActionTy &) {
4506     CGF.EmitStopPoint(CS);
4507     emitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
4508                       S.getV(), S.getExpr(), S.getUpdateExpr(),
4509                       S.isXLHSInRHSPart(), S.getBeginLoc());
4510   };
4511   OMPLexicalScope Scope(*this, S, OMPD_unknown);
4512   CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
4513 }
4514 
4515 static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
4516                                          const OMPExecutableDirective &S,
4517                                          const RegionCodeGenTy &CodeGen) {
4518   assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
4519   CodeGenModule &CGM = CGF.CGM;
4520 
4521   // On device emit this construct as inlined code.
4522   if (CGM.getLangOpts().OpenMPIsDevice) {
4523     OMPLexicalScope Scope(CGF, S, OMPD_target);
4524     CGM.getOpenMPRuntime().emitInlinedDirective(
4525         CGF, OMPD_target, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4526           CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
4527         });
4528     return;
4529   }
4530 
4531   auto LPCRegion =
4532       CGOpenMPRuntime::LastprivateConditionalRAII::disable(CGF, S);
4533   llvm::Function *Fn = nullptr;
4534   llvm::Constant *FnID = nullptr;
4535 
4536   const Expr *IfCond = nullptr;
4537   // Check for the at most one if clause associated with the target region.
4538   for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4539     if (C->getNameModifier() == OMPD_unknown ||
4540         C->getNameModifier() == OMPD_target) {
4541       IfCond = C->getCondition();
4542       break;
4543     }
4544   }
4545 
4546   // Check if we have any device clause associated with the directive.
4547   const Expr *Device = nullptr;
4548   if (auto *C = S.getSingleClause<OMPDeviceClause>())
4549     Device = C->getDevice();
4550 
4551   // Check if we have an if clause whose conditional always evaluates to false
4552   // or if we do not have any targets specified. If so the target region is not
4553   // an offload entry point.
4554   bool IsOffloadEntry = true;
4555   if (IfCond) {
4556     bool Val;
4557     if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
4558       IsOffloadEntry = false;
4559   }
4560   if (CGM.getLangOpts().OMPTargetTriples.empty())
4561     IsOffloadEntry = false;
4562 
4563   assert(CGF.CurFuncDecl && "No parent declaration for target region!");
4564   StringRef ParentName;
4565   // In case we have Ctors/Dtors we use the complete type variant to produce
4566   // the mangling of the device outlined kernel.
4567   if (const auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
4568     ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
4569   else if (const auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
4570     ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
4571   else
4572     ParentName =
4573         CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
4574 
4575   // Emit target region as a standalone region.
4576   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
4577                                                     IsOffloadEntry, CodeGen);
4578   OMPLexicalScope Scope(CGF, S, OMPD_task);
4579   auto &&SizeEmitter =
4580       [IsOffloadEntry](CodeGenFunction &CGF,
4581                        const OMPLoopDirective &D) -> llvm::Value * {
4582     if (IsOffloadEntry) {
4583       OMPLoopScope(CGF, D);
4584       // Emit calculation of the iterations count.
4585       llvm::Value *NumIterations = CGF.EmitScalarExpr(D.getNumIterations());
4586       NumIterations = CGF.Builder.CreateIntCast(NumIterations, CGF.Int64Ty,
4587                                                 /*isSigned=*/false);
4588       return NumIterations;
4589     }
4590     return nullptr;
4591   };
4592   CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device,
4593                                         SizeEmitter);
4594 }
4595 
4596 static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
4597                              PrePostActionTy &Action) {
4598   Action.Enter(CGF);
4599   CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4600   (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4601   CGF.EmitOMPPrivateClause(S, PrivateScope);
4602   (void)PrivateScope.Privatize();
4603   if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
4604     CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
4605 
4606   CGF.EmitStmt(S.getCapturedStmt(OMPD_target)->getCapturedStmt());
4607 }
4608 
4609 void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
4610                                                   StringRef ParentName,
4611                                                   const OMPTargetDirective &S) {
4612   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4613     emitTargetRegion(CGF, S, Action);
4614   };
4615   llvm::Function *Fn;
4616   llvm::Constant *Addr;
4617   // Emit target region as a standalone region.
4618   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4619       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4620   assert(Fn && Addr && "Target device function emission failed.");
4621 }
4622 
4623 void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
4624   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4625     emitTargetRegion(CGF, S, Action);
4626   };
4627   emitCommonOMPTargetDirective(*this, S, CodeGen);
4628 }
4629 
4630 static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
4631                                         const OMPExecutableDirective &S,
4632                                         OpenMPDirectiveKind InnermostKind,
4633                                         const RegionCodeGenTy &CodeGen) {
4634   const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
4635   llvm::Function *OutlinedFn =
4636       CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
4637           S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
4638 
4639   const auto *NT = S.getSingleClause<OMPNumTeamsClause>();
4640   const auto *TL = S.getSingleClause<OMPThreadLimitClause>();
4641   if (NT || TL) {
4642     const Expr *NumTeams = NT ? NT->getNumTeams() : nullptr;
4643     const Expr *ThreadLimit = TL ? TL->getThreadLimit() : nullptr;
4644 
4645     CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
4646                                                   S.getBeginLoc());
4647   }
4648 
4649   OMPTeamsScope Scope(CGF, S);
4650   llvm::SmallVector<llvm::Value *, 16> CapturedVars;
4651   CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
4652   CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getBeginLoc(), OutlinedFn,
4653                                            CapturedVars);
4654 }
4655 
4656 void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
4657   // Emit teams region as a standalone region.
4658   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4659     Action.Enter(CGF);
4660     OMPPrivateScope PrivateScope(CGF);
4661     (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4662     CGF.EmitOMPPrivateClause(S, PrivateScope);
4663     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4664     (void)PrivateScope.Privatize();
4665     CGF.EmitStmt(S.getCapturedStmt(OMPD_teams)->getCapturedStmt());
4666     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4667   };
4668   emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
4669   emitPostUpdateForReductionClause(*this, S,
4670                                    [](CodeGenFunction &) { return nullptr; });
4671 }
4672 
4673 static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4674                                   const OMPTargetTeamsDirective &S) {
4675   auto *CS = S.getCapturedStmt(OMPD_teams);
4676   Action.Enter(CGF);
4677   // Emit teams region as a standalone region.
4678   auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
4679     Action.Enter(CGF);
4680     CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4681     (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4682     CGF.EmitOMPPrivateClause(S, PrivateScope);
4683     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4684     (void)PrivateScope.Privatize();
4685     if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
4686       CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
4687     CGF.EmitStmt(CS->getCapturedStmt());
4688     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4689   };
4690   emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
4691   emitPostUpdateForReductionClause(CGF, S,
4692                                    [](CodeGenFunction &) { return nullptr; });
4693 }
4694 
4695 void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
4696     CodeGenModule &CGM, StringRef ParentName,
4697     const OMPTargetTeamsDirective &S) {
4698   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4699     emitTargetTeamsRegion(CGF, Action, S);
4700   };
4701   llvm::Function *Fn;
4702   llvm::Constant *Addr;
4703   // Emit target region as a standalone region.
4704   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4705       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4706   assert(Fn && Addr && "Target device function emission failed.");
4707 }
4708 
4709 void CodeGenFunction::EmitOMPTargetTeamsDirective(
4710     const OMPTargetTeamsDirective &S) {
4711   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4712     emitTargetTeamsRegion(CGF, Action, S);
4713   };
4714   emitCommonOMPTargetDirective(*this, S, CodeGen);
4715 }
4716 
4717 static void
4718 emitTargetTeamsDistributeRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4719                                 const OMPTargetTeamsDistributeDirective &S) {
4720   Action.Enter(CGF);
4721   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4722     CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4723   };
4724 
4725   // Emit teams region as a standalone region.
4726   auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4727                                             PrePostActionTy &Action) {
4728     Action.Enter(CGF);
4729     CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4730     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4731     (void)PrivateScope.Privatize();
4732     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4733                                                     CodeGenDistribute);
4734     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4735   };
4736   emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute, CodeGen);
4737   emitPostUpdateForReductionClause(CGF, S,
4738                                    [](CodeGenFunction &) { return nullptr; });
4739 }
4740 
4741 void CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
4742     CodeGenModule &CGM, StringRef ParentName,
4743     const OMPTargetTeamsDistributeDirective &S) {
4744   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4745     emitTargetTeamsDistributeRegion(CGF, Action, S);
4746   };
4747   llvm::Function *Fn;
4748   llvm::Constant *Addr;
4749   // Emit target region as a standalone region.
4750   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4751       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4752   assert(Fn && Addr && "Target device function emission failed.");
4753 }
4754 
4755 void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
4756     const OMPTargetTeamsDistributeDirective &S) {
4757   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4758     emitTargetTeamsDistributeRegion(CGF, Action, S);
4759   };
4760   emitCommonOMPTargetDirective(*this, S, CodeGen);
4761 }
4762 
4763 static void emitTargetTeamsDistributeSimdRegion(
4764     CodeGenFunction &CGF, PrePostActionTy &Action,
4765     const OMPTargetTeamsDistributeSimdDirective &S) {
4766   Action.Enter(CGF);
4767   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4768     CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4769   };
4770 
4771   // Emit teams region as a standalone region.
4772   auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4773                                             PrePostActionTy &Action) {
4774     Action.Enter(CGF);
4775     CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4776     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4777     (void)PrivateScope.Privatize();
4778     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4779                                                     CodeGenDistribute);
4780     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4781   };
4782   emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_simd, CodeGen);
4783   emitPostUpdateForReductionClause(CGF, S,
4784                                    [](CodeGenFunction &) { return nullptr; });
4785 }
4786 
4787 void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
4788     CodeGenModule &CGM, StringRef ParentName,
4789     const OMPTargetTeamsDistributeSimdDirective &S) {
4790   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4791     emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4792   };
4793   llvm::Function *Fn;
4794   llvm::Constant *Addr;
4795   // Emit target region as a standalone region.
4796   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4797       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4798   assert(Fn && Addr && "Target device function emission failed.");
4799 }
4800 
4801 void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
4802     const OMPTargetTeamsDistributeSimdDirective &S) {
4803   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4804     emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4805   };
4806   emitCommonOMPTargetDirective(*this, S, CodeGen);
4807 }
4808 
4809 void CodeGenFunction::EmitOMPTeamsDistributeDirective(
4810     const OMPTeamsDistributeDirective &S) {
4811 
4812   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4813     CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4814   };
4815 
4816   // Emit teams region as a standalone region.
4817   auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4818                                             PrePostActionTy &Action) {
4819     Action.Enter(CGF);
4820     OMPPrivateScope PrivateScope(CGF);
4821     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4822     (void)PrivateScope.Privatize();
4823     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4824                                                     CodeGenDistribute);
4825     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4826   };
4827   emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
4828   emitPostUpdateForReductionClause(*this, S,
4829                                    [](CodeGenFunction &) { return nullptr; });
4830 }
4831 
4832 void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
4833     const OMPTeamsDistributeSimdDirective &S) {
4834   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4835     CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4836   };
4837 
4838   // Emit teams region as a standalone region.
4839   auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4840                                             PrePostActionTy &Action) {
4841     Action.Enter(CGF);
4842     OMPPrivateScope PrivateScope(CGF);
4843     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4844     (void)PrivateScope.Privatize();
4845     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd,
4846                                                     CodeGenDistribute);
4847     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4848   };
4849   emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_simd, CodeGen);
4850   emitPostUpdateForReductionClause(*this, S,
4851                                    [](CodeGenFunction &) { return nullptr; });
4852 }
4853 
4854 void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
4855     const OMPTeamsDistributeParallelForDirective &S) {
4856   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4857     CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4858                               S.getDistInc());
4859   };
4860 
4861   // Emit teams region as a standalone region.
4862   auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4863                                             PrePostActionTy &Action) {
4864     Action.Enter(CGF);
4865     OMPPrivateScope PrivateScope(CGF);
4866     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4867     (void)PrivateScope.Privatize();
4868     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4869                                                     CodeGenDistribute);
4870     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4871   };
4872   emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4873   emitPostUpdateForReductionClause(*this, S,
4874                                    [](CodeGenFunction &) { return nullptr; });
4875 }
4876 
4877 void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
4878     const OMPTeamsDistributeParallelForSimdDirective &S) {
4879   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4880     CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4881                               S.getDistInc());
4882   };
4883 
4884   // Emit teams region as a standalone region.
4885   auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4886                                             PrePostActionTy &Action) {
4887     Action.Enter(CGF);
4888     OMPPrivateScope PrivateScope(CGF);
4889     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4890     (void)PrivateScope.Privatize();
4891     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4892         CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4893     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4894   };
4895   emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for_simd,
4896                               CodeGen);
4897   emitPostUpdateForReductionClause(*this, S,
4898                                    [](CodeGenFunction &) { return nullptr; });
4899 }
4900 
4901 static void emitTargetTeamsDistributeParallelForRegion(
4902     CodeGenFunction &CGF, const OMPTargetTeamsDistributeParallelForDirective &S,
4903     PrePostActionTy &Action) {
4904   Action.Enter(CGF);
4905   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4906     CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4907                               S.getDistInc());
4908   };
4909 
4910   // Emit teams region as a standalone region.
4911   auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4912                                                  PrePostActionTy &Action) {
4913     Action.Enter(CGF);
4914     CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4915     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4916     (void)PrivateScope.Privatize();
4917     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4918         CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4919     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4920   };
4921 
4922   emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for,
4923                               CodeGenTeams);
4924   emitPostUpdateForReductionClause(CGF, S,
4925                                    [](CodeGenFunction &) { return nullptr; });
4926 }
4927 
4928 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
4929     CodeGenModule &CGM, StringRef ParentName,
4930     const OMPTargetTeamsDistributeParallelForDirective &S) {
4931   // Emit SPMD target teams distribute parallel for region as a standalone
4932   // region.
4933   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4934     emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
4935   };
4936   llvm::Function *Fn;
4937   llvm::Constant *Addr;
4938   // Emit target region as a standalone region.
4939   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4940       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4941   assert(Fn && Addr && "Target device function emission failed.");
4942 }
4943 
4944 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
4945     const OMPTargetTeamsDistributeParallelForDirective &S) {
4946   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4947     emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
4948   };
4949   emitCommonOMPTargetDirective(*this, S, CodeGen);
4950 }
4951 
4952 static void emitTargetTeamsDistributeParallelForSimdRegion(
4953     CodeGenFunction &CGF,
4954     const OMPTargetTeamsDistributeParallelForSimdDirective &S,
4955     PrePostActionTy &Action) {
4956   Action.Enter(CGF);
4957   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4958     CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4959                               S.getDistInc());
4960   };
4961 
4962   // Emit teams region as a standalone region.
4963   auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4964                                                  PrePostActionTy &Action) {
4965     Action.Enter(CGF);
4966     CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4967     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4968     (void)PrivateScope.Privatize();
4969     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4970         CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4971     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4972   };
4973 
4974   emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for_simd,
4975                               CodeGenTeams);
4976   emitPostUpdateForReductionClause(CGF, S,
4977                                    [](CodeGenFunction &) { return nullptr; });
4978 }
4979 
4980 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
4981     CodeGenModule &CGM, StringRef ParentName,
4982     const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
4983   // Emit SPMD target teams distribute parallel for simd region as a standalone
4984   // region.
4985   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4986     emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
4987   };
4988   llvm::Function *Fn;
4989   llvm::Constant *Addr;
4990   // Emit target region as a standalone region.
4991   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4992       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4993   assert(Fn && Addr && "Target device function emission failed.");
4994 }
4995 
4996 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
4997     const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
4998   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4999     emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
5000   };
5001   emitCommonOMPTargetDirective(*this, S, CodeGen);
5002 }
5003 
5004 void CodeGenFunction::EmitOMPCancellationPointDirective(
5005     const OMPCancellationPointDirective &S) {
5006   CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getBeginLoc(),
5007                                                    S.getCancelRegion());
5008 }
5009 
5010 void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
5011   const Expr *IfCond = nullptr;
5012   for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
5013     if (C->getNameModifier() == OMPD_unknown ||
5014         C->getNameModifier() == OMPD_cancel) {
5015       IfCond = C->getCondition();
5016       break;
5017     }
5018   }
5019   if (llvm::OpenMPIRBuilder *OMPBuilder = CGM.getOpenMPIRBuilder()) {
5020     // TODO: This check is necessary as we only generate `omp parallel` through
5021     // the OpenMPIRBuilder for now.
5022     if (S.getCancelRegion() == OMPD_parallel) {
5023       llvm::Value *IfCondition = nullptr;
5024       if (IfCond)
5025         IfCondition = EmitScalarExpr(IfCond,
5026                                      /*IgnoreResultAssign=*/true);
5027       return Builder.restoreIP(
5028           OMPBuilder->CreateCancel(Builder, IfCondition, S.getCancelRegion()));
5029     }
5030   }
5031 
5032   CGM.getOpenMPRuntime().emitCancelCall(*this, S.getBeginLoc(), IfCond,
5033                                         S.getCancelRegion());
5034 }
5035 
5036 CodeGenFunction::JumpDest
5037 CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
5038   if (Kind == OMPD_parallel || Kind == OMPD_task ||
5039       Kind == OMPD_target_parallel)
5040     return ReturnBlock;
5041   assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
5042          Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
5043          Kind == OMPD_distribute_parallel_for ||
5044          Kind == OMPD_target_parallel_for ||
5045          Kind == OMPD_teams_distribute_parallel_for ||
5046          Kind == OMPD_target_teams_distribute_parallel_for);
5047   return OMPCancelStack.getExitBlock();
5048 }
5049 
5050 void CodeGenFunction::EmitOMPUseDevicePtrClause(
5051     const OMPClause &NC, OMPPrivateScope &PrivateScope,
5052     const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
5053   const auto &C = cast<OMPUseDevicePtrClause>(NC);
5054   auto OrigVarIt = C.varlist_begin();
5055   auto InitIt = C.inits().begin();
5056   for (const Expr *PvtVarIt : C.private_copies()) {
5057     const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
5058     const auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
5059     const auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
5060 
5061     // In order to identify the right initializer we need to match the
5062     // declaration used by the mapping logic. In some cases we may get
5063     // OMPCapturedExprDecl that refers to the original declaration.
5064     const ValueDecl *MatchingVD = OrigVD;
5065     if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
5066       // OMPCapturedExprDecl are used to privative fields of the current
5067       // structure.
5068       const auto *ME = cast<MemberExpr>(OED->getInit());
5069       assert(isa<CXXThisExpr>(ME->getBase()) &&
5070              "Base should be the current struct!");
5071       MatchingVD = ME->getMemberDecl();
5072     }
5073 
5074     // If we don't have information about the current list item, move on to
5075     // the next one.
5076     auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
5077     if (InitAddrIt == CaptureDeviceAddrMap.end())
5078       continue;
5079 
5080     bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, OrigVD,
5081                                                          InitAddrIt, InitVD,
5082                                                          PvtVD]() {
5083       // Initialize the temporary initialization variable with the address we
5084       // get from the runtime library. We have to cast the source address
5085       // because it is always a void *. References are materialized in the
5086       // privatization scope, so the initialization here disregards the fact
5087       // the original variable is a reference.
5088       QualType AddrQTy =
5089           getContext().getPointerType(OrigVD->getType().getNonReferenceType());
5090       llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
5091       Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
5092       setAddrOfLocalVar(InitVD, InitAddr);
5093 
5094       // Emit private declaration, it will be initialized by the value we
5095       // declaration we just added to the local declarations map.
5096       EmitDecl(*PvtVD);
5097 
5098       // The initialization variables reached its purpose in the emission
5099       // of the previous declaration, so we don't need it anymore.
5100       LocalDeclMap.erase(InitVD);
5101 
5102       // Return the address of the private variable.
5103       return GetAddrOfLocalVar(PvtVD);
5104     });
5105     assert(IsRegistered && "firstprivate var already registered as private");
5106     // Silence the warning about unused variable.
5107     (void)IsRegistered;
5108 
5109     ++OrigVarIt;
5110     ++InitIt;
5111   }
5112 }
5113 
5114 // Generate the instructions for '#pragma omp target data' directive.
5115 void CodeGenFunction::EmitOMPTargetDataDirective(
5116     const OMPTargetDataDirective &S) {
5117   CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true);
5118 
5119   // Create a pre/post action to signal the privatization of the device pointer.
5120   // This action can be replaced by the OpenMP runtime code generation to
5121   // deactivate privatization.
5122   bool PrivatizeDevicePointers = false;
5123   class DevicePointerPrivActionTy : public PrePostActionTy {
5124     bool &PrivatizeDevicePointers;
5125 
5126   public:
5127     explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
5128         : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
5129     void Enter(CodeGenFunction &CGF) override {
5130       PrivatizeDevicePointers = true;
5131     }
5132   };
5133   DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
5134 
5135   auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
5136                        CodeGenFunction &CGF, PrePostActionTy &Action) {
5137     auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
5138       CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
5139     };
5140 
5141     // Codegen that selects whether to generate the privatization code or not.
5142     auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
5143                           &InnermostCodeGen](CodeGenFunction &CGF,
5144                                              PrePostActionTy &Action) {
5145       RegionCodeGenTy RCG(InnermostCodeGen);
5146       PrivatizeDevicePointers = false;
5147 
5148       // Call the pre-action to change the status of PrivatizeDevicePointers if
5149       // needed.
5150       Action.Enter(CGF);
5151 
5152       if (PrivatizeDevicePointers) {
5153         OMPPrivateScope PrivateScope(CGF);
5154         // Emit all instances of the use_device_ptr clause.
5155         for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
5156           CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
5157                                         Info.CaptureDeviceAddrMap);
5158         (void)PrivateScope.Privatize();
5159         RCG(CGF);
5160       } else {
5161         RCG(CGF);
5162       }
5163     };
5164 
5165     // Forward the provided action to the privatization codegen.
5166     RegionCodeGenTy PrivRCG(PrivCodeGen);
5167     PrivRCG.setAction(Action);
5168 
5169     // Notwithstanding the body of the region is emitted as inlined directive,
5170     // we don't use an inline scope as changes in the references inside the
5171     // region are expected to be visible outside, so we do not privative them.
5172     OMPLexicalScope Scope(CGF, S);
5173     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
5174                                                     PrivRCG);
5175   };
5176 
5177   RegionCodeGenTy RCG(CodeGen);
5178 
5179   // If we don't have target devices, don't bother emitting the data mapping
5180   // code.
5181   if (CGM.getLangOpts().OMPTargetTriples.empty()) {
5182     RCG(*this);
5183     return;
5184   }
5185 
5186   // Check if we have any if clause associated with the directive.
5187   const Expr *IfCond = nullptr;
5188   if (const auto *C = S.getSingleClause<OMPIfClause>())
5189     IfCond = C->getCondition();
5190 
5191   // Check if we have any device clause associated with the directive.
5192   const Expr *Device = nullptr;
5193   if (const auto *C = S.getSingleClause<OMPDeviceClause>())
5194     Device = C->getDevice();
5195 
5196   // Set the action to signal privatization of device pointers.
5197   RCG.setAction(PrivAction);
5198 
5199   // Emit region code.
5200   CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
5201                                              Info);
5202 }
5203 
5204 void CodeGenFunction::EmitOMPTargetEnterDataDirective(
5205     const OMPTargetEnterDataDirective &S) {
5206   // If we don't have target devices, don't bother emitting the data mapping
5207   // code.
5208   if (CGM.getLangOpts().OMPTargetTriples.empty())
5209     return;
5210 
5211   // Check if we have any if clause associated with the directive.
5212   const Expr *IfCond = nullptr;
5213   if (const auto *C = S.getSingleClause<OMPIfClause>())
5214     IfCond = C->getCondition();
5215 
5216   // Check if we have any device clause associated with the directive.
5217   const Expr *Device = nullptr;
5218   if (const auto *C = S.getSingleClause<OMPDeviceClause>())
5219     Device = C->getDevice();
5220 
5221   OMPLexicalScope Scope(*this, S, OMPD_task);
5222   CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
5223 }
5224 
5225 void CodeGenFunction::EmitOMPTargetExitDataDirective(
5226     const OMPTargetExitDataDirective &S) {
5227   // If we don't have target devices, don't bother emitting the data mapping
5228   // code.
5229   if (CGM.getLangOpts().OMPTargetTriples.empty())
5230     return;
5231 
5232   // Check if we have any if clause associated with the directive.
5233   const Expr *IfCond = nullptr;
5234   if (const auto *C = S.getSingleClause<OMPIfClause>())
5235     IfCond = C->getCondition();
5236 
5237   // Check if we have any device clause associated with the directive.
5238   const Expr *Device = nullptr;
5239   if (const auto *C = S.getSingleClause<OMPDeviceClause>())
5240     Device = C->getDevice();
5241 
5242   OMPLexicalScope Scope(*this, S, OMPD_task);
5243   CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
5244 }
5245 
5246 static void emitTargetParallelRegion(CodeGenFunction &CGF,
5247                                      const OMPTargetParallelDirective &S,
5248                                      PrePostActionTy &Action) {
5249   // Get the captured statement associated with the 'parallel' region.
5250   const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
5251   Action.Enter(CGF);
5252   auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
5253     Action.Enter(CGF);
5254     CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5255     (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
5256     CGF.EmitOMPPrivateClause(S, PrivateScope);
5257     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
5258     (void)PrivateScope.Privatize();
5259     if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
5260       CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
5261     // TODO: Add support for clauses.
5262     CGF.EmitStmt(CS->getCapturedStmt());
5263     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
5264   };
5265   emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
5266                                  emitEmptyBoundParameters);
5267   emitPostUpdateForReductionClause(CGF, S,
5268                                    [](CodeGenFunction &) { return nullptr; });
5269 }
5270 
5271 void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
5272     CodeGenModule &CGM, StringRef ParentName,
5273     const OMPTargetParallelDirective &S) {
5274   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5275     emitTargetParallelRegion(CGF, S, Action);
5276   };
5277   llvm::Function *Fn;
5278   llvm::Constant *Addr;
5279   // Emit target region as a standalone region.
5280   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
5281       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
5282   assert(Fn && Addr && "Target device function emission failed.");
5283 }
5284 
5285 void CodeGenFunction::EmitOMPTargetParallelDirective(
5286     const OMPTargetParallelDirective &S) {
5287   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5288     emitTargetParallelRegion(CGF, S, Action);
5289   };
5290   emitCommonOMPTargetDirective(*this, S, CodeGen);
5291 }
5292 
5293 static void emitTargetParallelForRegion(CodeGenFunction &CGF,
5294                                         const OMPTargetParallelForDirective &S,
5295                                         PrePostActionTy &Action) {
5296   Action.Enter(CGF);
5297   // Emit directive as a combined directive that consists of two implicit
5298   // directives: 'parallel' with 'for' directive.
5299   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5300     Action.Enter(CGF);
5301     CodeGenFunction::OMPCancelStackRAII CancelRegion(
5302         CGF, OMPD_target_parallel_for, S.hasCancel());
5303     CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
5304                                emitDispatchForLoopBounds);
5305   };
5306   emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen,
5307                                  emitEmptyBoundParameters);
5308 }
5309 
5310 void CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
5311     CodeGenModule &CGM, StringRef ParentName,
5312     const OMPTargetParallelForDirective &S) {
5313   // Emit SPMD target parallel for region as a standalone region.
5314   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5315     emitTargetParallelForRegion(CGF, S, Action);
5316   };
5317   llvm::Function *Fn;
5318   llvm::Constant *Addr;
5319   // Emit target region as a standalone region.
5320   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
5321       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
5322   assert(Fn && Addr && "Target device function emission failed.");
5323 }
5324 
5325 void CodeGenFunction::EmitOMPTargetParallelForDirective(
5326     const OMPTargetParallelForDirective &S) {
5327   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5328     emitTargetParallelForRegion(CGF, S, Action);
5329   };
5330   emitCommonOMPTargetDirective(*this, S, CodeGen);
5331 }
5332 
5333 static void
5334 emitTargetParallelForSimdRegion(CodeGenFunction &CGF,
5335                                 const OMPTargetParallelForSimdDirective &S,
5336                                 PrePostActionTy &Action) {
5337   Action.Enter(CGF);
5338   // Emit directive as a combined directive that consists of two implicit
5339   // directives: 'parallel' with 'for' directive.
5340   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5341     Action.Enter(CGF);
5342     CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
5343                                emitDispatchForLoopBounds);
5344   };
5345   emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen,
5346                                  emitEmptyBoundParameters);
5347 }
5348 
5349 void CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
5350     CodeGenModule &CGM, StringRef ParentName,
5351     const OMPTargetParallelForSimdDirective &S) {
5352   // Emit SPMD target parallel for region as a standalone region.
5353   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5354     emitTargetParallelForSimdRegion(CGF, S, Action);
5355   };
5356   llvm::Function *Fn;
5357   llvm::Constant *Addr;
5358   // Emit target region as a standalone region.
5359   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
5360       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
5361   assert(Fn && Addr && "Target device function emission failed.");
5362 }
5363 
5364 void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
5365     const OMPTargetParallelForSimdDirective &S) {
5366   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5367     emitTargetParallelForSimdRegion(CGF, S, Action);
5368   };
5369   emitCommonOMPTargetDirective(*this, S, CodeGen);
5370 }
5371 
5372 /// Emit a helper variable and return corresponding lvalue.
5373 static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
5374                      const ImplicitParamDecl *PVD,
5375                      CodeGenFunction::OMPPrivateScope &Privates) {
5376   const auto *VDecl = cast<VarDecl>(Helper->getDecl());
5377   Privates.addPrivate(VDecl,
5378                       [&CGF, PVD]() { return CGF.GetAddrOfLocalVar(PVD); });
5379 }
5380 
5381 void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
5382   assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
5383   // Emit outlined function for task construct.
5384   const CapturedStmt *CS = S.getCapturedStmt(OMPD_taskloop);
5385   Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
5386   QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
5387   const Expr *IfCond = nullptr;
5388   for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
5389     if (C->getNameModifier() == OMPD_unknown ||
5390         C->getNameModifier() == OMPD_taskloop) {
5391       IfCond = C->getCondition();
5392       break;
5393     }
5394   }
5395 
5396   OMPTaskDataTy Data;
5397   // Check if taskloop must be emitted without taskgroup.
5398   Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
5399   // TODO: Check if we should emit tied or untied task.
5400   Data.Tied = true;
5401   // Set scheduling for taskloop
5402   if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
5403     // grainsize clause
5404     Data.Schedule.setInt(/*IntVal=*/false);
5405     Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
5406   } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
5407     // num_tasks clause
5408     Data.Schedule.setInt(/*IntVal=*/true);
5409     Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
5410   }
5411 
5412   auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
5413     // if (PreCond) {
5414     //   for (IV in 0..LastIteration) BODY;
5415     //   <Final counter/linear vars updates>;
5416     // }
5417     //
5418 
5419     // Emit: if (PreCond) - begin.
5420     // If the condition constant folds and can be elided, avoid emitting the
5421     // whole loop.
5422     bool CondConstant;
5423     llvm::BasicBlock *ContBlock = nullptr;
5424     OMPLoopScope PreInitScope(CGF, S);
5425     if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
5426       if (!CondConstant)
5427         return;
5428     } else {
5429       llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
5430       ContBlock = CGF.createBasicBlock("taskloop.if.end");
5431       emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
5432                   CGF.getProfileCount(&S));
5433       CGF.EmitBlock(ThenBlock);
5434       CGF.incrementProfileCounter(&S);
5435     }
5436 
5437     (void)CGF.EmitOMPLinearClauseInit(S);
5438 
5439     OMPPrivateScope LoopScope(CGF);
5440     // Emit helper vars inits.
5441     enum { LowerBound = 5, UpperBound, Stride, LastIter };
5442     auto *I = CS->getCapturedDecl()->param_begin();
5443     auto *LBP = std::next(I, LowerBound);
5444     auto *UBP = std::next(I, UpperBound);
5445     auto *STP = std::next(I, Stride);
5446     auto *LIP = std::next(I, LastIter);
5447     mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
5448              LoopScope);
5449     mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
5450              LoopScope);
5451     mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
5452     mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
5453              LoopScope);
5454     CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
5455     CGF.EmitOMPLinearClause(S, LoopScope);
5456     bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
5457     (void)LoopScope.Privatize();
5458     // Emit the loop iteration variable.
5459     const Expr *IVExpr = S.getIterationVariable();
5460     const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
5461     CGF.EmitVarDecl(*IVDecl);
5462     CGF.EmitIgnoredExpr(S.getInit());
5463 
5464     // Emit the iterations count variable.
5465     // If it is not a variable, Sema decided to calculate iterations count on
5466     // each iteration (e.g., it is foldable into a constant).
5467     if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
5468       CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
5469       // Emit calculation of the iterations count.
5470       CGF.EmitIgnoredExpr(S.getCalcLastIteration());
5471     }
5472 
5473     {
5474       OMPLexicalScope Scope(CGF, S, OMPD_taskloop, /*EmitPreInitStmt=*/false);
5475       emitCommonSimdLoop(
5476           CGF, S,
5477           [&S](CodeGenFunction &CGF, PrePostActionTy &) {
5478             if (isOpenMPSimdDirective(S.getDirectiveKind()))
5479               CGF.EmitOMPSimdInit(S);
5480           },
5481           [&S, &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) {
5482             CGF.EmitOMPInnerLoop(
5483                 S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
5484                 [&S](CodeGenFunction &CGF) {
5485                   CGF.EmitOMPLoopBody(S, CodeGenFunction::JumpDest());
5486                   CGF.EmitStopPoint(&S);
5487                 },
5488                 [](CodeGenFunction &) {});
5489           });
5490     }
5491     // Emit: if (PreCond) - end.
5492     if (ContBlock) {
5493       CGF.EmitBranch(ContBlock);
5494       CGF.EmitBlock(ContBlock, true);
5495     }
5496     // Emit final copy of the lastprivate variables if IsLastIter != 0.
5497     if (HasLastprivateClause) {
5498       CGF.EmitOMPLastprivateClauseFinal(
5499           S, isOpenMPSimdDirective(S.getDirectiveKind()),
5500           CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
5501               CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
5502               (*LIP)->getType(), S.getBeginLoc())));
5503     }
5504     CGF.EmitOMPLinearClauseFinal(S, [LIP, &S](CodeGenFunction &CGF) {
5505       return CGF.Builder.CreateIsNotNull(
5506           CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
5507                                (*LIP)->getType(), S.getBeginLoc()));
5508     });
5509   };
5510   auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
5511                     IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn,
5512                             const OMPTaskDataTy &Data) {
5513     auto &&CodeGen = [&S, OutlinedFn, SharedsTy, CapturedStruct, IfCond,
5514                       &Data](CodeGenFunction &CGF, PrePostActionTy &) {
5515       OMPLoopScope PreInitScope(CGF, S);
5516       CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getBeginLoc(), S,
5517                                                   OutlinedFn, SharedsTy,
5518                                                   CapturedStruct, IfCond, Data);
5519     };
5520     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
5521                                                     CodeGen);
5522   };
5523   if (Data.Nogroup) {
5524     EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen, Data);
5525   } else {
5526     CGM.getOpenMPRuntime().emitTaskgroupRegion(
5527         *this,
5528         [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF,
5529                                         PrePostActionTy &Action) {
5530           Action.Enter(CGF);
5531           CGF.EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen,
5532                                         Data);
5533         },
5534         S.getBeginLoc());
5535   }
5536 }
5537 
5538 void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
5539   auto LPCRegion =
5540       CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
5541   EmitOMPTaskLoopBasedDirective(S);
5542 }
5543 
5544 void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
5545     const OMPTaskLoopSimdDirective &S) {
5546   auto LPCRegion =
5547       CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
5548   OMPLexicalScope Scope(*this, S);
5549   EmitOMPTaskLoopBasedDirective(S);
5550 }
5551 
5552 void CodeGenFunction::EmitOMPMasterTaskLoopDirective(
5553     const OMPMasterTaskLoopDirective &S) {
5554   auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5555     Action.Enter(CGF);
5556     EmitOMPTaskLoopBasedDirective(S);
5557   };
5558   auto LPCRegion =
5559       CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
5560   OMPLexicalScope Scope(*this, S, llvm::None, /*EmitPreInitStmt=*/false);
5561   CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc());
5562 }
5563 
5564 void CodeGenFunction::EmitOMPMasterTaskLoopSimdDirective(
5565     const OMPMasterTaskLoopSimdDirective &S) {
5566   auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5567     Action.Enter(CGF);
5568     EmitOMPTaskLoopBasedDirective(S);
5569   };
5570   auto LPCRegion =
5571       CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
5572   OMPLexicalScope Scope(*this, S);
5573   CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc());
5574 }
5575 
5576 void CodeGenFunction::EmitOMPParallelMasterTaskLoopDirective(
5577     const OMPParallelMasterTaskLoopDirective &S) {
5578   auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5579     auto &&TaskLoopCodeGen = [&S](CodeGenFunction &CGF,
5580                                   PrePostActionTy &Action) {
5581       Action.Enter(CGF);
5582       CGF.EmitOMPTaskLoopBasedDirective(S);
5583     };
5584     OMPLexicalScope Scope(CGF, S, llvm::None, /*EmitPreInitStmt=*/false);
5585     CGM.getOpenMPRuntime().emitMasterRegion(CGF, TaskLoopCodeGen,
5586                                             S.getBeginLoc());
5587   };
5588   auto LPCRegion =
5589       CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
5590   emitCommonOMPParallelDirective(*this, S, OMPD_master_taskloop, CodeGen,
5591                                  emitEmptyBoundParameters);
5592 }
5593 
5594 void CodeGenFunction::EmitOMPParallelMasterTaskLoopSimdDirective(
5595     const OMPParallelMasterTaskLoopSimdDirective &S) {
5596   auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5597     auto &&TaskLoopCodeGen = [&S](CodeGenFunction &CGF,
5598                                   PrePostActionTy &Action) {
5599       Action.Enter(CGF);
5600       CGF.EmitOMPTaskLoopBasedDirective(S);
5601     };
5602     OMPLexicalScope Scope(CGF, S, OMPD_parallel, /*EmitPreInitStmt=*/false);
5603     CGM.getOpenMPRuntime().emitMasterRegion(CGF, TaskLoopCodeGen,
5604                                             S.getBeginLoc());
5605   };
5606   auto LPCRegion =
5607       CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
5608   emitCommonOMPParallelDirective(*this, S, OMPD_master_taskloop_simd, CodeGen,
5609                                  emitEmptyBoundParameters);
5610 }
5611 
5612 // Generate the instructions for '#pragma omp target update' directive.
5613 void CodeGenFunction::EmitOMPTargetUpdateDirective(
5614     const OMPTargetUpdateDirective &S) {
5615   // If we don't have target devices, don't bother emitting the data mapping
5616   // code.
5617   if (CGM.getLangOpts().OMPTargetTriples.empty())
5618     return;
5619 
5620   // Check if we have any if clause associated with the directive.
5621   const Expr *IfCond = nullptr;
5622   if (const auto *C = S.getSingleClause<OMPIfClause>())
5623     IfCond = C->getCondition();
5624 
5625   // Check if we have any device clause associated with the directive.
5626   const Expr *Device = nullptr;
5627   if (const auto *C = S.getSingleClause<OMPDeviceClause>())
5628     Device = C->getDevice();
5629 
5630   OMPLexicalScope Scope(*this, S, OMPD_task);
5631   CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
5632 }
5633 
5634 void CodeGenFunction::EmitSimpleOMPExecutableDirective(
5635     const OMPExecutableDirective &D) {
5636   if (!D.hasAssociatedStmt() || !D.getAssociatedStmt())
5637     return;
5638   auto &&CodeGen = [&D](CodeGenFunction &CGF, PrePostActionTy &Action) {
5639     if (isOpenMPSimdDirective(D.getDirectiveKind())) {
5640       emitOMPSimdRegion(CGF, cast<OMPLoopDirective>(D), Action);
5641     } else {
5642       OMPPrivateScope LoopGlobals(CGF);
5643       if (const auto *LD = dyn_cast<OMPLoopDirective>(&D)) {
5644         for (const Expr *E : LD->counters()) {
5645           const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
5646           if (!VD->hasLocalStorage() && !CGF.LocalDeclMap.count(VD)) {
5647             LValue GlobLVal = CGF.EmitLValue(E);
5648             LoopGlobals.addPrivate(
5649                 VD, [&GlobLVal, &CGF]() { return GlobLVal.getAddress(CGF); });
5650           }
5651           if (isa<OMPCapturedExprDecl>(VD)) {
5652             // Emit only those that were not explicitly referenced in clauses.
5653             if (!CGF.LocalDeclMap.count(VD))
5654               CGF.EmitVarDecl(*VD);
5655           }
5656         }
5657         for (const auto *C : D.getClausesOfKind<OMPOrderedClause>()) {
5658           if (!C->getNumForLoops())
5659             continue;
5660           for (unsigned I = LD->getCollapsedNumber(),
5661                         E = C->getLoopNumIterations().size();
5662                I < E; ++I) {
5663             if (const auto *VD = dyn_cast<OMPCapturedExprDecl>(
5664                     cast<DeclRefExpr>(C->getLoopCounter(I))->getDecl())) {
5665               // Emit only those that were not explicitly referenced in clauses.
5666               if (!CGF.LocalDeclMap.count(VD))
5667                 CGF.EmitVarDecl(*VD);
5668             }
5669           }
5670         }
5671       }
5672       LoopGlobals.Privatize();
5673       CGF.EmitStmt(D.getInnermostCapturedStmt()->getCapturedStmt());
5674     }
5675   };
5676   {
5677     auto LPCRegion =
5678         CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, D);
5679     OMPSimdLexicalScope Scope(*this, D);
5680     CGM.getOpenMPRuntime().emitInlinedDirective(
5681         *this,
5682         isOpenMPSimdDirective(D.getDirectiveKind()) ? OMPD_simd
5683                                                     : D.getDirectiveKind(),
5684         CodeGen);
5685   }
5686   // Check for outer lastprivate conditional update.
5687   checkForLastprivateConditionalUpdate(*this, D);
5688 }
5689