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