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