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