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