1 //===--- CGStmtOpenMP.cpp - Emit LLVM Code from Statements ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This contains code to emit OpenMP nodes as LLVM code.
12 //===----------------------------------------------------------------------===//
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;
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));
38 CodeGenFunction::AutoVarEmission Emission =
39 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
40 CGF.EmitAutoVarCleanups(Emission);
47 CodeGenFunction::OMPPrivateScope InlinedShareds;
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));
56 OMPLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S,
57 bool AsInlined = false, bool EmitPreInitStmt = true)
58 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
61 emitPreInitStmt(CGF, S);
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 assert(VD == VD->getCanonicalDecl() &&
69 "Canonical decl must be captured.");
70 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
71 isCapturedVar(CGF, VD) ||
72 (CGF.CapturedStmtInfo &&
73 InlinedShareds.isGlobalVarCaptured(VD)),
74 VD->getType().getNonReferenceType(), VK_LValue,
76 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
77 return CGF.EmitLValue(&DRE).getAddress();
81 (void)InlinedShareds.Privatize();
87 /// Lexical scope for OpenMP parallel construct, that handles correct codegen
88 /// for captured expressions.
89 class OMPParallelScope final : public OMPLexicalScope {
90 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
91 OpenMPDirectiveKind Kind = S.getDirectiveKind();
92 return !(isOpenMPTargetExecutionDirective(Kind) ||
93 isOpenMPLoopBoundSharingDirective(Kind)) &&
94 isOpenMPParallelDirective(Kind);
98 OMPParallelScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
99 : OMPLexicalScope(CGF, S,
101 /*EmitPreInitStmt=*/EmitPreInitStmt(S)) {}
104 /// Lexical scope for OpenMP teams construct, that handles correct codegen
105 /// for captured expressions.
106 class OMPTeamsScope final : public OMPLexicalScope {
107 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
108 OpenMPDirectiveKind Kind = S.getDirectiveKind();
109 return !isOpenMPTargetExecutionDirective(Kind) &&
110 isOpenMPTeamsDirective(Kind);
114 OMPTeamsScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
115 : OMPLexicalScope(CGF, S,
117 /*EmitPreInitStmt=*/EmitPreInitStmt(S)) {}
120 /// Private scope for OpenMP loop-based directives, that supports capturing
121 /// of used expression from loop statement.
122 class OMPLoopScope : public CodeGenFunction::RunCleanupsScope {
123 void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopDirective &S) {
124 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
125 for (auto *E : S.counters()) {
126 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
127 (void)PreCondScope.addPrivate(VD, [&CGF, VD]() {
128 return CGF.CreateMemTemp(VD->getType().getNonReferenceType());
131 (void)PreCondScope.Privatize();
132 if (auto *LD = dyn_cast<OMPLoopDirective>(&S)) {
133 if (auto *PreInits = cast_or_null<DeclStmt>(LD->getPreInits())) {
134 for (const auto *I : PreInits->decls())
135 CGF.EmitVarDecl(cast<VarDecl>(*I));
141 OMPLoopScope(CodeGenFunction &CGF, const OMPLoopDirective &S)
142 : CodeGenFunction::RunCleanupsScope(CGF) {
143 emitPreInitStmt(CGF, S);
149 static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
150 const OMPExecutableDirective &S,
151 const RegionCodeGenTy &CodeGen);
153 LValue CodeGenFunction::EmitOMPSharedLValue(const Expr *E) {
154 if (auto *OrigDRE = dyn_cast<DeclRefExpr>(E)) {
155 if (auto *OrigVD = dyn_cast<VarDecl>(OrigDRE->getDecl())) {
156 OrigVD = OrigVD->getCanonicalDecl();
158 LambdaCaptureFields.lookup(OrigVD) ||
159 (CapturedStmtInfo && CapturedStmtInfo->lookup(OrigVD)) ||
160 (CurCodeDecl && isa<BlockDecl>(CurCodeDecl));
161 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD), IsCaptured,
162 OrigDRE->getType(), VK_LValue, OrigDRE->getExprLoc());
163 return EmitLValue(&DRE);
166 return EmitLValue(E);
169 llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
170 auto &C = getContext();
171 llvm::Value *Size = nullptr;
172 auto SizeInChars = C.getTypeSizeInChars(Ty);
173 if (SizeInChars.isZero()) {
174 // getTypeSizeInChars() returns 0 for a VLA.
175 while (auto *VAT = C.getAsVariableArrayType(Ty)) {
176 llvm::Value *ArraySize;
177 std::tie(ArraySize, Ty) = getVLASize(VAT);
178 Size = Size ? Builder.CreateNUWMul(Size, ArraySize) : ArraySize;
180 SizeInChars = C.getTypeSizeInChars(Ty);
181 if (SizeInChars.isZero())
182 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
183 Size = Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
185 Size = CGM.getSize(SizeInChars);
189 void CodeGenFunction::GenerateOpenMPCapturedVars(
190 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
191 const RecordDecl *RD = S.getCapturedRecordDecl();
192 auto CurField = RD->field_begin();
193 auto CurCap = S.captures().begin();
194 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
195 E = S.capture_init_end();
196 I != E; ++I, ++CurField, ++CurCap) {
197 if (CurField->hasCapturedVLAType()) {
198 auto VAT = CurField->getCapturedVLAType();
199 auto *Val = VLASizeMap[VAT->getSizeExpr()];
200 CapturedVars.push_back(Val);
201 } else if (CurCap->capturesThis())
202 CapturedVars.push_back(CXXThisValue);
203 else if (CurCap->capturesVariableByCopy()) {
205 EmitLoadOfLValue(EmitLValue(*I), SourceLocation()).getScalarVal();
207 // If the field is not a pointer, we need to save the actual value
208 // and load it as a void pointer.
209 if (!CurField->getType()->isAnyPointerType()) {
210 auto &Ctx = getContext();
211 auto DstAddr = CreateMemTemp(
212 Ctx.getUIntPtrType(),
213 Twine(CurCap->getCapturedVar()->getName()) + ".casted");
214 LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
216 auto *SrcAddrVal = EmitScalarConversion(
217 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
218 Ctx.getPointerType(CurField->getType()), SourceLocation());
220 MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType());
222 // Store the value using the source type pointer.
223 EmitStoreThroughLValue(RValue::get(CV), SrcLV);
225 // Load the value using the destination type pointer.
226 CV = EmitLoadOfLValue(DstLV, SourceLocation()).getScalarVal();
228 CapturedVars.push_back(CV);
230 assert(CurCap->capturesVariable() && "Expected capture by reference.");
231 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
236 static Address castValueFromUintptr(CodeGenFunction &CGF, QualType DstType,
237 StringRef Name, LValue AddrLV,
238 bool isReferenceType = false) {
239 ASTContext &Ctx = CGF.getContext();
241 auto *CastedPtr = CGF.EmitScalarConversion(
242 AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
243 Ctx.getPointerType(DstType), SourceLocation());
245 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
248 // If we are dealing with references we need to return the address of the
249 // reference instead of the reference of the value.
250 if (isReferenceType) {
251 QualType RefType = Ctx.getLValueReferenceType(DstType);
252 auto *RefVal = TmpAddr.getPointer();
253 TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref");
254 auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
255 CGF.EmitStoreThroughLValue(RValue::get(RefVal), TmpLVal, /*isInit*/ true);
261 static QualType getCanonicalParamType(ASTContext &C, QualType T) {
262 if (T->isLValueReferenceType()) {
263 return C.getLValueReferenceType(
264 getCanonicalParamType(C, T.getNonReferenceType()),
265 /*SpelledAsLValue=*/false);
267 if (T->isPointerType())
268 return C.getPointerType(getCanonicalParamType(C, T->getPointeeType()));
269 if (auto *A = T->getAsArrayTypeUnsafe()) {
270 if (auto *VLA = dyn_cast<VariableArrayType>(A))
271 return getCanonicalParamType(C, VLA->getElementType());
272 else if (!A->isVariablyModifiedType())
273 return C.getCanonicalType(T);
275 return C.getCanonicalParamType(T);
279 /// Contains required data for proper outlined function codegen.
280 struct FunctionOptions {
281 /// Captured statement for which the function is generated.
282 const CapturedStmt *S = nullptr;
283 /// true if cast to/from UIntPtr is required for variables captured by
285 const bool UIntPtrCastRequired = true;
286 /// true if only casted arguments must be registered as local args or VLA
288 const bool RegisterCastedArgsOnly = false;
289 /// Name of the generated function.
290 const StringRef FunctionName;
291 explicit FunctionOptions(const CapturedStmt *S, bool UIntPtrCastRequired,
292 bool RegisterCastedArgsOnly,
293 StringRef FunctionName)
294 : S(S), UIntPtrCastRequired(UIntPtrCastRequired),
295 RegisterCastedArgsOnly(UIntPtrCastRequired && RegisterCastedArgsOnly),
296 FunctionName(FunctionName) {}
300 static llvm::Function *emitOutlinedFunctionPrologue(
301 CodeGenFunction &CGF, FunctionArgList &Args,
302 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>>
304 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>>
306 llvm::Value *&CXXThisValue, const FunctionOptions &FO) {
307 const CapturedDecl *CD = FO.S->getCapturedDecl();
308 const RecordDecl *RD = FO.S->getCapturedRecordDecl();
309 assert(CD->hasBody() && "missing CapturedDecl body");
311 CXXThisValue = nullptr;
312 // Build the argument list.
313 CodeGenModule &CGM = CGF.CGM;
314 ASTContext &Ctx = CGM.getContext();
315 FunctionArgList TargetArgs;
316 Args.append(CD->param_begin(),
317 std::next(CD->param_begin(), CD->getContextParamPosition()));
320 std::next(CD->param_begin(), CD->getContextParamPosition()));
321 auto I = FO.S->captures().begin();
322 FunctionDecl *DebugFunctionDecl = nullptr;
323 if (!FO.UIntPtrCastRequired) {
324 FunctionProtoType::ExtProtoInfo EPI;
325 DebugFunctionDecl = FunctionDecl::Create(
326 Ctx, Ctx.getTranslationUnitDecl(), FO.S->getLocStart(),
327 SourceLocation(), DeclarationName(), Ctx.VoidTy,
328 Ctx.getTrivialTypeSourceInfo(
329 Ctx.getFunctionType(Ctx.VoidTy, llvm::None, EPI)),
330 SC_Static, /*isInlineSpecified=*/false, /*hasWrittenPrototype=*/false);
332 for (auto *FD : RD->fields()) {
333 QualType ArgType = FD->getType();
334 IdentifierInfo *II = nullptr;
335 VarDecl *CapVar = nullptr;
337 // If this is a capture by copy and the type is not a pointer, the outlined
338 // function argument type should be uintptr and the value properly casted to
339 // uintptr. This is necessary given that the runtime library is only able to
340 // deal with pointers. We can pass in the same way the VLA type sizes to the
341 // outlined function.
342 if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
343 I->capturesVariableArrayType()) {
344 if (FO.UIntPtrCastRequired)
345 ArgType = Ctx.getUIntPtrType();
348 if (I->capturesVariable() || I->capturesVariableByCopy()) {
349 CapVar = I->getCapturedVar();
350 II = CapVar->getIdentifier();
351 } else if (I->capturesThis())
352 II = &Ctx.Idents.get("this");
354 assert(I->capturesVariableArrayType());
355 II = &Ctx.Idents.get("vla");
357 if (ArgType->isVariablyModifiedType())
358 ArgType = getCanonicalParamType(Ctx, ArgType);
360 if (DebugFunctionDecl && (CapVar || I->capturesThis())) {
361 Arg = ParmVarDecl::Create(
362 Ctx, DebugFunctionDecl,
363 CapVar ? CapVar->getLocStart() : FD->getLocStart(),
364 CapVar ? CapVar->getLocation() : FD->getLocation(), II, ArgType,
365 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
367 Arg = ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(),
368 II, ArgType, ImplicitParamDecl::Other);
370 Args.emplace_back(Arg);
371 // Do not cast arguments if we emit function with non-original types.
372 TargetArgs.emplace_back(
373 FO.UIntPtrCastRequired
375 : CGM.getOpenMPRuntime().translateParameter(FD, Arg));
379 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
382 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
385 // Create the function declaration.
386 const CGFunctionInfo &FuncInfo =
387 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, TargetArgs);
388 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
391 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
392 FO.FunctionName, &CGM.getModule());
393 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
395 F->setDoesNotThrow();
397 // Generate the function.
398 CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, TargetArgs,
399 FO.S->getLocStart(), CD->getBody()->getLocStart());
400 unsigned Cnt = CD->getContextParamPosition();
401 I = FO.S->captures().begin();
402 for (auto *FD : RD->fields()) {
403 // Do not map arguments if we emit function with non-original types.
404 Address LocalAddr(Address::invalid());
405 if (!FO.UIntPtrCastRequired && Args[Cnt] != TargetArgs[Cnt]) {
406 LocalAddr = CGM.getOpenMPRuntime().getParameterAddress(CGF, Args[Cnt],
409 LocalAddr = CGF.GetAddrOfLocalVar(Args[Cnt]);
411 // If we are capturing a pointer by copy we don't need to do anything, just
412 // use the value that we get from the arguments.
413 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
414 const VarDecl *CurVD = I->getCapturedVar();
415 // If the variable is a reference we need to materialize it here.
416 if (CurVD->getType()->isReferenceType()) {
417 Address RefAddr = CGF.CreateMemTemp(
418 CurVD->getType(), CGM.getPointerAlign(), ".materialized_ref");
419 CGF.EmitStoreOfScalar(LocalAddr.getPointer(), RefAddr,
420 /*Volatile=*/false, CurVD->getType());
423 if (!FO.RegisterCastedArgsOnly)
424 LocalAddrs.insert({Args[Cnt], {CurVD, LocalAddr}});
430 LValue ArgLVal = CGF.MakeAddrLValue(LocalAddr, Args[Cnt]->getType(),
431 AlignmentSource::Decl);
432 if (FD->hasCapturedVLAType()) {
433 if (FO.UIntPtrCastRequired) {
434 ArgLVal = CGF.MakeAddrLValue(castValueFromUintptr(CGF, FD->getType(),
435 Args[Cnt]->getName(),
437 FD->getType(), AlignmentSource::Decl);
440 CGF.EmitLoadOfLValue(ArgLVal, SourceLocation()).getScalarVal();
441 auto VAT = FD->getCapturedVLAType();
442 VLASizes.insert({Args[Cnt], {VAT->getSizeExpr(), ExprArg}});
443 } else if (I->capturesVariable()) {
444 auto *Var = I->getCapturedVar();
445 QualType VarTy = Var->getType();
446 Address ArgAddr = ArgLVal.getAddress();
447 if (!VarTy->isReferenceType()) {
448 if (ArgLVal.getType()->isLValueReferenceType()) {
449 ArgAddr = CGF.EmitLoadOfReference(ArgLVal);
450 } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) {
451 assert(ArgLVal.getType()->isPointerType());
452 ArgAddr = CGF.EmitLoadOfPointer(
453 ArgAddr, ArgLVal.getType()->castAs<PointerType>());
456 if (!FO.RegisterCastedArgsOnly) {
459 {Var, Address(ArgAddr.getPointer(), Ctx.getDeclAlign(Var))}});
461 } else if (I->capturesVariableByCopy()) {
462 assert(!FD->getType()->isAnyPointerType() &&
463 "Not expecting a captured pointer.");
464 auto *Var = I->getCapturedVar();
465 QualType VarTy = Var->getType();
469 FO.UIntPtrCastRequired
470 ? castValueFromUintptr(CGF, FD->getType(), Args[Cnt]->getName(),
471 ArgLVal, VarTy->isReferenceType())
472 : ArgLVal.getAddress()}});
474 // If 'this' is captured, load it into CXXThisValue.
475 assert(I->capturesThis());
476 CXXThisValue = CGF.EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation())
478 LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress()}});
488 CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
491 "CapturedStmtInfo should be set when generating the captured function");
492 const CapturedDecl *CD = S.getCapturedDecl();
493 // Build the argument list.
494 bool NeedWrapperFunction =
496 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo;
497 FunctionArgList Args;
498 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs;
499 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes;
500 SmallString<256> Buffer;
501 llvm::raw_svector_ostream Out(Buffer);
502 Out << CapturedStmtInfo->getHelperName();
503 if (NeedWrapperFunction)
505 FunctionOptions FO(&S, !NeedWrapperFunction, /*RegisterCastedArgsOnly=*/false,
507 llvm::Function *F = emitOutlinedFunctionPrologue(*this, Args, LocalAddrs,
508 VLASizes, CXXThisValue, FO);
509 for (const auto &LocalAddrPair : LocalAddrs) {
510 if (LocalAddrPair.second.first) {
511 setAddrOfLocalVar(LocalAddrPair.second.first,
512 LocalAddrPair.second.second);
515 for (const auto &VLASizePair : VLASizes)
516 VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second;
517 PGO.assignRegionCounters(GlobalDecl(CD), F);
518 CapturedStmtInfo->EmitBody(*this, CD->getBody());
519 FinishFunction(CD->getBodyRBrace());
520 if (!NeedWrapperFunction)
523 FunctionOptions WrapperFO(&S, /*UIntPtrCastRequired=*/true,
524 /*RegisterCastedArgsOnly=*/true,
525 CapturedStmtInfo->getHelperName());
526 CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true);
530 llvm::Function *WrapperF =
531 emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes,
532 WrapperCGF.CXXThisValue, WrapperFO);
533 llvm::SmallVector<llvm::Value *, 4> CallArgs;
534 for (const auto *Arg : Args) {
535 llvm::Value *CallArg;
536 auto I = LocalAddrs.find(Arg);
537 if (I != LocalAddrs.end()) {
538 LValue LV = WrapperCGF.MakeAddrLValue(
540 I->second.first ? I->second.first->getType() : Arg->getType(),
541 AlignmentSource::Decl);
542 CallArg = WrapperCGF.EmitLoadOfScalar(LV, SourceLocation());
544 auto EI = VLASizes.find(Arg);
545 if (EI != VLASizes.end())
546 CallArg = EI->second.second;
548 LValue LV = WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg),
550 AlignmentSource::Decl);
551 CallArg = WrapperCGF.EmitLoadOfScalar(LV, SourceLocation());
554 CallArgs.emplace_back(WrapperCGF.EmitFromMemory(CallArg, Arg->getType()));
556 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, S.getLocStart(),
558 WrapperCGF.FinishFunction();
562 //===----------------------------------------------------------------------===//
563 // OpenMP Directive Emission
564 //===----------------------------------------------------------------------===//
565 void CodeGenFunction::EmitOMPAggregateAssign(
566 Address DestAddr, Address SrcAddr, QualType OriginalType,
567 const llvm::function_ref<void(Address, Address)> &CopyGen) {
568 // Perform element-by-element initialization.
571 // Drill down to the base element type on both arrays.
572 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
573 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
574 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
576 auto SrcBegin = SrcAddr.getPointer();
577 auto DestBegin = DestAddr.getPointer();
578 // Cast from pointer to array type to pointer to single element.
579 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
580 // The basic structure here is a while-do loop.
581 auto BodyBB = createBasicBlock("omp.arraycpy.body");
582 auto DoneBB = createBasicBlock("omp.arraycpy.done");
584 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
585 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
587 // Enter the loop body, making that address the current address.
588 auto EntryBB = Builder.GetInsertBlock();
591 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
593 llvm::PHINode *SrcElementPHI =
594 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
595 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
596 Address SrcElementCurrent =
597 Address(SrcElementPHI,
598 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
600 llvm::PHINode *DestElementPHI =
601 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
602 DestElementPHI->addIncoming(DestBegin, EntryBB);
603 Address DestElementCurrent =
604 Address(DestElementPHI,
605 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
608 CopyGen(DestElementCurrent, SrcElementCurrent);
610 // Shift the address forward by one element.
611 auto DestElementNext = Builder.CreateConstGEP1_32(
612 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
613 auto SrcElementNext = Builder.CreateConstGEP1_32(
614 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
615 // Check whether we've reached the end.
617 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
618 Builder.CreateCondBr(Done, DoneBB, BodyBB);
619 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
620 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
623 EmitBlock(DoneBB, /*IsFinished=*/true);
626 void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
627 Address SrcAddr, const VarDecl *DestVD,
628 const VarDecl *SrcVD, const Expr *Copy) {
629 if (OriginalType->isArrayType()) {
630 auto *BO = dyn_cast<BinaryOperator>(Copy);
631 if (BO && BO->getOpcode() == BO_Assign) {
632 // Perform simple memcpy for simple copying.
633 EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
635 // For arrays with complex element types perform element by element
637 EmitOMPAggregateAssign(
638 DestAddr, SrcAddr, OriginalType,
639 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
640 // Working with the single array element, so have to remap
641 // destination and source variables to corresponding array
643 CodeGenFunction::OMPPrivateScope Remap(*this);
644 Remap.addPrivate(DestVD, [DestElement]() -> Address {
648 SrcVD, [SrcElement]() -> Address { return SrcElement; });
649 (void)Remap.Privatize();
650 EmitIgnoredExpr(Copy);
654 // Remap pseudo source variable to private copy.
655 CodeGenFunction::OMPPrivateScope Remap(*this);
656 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
657 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
658 (void)Remap.Privatize();
659 // Emit copying of the whole variable.
660 EmitIgnoredExpr(Copy);
664 bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
665 OMPPrivateScope &PrivateScope) {
666 if (!HaveInsertPoint())
668 bool FirstprivateIsLastprivate = false;
669 llvm::DenseSet<const VarDecl *> Lastprivates;
670 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
671 for (const auto *D : C->varlists())
673 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
675 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
676 CGCapturedStmtInfo CapturesInfo(cast<CapturedStmt>(*D.getAssociatedStmt()));
677 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
678 auto IRef = C->varlist_begin();
679 auto InitsRef = C->inits().begin();
680 for (auto IInit : C->private_copies()) {
681 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
682 bool ThisFirstprivateIsLastprivate =
683 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
684 auto *CapFD = CapturesInfo.lookup(OrigVD);
685 auto *FD = CapturedStmtInfo->lookup(OrigVD);
686 if (!ThisFirstprivateIsLastprivate && FD && (FD == CapFD) &&
687 !FD->getType()->isReferenceType()) {
688 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
693 FirstprivateIsLastprivate =
694 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
695 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
696 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
697 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
699 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
700 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
701 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
702 Address OriginalAddr = EmitLValue(&DRE).getAddress();
703 QualType Type = VD->getType();
704 if (Type->isArrayType()) {
705 // Emit VarDecl with copy init for arrays.
706 // Get the address of the original variable captured in current
708 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
709 auto Emission = EmitAutoVarAlloca(*VD);
710 auto *Init = VD->getInit();
711 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
712 // Perform simple memcpy.
713 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
716 EmitOMPAggregateAssign(
717 Emission.getAllocatedAddress(), OriginalAddr, Type,
718 [this, VDInit, Init](Address DestElement,
719 Address SrcElement) {
720 // Clean up any temporaries needed by the initialization.
721 RunCleanupsScope InitScope(*this);
722 // Emit initialization for single element.
723 setAddrOfLocalVar(VDInit, SrcElement);
724 EmitAnyExprToMem(Init, DestElement,
725 Init->getType().getQualifiers(),
726 /*IsInitializer*/ false);
727 LocalDeclMap.erase(VDInit);
730 EmitAutoVarCleanups(Emission);
731 return Emission.getAllocatedAddress();
734 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
735 // Emit private VarDecl with copy init.
736 // Remap temp VDInit variable to the address of the original
738 // (for proper handling of captured global variables).
739 setAddrOfLocalVar(VDInit, OriginalAddr);
741 LocalDeclMap.erase(VDInit);
742 return GetAddrOfLocalVar(VD);
745 assert(IsRegistered &&
746 "firstprivate var already registered as private");
747 // Silence the warning about unused variable.
754 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
757 void CodeGenFunction::EmitOMPPrivateClause(
758 const OMPExecutableDirective &D,
759 CodeGenFunction::OMPPrivateScope &PrivateScope) {
760 if (!HaveInsertPoint())
762 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
763 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
764 auto IRef = C->varlist_begin();
765 for (auto IInit : C->private_copies()) {
766 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
767 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
768 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
770 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
771 // Emit private VarDecl with copy init.
773 return GetAddrOfLocalVar(VD);
775 assert(IsRegistered && "private var already registered as private");
776 // Silence the warning about unused variable.
784 bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
785 if (!HaveInsertPoint())
787 // threadprivate_var1 = master_threadprivate_var1;
788 // operator=(threadprivate_var2, master_threadprivate_var2);
790 // __kmpc_barrier(&loc, global_tid);
791 llvm::DenseSet<const VarDecl *> CopiedVars;
792 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
793 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
794 auto IRef = C->varlist_begin();
795 auto ISrcRef = C->source_exprs().begin();
796 auto IDestRef = C->destination_exprs().begin();
797 for (auto *AssignOp : C->assignment_ops()) {
798 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
799 QualType Type = VD->getType();
800 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
801 // Get the address of the master variable. If we are emitting code with
802 // TLS support, the address is passed from the master as field in the
803 // captured declaration.
804 Address MasterAddr = Address::invalid();
805 if (getLangOpts().OpenMPUseTLS &&
806 getContext().getTargetInfo().isTLSSupported()) {
807 assert(CapturedStmtInfo->lookup(VD) &&
808 "Copyin threadprivates should have been captured!");
809 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
810 VK_LValue, (*IRef)->getExprLoc());
811 MasterAddr = EmitLValue(&DRE).getAddress();
812 LocalDeclMap.erase(VD);
815 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
816 : CGM.GetAddrOfGlobal(VD),
817 getContext().getDeclAlign(VD));
819 // Get the address of the threadprivate variable.
820 Address PrivateAddr = EmitLValue(*IRef).getAddress();
821 if (CopiedVars.size() == 1) {
822 // At first check if current thread is a master thread. If it is, no
823 // need to copy data.
824 CopyBegin = createBasicBlock("copyin.not.master");
825 CopyEnd = createBasicBlock("copyin.not.master.end");
826 Builder.CreateCondBr(
827 Builder.CreateICmpNE(
828 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
829 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
831 EmitBlock(CopyBegin);
833 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
834 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
835 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
843 // Exit out of copying procedure for non-master thread.
844 EmitBlock(CopyEnd, /*IsFinished=*/true);
850 bool CodeGenFunction::EmitOMPLastprivateClauseInit(
851 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
852 if (!HaveInsertPoint())
854 bool HasAtLeastOneLastprivate = false;
855 llvm::DenseSet<const VarDecl *> SIMDLCVs;
856 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
857 auto *LoopDirective = cast<OMPLoopDirective>(&D);
858 for (auto *C : LoopDirective->counters()) {
860 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
863 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
864 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
865 HasAtLeastOneLastprivate = true;
866 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()))
868 auto IRef = C->varlist_begin();
869 auto IDestRef = C->destination_exprs().begin();
870 for (auto *IInit : C->private_copies()) {
871 // Keep the address of the original variable for future update at the end
873 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
874 // Taskloops do not require additional initialization, it is done in
875 // runtime support library.
876 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
877 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
878 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
880 const_cast<VarDecl *>(OrigVD),
881 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
883 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
884 return EmitLValue(&DRE).getAddress();
886 // Check if the variable is also a firstprivate: in this case IInit is
887 // not generated. Initialization of this variable will happen in codegen
888 // for 'firstprivate' clause.
889 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
890 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
891 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
892 // Emit private VarDecl with copy init.
894 return GetAddrOfLocalVar(VD);
896 assert(IsRegistered &&
897 "lastprivate var already registered as private");
905 return HasAtLeastOneLastprivate;
908 void CodeGenFunction::EmitOMPLastprivateClauseFinal(
909 const OMPExecutableDirective &D, bool NoFinals,
910 llvm::Value *IsLastIterCond) {
911 if (!HaveInsertPoint())
913 // Emit following code:
914 // if (<IsLastIterCond>) {
915 // orig_var1 = private_orig_var1;
917 // orig_varn = private_orig_varn;
919 llvm::BasicBlock *ThenBB = nullptr;
920 llvm::BasicBlock *DoneBB = nullptr;
921 if (IsLastIterCond) {
922 ThenBB = createBasicBlock(".omp.lastprivate.then");
923 DoneBB = createBasicBlock(".omp.lastprivate.done");
924 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
927 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
928 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
929 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
930 auto IC = LoopDirective->counters().begin();
931 for (auto F : LoopDirective->finals()) {
933 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
935 AlreadyEmittedVars.insert(D);
937 LoopCountersAndUpdates[D] = F;
941 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
942 auto IRef = C->varlist_begin();
943 auto ISrcRef = C->source_exprs().begin();
944 auto IDestRef = C->destination_exprs().begin();
945 for (auto *AssignOp : C->assignment_ops()) {
946 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
947 QualType Type = PrivateVD->getType();
948 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
949 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
950 // If lastprivate variable is a loop control variable for loop-based
951 // directive, update its value before copyin back to original
953 if (auto *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
954 EmitIgnoredExpr(FinalExpr);
955 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
956 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
957 // Get the address of the original variable.
958 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
959 // Get the address of the private variable.
960 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
961 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
963 Address(Builder.CreateLoad(PrivateAddr),
964 getNaturalTypeAlignment(RefTy->getPointeeType()));
965 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
971 if (auto *PostUpdate = C->getPostUpdateExpr())
972 EmitIgnoredExpr(PostUpdate);
975 EmitBlock(DoneBB, /*IsFinished=*/true);
978 void CodeGenFunction::EmitOMPReductionClauseInit(
979 const OMPExecutableDirective &D,
980 CodeGenFunction::OMPPrivateScope &PrivateScope) {
981 if (!HaveInsertPoint())
983 SmallVector<const Expr *, 4> Shareds;
984 SmallVector<const Expr *, 4> Privates;
985 SmallVector<const Expr *, 4> ReductionOps;
986 SmallVector<const Expr *, 4> LHSs;
987 SmallVector<const Expr *, 4> RHSs;
988 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
989 auto IPriv = C->privates().begin();
990 auto IRed = C->reduction_ops().begin();
991 auto ILHS = C->lhs_exprs().begin();
992 auto IRHS = C->rhs_exprs().begin();
993 for (const auto *Ref : C->varlists()) {
994 Shareds.emplace_back(Ref);
995 Privates.emplace_back(*IPriv);
996 ReductionOps.emplace_back(*IRed);
997 LHSs.emplace_back(*ILHS);
998 RHSs.emplace_back(*IRHS);
999 std::advance(IPriv, 1);
1000 std::advance(IRed, 1);
1001 std::advance(ILHS, 1);
1002 std::advance(IRHS, 1);
1005 ReductionCodeGen RedCG(Shareds, Privates, ReductionOps);
1007 auto ILHS = LHSs.begin();
1008 auto IRHS = RHSs.begin();
1009 auto IPriv = Privates.begin();
1010 for (const auto *IRef : Shareds) {
1011 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
1012 // Emit private VarDecl with reduction init.
1013 RedCG.emitSharedLValue(*this, Count);
1014 RedCG.emitAggregateType(*this, Count);
1015 auto Emission = EmitAutoVarAlloca(*PrivateVD);
1016 RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(),
1017 RedCG.getSharedLValue(Count),
1018 [&Emission](CodeGenFunction &CGF) {
1019 CGF.EmitAutoVarInit(Emission);
1022 EmitAutoVarCleanups(Emission);
1023 Address BaseAddr = RedCG.adjustPrivateAddress(
1024 *this, Count, Emission.getAllocatedAddress());
1025 bool IsRegistered = PrivateScope.addPrivate(
1026 RedCG.getBaseDecl(Count), [BaseAddr]() -> Address { return BaseAddr; });
1027 assert(IsRegistered && "private var already registered as private");
1028 // Silence the warning about unused variable.
1031 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
1032 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
1033 QualType Type = PrivateVD->getType();
1034 bool isaOMPArraySectionExpr = isa<OMPArraySectionExpr>(IRef);
1035 if (isaOMPArraySectionExpr && Type->isVariablyModifiedType()) {
1036 // Store the address of the original variable associated with the LHS
1037 // implicit variable.
1038 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
1039 return RedCG.getSharedLValue(Count).getAddress();
1041 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
1042 return GetAddrOfLocalVar(PrivateVD);
1044 } else if ((isaOMPArraySectionExpr && Type->isScalarType()) ||
1045 isa<ArraySubscriptExpr>(IRef)) {
1046 // Store the address of the original variable associated with the LHS
1047 // implicit variable.
1048 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
1049 return RedCG.getSharedLValue(Count).getAddress();
1051 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
1052 return Builder.CreateElementBitCast(GetAddrOfLocalVar(PrivateVD),
1053 ConvertTypeForMem(RHSVD->getType()),
1057 QualType Type = PrivateVD->getType();
1058 bool IsArray = getContext().getAsArrayType(Type) != nullptr;
1059 Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress();
1060 // Store the address of the original variable associated with the LHS
1061 // implicit variable.
1063 OriginalAddr = Builder.CreateElementBitCast(
1064 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
1066 PrivateScope.addPrivate(
1067 LHSVD, [OriginalAddr]() -> Address { return OriginalAddr; });
1068 PrivateScope.addPrivate(
1069 RHSVD, [this, PrivateVD, RHSVD, IsArray]() -> Address {
1071 ? Builder.CreateElementBitCast(
1072 GetAddrOfLocalVar(PrivateVD),
1073 ConvertTypeForMem(RHSVD->getType()), "rhs.begin")
1074 : GetAddrOfLocalVar(PrivateVD);
1084 void CodeGenFunction::EmitOMPReductionClauseFinal(
1085 const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
1086 if (!HaveInsertPoint())
1088 llvm::SmallVector<const Expr *, 8> Privates;
1089 llvm::SmallVector<const Expr *, 8> LHSExprs;
1090 llvm::SmallVector<const Expr *, 8> RHSExprs;
1091 llvm::SmallVector<const Expr *, 8> ReductionOps;
1092 bool HasAtLeastOneReduction = false;
1093 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1094 HasAtLeastOneReduction = true;
1095 Privates.append(C->privates().begin(), C->privates().end());
1096 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1097 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1098 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1100 if (HasAtLeastOneReduction) {
1101 bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
1102 isOpenMPParallelDirective(D.getDirectiveKind()) ||
1103 D.getDirectiveKind() == OMPD_simd;
1104 bool SimpleReduction = D.getDirectiveKind() == OMPD_simd ||
1105 D.getDirectiveKind() == OMPD_distribute_simd;
1106 // Emit nowait reduction if nowait clause is present or directive is a
1107 // parallel directive (it always has implicit barrier).
1108 CGM.getOpenMPRuntime().emitReduction(
1109 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
1110 {WithNowait, SimpleReduction, ReductionKind});
1114 static void emitPostUpdateForReductionClause(
1115 CodeGenFunction &CGF, const OMPExecutableDirective &D,
1116 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
1117 if (!CGF.HaveInsertPoint())
1119 llvm::BasicBlock *DoneBB = nullptr;
1120 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1121 if (auto *PostUpdate = C->getPostUpdateExpr()) {
1123 if (auto *Cond = CondGen(CGF)) {
1124 // If the first post-update expression is found, emit conditional
1125 // block if it was requested.
1126 auto *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
1127 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1128 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1129 CGF.EmitBlock(ThenBB);
1132 CGF.EmitIgnoredExpr(PostUpdate);
1136 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1140 /// Codegen lambda for appending distribute lower and upper bounds to outlined
1141 /// parallel function. This is necessary for combined constructs such as
1142 /// 'distribute parallel for'
1143 typedef llvm::function_ref<void(CodeGenFunction &,
1144 const OMPExecutableDirective &,
1145 llvm::SmallVectorImpl<llvm::Value *> &)>
1146 CodeGenBoundParametersTy;
1147 } // anonymous namespace
1149 static void emitCommonOMPParallelDirective(
1150 CodeGenFunction &CGF, const OMPExecutableDirective &S,
1151 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1152 const CodeGenBoundParametersTy &CodeGenBoundParameters) {
1153 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
1154 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
1155 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
1156 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
1157 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
1158 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1159 /*IgnoreResultAssign*/ true);
1160 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
1161 CGF, NumThreads, NumThreadsClause->getLocStart());
1163 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
1164 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
1165 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
1166 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
1168 const Expr *IfCond = nullptr;
1169 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1170 if (C->getNameModifier() == OMPD_unknown ||
1171 C->getNameModifier() == OMPD_parallel) {
1172 IfCond = C->getCondition();
1177 OMPParallelScope Scope(CGF, S);
1178 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
1179 // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk
1180 // lower and upper bounds with the pragma 'for' chunking mechanism.
1181 // The following lambda takes care of appending the lower and upper bound
1182 // parameters when necessary
1183 CodeGenBoundParameters(CGF, S, CapturedVars);
1184 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
1185 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
1186 CapturedVars, IfCond);
1189 static void emitEmptyBoundParameters(CodeGenFunction &,
1190 const OMPExecutableDirective &,
1191 llvm::SmallVectorImpl<llvm::Value *> &) {}
1193 void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
1194 // Emit parallel region as a standalone region.
1195 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1196 OMPPrivateScope PrivateScope(CGF);
1197 bool Copyins = CGF.EmitOMPCopyinClause(S);
1198 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1200 // Emit implicit barrier to synchronize threads and avoid data races on
1201 // propagation master's thread values of threadprivate variables to local
1202 // instances of that variables of all other implicit threads.
1203 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1204 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1205 /*ForceSimpleCall=*/true);
1207 CGF.EmitOMPPrivateClause(S, PrivateScope);
1208 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1209 (void)PrivateScope.Privatize();
1210 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1211 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
1213 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen,
1214 emitEmptyBoundParameters);
1215 emitPostUpdateForReductionClause(
1216 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1219 void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1220 JumpDest LoopExit) {
1221 RunCleanupsScope BodyScope(*this);
1222 // Update counters values on current iteration.
1223 for (auto I : D.updates()) {
1226 // Update the linear variables.
1227 // In distribute directives only loop counters may be marked as linear, no
1228 // need to generate the code for them.
1229 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
1230 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
1231 for (auto *U : C->updates())
1236 // On a continue in the body, jump to the end.
1237 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
1238 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1240 EmitStmt(D.getBody());
1241 // The end (updates/cleanups).
1242 EmitBlock(Continue.getBlock());
1243 BreakContinueStack.pop_back();
1246 void CodeGenFunction::EmitOMPInnerLoop(
1247 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1248 const Expr *IncExpr,
1249 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1250 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
1251 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
1253 // Start the loop with a block that tests the condition.
1254 auto CondBlock = createBasicBlock("omp.inner.for.cond");
1255 EmitBlock(CondBlock);
1256 const SourceRange &R = S.getSourceRange();
1257 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1258 SourceLocToDebugLoc(R.getEnd()));
1260 // If there are any cleanups between here and the loop-exit scope,
1261 // create a block to stage a loop exit along.
1262 auto ExitBlock = LoopExit.getBlock();
1263 if (RequiresCleanup)
1264 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
1266 auto LoopBody = createBasicBlock("omp.inner.for.body");
1269 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
1270 if (ExitBlock != LoopExit.getBlock()) {
1271 EmitBlock(ExitBlock);
1272 EmitBranchThroughCleanup(LoopExit);
1275 EmitBlock(LoopBody);
1276 incrementProfileCounter(&S);
1278 // Create a block for the increment.
1279 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
1280 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1284 // Emit "IV = IV + 1" and a back-edge to the condition block.
1285 EmitBlock(Continue.getBlock());
1286 EmitIgnoredExpr(IncExpr);
1288 BreakContinueStack.pop_back();
1289 EmitBranch(CondBlock);
1291 // Emit the fall-through block.
1292 EmitBlock(LoopExit.getBlock());
1295 bool CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
1296 if (!HaveInsertPoint())
1298 // Emit inits for the linear variables.
1299 bool HasLinears = false;
1300 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
1301 for (auto *Init : C->inits()) {
1303 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
1304 if (auto *Ref = dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
1305 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1306 auto *OrigVD = cast<VarDecl>(Ref->getDecl());
1307 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1308 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1309 VD->getInit()->getType(), VK_LValue,
1310 VD->getInit()->getExprLoc());
1311 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1313 /*capturedByInit=*/false);
1314 EmitAutoVarCleanups(Emission);
1318 // Emit the linear steps for the linear clauses.
1319 // If a step is not constant, it is pre-calculated before the loop.
1320 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1321 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
1322 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
1323 // Emit calculation of the linear step.
1324 EmitIgnoredExpr(CS);
1330 void CodeGenFunction::EmitOMPLinearClauseFinal(
1331 const OMPLoopDirective &D,
1332 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
1333 if (!HaveInsertPoint())
1335 llvm::BasicBlock *DoneBB = nullptr;
1336 // Emit the final values of the linear variables.
1337 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
1338 auto IC = C->varlist_begin();
1339 for (auto *F : C->finals()) {
1341 if (auto *Cond = CondGen(*this)) {
1342 // If the first post-update expression is found, emit conditional
1343 // block if it was requested.
1344 auto *ThenBB = createBasicBlock(".omp.linear.pu");
1345 DoneBB = createBasicBlock(".omp.linear.pu.done");
1346 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1350 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1351 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1352 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1353 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
1354 Address OrigAddr = EmitLValue(&DRE).getAddress();
1355 CodeGenFunction::OMPPrivateScope VarScope(*this);
1356 VarScope.addPrivate(OrigVD, [OrigAddr]() -> Address { return OrigAddr; });
1357 (void)VarScope.Privatize();
1361 if (auto *PostUpdate = C->getPostUpdateExpr())
1362 EmitIgnoredExpr(PostUpdate);
1365 EmitBlock(DoneBB, /*IsFinished=*/true);
1368 static void emitAlignedClause(CodeGenFunction &CGF,
1369 const OMPExecutableDirective &D) {
1370 if (!CGF.HaveInsertPoint())
1372 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
1373 unsigned ClauseAlignment = 0;
1374 if (auto AlignmentExpr = Clause->getAlignment()) {
1376 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1377 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
1379 for (auto E : Clause->varlists()) {
1380 unsigned Alignment = ClauseAlignment;
1381 if (Alignment == 0) {
1382 // OpenMP [2.8.1, Description]
1383 // If no optional parameter is specified, implementation-defined default
1384 // alignments for SIMD instructions on the target platforms are assumed.
1387 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1388 E->getType()->getPointeeType()))
1391 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1392 "alignment is not power of 2");
1393 if (Alignment != 0) {
1394 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1395 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1401 void CodeGenFunction::EmitOMPPrivateLoopCounters(
1402 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1403 if (!HaveInsertPoint())
1405 auto I = S.private_counters().begin();
1406 for (auto *E : S.counters()) {
1407 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1408 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
1409 (void)LoopScope.addPrivate(VD, [&]() -> Address {
1410 // Emit var without initialization.
1411 if (!LocalDeclMap.count(PrivateVD)) {
1412 auto VarEmission = EmitAutoVarAlloca(*PrivateVD);
1413 EmitAutoVarCleanups(VarEmission);
1415 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1416 /*RefersToEnclosingVariableOrCapture=*/false,
1417 (*I)->getType(), VK_LValue, (*I)->getExprLoc());
1418 return EmitLValue(&DRE).getAddress();
1420 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1421 VD->hasGlobalStorage()) {
1422 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
1423 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
1424 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1425 E->getType(), VK_LValue, E->getExprLoc());
1426 return EmitLValue(&DRE).getAddress();
1433 static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1434 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1435 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
1436 if (!CGF.HaveInsertPoint())
1439 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
1440 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
1441 (void)PreCondScope.Privatize();
1442 // Get initial values of real counters.
1443 for (auto I : S.inits()) {
1444 CGF.EmitIgnoredExpr(I);
1447 // Check that loop is executed at least one time.
1448 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1451 void CodeGenFunction::EmitOMPLinearClause(
1452 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1453 if (!HaveInsertPoint())
1455 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1456 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
1457 auto *LoopDirective = cast<OMPLoopDirective>(&D);
1458 for (auto *C : LoopDirective->counters()) {
1460 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1463 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
1464 auto CurPrivate = C->privates().begin();
1465 for (auto *E : C->varlists()) {
1466 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1468 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
1469 if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
1470 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
1471 // Emit private VarDecl with copy init.
1472 EmitVarDecl(*PrivateVD);
1473 return GetAddrOfLocalVar(PrivateVD);
1475 assert(IsRegistered && "linear var already registered as private");
1476 // Silence the warning about unused variable.
1479 EmitVarDecl(*PrivateVD);
1485 static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
1486 const OMPExecutableDirective &D,
1488 if (!CGF.HaveInsertPoint())
1490 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
1491 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1492 /*ignoreResult=*/true);
1493 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1494 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1495 // In presence of finite 'safelen', it may be unsafe to mark all
1496 // the memory instructions parallel, because loop-carried
1497 // dependences of 'safelen' iterations are possible.
1499 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
1500 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
1501 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1502 /*ignoreResult=*/true);
1503 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1504 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1505 // In presence of finite 'safelen', it may be unsafe to mark all
1506 // the memory instructions parallel, because loop-carried
1507 // dependences of 'safelen' iterations are possible.
1508 CGF.LoopStack.setParallel(false);
1512 void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1514 // Walk clauses and process safelen/lastprivate.
1515 LoopStack.setParallel(!IsMonotonic);
1516 LoopStack.setVectorizeEnable(true);
1517 emitSimdlenSafelenClause(*this, D, IsMonotonic);
1520 void CodeGenFunction::EmitOMPSimdFinal(
1521 const OMPLoopDirective &D,
1522 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
1523 if (!HaveInsertPoint())
1525 llvm::BasicBlock *DoneBB = nullptr;
1526 auto IC = D.counters().begin();
1527 auto IPC = D.private_counters().begin();
1528 for (auto F : D.finals()) {
1529 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
1530 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1531 auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
1532 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1533 OrigVD->hasGlobalStorage() || CED) {
1535 if (auto *Cond = CondGen(*this)) {
1536 // If the first post-update expression is found, emit conditional
1537 // block if it was requested.
1538 auto *ThenBB = createBasicBlock(".omp.final.then");
1539 DoneBB = createBasicBlock(".omp.final.done");
1540 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1544 Address OrigAddr = Address::invalid();
1546 OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
1548 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1549 /*RefersToEnclosingVariableOrCapture=*/false,
1550 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
1551 OrigAddr = EmitLValue(&DRE).getAddress();
1553 OMPPrivateScope VarScope(*this);
1554 VarScope.addPrivate(OrigVD,
1555 [OrigAddr]() -> Address { return OrigAddr; });
1556 (void)VarScope.Privatize();
1563 EmitBlock(DoneBB, /*IsFinished=*/true);
1566 static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF,
1567 const OMPLoopDirective &S,
1568 CodeGenFunction::JumpDest LoopExit) {
1569 CGF.EmitOMPLoopBody(S, LoopExit);
1570 CGF.EmitStopPoint(&S);
1573 static void emitOMPSimdRegion(CodeGenFunction &CGF, const OMPLoopDirective &S,
1574 PrePostActionTy &Action) {
1576 assert(isOpenMPSimdDirective(S.getDirectiveKind()) &&
1577 "Expected simd directive");
1578 OMPLoopScope PreInitScope(CGF, S);
1580 // for (IV in 0..LastIteration) BODY;
1581 // <Final counter/linear vars updates>;
1585 // Emit: if (PreCond) - begin.
1586 // If the condition constant folds and can be elided, avoid emitting the
1589 llvm::BasicBlock *ContBlock = nullptr;
1590 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1594 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1595 ContBlock = CGF.createBasicBlock("simd.if.end");
1596 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1597 CGF.getProfileCount(&S));
1598 CGF.EmitBlock(ThenBlock);
1599 CGF.incrementProfileCounter(&S);
1602 // Emit the loop iteration variable.
1603 const Expr *IVExpr = S.getIterationVariable();
1604 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1605 CGF.EmitVarDecl(*IVDecl);
1606 CGF.EmitIgnoredExpr(S.getInit());
1608 // Emit the iterations count variable.
1609 // If it is not a variable, Sema decided to calculate iterations count on
1610 // each iteration (e.g., it is foldable into a constant).
1611 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1612 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1613 // Emit calculation of the iterations count.
1614 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
1617 CGF.EmitOMPSimdInit(S);
1619 emitAlignedClause(CGF, S);
1620 (void)CGF.EmitOMPLinearClauseInit(S);
1622 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1623 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
1624 CGF.EmitOMPLinearClause(S, LoopScope);
1625 CGF.EmitOMPPrivateClause(S, LoopScope);
1626 CGF.EmitOMPReductionClauseInit(S, LoopScope);
1627 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
1628 (void)LoopScope.Privatize();
1629 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1631 [&S](CodeGenFunction &CGF) {
1632 CGF.EmitOMPLoopBody(S, CodeGenFunction::JumpDest());
1633 CGF.EmitStopPoint(&S);
1635 [](CodeGenFunction &) {});
1636 CGF.EmitOMPSimdFinal(
1637 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1638 // Emit final copy of the lastprivate variables at the end of loops.
1639 if (HasLastprivateClause)
1640 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
1641 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
1642 emitPostUpdateForReductionClause(
1643 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1645 CGF.EmitOMPLinearClauseFinal(
1646 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1647 // Emit: if (PreCond) - end.
1649 CGF.EmitBranch(ContBlock);
1650 CGF.EmitBlock(ContBlock, true);
1654 void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
1655 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
1656 emitOMPSimdRegion(CGF, S, Action);
1658 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1659 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
1662 void CodeGenFunction::EmitOMPOuterLoop(
1663 bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S,
1664 CodeGenFunction::OMPPrivateScope &LoopScope,
1665 const CodeGenFunction::OMPLoopArguments &LoopArgs,
1666 const CodeGenFunction::CodeGenLoopTy &CodeGenLoop,
1667 const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) {
1668 auto &RT = CGM.getOpenMPRuntime();
1670 const Expr *IVExpr = S.getIterationVariable();
1671 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1672 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1674 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1676 // Start the loop with a block that tests the condition.
1677 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1678 EmitBlock(CondBlock);
1679 const SourceRange &R = S.getSourceRange();
1680 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1681 SourceLocToDebugLoc(R.getEnd()));
1683 llvm::Value *BoolCondVal = nullptr;
1684 if (!DynamicOrOrdered) {
1685 // UB = min(UB, GlobalUB) or
1686 // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g.
1687 // 'distribute parallel for')
1688 EmitIgnoredExpr(LoopArgs.EUB);
1690 EmitIgnoredExpr(LoopArgs.Init);
1692 BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond);
1695 RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned, LoopArgs.IL,
1696 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST);
1699 // If there are any cleanups between here and the loop-exit scope,
1700 // create a block to stage a loop exit along.
1701 auto ExitBlock = LoopExit.getBlock();
1702 if (LoopScope.requiresCleanups())
1703 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1705 auto LoopBody = createBasicBlock("omp.dispatch.body");
1706 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1707 if (ExitBlock != LoopExit.getBlock()) {
1708 EmitBlock(ExitBlock);
1709 EmitBranchThroughCleanup(LoopExit);
1711 EmitBlock(LoopBody);
1713 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1714 // LB for loop condition and emitted it above).
1715 if (DynamicOrOrdered)
1716 EmitIgnoredExpr(LoopArgs.Init);
1718 // Create a block for the increment.
1719 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1720 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1722 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1723 // with dynamic/guided scheduling and without ordered clause.
1724 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1725 LoopStack.setParallel(!IsMonotonic);
1727 EmitOMPSimdInit(S, IsMonotonic);
1729 SourceLocation Loc = S.getLocStart();
1731 // when 'distribute' is not combined with a 'for':
1732 // while (idx <= UB) { BODY; ++idx; }
1733 // when 'distribute' is combined with a 'for'
1734 // (e.g. 'distribute parallel for')
1735 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
1737 S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr,
1738 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
1739 CodeGenLoop(CGF, S, LoopExit);
1741 [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) {
1742 CodeGenOrdered(CGF, Loc, IVSize, IVSigned);
1745 EmitBlock(Continue.getBlock());
1746 BreakContinueStack.pop_back();
1747 if (!DynamicOrOrdered) {
1748 // Emit "LB = LB + Stride", "UB = UB + Stride".
1749 EmitIgnoredExpr(LoopArgs.NextLB);
1750 EmitIgnoredExpr(LoopArgs.NextUB);
1753 EmitBranch(CondBlock);
1755 // Emit the fall-through block.
1756 EmitBlock(LoopExit.getBlock());
1758 // Tell the runtime we are done.
1759 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
1760 if (!DynamicOrOrdered)
1761 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
1762 S.getDirectiveKind());
1764 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
1767 void CodeGenFunction::EmitOMPForOuterLoop(
1768 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
1769 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
1770 const OMPLoopArguments &LoopArgs,
1771 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
1772 auto &RT = CGM.getOpenMPRuntime();
1774 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
1775 const bool DynamicOrOrdered =
1776 Ordered || RT.isDynamic(ScheduleKind.Schedule);
1779 !RT.isStaticNonchunked(ScheduleKind.Schedule,
1780 LoopArgs.Chunk != nullptr)) &&
1781 "static non-chunked schedule does not need outer loop");
1785 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1786 // When schedule(dynamic,chunk_size) is specified, the iterations are
1787 // distributed to threads in the team in chunks as the threads request them.
1788 // Each thread executes a chunk of iterations, then requests another chunk,
1789 // until no chunks remain to be distributed. Each chunk contains chunk_size
1790 // iterations, except for the last chunk to be distributed, which may have
1791 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1793 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1794 // to threads in the team in chunks as the executing threads request them.
1795 // Each thread executes a chunk of iterations, then requests another chunk,
1796 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1797 // each chunk is proportional to the number of unassigned iterations divided
1798 // by the number of threads in the team, decreasing to 1. For a chunk_size
1799 // with value k (greater than 1), the size of each chunk is determined in the
1800 // same way, with the restriction that the chunks do not contain fewer than k
1801 // iterations (except for the last chunk to be assigned, which may have fewer
1802 // than k iterations).
1804 // When schedule(auto) is specified, the decision regarding scheduling is
1805 // delegated to the compiler and/or runtime system. The programmer gives the
1806 // implementation the freedom to choose any possible mapping of iterations to
1807 // threads in the team.
1809 // When schedule(runtime) is specified, the decision regarding scheduling is
1810 // deferred until run time, and the schedule and chunk size are taken from the
1811 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1812 // implementation defined
1814 // while(__kmpc_dispatch_next(&LB, &UB)) {
1816 // while (idx <= UB) { BODY; ++idx;
1817 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1821 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1822 // When schedule(static, chunk_size) is specified, iterations are divided into
1823 // chunks of size chunk_size, and the chunks are assigned to the threads in
1824 // the team in a round-robin fashion in the order of the thread number.
1826 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1827 // while (idx <= UB) { BODY; ++idx; } // inner loop
1833 const Expr *IVExpr = S.getIterationVariable();
1834 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1835 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1837 if (DynamicOrOrdered) {
1838 auto DispatchBounds = CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB);
1839 llvm::Value *LBVal = DispatchBounds.first;
1840 llvm::Value *UBVal = DispatchBounds.second;
1841 CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal,
1843 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind, IVSize,
1844 IVSigned, Ordered, DipatchRTInputValues);
1846 CGOpenMPRuntime::StaticRTInput StaticInit(
1847 IVSize, IVSigned, Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB,
1848 LoopArgs.ST, LoopArgs.Chunk);
1849 RT.emitForStaticInit(*this, S.getLocStart(), S.getDirectiveKind(),
1850 ScheduleKind, StaticInit);
1853 auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc,
1854 const unsigned IVSize,
1855 const bool IVSigned) {
1857 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize,
1862 OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
1863 LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB);
1864 OuterLoopArgs.IncExpr = S.getInc();
1865 OuterLoopArgs.Init = S.getInit();
1866 OuterLoopArgs.Cond = S.getCond();
1867 OuterLoopArgs.NextLB = S.getNextLowerBound();
1868 OuterLoopArgs.NextUB = S.getNextUpperBound();
1869 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs,
1870 emitOMPLoopBodyWithStopPoint, CodeGenOrdered);
1873 static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc,
1874 const unsigned IVSize, const bool IVSigned) {}
1876 void CodeGenFunction::EmitOMPDistributeOuterLoop(
1877 OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S,
1878 OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs,
1879 const CodeGenLoopTy &CodeGenLoopContent) {
1881 auto &RT = CGM.getOpenMPRuntime();
1884 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
1888 const Expr *IVExpr = S.getIterationVariable();
1889 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1890 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1892 CGOpenMPRuntime::StaticRTInput StaticInit(
1893 IVSize, IVSigned, /* Ordered = */ false, LoopArgs.IL, LoopArgs.LB,
1894 LoopArgs.UB, LoopArgs.ST, LoopArgs.Chunk);
1895 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind, StaticInit);
1897 // for combined 'distribute' and 'for' the increment expression of distribute
1898 // is store in DistInc. For 'distribute' alone, it is in Inc.
1900 if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()))
1901 IncExpr = S.getDistInc();
1903 IncExpr = S.getInc();
1905 // this routine is shared by 'omp distribute parallel for' and
1906 // 'omp distribute': select the right EUB expression depending on the
1908 OMPLoopArguments OuterLoopArgs;
1909 OuterLoopArgs.LB = LoopArgs.LB;
1910 OuterLoopArgs.UB = LoopArgs.UB;
1911 OuterLoopArgs.ST = LoopArgs.ST;
1912 OuterLoopArgs.IL = LoopArgs.IL;
1913 OuterLoopArgs.Chunk = LoopArgs.Chunk;
1914 OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1915 ? S.getCombinedEnsureUpperBound()
1916 : S.getEnsureUpperBound();
1917 OuterLoopArgs.IncExpr = IncExpr;
1918 OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1919 ? S.getCombinedInit()
1921 OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1922 ? S.getCombinedCond()
1924 OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1925 ? S.getCombinedNextLowerBound()
1926 : S.getNextLowerBound();
1927 OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1928 ? S.getCombinedNextUpperBound()
1929 : S.getNextUpperBound();
1931 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S,
1932 LoopScope, OuterLoopArgs, CodeGenLoopContent,
1936 /// Emit a helper variable and return corresponding lvalue.
1937 static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1938 const DeclRefExpr *Helper) {
1939 auto VDecl = cast<VarDecl>(Helper->getDecl());
1940 CGF.EmitVarDecl(*VDecl);
1941 return CGF.EmitLValue(Helper);
1944 static std::pair<LValue, LValue>
1945 emitDistributeParallelForInnerBounds(CodeGenFunction &CGF,
1946 const OMPExecutableDirective &S) {
1947 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
1949 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
1951 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
1953 // When composing 'distribute' with 'for' (e.g. as in 'distribute
1954 // parallel for') we need to use the 'distribute'
1955 // chunk lower and upper bounds rather than the whole loop iteration
1956 // space. These are parameters to the outlined function for 'parallel'
1957 // and we copy the bounds of the previous schedule into the
1958 // the current ones.
1959 LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable());
1960 LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable());
1961 llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar(PrevLB, SourceLocation());
1962 PrevLBVal = CGF.EmitScalarConversion(
1963 PrevLBVal, LS.getPrevLowerBoundVariable()->getType(),
1964 LS.getIterationVariable()->getType(), SourceLocation());
1965 llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar(PrevUB, SourceLocation());
1966 PrevUBVal = CGF.EmitScalarConversion(
1967 PrevUBVal, LS.getPrevUpperBoundVariable()->getType(),
1968 LS.getIterationVariable()->getType(), SourceLocation());
1970 CGF.EmitStoreOfScalar(PrevLBVal, LB);
1971 CGF.EmitStoreOfScalar(PrevUBVal, UB);
1976 /// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then
1977 /// we need to use the LB and UB expressions generated by the worksharing
1978 /// code generation support, whereas in non combined situations we would
1979 /// just emit 0 and the LastIteration expression
1980 /// This function is necessary due to the difference of the LB and UB
1981 /// types for the RT emission routines for 'for_static_init' and
1982 /// 'for_dispatch_init'
1983 static std::pair<llvm::Value *, llvm::Value *>
1984 emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF,
1985 const OMPExecutableDirective &S,
1986 Address LB, Address UB) {
1987 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
1988 const Expr *IVExpr = LS.getIterationVariable();
1989 // when implementing a dynamic schedule for a 'for' combined with a
1990 // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop
1991 // is not normalized as each team only executes its own assigned
1993 QualType IteratorTy = IVExpr->getType();
1994 llvm::Value *LBVal = CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy,
1996 llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy,
1998 return {LBVal, UBVal};
2001 static void emitDistributeParallelForDistributeInnerBoundParams(
2002 CodeGenFunction &CGF, const OMPExecutableDirective &S,
2003 llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) {
2004 const auto &Dir = cast<OMPLoopDirective>(S);
2006 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable()));
2007 auto LBCast = CGF.Builder.CreateIntCast(
2008 CGF.Builder.CreateLoad(LB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2009 CapturedVars.push_back(LBCast);
2011 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable()));
2013 auto UBCast = CGF.Builder.CreateIntCast(
2014 CGF.Builder.CreateLoad(UB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2015 CapturedVars.push_back(UBCast);
2019 emitInnerParallelForWhenCombined(CodeGenFunction &CGF,
2020 const OMPLoopDirective &S,
2021 CodeGenFunction::JumpDest LoopExit) {
2022 auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF,
2023 PrePostActionTy &) {
2024 bool HasCancel = false;
2025 if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
2026 if (const auto *D = dyn_cast<OMPTeamsDistributeParallelForDirective>(&S))
2027 HasCancel = D->hasCancel();
2028 else if (const auto *D = dyn_cast<OMPDistributeParallelForDirective>(&S))
2029 HasCancel = D->hasCancel();
2030 else if (const auto *D =
2031 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&S))
2032 HasCancel = D->hasCancel();
2034 CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, S.getDirectiveKind(),
2036 CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(),
2037 emitDistributeParallelForInnerBounds,
2038 emitDistributeParallelForDispatchBounds);
2041 emitCommonOMPParallelDirective(
2043 isOpenMPSimdDirective(S.getDirectiveKind()) ? OMPD_for_simd : OMPD_for,
2044 CGInlinedWorksharingLoop,
2045 emitDistributeParallelForDistributeInnerBoundParams);
2048 void CodeGenFunction::EmitOMPDistributeParallelForDirective(
2049 const OMPDistributeParallelForDirective &S) {
2050 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2051 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2054 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2055 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
2058 void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
2059 const OMPDistributeParallelForSimdDirective &S) {
2060 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2061 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2064 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2065 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
2068 void CodeGenFunction::EmitOMPDistributeSimdDirective(
2069 const OMPDistributeSimdDirective &S) {
2070 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2071 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
2073 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2074 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2077 void CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
2078 CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S) {
2079 // Emit SPMD target parallel for region as a standalone region.
2080 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2081 emitOMPSimdRegion(CGF, S, Action);
2084 llvm::Constant *Addr;
2085 // Emit target region as a standalone region.
2086 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
2087 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
2088 assert(Fn && Addr && "Target device function emission failed.");
2091 void CodeGenFunction::EmitOMPTargetSimdDirective(
2092 const OMPTargetSimdDirective &S) {
2093 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2094 emitOMPSimdRegion(CGF, S, Action);
2096 emitCommonOMPTargetDirective(*this, S, CodeGen);
2099 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
2100 const OMPTargetTeamsDistributeParallelForDirective &S) {
2101 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2102 CGM.getOpenMPRuntime().emitInlinedDirective(
2103 *this, OMPD_target_teams_distribute_parallel_for,
2104 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2106 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2110 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
2111 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
2112 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2113 CGM.getOpenMPRuntime().emitInlinedDirective(
2114 *this, OMPD_target_teams_distribute_parallel_for_simd,
2115 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2117 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2122 struct ScheduleKindModifiersTy {
2123 OpenMPScheduleClauseKind Kind;
2124 OpenMPScheduleClauseModifier M1;
2125 OpenMPScheduleClauseModifier M2;
2126 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
2127 OpenMPScheduleClauseModifier M1,
2128 OpenMPScheduleClauseModifier M2)
2129 : Kind(Kind), M1(M1), M2(M2) {}
2133 bool CodeGenFunction::EmitOMPWorksharingLoop(
2134 const OMPLoopDirective &S, Expr *EUB,
2135 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
2136 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
2137 // Emit the loop iteration variable.
2138 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2139 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2140 EmitVarDecl(*IVDecl);
2142 // Emit the iterations count variable.
2143 // If it is not a variable, Sema decided to calculate iterations count on each
2144 // iteration (e.g., it is foldable into a constant).
2145 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2146 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2147 // Emit calculation of the iterations count.
2148 EmitIgnoredExpr(S.getCalcLastIteration());
2151 auto &RT = CGM.getOpenMPRuntime();
2153 bool HasLastprivateClause;
2154 // Check pre-condition.
2156 OMPLoopScope PreInitScope(*this, S);
2157 // Skip the entire loop if we don't meet the precondition.
2158 // If the condition constant folds and can be elided, avoid emitting the
2161 llvm::BasicBlock *ContBlock = nullptr;
2162 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2166 auto *ThenBlock = createBasicBlock("omp.precond.then");
2167 ContBlock = createBasicBlock("omp.precond.end");
2168 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
2169 getProfileCount(&S));
2170 EmitBlock(ThenBlock);
2171 incrementProfileCounter(&S);
2174 bool Ordered = false;
2175 if (auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
2176 if (OrderedClause->getNumForLoops())
2177 RT.emitDoacrossInit(*this, S);
2182 llvm::DenseSet<const Expr *> EmittedFinals;
2183 emitAlignedClause(*this, S);
2184 bool HasLinears = EmitOMPLinearClauseInit(S);
2185 // Emit helper vars inits.
2187 std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S);
2188 LValue LB = Bounds.first;
2189 LValue UB = Bounds.second;
2191 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2193 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2195 // Emit 'then' code.
2197 OMPPrivateScope LoopScope(*this);
2198 if (EmitOMPFirstprivateClause(S, LoopScope) || HasLinears) {
2199 // Emit implicit barrier to synchronize threads and avoid data races on
2200 // initialization of firstprivate variables and post-update of
2201 // lastprivate variables.
2202 CGM.getOpenMPRuntime().emitBarrierCall(
2203 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2204 /*ForceSimpleCall=*/true);
2206 EmitOMPPrivateClause(S, LoopScope);
2207 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
2208 EmitOMPReductionClauseInit(S, LoopScope);
2209 EmitOMPPrivateLoopCounters(S, LoopScope);
2210 EmitOMPLinearClause(S, LoopScope);
2211 (void)LoopScope.Privatize();
2213 // Detect the loop schedule kind and chunk.
2214 llvm::Value *Chunk = nullptr;
2215 OpenMPScheduleTy ScheduleKind;
2216 if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
2217 ScheduleKind.Schedule = C->getScheduleKind();
2218 ScheduleKind.M1 = C->getFirstScheduleModifier();
2219 ScheduleKind.M2 = C->getSecondScheduleModifier();
2220 if (const auto *Ch = C->getChunkSize()) {
2221 Chunk = EmitScalarExpr(Ch);
2222 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
2223 S.getIterationVariable()->getType(),
2227 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2228 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2229 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
2230 // If the static schedule kind is specified or if the ordered clause is
2231 // specified, and if no monotonic modifier is specified, the effect will
2232 // be as if the monotonic modifier was specified.
2233 if (RT.isStaticNonchunked(ScheduleKind.Schedule,
2234 /* Chunked */ Chunk != nullptr) &&
2236 if (isOpenMPSimdDirective(S.getDirectiveKind()))
2237 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
2238 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2239 // When no chunk_size is specified, the iteration space is divided into
2240 // chunks that are approximately equal in size, and at most one chunk is
2241 // distributed to each thread. Note that the size of the chunks is
2242 // unspecified in this case.
2243 CGOpenMPRuntime::StaticRTInput StaticInit(
2244 IVSize, IVSigned, Ordered, IL.getAddress(), LB.getAddress(),
2245 UB.getAddress(), ST.getAddress());
2246 RT.emitForStaticInit(*this, S.getLocStart(), S.getDirectiveKind(),
2247 ScheduleKind, StaticInit);
2249 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
2250 // UB = min(UB, GlobalUB);
2251 EmitIgnoredExpr(S.getEnsureUpperBound());
2253 EmitIgnoredExpr(S.getInit());
2254 // while (idx <= UB) { BODY; ++idx; }
2255 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
2257 [&S, LoopExit](CodeGenFunction &CGF) {
2258 CGF.EmitOMPLoopBody(S, LoopExit);
2259 CGF.EmitStopPoint(&S);
2261 [](CodeGenFunction &) {});
2262 EmitBlock(LoopExit.getBlock());
2263 // Tell the runtime we are done.
2264 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2265 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
2266 S.getDirectiveKind());
2268 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
2270 const bool IsMonotonic =
2271 Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static ||
2272 ScheduleKind.Schedule == OMPC_SCHEDULE_unknown ||
2273 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
2274 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
2275 // Emit the outer loop, which requests its work chunk [LB..UB] from
2276 // runtime and runs the inner loop to process it.
2277 const OMPLoopArguments LoopArguments(LB.getAddress(), UB.getAddress(),
2278 ST.getAddress(), IL.getAddress(),
2280 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
2281 LoopArguments, CGDispatchBounds);
2283 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
2285 [&](CodeGenFunction &CGF) -> llvm::Value * {
2286 return CGF.Builder.CreateIsNotNull(
2287 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2290 EmitOMPReductionClauseFinal(
2291 S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind())
2292 ? /*Parallel and Simd*/ OMPD_parallel_for_simd
2293 : /*Parallel only*/ OMPD_parallel);
2294 // Emit post-update of the reduction variables if IsLastIter != 0.
2295 emitPostUpdateForReductionClause(
2296 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2297 return CGF.Builder.CreateIsNotNull(
2298 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2300 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2301 if (HasLastprivateClause)
2302 EmitOMPLastprivateClauseFinal(
2303 S, isOpenMPSimdDirective(S.getDirectiveKind()),
2304 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
2306 EmitOMPLinearClauseFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2307 return CGF.Builder.CreateIsNotNull(
2308 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2310 // We're now done with the loop, so jump to the continuation block.
2312 EmitBranch(ContBlock);
2313 EmitBlock(ContBlock, true);
2316 return HasLastprivateClause;
2319 /// The following two functions generate expressions for the loop lower
2320 /// and upper bounds in case of static and dynamic (dispatch) schedule
2321 /// of the associated 'for' or 'distribute' loop.
2322 static std::pair<LValue, LValue>
2323 emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
2324 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2326 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2328 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2332 /// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
2333 /// consider the lower and upper bound expressions generated by the
2334 /// worksharing loop support, but we use 0 and the iteration space size as
2336 static std::pair<llvm::Value *, llvm::Value *>
2337 emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S,
2338 Address LB, Address UB) {
2339 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2340 const Expr *IVExpr = LS.getIterationVariable();
2341 const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
2342 llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
2343 llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
2344 return {LBVal, UBVal};
2347 void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
2348 bool HasLastprivates = false;
2349 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2350 PrePostActionTy &) {
2351 OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
2352 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2354 emitDispatchForLoopBounds);
2357 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2358 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2362 // Emit an implicit barrier at the end.
2363 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
2364 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2368 void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
2369 bool HasLastprivates = false;
2370 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2371 PrePostActionTy &) {
2372 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2374 emitDispatchForLoopBounds);
2377 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2378 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2381 // Emit an implicit barrier at the end.
2382 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
2383 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2387 static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2389 llvm::Value *Init = nullptr) {
2390 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
2392 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
2396 void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
2397 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
2398 auto *CS = dyn_cast<CompoundStmt>(Stmt);
2399 bool HasLastprivates = false;
2400 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF,
2401 PrePostActionTy &) {
2402 auto &C = CGF.CGM.getContext();
2403 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2404 // Emit helper vars inits.
2405 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2406 CGF.Builder.getInt32(0));
2407 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
2408 : CGF.Builder.getInt32(0);
2410 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2411 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2412 CGF.Builder.getInt32(1));
2413 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2414 CGF.Builder.getInt32(0));
2416 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
2417 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2418 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
2419 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2420 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2421 // Generate condition for loop.
2422 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
2423 OK_Ordinary, S.getLocStart(), FPOptions());
2424 // Increment for loop counter.
2425 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
2427 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
2428 // Iterate through all sections and emit a switch construct:
2431 // <SectionStmt[0]>;
2434 // case <NumSection> - 1:
2435 // <SectionStmt[<NumSection> - 1]>;
2438 // .omp.sections.exit:
2439 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
2440 auto *SwitchStmt = CGF.Builder.CreateSwitch(
2441 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
2442 CS == nullptr ? 1 : CS->size());
2444 unsigned CaseNumber = 0;
2445 for (auto *SubStmt : CS->children()) {
2446 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2447 CGF.EmitBlock(CaseBB);
2448 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
2449 CGF.EmitStmt(SubStmt);
2450 CGF.EmitBranch(ExitBB);
2454 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2455 CGF.EmitBlock(CaseBB);
2456 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
2458 CGF.EmitBranch(ExitBB);
2460 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2463 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2464 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
2465 // Emit implicit barrier to synchronize threads and avoid data races on
2466 // initialization of firstprivate variables and post-update of lastprivate
2468 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
2469 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2470 /*ForceSimpleCall=*/true);
2472 CGF.EmitOMPPrivateClause(S, LoopScope);
2473 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2474 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2475 (void)LoopScope.Privatize();
2477 // Emit static non-chunked loop.
2478 OpenMPScheduleTy ScheduleKind;
2479 ScheduleKind.Schedule = OMPC_SCHEDULE_static;
2480 CGOpenMPRuntime::StaticRTInput StaticInit(
2481 /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
2482 LB.getAddress(), UB.getAddress(), ST.getAddress());
2483 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
2484 CGF, S.getLocStart(), S.getDirectiveKind(), ScheduleKind, StaticInit);
2485 // UB = min(UB, GlobalUB);
2486 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
2487 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
2488 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2489 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2491 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
2492 // while (idx <= UB) { BODY; ++idx; }
2493 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2494 [](CodeGenFunction &) {});
2495 // Tell the runtime we are done.
2496 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2497 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
2498 S.getDirectiveKind());
2500 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
2501 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
2502 // Emit post-update of the reduction variables if IsLastIter != 0.
2503 emitPostUpdateForReductionClause(
2504 CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2505 return CGF.Builder.CreateIsNotNull(
2506 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2509 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2510 if (HasLastprivates)
2511 CGF.EmitOMPLastprivateClauseFinal(
2512 S, /*NoFinals=*/false,
2513 CGF.Builder.CreateIsNotNull(
2514 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
2517 bool HasCancel = false;
2518 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2519 HasCancel = OSD->hasCancel();
2520 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2521 HasCancel = OPSD->hasCancel();
2522 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
2523 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2525 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2526 // clause. Otherwise the barrier will be generated by the codegen for the
2528 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
2529 // Emit implicit barrier to synchronize threads and avoid data races on
2530 // initialization of firstprivate variables.
2531 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2536 void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
2538 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2541 // Emit an implicit barrier at the end.
2542 if (!S.getSingleClause<OMPNowaitClause>()) {
2543 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2548 void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
2549 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2550 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2552 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2553 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2557 void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
2558 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
2559 llvm::SmallVector<const Expr *, 8> DestExprs;
2560 llvm::SmallVector<const Expr *, 8> SrcExprs;
2561 llvm::SmallVector<const Expr *, 8> AssignmentOps;
2562 // Check if there are any 'copyprivate' clauses associated with this
2563 // 'single' construct.
2564 // Build a list of copyprivate variables along with helper expressions
2565 // (<source>, <destination>, <destination>=<source> expressions)
2566 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
2567 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
2568 DestExprs.append(C->destination_exprs().begin(),
2569 C->destination_exprs().end());
2570 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
2571 AssignmentOps.append(C->assignment_ops().begin(),
2572 C->assignment_ops().end());
2574 // Emit code for 'single' region along with 'copyprivate' clauses
2575 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2577 OMPPrivateScope SingleScope(CGF);
2578 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2579 CGF.EmitOMPPrivateClause(S, SingleScope);
2580 (void)SingleScope.Privatize();
2581 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2584 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2585 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
2586 CopyprivateVars, DestExprs,
2587 SrcExprs, AssignmentOps);
2589 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2590 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
2591 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
2592 CGM.getOpenMPRuntime().emitBarrierCall(
2593 *this, S.getLocStart(),
2594 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
2598 void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
2599 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2601 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2603 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2604 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
2607 void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
2608 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2610 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2612 Expr *Hint = nullptr;
2613 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
2614 Hint = HintClause->getHint();
2615 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2616 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2617 S.getDirectiveName().getAsString(),
2618 CodeGen, S.getLocStart(), Hint);
2621 void CodeGenFunction::EmitOMPParallelForDirective(
2622 const OMPParallelForDirective &S) {
2623 // Emit directive as a combined directive that consists of two implicit
2624 // directives: 'parallel' with 'for' directive.
2625 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2626 OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
2627 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2628 emitDispatchForLoopBounds);
2630 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
2631 emitEmptyBoundParameters);
2634 void CodeGenFunction::EmitOMPParallelForSimdDirective(
2635 const OMPParallelForSimdDirective &S) {
2636 // Emit directive as a combined directive that consists of two implicit
2637 // directives: 'parallel' with 'for' directive.
2638 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2639 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2640 emitDispatchForLoopBounds);
2642 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen,
2643 emitEmptyBoundParameters);
2646 void CodeGenFunction::EmitOMPParallelSectionsDirective(
2647 const OMPParallelSectionsDirective &S) {
2648 // Emit directive as a combined directive that consists of two implicit
2649 // directives: 'parallel' with 'sections' directive.
2650 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2651 CGF.EmitSections(S);
2653 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
2654 emitEmptyBoundParameters);
2657 void CodeGenFunction::EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
2658 const RegionCodeGenTy &BodyGen,
2659 const TaskGenTy &TaskGen,
2660 OMPTaskDataTy &Data) {
2661 // Emit outlined function for task construct.
2662 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2663 auto *I = CS->getCapturedDecl()->param_begin();
2664 auto *PartId = std::next(I);
2665 auto *TaskT = std::next(I, 4);
2666 // Check if the task is final
2667 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
2668 // If the condition constant folds and can be elided, try to avoid emitting
2669 // the condition and the dead arm of the if/else.
2670 auto *Cond = Clause->getCondition();
2672 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2673 Data.Final.setInt(CondConstant);
2675 Data.Final.setPointer(EvaluateExprAsBool(Cond));
2677 // By default the task is not final.
2678 Data.Final.setInt(/*IntVal=*/false);
2680 // Check if the task has 'priority' clause.
2681 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
2682 auto *Prio = Clause->getPriority();
2683 Data.Priority.setInt(/*IntVal=*/true);
2684 Data.Priority.setPointer(EmitScalarConversion(
2685 EmitScalarExpr(Prio), Prio->getType(),
2686 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2687 Prio->getExprLoc()));
2689 // The first function argument for tasks is a thread id, the second one is a
2690 // part id (0 for tied tasks, >=0 for untied task).
2691 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2692 // Get list of private variables.
2693 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
2694 auto IRef = C->varlist_begin();
2695 for (auto *IInit : C->private_copies()) {
2696 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2697 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2698 Data.PrivateVars.push_back(*IRef);
2699 Data.PrivateCopies.push_back(IInit);
2704 EmittedAsPrivate.clear();
2705 // Get list of firstprivate variables.
2706 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
2707 auto IRef = C->varlist_begin();
2708 auto IElemInitRef = C->inits().begin();
2709 for (auto *IInit : C->private_copies()) {
2710 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2711 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2712 Data.FirstprivateVars.push_back(*IRef);
2713 Data.FirstprivateCopies.push_back(IInit);
2714 Data.FirstprivateInits.push_back(*IElemInitRef);
2720 // Get list of lastprivate variables (for taskloops).
2721 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
2722 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
2723 auto IRef = C->varlist_begin();
2724 auto ID = C->destination_exprs().begin();
2725 for (auto *IInit : C->private_copies()) {
2726 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2727 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2728 Data.LastprivateVars.push_back(*IRef);
2729 Data.LastprivateCopies.push_back(IInit);
2731 LastprivateDstsOrigs.insert(
2732 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
2733 cast<DeclRefExpr>(*IRef)});
2738 SmallVector<const Expr *, 4> LHSs;
2739 SmallVector<const Expr *, 4> RHSs;
2740 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
2741 auto IPriv = C->privates().begin();
2742 auto IRed = C->reduction_ops().begin();
2743 auto ILHS = C->lhs_exprs().begin();
2744 auto IRHS = C->rhs_exprs().begin();
2745 for (const auto *Ref : C->varlists()) {
2746 Data.ReductionVars.emplace_back(Ref);
2747 Data.ReductionCopies.emplace_back(*IPriv);
2748 Data.ReductionOps.emplace_back(*IRed);
2749 LHSs.emplace_back(*ILHS);
2750 RHSs.emplace_back(*IRHS);
2751 std::advance(IPriv, 1);
2752 std::advance(IRed, 1);
2753 std::advance(ILHS, 1);
2754 std::advance(IRHS, 1);
2757 Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit(
2758 *this, S.getLocStart(), LHSs, RHSs, Data);
2759 // Build list of dependences.
2760 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
2761 for (auto *IRef : C->varlists())
2762 Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
2763 auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs](
2764 CodeGenFunction &CGF, PrePostActionTy &Action) {
2765 // Set proper addresses for generated private copies.
2766 OMPPrivateScope Scope(CGF);
2767 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
2768 !Data.LastprivateVars.empty()) {
2769 enum { PrivatesParam = 2, CopyFnParam = 3 };
2770 auto *CopyFn = CGF.Builder.CreateLoad(
2771 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2772 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2773 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
2775 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
2776 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2777 CallArgs.push_back(PrivatesPtr);
2778 for (auto *E : Data.PrivateVars) {
2779 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2780 Address PrivatePtr = CGF.CreateMemTemp(
2781 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
2782 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2783 CallArgs.push_back(PrivatePtr.getPointer());
2785 for (auto *E : Data.FirstprivateVars) {
2786 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2787 Address PrivatePtr =
2788 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2789 ".firstpriv.ptr.addr");
2790 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2791 CallArgs.push_back(PrivatePtr.getPointer());
2793 for (auto *E : Data.LastprivateVars) {
2794 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2795 Address PrivatePtr =
2796 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2797 ".lastpriv.ptr.addr");
2798 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2799 CallArgs.push_back(PrivatePtr.getPointer());
2801 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
2803 for (auto &&Pair : LastprivateDstsOrigs) {
2804 auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
2806 const_cast<VarDecl *>(OrigVD),
2807 /*RefersToEnclosingVariableOrCapture=*/CGF.CapturedStmtInfo->lookup(
2809 Pair.second->getType(), VK_LValue, Pair.second->getExprLoc());
2810 Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
2811 return CGF.EmitLValue(&DRE).getAddress();
2814 for (auto &&Pair : PrivatePtrs) {
2815 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2816 CGF.getContext().getDeclAlign(Pair.first));
2817 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2820 if (Data.Reductions) {
2821 OMPLexicalScope LexScope(CGF, S, /*AsInlined=*/true);
2822 ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionCopies,
2824 llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
2825 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9)));
2826 for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
2827 RedCG.emitSharedLValue(CGF, Cnt);
2828 RedCG.emitAggregateType(CGF, Cnt);
2829 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2830 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2832 Address(CGF.EmitScalarConversion(
2833 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2834 CGF.getContext().getPointerType(
2835 Data.ReductionCopies[Cnt]->getType()),
2837 Replacement.getAlignment());
2838 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2839 Scope.addPrivate(RedCG.getBaseDecl(Cnt),
2840 [Replacement]() { return Replacement; });
2841 // FIXME: This must removed once the runtime library is fixed.
2842 // Emit required threadprivate variables for
2843 // initilizer/combiner/finalizer.
2844 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2848 // Privatize all private variables except for in_reduction items.
2849 (void)Scope.Privatize();
2850 SmallVector<const Expr *, 4> InRedVars;
2851 SmallVector<const Expr *, 4> InRedPrivs;
2852 SmallVector<const Expr *, 4> InRedOps;
2853 SmallVector<const Expr *, 4> TaskgroupDescriptors;
2854 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
2855 auto IPriv = C->privates().begin();
2856 auto IRed = C->reduction_ops().begin();
2857 auto ITD = C->taskgroup_descriptors().begin();
2858 for (const auto *Ref : C->varlists()) {
2859 InRedVars.emplace_back(Ref);
2860 InRedPrivs.emplace_back(*IPriv);
2861 InRedOps.emplace_back(*IRed);
2862 TaskgroupDescriptors.emplace_back(*ITD);
2863 std::advance(IPriv, 1);
2864 std::advance(IRed, 1);
2865 std::advance(ITD, 1);
2868 // Privatize in_reduction items here, because taskgroup descriptors must be
2869 // privatized earlier.
2870 OMPPrivateScope InRedScope(CGF);
2871 if (!InRedVars.empty()) {
2872 ReductionCodeGen RedCG(InRedVars, InRedPrivs, InRedOps);
2873 for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
2874 RedCG.emitSharedLValue(CGF, Cnt);
2875 RedCG.emitAggregateType(CGF, Cnt);
2876 // The taskgroup descriptor variable is always implicit firstprivate and
2877 // privatized already during procoessing of the firstprivates.
2878 llvm::Value *ReductionsPtr = CGF.EmitLoadOfScalar(
2879 CGF.EmitLValue(TaskgroupDescriptors[Cnt]), SourceLocation());
2880 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2881 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2882 Replacement = Address(
2883 CGF.EmitScalarConversion(
2884 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2885 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
2887 Replacement.getAlignment());
2888 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2889 InRedScope.addPrivate(RedCG.getBaseDecl(Cnt),
2890 [Replacement]() { return Replacement; });
2891 // FIXME: This must removed once the runtime library is fixed.
2892 // Emit required threadprivate variables for
2893 // initilizer/combiner/finalizer.
2894 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2898 (void)InRedScope.Privatize();
2903 auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2904 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
2905 Data.NumberOfParts);
2906 OMPLexicalScope Scope(*this, S);
2907 TaskGen(*this, OutlinedFn, Data);
2910 void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
2911 // Emit outlined function for task construct.
2912 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2913 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
2914 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
2915 const Expr *IfCond = nullptr;
2916 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2917 if (C->getNameModifier() == OMPD_unknown ||
2918 C->getNameModifier() == OMPD_task) {
2919 IfCond = C->getCondition();
2925 // Check if we should emit tied or untied task.
2926 Data.Tied = !S.getSingleClause<OMPUntiedClause>();
2927 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
2928 CGF.EmitStmt(CS->getCapturedStmt());
2930 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
2931 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
2932 const OMPTaskDataTy &Data) {
2933 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getLocStart(), S, OutlinedFn,
2934 SharedsTy, CapturedStruct, IfCond,
2937 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
2940 void CodeGenFunction::EmitOMPTaskyieldDirective(
2941 const OMPTaskyieldDirective &S) {
2942 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
2945 void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
2946 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
2949 void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
2950 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
2953 void CodeGenFunction::EmitOMPTaskgroupDirective(
2954 const OMPTaskgroupDirective &S) {
2955 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2957 if (const Expr *E = S.getReductionRef()) {
2958 SmallVector<const Expr *, 4> LHSs;
2959 SmallVector<const Expr *, 4> RHSs;
2961 for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) {
2962 auto IPriv = C->privates().begin();
2963 auto IRed = C->reduction_ops().begin();
2964 auto ILHS = C->lhs_exprs().begin();
2965 auto IRHS = C->rhs_exprs().begin();
2966 for (const auto *Ref : C->varlists()) {
2967 Data.ReductionVars.emplace_back(Ref);
2968 Data.ReductionCopies.emplace_back(*IPriv);
2969 Data.ReductionOps.emplace_back(*IRed);
2970 LHSs.emplace_back(*ILHS);
2971 RHSs.emplace_back(*IRHS);
2972 std::advance(IPriv, 1);
2973 std::advance(IRed, 1);
2974 std::advance(ILHS, 1);
2975 std::advance(IRHS, 1);
2978 llvm::Value *ReductionDesc =
2979 CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getLocStart(),
2981 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2982 CGF.EmitVarDecl(*VD);
2983 CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD),
2984 /*Volatile=*/false, E->getType());
2986 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2988 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2989 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
2992 void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
2993 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
2994 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
2995 return llvm::makeArrayRef(FlushClause->varlist_begin(),
2996 FlushClause->varlist_end());
2999 }(), S.getLocStart());
3002 void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S,
3003 const CodeGenLoopTy &CodeGenLoop,
3005 // Emit the loop iteration variable.
3006 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
3007 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
3008 EmitVarDecl(*IVDecl);
3010 // Emit the iterations count variable.
3011 // If it is not a variable, Sema decided to calculate iterations count on each
3012 // iteration (e.g., it is foldable into a constant).
3013 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
3014 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3015 // Emit calculation of the iterations count.
3016 EmitIgnoredExpr(S.getCalcLastIteration());
3019 auto &RT = CGM.getOpenMPRuntime();
3021 bool HasLastprivateClause = false;
3022 // Check pre-condition.
3024 OMPLoopScope PreInitScope(*this, S);
3025 // Skip the entire loop if we don't meet the precondition.
3026 // If the condition constant folds and can be elided, avoid emitting the
3029 llvm::BasicBlock *ContBlock = nullptr;
3030 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3034 auto *ThenBlock = createBasicBlock("omp.precond.then");
3035 ContBlock = createBasicBlock("omp.precond.end");
3036 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
3037 getProfileCount(&S));
3038 EmitBlock(ThenBlock);
3039 incrementProfileCounter(&S);
3042 emitAlignedClause(*this, S);
3043 // Emit 'then' code.
3045 // Emit helper vars inits.
3047 LValue LB = EmitOMPHelperVar(
3048 *this, cast<DeclRefExpr>(
3049 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3050 ? S.getCombinedLowerBoundVariable()
3051 : S.getLowerBoundVariable())));
3052 LValue UB = EmitOMPHelperVar(
3053 *this, cast<DeclRefExpr>(
3054 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3055 ? S.getCombinedUpperBoundVariable()
3056 : S.getUpperBoundVariable())));
3058 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
3060 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
3062 OMPPrivateScope LoopScope(*this);
3063 if (EmitOMPFirstprivateClause(S, LoopScope)) {
3064 // Emit implicit barrier to synchronize threads and avoid data races
3065 // on initialization of firstprivate variables and post-update of
3066 // lastprivate variables.
3067 CGM.getOpenMPRuntime().emitBarrierCall(
3068 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
3069 /*ForceSimpleCall=*/true);
3071 EmitOMPPrivateClause(S, LoopScope);
3072 if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
3073 !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3074 !isOpenMPTeamsDirective(S.getDirectiveKind()))
3075 EmitOMPReductionClauseInit(S, LoopScope);
3076 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
3077 EmitOMPPrivateLoopCounters(S, LoopScope);
3078 (void)LoopScope.Privatize();
3080 // Detect the distribute schedule kind and chunk.
3081 llvm::Value *Chunk = nullptr;
3082 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
3083 if (auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
3084 ScheduleKind = C->getDistScheduleKind();
3085 if (const auto *Ch = C->getChunkSize()) {
3086 Chunk = EmitScalarExpr(Ch);
3087 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
3088 S.getIterationVariable()->getType(),
3092 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3093 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3095 // OpenMP [2.10.8, distribute Construct, Description]
3096 // If dist_schedule is specified, kind must be static. If specified,
3097 // iterations are divided into chunks of size chunk_size, chunks are
3098 // assigned to the teams of the league in a round-robin fashion in the
3099 // order of the team number. When no chunk_size is specified, the
3100 // iteration space is divided into chunks that are approximately equal
3101 // in size, and at most one chunk is distributed to each team of the
3102 // league. The size of the chunks is unspecified in this case.
3103 if (RT.isStaticNonchunked(ScheduleKind,
3104 /* Chunked */ Chunk != nullptr)) {
3105 if (isOpenMPSimdDirective(S.getDirectiveKind()))
3106 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
3107 CGOpenMPRuntime::StaticRTInput StaticInit(
3108 IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(),
3109 LB.getAddress(), UB.getAddress(), ST.getAddress());
3110 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
3113 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
3114 // UB = min(UB, GlobalUB);
3115 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3116 ? S.getCombinedEnsureUpperBound()
3117 : S.getEnsureUpperBound());
3119 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3120 ? S.getCombinedInit()
3123 Expr *Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3124 ? S.getCombinedCond()
3127 // for distribute alone, codegen
3128 // while (idx <= UB) { BODY; ++idx; }
3129 // when combined with 'for' (e.g. as in 'distribute parallel for')
3130 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
3131 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), Cond, IncExpr,
3132 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
3133 CodeGenLoop(CGF, S, LoopExit);
3135 [](CodeGenFunction &) {});
3136 EmitBlock(LoopExit.getBlock());
3137 // Tell the runtime we are done.
3138 RT.emitForStaticFinish(*this, S.getLocStart(), S.getDirectiveKind());
3140 // Emit the outer loop, which requests its work chunk [LB..UB] from
3141 // runtime and runs the inner loop to process it.
3142 const OMPLoopArguments LoopArguments = {
3143 LB.getAddress(), UB.getAddress(), ST.getAddress(), IL.getAddress(),
3145 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
3148 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
3149 EmitOMPSimdFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
3150 return CGF.Builder.CreateIsNotNull(
3151 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
3154 OpenMPDirectiveKind ReductionKind = OMPD_unknown;
3155 if (isOpenMPParallelDirective(S.getDirectiveKind()) &&
3156 isOpenMPSimdDirective(S.getDirectiveKind())) {
3157 ReductionKind = OMPD_parallel_for_simd;
3158 } else if (isOpenMPParallelDirective(S.getDirectiveKind())) {
3159 ReductionKind = OMPD_parallel_for;
3160 } else if (isOpenMPSimdDirective(S.getDirectiveKind())) {
3161 ReductionKind = OMPD_simd;
3162 } else if (!isOpenMPTeamsDirective(S.getDirectiveKind()) &&
3163 S.hasClausesOfKind<OMPReductionClause>()) {
3165 "No reduction clauses is allowed in distribute directive.");
3167 EmitOMPReductionClauseFinal(S, ReductionKind);
3168 // Emit post-update of the reduction variables if IsLastIter != 0.
3169 emitPostUpdateForReductionClause(
3170 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
3171 return CGF.Builder.CreateIsNotNull(
3172 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
3174 // Emit final copy of the lastprivate variables if IsLastIter != 0.
3175 if (HasLastprivateClause) {
3176 EmitOMPLastprivateClauseFinal(
3177 S, /*NoFinals=*/false,
3178 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
3182 // We're now done with the loop, so jump to the continuation block.
3184 EmitBranch(ContBlock);
3185 EmitBlock(ContBlock, true);
3190 void CodeGenFunction::EmitOMPDistributeDirective(
3191 const OMPDistributeDirective &S) {
3192 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3194 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
3196 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
3197 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
3200 static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
3201 const CapturedStmt *S) {
3202 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3203 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
3204 CGF.CapturedStmtInfo = &CapStmtInfo;
3205 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
3206 Fn->addFnAttr(llvm::Attribute::NoInline);
3210 void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
3211 if (!S.getAssociatedStmt()) {
3212 for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
3213 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
3216 auto *C = S.getSingleClause<OMPSIMDClause>();
3217 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
3218 PrePostActionTy &Action) {
3220 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
3221 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3222 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
3223 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
3224 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
3225 OutlinedFn, CapturedVars);
3229 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3232 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
3233 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
3236 static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
3237 QualType SrcType, QualType DestType,
3238 SourceLocation Loc) {
3239 assert(CGF.hasScalarEvaluationKind(DestType) &&
3240 "DestType must have scalar evaluation kind.");
3241 assert(!Val.isAggregate() && "Must be a scalar or complex.");
3242 return Val.isScalar()
3243 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
3245 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
3249 static CodeGenFunction::ComplexPairTy
3250 convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
3251 QualType DestType, SourceLocation Loc) {
3252 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
3253 "DestType must have complex evaluation kind.");
3254 CodeGenFunction::ComplexPairTy ComplexVal;
3255 if (Val.isScalar()) {
3256 // Convert the input element to the element type of the complex.
3257 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
3258 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
3259 DestElementType, Loc);
3260 ComplexVal = CodeGenFunction::ComplexPairTy(
3261 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
3263 assert(Val.isComplex() && "Must be a scalar or complex.");
3264 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
3265 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
3266 ComplexVal.first = CGF.EmitScalarConversion(
3267 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
3268 ComplexVal.second = CGF.EmitScalarConversion(
3269 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
3274 static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
3275 LValue LVal, RValue RVal) {
3276 if (LVal.isGlobalReg()) {
3277 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
3279 CGF.EmitAtomicStore(RVal, LVal,
3280 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3281 : llvm::AtomicOrdering::Monotonic,
3282 LVal.isVolatile(), /*IsInit=*/false);
3286 void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
3287 QualType RValTy, SourceLocation Loc) {
3288 switch (getEvaluationKind(LVal.getType())) {
3290 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
3291 *this, RVal, RValTy, LVal.getType(), Loc)),
3296 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
3300 llvm_unreachable("Must be a scalar or complex.");
3304 static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
3305 const Expr *X, const Expr *V,
3306 SourceLocation Loc) {
3308 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
3309 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
3310 LValue XLValue = CGF.EmitLValue(X);
3311 LValue VLValue = CGF.EmitLValue(V);
3312 RValue Res = XLValue.isGlobalReg()
3313 ? CGF.EmitLoadOfLValue(XLValue, Loc)
3314 : CGF.EmitAtomicLoad(
3316 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3317 : llvm::AtomicOrdering::Monotonic,
3318 XLValue.isVolatile());
3319 // OpenMP, 2.12.6, atomic Construct
3320 // Any atomic construct with a seq_cst clause forces the atomically
3321 // performed operation to include an implicit flush operation without a
3324 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3325 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
3328 static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
3329 const Expr *X, const Expr *E,
3330 SourceLocation Loc) {
3332 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
3333 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
3334 // OpenMP, 2.12.6, atomic Construct
3335 // Any atomic construct with a seq_cst clause forces the atomically
3336 // performed operation to include an implicit flush operation without a
3339 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3342 static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
3344 BinaryOperatorKind BO,
3345 llvm::AtomicOrdering AO,
3346 bool IsXLHSInRHSPart) {
3347 auto &Context = CGF.CGM.getContext();
3348 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
3349 // expression is simple and atomic is allowed for the given type for the
3351 if (BO == BO_Comma || !Update.isScalar() ||
3352 !Update.getScalarVal()->getType()->isIntegerTy() ||
3353 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
3354 (Update.getScalarVal()->getType() !=
3355 X.getAddress().getElementType())) ||
3356 !X.getAddress().getElementType()->isIntegerTy() ||
3357 !Context.getTargetInfo().hasBuiltinAtomic(
3358 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
3359 return std::make_pair(false, RValue::get(nullptr));
3361 llvm::AtomicRMWInst::BinOp RMWOp;
3364 RMWOp = llvm::AtomicRMWInst::Add;
3367 if (!IsXLHSInRHSPart)
3368 return std::make_pair(false, RValue::get(nullptr));
3369 RMWOp = llvm::AtomicRMWInst::Sub;
3372 RMWOp = llvm::AtomicRMWInst::And;
3375 RMWOp = llvm::AtomicRMWInst::Or;
3378 RMWOp = llvm::AtomicRMWInst::Xor;
3381 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3382 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
3383 : llvm::AtomicRMWInst::Max)
3384 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
3385 : llvm::AtomicRMWInst::UMax);
3388 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3389 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
3390 : llvm::AtomicRMWInst::Min)
3391 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
3392 : llvm::AtomicRMWInst::UMin);
3395 RMWOp = llvm::AtomicRMWInst::Xchg;
3404 return std::make_pair(false, RValue::get(nullptr));
3423 llvm_unreachable("Unsupported atomic update operation");
3425 auto *UpdateVal = Update.getScalarVal();
3426 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
3427 UpdateVal = CGF.Builder.CreateIntCast(
3428 IC, X.getAddress().getElementType(),
3429 X.getType()->hasSignedIntegerRepresentation());
3431 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
3432 return std::make_pair(true, RValue::get(Res));
3435 std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
3436 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3437 llvm::AtomicOrdering AO, SourceLocation Loc,
3438 const llvm::function_ref<RValue(RValue)> &CommonGen) {
3439 // Update expressions are allowed to have the following forms:
3440 // x binop= expr; -> xrval + expr;
3441 // x++, ++x -> xrval + 1;
3442 // x--, --x -> xrval - 1;
3443 // x = x binop expr; -> xrval binop expr
3444 // x = expr Op x; - > expr binop xrval;
3445 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
3447 if (X.isGlobalReg()) {
3448 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
3450 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
3452 // Perform compare-and-swap procedure.
3453 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
3459 static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
3460 const Expr *X, const Expr *E,
3461 const Expr *UE, bool IsXLHSInRHSPart,
3462 SourceLocation Loc) {
3463 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3464 "Update expr in 'atomic update' must be a binary operator.");
3465 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3466 // Update expressions are allowed to have the following forms:
3467 // x binop= expr; -> xrval + expr;
3468 // x++, ++x -> xrval + 1;
3469 // x--, --x -> xrval - 1;
3470 // x = x binop expr; -> xrval binop expr
3471 // x = expr Op x; - > expr binop xrval;
3472 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
3473 LValue XLValue = CGF.EmitLValue(X);
3474 RValue ExprRValue = CGF.EmitAnyExpr(E);
3475 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3476 : llvm::AtomicOrdering::Monotonic;
3477 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3478 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3479 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3480 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3482 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
3483 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3484 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3485 return CGF.EmitAnyExpr(UE);
3487 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
3488 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3489 // OpenMP, 2.12.6, atomic Construct
3490 // Any atomic construct with a seq_cst clause forces the atomically
3491 // performed operation to include an implicit flush operation without a
3494 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3497 static RValue convertToType(CodeGenFunction &CGF, RValue Value,
3498 QualType SourceType, QualType ResType,
3499 SourceLocation Loc) {
3500 switch (CGF.getEvaluationKind(ResType)) {
3503 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
3505 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
3506 return RValue::getComplex(Res.first, Res.second);
3511 llvm_unreachable("Must be a scalar or complex.");
3514 static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
3515 bool IsPostfixUpdate, const Expr *V,
3516 const Expr *X, const Expr *E,
3517 const Expr *UE, bool IsXLHSInRHSPart,
3518 SourceLocation Loc) {
3519 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
3520 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
3522 LValue VLValue = CGF.EmitLValue(V);
3523 LValue XLValue = CGF.EmitLValue(X);
3524 RValue ExprRValue = CGF.EmitAnyExpr(E);
3525 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3526 : llvm::AtomicOrdering::Monotonic;
3527 QualType NewVValType;
3529 // 'x' is updated with some additional value.
3530 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3531 "Update expr in 'atomic capture' must be a binary operator.");
3532 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3533 // Update expressions are allowed to have the following forms:
3534 // x binop= expr; -> xrval + expr;
3535 // x++, ++x -> xrval + 1;
3536 // x--, --x -> xrval - 1;
3537 // x = x binop expr; -> xrval binop expr
3538 // x = expr Op x; - > expr binop xrval;
3539 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3540 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3541 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3542 NewVValType = XRValExpr->getType();
3543 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3544 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
3545 IsPostfixUpdate](RValue XRValue) -> RValue {
3546 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3547 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3548 RValue Res = CGF.EmitAnyExpr(UE);
3549 NewVVal = IsPostfixUpdate ? XRValue : Res;
3552 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3553 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3555 // 'atomicrmw' instruction was generated.
3556 if (IsPostfixUpdate) {
3557 // Use old value from 'atomicrmw'.
3558 NewVVal = Res.second;
3560 // 'atomicrmw' does not provide new value, so evaluate it using old
3562 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3563 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
3564 NewVVal = CGF.EmitAnyExpr(UE);
3568 // 'x' is simply rewritten with some 'expr'.
3569 NewVValType = X->getType().getNonReferenceType();
3570 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
3571 X->getType().getNonReferenceType(), Loc);
3572 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) -> RValue {
3576 // Try to perform atomicrmw xchg, otherwise simple exchange.
3577 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3578 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
3581 // 'atomicrmw' instruction was generated.
3582 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
3585 // Emit post-update store to 'v' of old/new 'x' value.
3586 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
3587 // OpenMP, 2.12.6, atomic Construct
3588 // Any atomic construct with a seq_cst clause forces the atomically
3589 // performed operation to include an implicit flush operation without a
3592 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3595 static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
3596 bool IsSeqCst, bool IsPostfixUpdate,
3597 const Expr *X, const Expr *V, const Expr *E,
3598 const Expr *UE, bool IsXLHSInRHSPart,
3599 SourceLocation Loc) {
3602 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
3605 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
3609 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
3612 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
3613 IsXLHSInRHSPart, Loc);
3617 case OMPC_num_threads:
3619 case OMPC_firstprivate:
3620 case OMPC_lastprivate:
3621 case OMPC_reduction:
3622 case OMPC_task_reduction:
3623 case OMPC_in_reduction:
3633 case OMPC_copyprivate:
3635 case OMPC_proc_bind:
3640 case OMPC_threadprivate:
3642 case OMPC_mergeable:
3647 case OMPC_num_teams:
3648 case OMPC_thread_limit:
3650 case OMPC_grainsize:
3652 case OMPC_num_tasks:
3654 case OMPC_dist_schedule:
3655 case OMPC_defaultmap:
3659 case OMPC_use_device_ptr:
3660 case OMPC_is_device_ptr:
3661 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
3665 void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
3666 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
3667 OpenMPClauseKind Kind = OMPC_unknown;
3668 for (auto *C : S.clauses()) {
3669 // Find first clause (skip seq_cst clause, if it is first).
3670 if (C->getClauseKind() != OMPC_seq_cst) {
3671 Kind = C->getClauseKind();
3677 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
3678 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
3679 enterFullExpression(EWC);
3681 // Processing for statements under 'atomic capture'.
3682 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
3683 for (const auto *C : Compound->body()) {
3684 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
3685 enterFullExpression(EWC);
3690 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
3691 PrePostActionTy &) {
3692 CGF.EmitStopPoint(CS);
3693 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
3694 S.getV(), S.getExpr(), S.getUpdateExpr(),
3695 S.isXLHSInRHSPart(), S.getLocStart());
3697 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
3698 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
3701 static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
3702 const OMPExecutableDirective &S,
3703 const RegionCodeGenTy &CodeGen) {
3704 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
3705 CodeGenModule &CGM = CGF.CGM;
3706 const CapturedStmt &CS = *S.getCapturedStmt(OMPD_target);
3708 llvm::Function *Fn = nullptr;
3709 llvm::Constant *FnID = nullptr;
3711 const Expr *IfCond = nullptr;
3712 // Check for the at most one if clause associated with the target region.
3713 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3714 if (C->getNameModifier() == OMPD_unknown ||
3715 C->getNameModifier() == OMPD_target) {
3716 IfCond = C->getCondition();
3721 // Check if we have any device clause associated with the directive.
3722 const Expr *Device = nullptr;
3723 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
3724 Device = C->getDevice();
3727 // Check if we have an if clause whose conditional always evaluates to false
3728 // or if we do not have any targets specified. If so the target region is not
3729 // an offload entry point.
3730 bool IsOffloadEntry = true;
3733 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
3734 IsOffloadEntry = false;
3736 if (CGM.getLangOpts().OMPTargetTriples.empty())
3737 IsOffloadEntry = false;
3739 assert(CGF.CurFuncDecl && "No parent declaration for target region!");
3740 StringRef ParentName;
3741 // In case we have Ctors/Dtors we use the complete type variant to produce
3742 // the mangling of the device outlined kernel.
3743 if (auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
3744 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
3745 else if (auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
3746 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
3749 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
3751 // Emit target region as a standalone region.
3752 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
3753 IsOffloadEntry, CodeGen);
3754 OMPLexicalScope Scope(CGF, S);
3755 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3756 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
3757 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device,
3761 static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
3762 PrePostActionTy &Action) {
3763 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3764 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3765 CGF.EmitOMPPrivateClause(S, PrivateScope);
3766 (void)PrivateScope.Privatize();
3769 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3772 void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
3773 StringRef ParentName,
3774 const OMPTargetDirective &S) {
3775 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3776 emitTargetRegion(CGF, S, Action);
3779 llvm::Constant *Addr;
3780 // Emit target region as a standalone region.
3781 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3782 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3783 assert(Fn && Addr && "Target device function emission failed.");
3786 void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
3787 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3788 emitTargetRegion(CGF, S, Action);
3790 emitCommonOMPTargetDirective(*this, S, CodeGen);
3793 static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
3794 const OMPExecutableDirective &S,
3795 OpenMPDirectiveKind InnermostKind,
3796 const RegionCodeGenTy &CodeGen) {
3797 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
3798 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
3799 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
3801 const OMPNumTeamsClause *NT = S.getSingleClause<OMPNumTeamsClause>();
3802 const OMPThreadLimitClause *TL = S.getSingleClause<OMPThreadLimitClause>();
3804 Expr *NumTeams = (NT) ? NT->getNumTeams() : nullptr;
3805 Expr *ThreadLimit = (TL) ? TL->getThreadLimit() : nullptr;
3807 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
3811 OMPTeamsScope Scope(CGF, S);
3812 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3813 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
3814 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn,
3818 void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
3819 // Emit teams region as a standalone region.
3820 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3821 OMPPrivateScope PrivateScope(CGF);
3822 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3823 CGF.EmitOMPPrivateClause(S, PrivateScope);
3824 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
3825 (void)PrivateScope.Privatize();
3826 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3827 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
3829 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
3830 emitPostUpdateForReductionClause(
3831 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
3834 static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
3835 const OMPTargetTeamsDirective &S) {
3836 auto *CS = S.getCapturedStmt(OMPD_teams);
3838 // Emit teams region as a standalone region.
3839 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
3840 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3841 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3842 CGF.EmitOMPPrivateClause(S, PrivateScope);
3843 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
3844 (void)PrivateScope.Privatize();
3846 CGF.EmitStmt(CS->getCapturedStmt());
3847 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
3849 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
3850 emitPostUpdateForReductionClause(
3851 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
3854 void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
3855 CodeGenModule &CGM, StringRef ParentName,
3856 const OMPTargetTeamsDirective &S) {
3857 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3858 emitTargetTeamsRegion(CGF, Action, S);
3861 llvm::Constant *Addr;
3862 // Emit target region as a standalone region.
3863 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3864 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3865 assert(Fn && Addr && "Target device function emission failed.");
3868 void CodeGenFunction::EmitOMPTargetTeamsDirective(
3869 const OMPTargetTeamsDirective &S) {
3870 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3871 emitTargetTeamsRegion(CGF, Action, S);
3873 emitCommonOMPTargetDirective(*this, S, CodeGen);
3877 emitTargetTeamsDistributeRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
3878 const OMPTargetTeamsDistributeDirective &S) {
3880 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3881 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
3884 // Emit teams region as a standalone region.
3885 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
3886 PrePostActionTy &) {
3887 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3888 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
3889 (void)PrivateScope.Privatize();
3890 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
3892 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
3894 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute, CodeGen);
3895 emitPostUpdateForReductionClause(CGF, S,
3896 [](CodeGenFunction &) { return nullptr; });
3899 void CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
3900 CodeGenModule &CGM, StringRef ParentName,
3901 const OMPTargetTeamsDistributeDirective &S) {
3902 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3903 emitTargetTeamsDistributeRegion(CGF, Action, S);
3906 llvm::Constant *Addr;
3907 // Emit target region as a standalone region.
3908 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3909 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3910 assert(Fn && Addr && "Target device function emission failed.");
3913 void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
3914 const OMPTargetTeamsDistributeDirective &S) {
3915 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3916 emitTargetTeamsDistributeRegion(CGF, Action, S);
3918 emitCommonOMPTargetDirective(*this, S, CodeGen);
3921 static void emitTargetTeamsDistributeSimdRegion(
3922 CodeGenFunction &CGF, PrePostActionTy &Action,
3923 const OMPTargetTeamsDistributeSimdDirective &S) {
3925 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3926 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
3929 // Emit teams region as a standalone region.
3930 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
3931 PrePostActionTy &) {
3932 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3933 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
3934 (void)PrivateScope.Privatize();
3935 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
3937 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
3939 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_simd, CodeGen);
3940 emitPostUpdateForReductionClause(CGF, S,
3941 [](CodeGenFunction &) { return nullptr; });
3944 void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
3945 CodeGenModule &CGM, StringRef ParentName,
3946 const OMPTargetTeamsDistributeSimdDirective &S) {
3947 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3948 emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
3951 llvm::Constant *Addr;
3952 // Emit target region as a standalone region.
3953 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3954 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3955 assert(Fn && Addr && "Target device function emission failed.");
3958 void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
3959 const OMPTargetTeamsDistributeSimdDirective &S) {
3960 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3961 emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
3963 emitCommonOMPTargetDirective(*this, S, CodeGen);
3966 void CodeGenFunction::EmitOMPTeamsDistributeDirective(
3967 const OMPTeamsDistributeDirective &S) {
3969 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3970 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
3973 // Emit teams region as a standalone region.
3974 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
3975 PrePostActionTy &) {
3976 OMPPrivateScope PrivateScope(CGF);
3977 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
3978 (void)PrivateScope.Privatize();
3979 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
3981 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
3983 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
3984 emitPostUpdateForReductionClause(*this, S,
3985 [](CodeGenFunction &) { return nullptr; });
3988 void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
3989 const OMPTeamsDistributeSimdDirective &S) {
3990 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3991 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
3994 // Emit teams region as a standalone region.
3995 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
3996 PrePostActionTy &) {
3997 OMPPrivateScope PrivateScope(CGF);
3998 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
3999 (void)PrivateScope.Privatize();
4000 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd,
4002 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4004 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_simd, CodeGen);
4005 emitPostUpdateForReductionClause(*this, S,
4006 [](CodeGenFunction &) { return nullptr; });
4009 void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
4010 const OMPTeamsDistributeParallelForDirective &S) {
4011 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4012 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4016 // Emit teams region as a standalone region.
4017 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4018 PrePostActionTy &) {
4019 OMPPrivateScope PrivateScope(CGF);
4020 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4021 (void)PrivateScope.Privatize();
4022 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4024 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4026 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4027 emitPostUpdateForReductionClause(*this, S,
4028 [](CodeGenFunction &) { return nullptr; });
4031 void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
4032 const OMPTeamsDistributeParallelForSimdDirective &S) {
4033 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4034 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4038 // Emit teams region as a standalone region.
4039 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4040 PrePostActionTy &) {
4041 OMPPrivateScope PrivateScope(CGF);
4042 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4043 (void)PrivateScope.Privatize();
4044 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4045 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4046 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4048 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4049 emitPostUpdateForReductionClause(*this, S,
4050 [](CodeGenFunction &) { return nullptr; });
4053 void CodeGenFunction::EmitOMPCancellationPointDirective(
4054 const OMPCancellationPointDirective &S) {
4055 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
4056 S.getCancelRegion());
4059 void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
4060 const Expr *IfCond = nullptr;
4061 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4062 if (C->getNameModifier() == OMPD_unknown ||
4063 C->getNameModifier() == OMPD_cancel) {
4064 IfCond = C->getCondition();
4068 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
4069 S.getCancelRegion());
4072 CodeGenFunction::JumpDest
4073 CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
4074 if (Kind == OMPD_parallel || Kind == OMPD_task ||
4075 Kind == OMPD_target_parallel)
4077 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
4078 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
4079 Kind == OMPD_distribute_parallel_for ||
4080 Kind == OMPD_target_parallel_for ||
4081 Kind == OMPD_teams_distribute_parallel_for ||
4082 Kind == OMPD_target_teams_distribute_parallel_for);
4083 return OMPCancelStack.getExitBlock();
4086 void CodeGenFunction::EmitOMPUseDevicePtrClause(
4087 const OMPClause &NC, OMPPrivateScope &PrivateScope,
4088 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
4089 const auto &C = cast<OMPUseDevicePtrClause>(NC);
4090 auto OrigVarIt = C.varlist_begin();
4091 auto InitIt = C.inits().begin();
4092 for (auto PvtVarIt : C.private_copies()) {
4093 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
4094 auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
4095 auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
4097 // In order to identify the right initializer we need to match the
4098 // declaration used by the mapping logic. In some cases we may get
4099 // OMPCapturedExprDecl that refers to the original declaration.
4100 const ValueDecl *MatchingVD = OrigVD;
4101 if (auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
4102 // OMPCapturedExprDecl are used to privative fields of the current
4104 auto *ME = cast<MemberExpr>(OED->getInit());
4105 assert(isa<CXXThisExpr>(ME->getBase()) &&
4106 "Base should be the current struct!");
4107 MatchingVD = ME->getMemberDecl();
4110 // If we don't have information about the current list item, move on to
4112 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
4113 if (InitAddrIt == CaptureDeviceAddrMap.end())
4116 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
4117 // Initialize the temporary initialization variable with the address we
4118 // get from the runtime library. We have to cast the source address
4119 // because it is always a void *. References are materialized in the
4120 // privatization scope, so the initialization here disregards the fact
4121 // the original variable is a reference.
4123 getContext().getPointerType(OrigVD->getType().getNonReferenceType());
4124 llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
4125 Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
4126 setAddrOfLocalVar(InitVD, InitAddr);
4128 // Emit private declaration, it will be initialized by the value we
4129 // declaration we just added to the local declarations map.
4132 // The initialization variables reached its purpose in the emission
4133 // ofthe previous declaration, so we don't need it anymore.
4134 LocalDeclMap.erase(InitVD);
4136 // Return the address of the private variable.
4137 return GetAddrOfLocalVar(PvtVD);
4139 assert(IsRegistered && "firstprivate var already registered as private");
4140 // Silence the warning about unused variable.
4148 // Generate the instructions for '#pragma omp target data' directive.
4149 void CodeGenFunction::EmitOMPTargetDataDirective(
4150 const OMPTargetDataDirective &S) {
4151 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true);
4153 // Create a pre/post action to signal the privatization of the device pointer.
4154 // This action can be replaced by the OpenMP runtime code generation to
4155 // deactivate privatization.
4156 bool PrivatizeDevicePointers = false;
4157 class DevicePointerPrivActionTy : public PrePostActionTy {
4158 bool &PrivatizeDevicePointers;
4161 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
4162 : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
4163 void Enter(CodeGenFunction &CGF) override {
4164 PrivatizeDevicePointers = true;
4167 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
4169 auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
4170 CodeGenFunction &CGF, PrePostActionTy &Action) {
4171 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4173 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
4176 // Codegen that selects wheather to generate the privatization code or not.
4177 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
4178 &InnermostCodeGen](CodeGenFunction &CGF,
4179 PrePostActionTy &Action) {
4180 RegionCodeGenTy RCG(InnermostCodeGen);
4181 PrivatizeDevicePointers = false;
4183 // Call the pre-action to change the status of PrivatizeDevicePointers if
4187 if (PrivatizeDevicePointers) {
4188 OMPPrivateScope PrivateScope(CGF);
4189 // Emit all instances of the use_device_ptr clause.
4190 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
4191 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
4192 Info.CaptureDeviceAddrMap);
4193 (void)PrivateScope.Privatize();
4199 // Forward the provided action to the privatization codegen.
4200 RegionCodeGenTy PrivRCG(PrivCodeGen);
4201 PrivRCG.setAction(Action);
4203 // Notwithstanding the body of the region is emitted as inlined directive,
4204 // we don't use an inline scope as changes in the references inside the
4205 // region are expected to be visible outside, so we do not privative them.
4206 OMPLexicalScope Scope(CGF, S);
4207 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
4211 RegionCodeGenTy RCG(CodeGen);
4213 // If we don't have target devices, don't bother emitting the data mapping
4215 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
4220 // Check if we have any if clause associated with the directive.
4221 const Expr *IfCond = nullptr;
4222 if (auto *C = S.getSingleClause<OMPIfClause>())
4223 IfCond = C->getCondition();
4225 // Check if we have any device clause associated with the directive.
4226 const Expr *Device = nullptr;
4227 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4228 Device = C->getDevice();
4230 // Set the action to signal privatization of device pointers.
4231 RCG.setAction(PrivAction);
4233 // Emit region code.
4234 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
4238 void CodeGenFunction::EmitOMPTargetEnterDataDirective(
4239 const OMPTargetEnterDataDirective &S) {
4240 // If we don't have target devices, don't bother emitting the data mapping
4242 if (CGM.getLangOpts().OMPTargetTriples.empty())
4245 // Check if we have any if clause associated with the directive.
4246 const Expr *IfCond = nullptr;
4247 if (auto *C = S.getSingleClause<OMPIfClause>())
4248 IfCond = C->getCondition();
4250 // Check if we have any device clause associated with the directive.
4251 const Expr *Device = nullptr;
4252 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4253 Device = C->getDevice();
4255 auto &&CodeGen = [&S, IfCond, Device](CodeGenFunction &CGF,
4256 PrePostActionTy &) {
4257 CGF.CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(CGF, S, IfCond,
4260 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
4261 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_target_enter_data,
4265 void CodeGenFunction::EmitOMPTargetExitDataDirective(
4266 const OMPTargetExitDataDirective &S) {
4267 // If we don't have target devices, don't bother emitting the data mapping
4269 if (CGM.getLangOpts().OMPTargetTriples.empty())
4272 // Check if we have any if clause associated with the directive.
4273 const Expr *IfCond = nullptr;
4274 if (auto *C = S.getSingleClause<OMPIfClause>())
4275 IfCond = C->getCondition();
4277 // Check if we have any device clause associated with the directive.
4278 const Expr *Device = nullptr;
4279 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4280 Device = C->getDevice();
4282 auto &&CodeGen = [&S, IfCond, Device](CodeGenFunction &CGF,
4283 PrePostActionTy &) {
4284 CGF.CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(CGF, S, IfCond,
4287 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
4288 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_target_exit_data,
4292 static void emitTargetParallelRegion(CodeGenFunction &CGF,
4293 const OMPTargetParallelDirective &S,
4294 PrePostActionTy &Action) {
4295 // Get the captured statement associated with the 'parallel' region.
4296 auto *CS = S.getCapturedStmt(OMPD_parallel);
4298 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &) {
4299 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4300 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4301 CGF.EmitOMPPrivateClause(S, PrivateScope);
4302 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4303 (void)PrivateScope.Privatize();
4304 // TODO: Add support for clauses.
4305 CGF.EmitStmt(CS->getCapturedStmt());
4306 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
4308 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
4309 emitEmptyBoundParameters);
4310 emitPostUpdateForReductionClause(
4311 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
4314 void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
4315 CodeGenModule &CGM, StringRef ParentName,
4316 const OMPTargetParallelDirective &S) {
4317 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4318 emitTargetParallelRegion(CGF, S, Action);
4321 llvm::Constant *Addr;
4322 // Emit target region as a standalone region.
4323 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4324 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4325 assert(Fn && Addr && "Target device function emission failed.");
4328 void CodeGenFunction::EmitOMPTargetParallelDirective(
4329 const OMPTargetParallelDirective &S) {
4330 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4331 emitTargetParallelRegion(CGF, S, Action);
4333 emitCommonOMPTargetDirective(*this, S, CodeGen);
4336 static void emitTargetParallelForRegion(CodeGenFunction &CGF,
4337 const OMPTargetParallelForDirective &S,
4338 PrePostActionTy &Action) {
4340 // Emit directive as a combined directive that consists of two implicit
4341 // directives: 'parallel' with 'for' directive.
4342 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4343 CodeGenFunction::OMPCancelStackRAII CancelRegion(
4344 CGF, OMPD_target_parallel_for, S.hasCancel());
4345 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4346 emitDispatchForLoopBounds);
4348 emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen,
4349 emitEmptyBoundParameters);
4352 void CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
4353 CodeGenModule &CGM, StringRef ParentName,
4354 const OMPTargetParallelForDirective &S) {
4355 // Emit SPMD target parallel for region as a standalone region.
4356 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4357 emitTargetParallelForRegion(CGF, S, Action);
4360 llvm::Constant *Addr;
4361 // Emit target region as a standalone region.
4362 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4363 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4364 assert(Fn && Addr && "Target device function emission failed.");
4367 void CodeGenFunction::EmitOMPTargetParallelForDirective(
4368 const OMPTargetParallelForDirective &S) {
4369 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4370 emitTargetParallelForRegion(CGF, S, Action);
4372 emitCommonOMPTargetDirective(*this, S, CodeGen);
4376 emitTargetParallelForSimdRegion(CodeGenFunction &CGF,
4377 const OMPTargetParallelForSimdDirective &S,
4378 PrePostActionTy &Action) {
4380 // Emit directive as a combined directive that consists of two implicit
4381 // directives: 'parallel' with 'for' directive.
4382 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4383 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4384 emitDispatchForLoopBounds);
4386 emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen,
4387 emitEmptyBoundParameters);
4390 void CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
4391 CodeGenModule &CGM, StringRef ParentName,
4392 const OMPTargetParallelForSimdDirective &S) {
4393 // Emit SPMD target parallel for region as a standalone region.
4394 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4395 emitTargetParallelForSimdRegion(CGF, S, Action);
4398 llvm::Constant *Addr;
4399 // Emit target region as a standalone region.
4400 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4401 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4402 assert(Fn && Addr && "Target device function emission failed.");
4405 void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
4406 const OMPTargetParallelForSimdDirective &S) {
4407 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4408 emitTargetParallelForSimdRegion(CGF, S, Action);
4410 emitCommonOMPTargetDirective(*this, S, CodeGen);
4413 /// Emit a helper variable and return corresponding lvalue.
4414 static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
4415 const ImplicitParamDecl *PVD,
4416 CodeGenFunction::OMPPrivateScope &Privates) {
4417 auto *VDecl = cast<VarDecl>(Helper->getDecl());
4418 Privates.addPrivate(
4419 VDecl, [&CGF, PVD]() -> Address { return CGF.GetAddrOfLocalVar(PVD); });
4422 void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
4423 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
4424 // Emit outlined function for task construct.
4425 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
4426 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
4427 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
4428 const Expr *IfCond = nullptr;
4429 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4430 if (C->getNameModifier() == OMPD_unknown ||
4431 C->getNameModifier() == OMPD_taskloop) {
4432 IfCond = C->getCondition();
4438 // Check if taskloop must be emitted without taskgroup.
4439 Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
4440 // TODO: Check if we should emit tied or untied task.
4442 // Set scheduling for taskloop
4443 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
4445 Data.Schedule.setInt(/*IntVal=*/false);
4446 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
4447 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
4449 Data.Schedule.setInt(/*IntVal=*/true);
4450 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
4453 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
4455 // for (IV in 0..LastIteration) BODY;
4456 // <Final counter/linear vars updates>;
4460 // Emit: if (PreCond) - begin.
4461 // If the condition constant folds and can be elided, avoid emitting the
4464 llvm::BasicBlock *ContBlock = nullptr;
4465 OMPLoopScope PreInitScope(CGF, S);
4466 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
4470 auto *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
4471 ContBlock = CGF.createBasicBlock("taskloop.if.end");
4472 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
4473 CGF.getProfileCount(&S));
4474 CGF.EmitBlock(ThenBlock);
4475 CGF.incrementProfileCounter(&S);
4478 if (isOpenMPSimdDirective(S.getDirectiveKind()))
4479 CGF.EmitOMPSimdInit(S);
4481 OMPPrivateScope LoopScope(CGF);
4482 // Emit helper vars inits.
4483 enum { LowerBound = 5, UpperBound, Stride, LastIter };
4484 auto *I = CS->getCapturedDecl()->param_begin();
4485 auto *LBP = std::next(I, LowerBound);
4486 auto *UBP = std::next(I, UpperBound);
4487 auto *STP = std::next(I, Stride);
4488 auto *LIP = std::next(I, LastIter);
4489 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
4491 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
4493 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
4494 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
4496 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
4497 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
4498 (void)LoopScope.Privatize();
4499 // Emit the loop iteration variable.
4500 const Expr *IVExpr = S.getIterationVariable();
4501 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
4502 CGF.EmitVarDecl(*IVDecl);
4503 CGF.EmitIgnoredExpr(S.getInit());
4505 // Emit the iterations count variable.
4506 // If it is not a variable, Sema decided to calculate iterations count on
4507 // each iteration (e.g., it is foldable into a constant).
4508 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
4509 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
4510 // Emit calculation of the iterations count.
4511 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
4514 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
4516 [&S](CodeGenFunction &CGF) {
4517 CGF.EmitOMPLoopBody(S, JumpDest());
4518 CGF.EmitStopPoint(&S);
4520 [](CodeGenFunction &) {});
4521 // Emit: if (PreCond) - end.
4523 CGF.EmitBranch(ContBlock);
4524 CGF.EmitBlock(ContBlock, true);
4526 // Emit final copy of the lastprivate variables if IsLastIter != 0.
4527 if (HasLastprivateClause) {
4528 CGF.EmitOMPLastprivateClauseFinal(
4529 S, isOpenMPSimdDirective(S.getDirectiveKind()),
4530 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
4531 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
4532 (*LIP)->getType(), S.getLocStart())));
4535 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
4536 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
4537 const OMPTaskDataTy &Data) {
4538 auto &&CodeGen = [&](CodeGenFunction &CGF, PrePostActionTy &) {
4539 OMPLoopScope PreInitScope(CGF, S);
4540 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getLocStart(), S,
4541 OutlinedFn, SharedsTy,
4542 CapturedStruct, IfCond, Data);
4544 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
4548 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
4550 CGM.getOpenMPRuntime().emitTaskgroupRegion(
4552 [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF,
4553 PrePostActionTy &Action) {
4555 CGF.EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
4561 void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
4562 EmitOMPTaskLoopBasedDirective(S);
4565 void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
4566 const OMPTaskLoopSimdDirective &S) {
4567 EmitOMPTaskLoopBasedDirective(S);
4570 // Generate the instructions for '#pragma omp target update' directive.
4571 void CodeGenFunction::EmitOMPTargetUpdateDirective(
4572 const OMPTargetUpdateDirective &S) {
4573 // If we don't have target devices, don't bother emitting the data mapping
4575 if (CGM.getLangOpts().OMPTargetTriples.empty())
4578 // Check if we have any if clause associated with the directive.
4579 const Expr *IfCond = nullptr;
4580 if (auto *C = S.getSingleClause<OMPIfClause>())
4581 IfCond = C->getCondition();
4583 // Check if we have any device clause associated with the directive.
4584 const Expr *Device = nullptr;
4585 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4586 Device = C->getDevice();
4588 auto &&CodeGen = [&S, IfCond, Device](CodeGenFunction &CGF,
4589 PrePostActionTy &) {
4590 CGF.CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(CGF, S, IfCond,
4593 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
4594 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_target_update,