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