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