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