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