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