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