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