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