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