1 //===--- CGStmtOpenMP.cpp - Emit LLVM Code from Statements ----------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This contains code to emit OpenMP nodes as LLVM code.
11 //===----------------------------------------------------------------------===//
13 #include "CGCleanup.h"
14 #include "CGOpenMPRuntime.h"
15 #include "CodeGenFunction.h"
16 #include "CodeGenModule.h"
17 #include "TargetInfo.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/Attr.h"
20 #include "clang/AST/DeclOpenMP.h"
21 #include "clang/AST/OpenMPClause.h"
22 #include "clang/AST/Stmt.h"
23 #include "clang/AST/StmtOpenMP.h"
24 #include "clang/Basic/OpenMPKinds.h"
25 #include "clang/Basic/PrettyStackTrace.h"
26 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
27 #include "llvm/IR/Instructions.h"
28 #include "llvm/Support/AtomicOrdering.h"
29 using namespace clang;
30 using namespace CodeGen;
31 using namespace llvm::omp;
34 /// Lexical scope for OpenMP executable constructs, that handles correct codegen
35 /// for captured expressions.
36 class OMPLexicalScope : public CodeGenFunction::LexicalScope {
37 void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
38 for (const auto *C : S.clauses()) {
39 if (const auto *CPI = OMPClauseWithPreInit::get(C)) {
40 if (const auto *PreInit =
41 cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
42 for (const auto *I : PreInit->decls()) {
43 if (!I->hasAttr<OMPCaptureNoInitAttr>()) {
44 CGF.EmitVarDecl(cast<VarDecl>(*I));
46 CodeGenFunction::AutoVarEmission Emission =
47 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
48 CGF.EmitAutoVarCleanups(Emission);
55 CodeGenFunction::OMPPrivateScope InlinedShareds;
57 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
58 return CGF.LambdaCaptureFields.lookup(VD) ||
59 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
60 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl) &&
61 cast<BlockDecl>(CGF.CurCodeDecl)->capturesVariable(VD));
66 CodeGenFunction &CGF, const OMPExecutableDirective &S,
67 const llvm::Optional<OpenMPDirectiveKind> CapturedRegion = llvm::None,
68 const bool EmitPreInitStmt = true)
69 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
72 emitPreInitStmt(CGF, S);
73 if (!CapturedRegion.hasValue())
75 assert(S.hasAssociatedStmt() &&
76 "Expected associated statement for inlined directive.");
77 const CapturedStmt *CS = S.getCapturedStmt(*CapturedRegion);
78 for (const auto &C : CS->captures()) {
79 if (C.capturesVariable() || C.capturesVariableByCopy()) {
80 auto *VD = C.getCapturedVar();
81 assert(VD == VD->getCanonicalDecl() &&
82 "Canonical decl must be captured.");
84 CGF.getContext(), const_cast<VarDecl *>(VD),
85 isCapturedVar(CGF, VD) || (CGF.CapturedStmtInfo &&
86 InlinedShareds.isGlobalVarCaptured(VD)),
87 VD->getType().getNonReferenceType(), VK_LValue, C.getLocation());
88 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
89 return CGF.EmitLValue(&DRE).getAddress(CGF);
93 (void)InlinedShareds.Privatize();
97 /// Lexical scope for OpenMP parallel construct, that handles correct codegen
98 /// for captured expressions.
99 class OMPParallelScope final : public OMPLexicalScope {
100 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
101 OpenMPDirectiveKind Kind = S.getDirectiveKind();
102 return !(isOpenMPTargetExecutionDirective(Kind) ||
103 isOpenMPLoopBoundSharingDirective(Kind)) &&
104 isOpenMPParallelDirective(Kind);
108 OMPParallelScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
109 : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None,
110 EmitPreInitStmt(S)) {}
113 /// Lexical scope for OpenMP teams construct, that handles correct codegen
114 /// for captured expressions.
115 class OMPTeamsScope final : public OMPLexicalScope {
116 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
117 OpenMPDirectiveKind Kind = S.getDirectiveKind();
118 return !isOpenMPTargetExecutionDirective(Kind) &&
119 isOpenMPTeamsDirective(Kind);
123 OMPTeamsScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
124 : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None,
125 EmitPreInitStmt(S)) {}
128 /// Private scope for OpenMP loop-based directives, that supports capturing
129 /// of used expression from loop statement.
130 class OMPLoopScope : public CodeGenFunction::RunCleanupsScope {
131 void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopDirective &S) {
132 CodeGenFunction::OMPMapVars PreCondVars;
133 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
134 for (const auto *E : S.counters()) {
135 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
136 EmittedAsPrivate.insert(VD->getCanonicalDecl());
137 (void)PreCondVars.setVarAddr(
138 CGF, VD, CGF.CreateMemTemp(VD->getType().getNonReferenceType()));
140 // Mark private vars as undefs.
141 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
142 for (const Expr *IRef : C->varlists()) {
143 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
144 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
145 (void)PreCondVars.setVarAddr(
147 Address(llvm::UndefValue::get(
148 CGF.ConvertTypeForMem(CGF.getContext().getPointerType(
149 OrigVD->getType().getNonReferenceType()))),
150 CGF.getContext().getDeclAlign(OrigVD)));
154 (void)PreCondVars.apply(CGF);
155 // Emit init, __range and __end variables for C++ range loops.
157 S.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers();
158 for (unsigned Cnt = 0; Cnt < S.getCollapsedNumber(); ++Cnt) {
159 Body = OMPLoopDirective::tryToFindNextInnerLoop(
160 Body, /*TryImperfectlyNestedLoops=*/true);
161 if (auto *For = dyn_cast<ForStmt>(Body)) {
162 Body = For->getBody();
164 assert(isa<CXXForRangeStmt>(Body) &&
165 "Expected canonical for loop or range-based for loop.");
166 auto *CXXFor = cast<CXXForRangeStmt>(Body);
167 if (const Stmt *Init = CXXFor->getInit())
169 CGF.EmitStmt(CXXFor->getRangeStmt());
170 CGF.EmitStmt(CXXFor->getEndStmt());
171 Body = CXXFor->getBody();
174 if (const auto *PreInits = cast_or_null<DeclStmt>(S.getPreInits())) {
175 for (const auto *I : PreInits->decls())
176 CGF.EmitVarDecl(cast<VarDecl>(*I));
178 PreCondVars.restore(CGF);
182 OMPLoopScope(CodeGenFunction &CGF, const OMPLoopDirective &S)
183 : CodeGenFunction::RunCleanupsScope(CGF) {
184 emitPreInitStmt(CGF, S);
188 class OMPSimdLexicalScope : public CodeGenFunction::LexicalScope {
189 CodeGenFunction::OMPPrivateScope InlinedShareds;
191 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
192 return CGF.LambdaCaptureFields.lookup(VD) ||
193 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
194 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl) &&
195 cast<BlockDecl>(CGF.CurCodeDecl)->capturesVariable(VD));
199 OMPSimdLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
200 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
201 InlinedShareds(CGF) {
202 for (const auto *C : S.clauses()) {
203 if (const auto *CPI = OMPClauseWithPreInit::get(C)) {
204 if (const auto *PreInit =
205 cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
206 for (const auto *I : PreInit->decls()) {
207 if (!I->hasAttr<OMPCaptureNoInitAttr>()) {
208 CGF.EmitVarDecl(cast<VarDecl>(*I));
210 CodeGenFunction::AutoVarEmission Emission =
211 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
212 CGF.EmitAutoVarCleanups(Emission);
216 } else if (const auto *UDP = dyn_cast<OMPUseDevicePtrClause>(C)) {
217 for (const Expr *E : UDP->varlists()) {
218 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
219 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(D))
220 CGF.EmitVarDecl(*OED);
224 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
225 CGF.EmitOMPPrivateClause(S, InlinedShareds);
226 if (const auto *TG = dyn_cast<OMPTaskgroupDirective>(&S)) {
227 if (const Expr *E = TG->getReductionRef())
228 CGF.EmitVarDecl(*cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()));
230 const auto *CS = cast_or_null<CapturedStmt>(S.getAssociatedStmt());
232 for (auto &C : CS->captures()) {
233 if (C.capturesVariable() || C.capturesVariableByCopy()) {
234 auto *VD = C.getCapturedVar();
235 assert(VD == VD->getCanonicalDecl() &&
236 "Canonical decl must be captured.");
237 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(VD),
238 isCapturedVar(CGF, VD) ||
239 (CGF.CapturedStmtInfo &&
240 InlinedShareds.isGlobalVarCaptured(VD)),
241 VD->getType().getNonReferenceType(), VK_LValue,
243 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
244 return CGF.EmitLValue(&DRE).getAddress(CGF);
248 CS = dyn_cast<CapturedStmt>(CS->getCapturedStmt());
250 (void)InlinedShareds.Privatize();
256 static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
257 const OMPExecutableDirective &S,
258 const RegionCodeGenTy &CodeGen);
260 LValue CodeGenFunction::EmitOMPSharedLValue(const Expr *E) {
261 if (const auto *OrigDRE = dyn_cast<DeclRefExpr>(E)) {
262 if (const auto *OrigVD = dyn_cast<VarDecl>(OrigDRE->getDecl())) {
263 OrigVD = OrigVD->getCanonicalDecl();
265 LambdaCaptureFields.lookup(OrigVD) ||
266 (CapturedStmtInfo && CapturedStmtInfo->lookup(OrigVD)) ||
267 (CurCodeDecl && isa<BlockDecl>(CurCodeDecl));
268 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD), IsCaptured,
269 OrigDRE->getType(), VK_LValue, OrigDRE->getExprLoc());
270 return EmitLValue(&DRE);
273 return EmitLValue(E);
276 llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
277 ASTContext &C = getContext();
278 llvm::Value *Size = nullptr;
279 auto SizeInChars = C.getTypeSizeInChars(Ty);
280 if (SizeInChars.isZero()) {
281 // getTypeSizeInChars() returns 0 for a VLA.
282 while (const VariableArrayType *VAT = C.getAsVariableArrayType(Ty)) {
283 VlaSizePair VlaSize = getVLASize(VAT);
285 Size = Size ? Builder.CreateNUWMul(Size, VlaSize.NumElts)
288 SizeInChars = C.getTypeSizeInChars(Ty);
289 if (SizeInChars.isZero())
290 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
291 return Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
293 return CGM.getSize(SizeInChars);
296 void CodeGenFunction::GenerateOpenMPCapturedVars(
297 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
298 const RecordDecl *RD = S.getCapturedRecordDecl();
299 auto CurField = RD->field_begin();
300 auto CurCap = S.captures().begin();
301 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
302 E = S.capture_init_end();
303 I != E; ++I, ++CurField, ++CurCap) {
304 if (CurField->hasCapturedVLAType()) {
305 const VariableArrayType *VAT = CurField->getCapturedVLAType();
306 llvm::Value *Val = VLASizeMap[VAT->getSizeExpr()];
307 CapturedVars.push_back(Val);
308 } else if (CurCap->capturesThis()) {
309 CapturedVars.push_back(CXXThisValue);
310 } else if (CurCap->capturesVariableByCopy()) {
311 llvm::Value *CV = EmitLoadOfScalar(EmitLValue(*I), CurCap->getLocation());
313 // If the field is not a pointer, we need to save the actual value
314 // and load it as a void pointer.
315 if (!CurField->getType()->isAnyPointerType()) {
316 ASTContext &Ctx = getContext();
317 Address DstAddr = CreateMemTemp(
318 Ctx.getUIntPtrType(),
319 Twine(CurCap->getCapturedVar()->getName(), ".casted"));
320 LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
322 llvm::Value *SrcAddrVal = EmitScalarConversion(
323 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
324 Ctx.getPointerType(CurField->getType()), CurCap->getLocation());
326 MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType());
328 // Store the value using the source type pointer.
329 EmitStoreThroughLValue(RValue::get(CV), SrcLV);
331 // Load the value using the destination type pointer.
332 CV = EmitLoadOfScalar(DstLV, CurCap->getLocation());
334 CapturedVars.push_back(CV);
336 assert(CurCap->capturesVariable() && "Expected capture by reference.");
337 CapturedVars.push_back(EmitLValue(*I).getAddress(*this).getPointer());
342 static Address castValueFromUintptr(CodeGenFunction &CGF, SourceLocation Loc,
343 QualType DstType, StringRef Name,
345 ASTContext &Ctx = CGF.getContext();
347 llvm::Value *CastedPtr = CGF.EmitScalarConversion(
348 AddrLV.getAddress(CGF).getPointer(), Ctx.getUIntPtrType(),
349 Ctx.getPointerType(DstType), Loc);
351 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
356 static QualType getCanonicalParamType(ASTContext &C, QualType T) {
357 if (T->isLValueReferenceType())
358 return C.getLValueReferenceType(
359 getCanonicalParamType(C, T.getNonReferenceType()),
360 /*SpelledAsLValue=*/false);
361 if (T->isPointerType())
362 return C.getPointerType(getCanonicalParamType(C, T->getPointeeType()));
363 if (const ArrayType *A = T->getAsArrayTypeUnsafe()) {
364 if (const auto *VLA = dyn_cast<VariableArrayType>(A))
365 return getCanonicalParamType(C, VLA->getElementType());
366 if (!A->isVariablyModifiedType())
367 return C.getCanonicalType(T);
369 return C.getCanonicalParamType(T);
373 /// Contains required data for proper outlined function codegen.
374 struct FunctionOptions {
375 /// Captured statement for which the function is generated.
376 const CapturedStmt *S = nullptr;
377 /// true if cast to/from UIntPtr is required for variables captured by
379 const bool UIntPtrCastRequired = true;
380 /// true if only casted arguments must be registered as local args or VLA
382 const bool RegisterCastedArgsOnly = false;
383 /// Name of the generated function.
384 const StringRef FunctionName;
385 /// Location of the non-debug version of the outlined function.
387 explicit FunctionOptions(const CapturedStmt *S, bool UIntPtrCastRequired,
388 bool RegisterCastedArgsOnly, StringRef FunctionName,
390 : S(S), UIntPtrCastRequired(UIntPtrCastRequired),
391 RegisterCastedArgsOnly(UIntPtrCastRequired && RegisterCastedArgsOnly),
392 FunctionName(FunctionName), Loc(Loc) {}
396 static llvm::Function *emitOutlinedFunctionPrologue(
397 CodeGenFunction &CGF, FunctionArgList &Args,
398 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>>
400 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>>
402 llvm::Value *&CXXThisValue, const FunctionOptions &FO) {
403 const CapturedDecl *CD = FO.S->getCapturedDecl();
404 const RecordDecl *RD = FO.S->getCapturedRecordDecl();
405 assert(CD->hasBody() && "missing CapturedDecl body");
407 CXXThisValue = nullptr;
408 // Build the argument list.
409 CodeGenModule &CGM = CGF.CGM;
410 ASTContext &Ctx = CGM.getContext();
411 FunctionArgList TargetArgs;
412 Args.append(CD->param_begin(),
413 std::next(CD->param_begin(), CD->getContextParamPosition()));
416 std::next(CD->param_begin(), CD->getContextParamPosition()));
417 auto I = FO.S->captures().begin();
418 FunctionDecl *DebugFunctionDecl = nullptr;
419 if (!FO.UIntPtrCastRequired) {
420 FunctionProtoType::ExtProtoInfo EPI;
421 QualType FunctionTy = Ctx.getFunctionType(Ctx.VoidTy, llvm::None, EPI);
422 DebugFunctionDecl = FunctionDecl::Create(
423 Ctx, Ctx.getTranslationUnitDecl(), FO.S->getBeginLoc(),
424 SourceLocation(), DeclarationName(), FunctionTy,
425 Ctx.getTrivialTypeSourceInfo(FunctionTy), SC_Static,
426 /*isInlineSpecified=*/false, /*hasWrittenPrototype=*/false);
428 for (const FieldDecl *FD : RD->fields()) {
429 QualType ArgType = FD->getType();
430 IdentifierInfo *II = nullptr;
431 VarDecl *CapVar = nullptr;
433 // If this is a capture by copy and the type is not a pointer, the outlined
434 // function argument type should be uintptr and the value properly casted to
435 // uintptr. This is necessary given that the runtime library is only able to
436 // deal with pointers. We can pass in the same way the VLA type sizes to the
437 // outlined function.
438 if (FO.UIntPtrCastRequired &&
439 ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
440 I->capturesVariableArrayType()))
441 ArgType = Ctx.getUIntPtrType();
443 if (I->capturesVariable() || I->capturesVariableByCopy()) {
444 CapVar = I->getCapturedVar();
445 II = CapVar->getIdentifier();
446 } else if (I->capturesThis()) {
447 II = &Ctx.Idents.get("this");
449 assert(I->capturesVariableArrayType());
450 II = &Ctx.Idents.get("vla");
452 if (ArgType->isVariablyModifiedType())
453 ArgType = getCanonicalParamType(Ctx, ArgType);
455 if (DebugFunctionDecl && (CapVar || I->capturesThis())) {
456 Arg = ParmVarDecl::Create(
457 Ctx, DebugFunctionDecl,
458 CapVar ? CapVar->getBeginLoc() : FD->getBeginLoc(),
459 CapVar ? CapVar->getLocation() : FD->getLocation(), II, ArgType,
460 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
462 Arg = ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(),
463 II, ArgType, ImplicitParamDecl::Other);
465 Args.emplace_back(Arg);
466 // Do not cast arguments if we emit function with non-original types.
467 TargetArgs.emplace_back(
468 FO.UIntPtrCastRequired
470 : CGM.getOpenMPRuntime().translateParameter(FD, Arg));
474 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
477 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
480 // Create the function declaration.
481 const CGFunctionInfo &FuncInfo =
482 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, TargetArgs);
483 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
486 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
487 FO.FunctionName, &CGM.getModule());
488 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
490 F->setDoesNotThrow();
491 F->setDoesNotRecurse();
493 // Generate the function.
494 CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, TargetArgs,
495 FO.UIntPtrCastRequired ? FO.Loc : FO.S->getBeginLoc(),
496 FO.UIntPtrCastRequired ? FO.Loc
497 : CD->getBody()->getBeginLoc());
498 unsigned Cnt = CD->getContextParamPosition();
499 I = FO.S->captures().begin();
500 for (const FieldDecl *FD : RD->fields()) {
501 // Do not map arguments if we emit function with non-original types.
502 Address LocalAddr(Address::invalid());
503 if (!FO.UIntPtrCastRequired && Args[Cnt] != TargetArgs[Cnt]) {
504 LocalAddr = CGM.getOpenMPRuntime().getParameterAddress(CGF, Args[Cnt],
507 LocalAddr = CGF.GetAddrOfLocalVar(Args[Cnt]);
509 // If we are capturing a pointer by copy we don't need to do anything, just
510 // use the value that we get from the arguments.
511 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
512 const VarDecl *CurVD = I->getCapturedVar();
513 if (!FO.RegisterCastedArgsOnly)
514 LocalAddrs.insert({Args[Cnt], {CurVD, LocalAddr}});
520 LValue ArgLVal = CGF.MakeAddrLValue(LocalAddr, Args[Cnt]->getType(),
521 AlignmentSource::Decl);
522 if (FD->hasCapturedVLAType()) {
523 if (FO.UIntPtrCastRequired) {
524 ArgLVal = CGF.MakeAddrLValue(
525 castValueFromUintptr(CGF, I->getLocation(), FD->getType(),
526 Args[Cnt]->getName(), ArgLVal),
527 FD->getType(), AlignmentSource::Decl);
529 llvm::Value *ExprArg = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation());
530 const VariableArrayType *VAT = FD->getCapturedVLAType();
531 VLASizes.try_emplace(Args[Cnt], VAT->getSizeExpr(), ExprArg);
532 } else if (I->capturesVariable()) {
533 const VarDecl *Var = I->getCapturedVar();
534 QualType VarTy = Var->getType();
535 Address ArgAddr = ArgLVal.getAddress(CGF);
536 if (ArgLVal.getType()->isLValueReferenceType()) {
537 ArgAddr = CGF.EmitLoadOfReference(ArgLVal);
538 } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) {
539 assert(ArgLVal.getType()->isPointerType());
540 ArgAddr = CGF.EmitLoadOfPointer(
541 ArgAddr, ArgLVal.getType()->castAs<PointerType>());
543 if (!FO.RegisterCastedArgsOnly) {
546 {Var, Address(ArgAddr.getPointer(), Ctx.getDeclAlign(Var))}});
548 } else if (I->capturesVariableByCopy()) {
549 assert(!FD->getType()->isAnyPointerType() &&
550 "Not expecting a captured pointer.");
551 const VarDecl *Var = I->getCapturedVar();
552 LocalAddrs.insert({Args[Cnt],
553 {Var, FO.UIntPtrCastRequired
554 ? castValueFromUintptr(
555 CGF, I->getLocation(), FD->getType(),
556 Args[Cnt]->getName(), ArgLVal)
557 : ArgLVal.getAddress(CGF)}});
559 // If 'this' is captured, load it into CXXThisValue.
560 assert(I->capturesThis());
561 CXXThisValue = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation());
562 LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress(CGF)}});
572 CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S,
573 SourceLocation Loc) {
576 "CapturedStmtInfo should be set when generating the captured function");
577 const CapturedDecl *CD = S.getCapturedDecl();
578 // Build the argument list.
579 bool NeedWrapperFunction =
580 getDebugInfo() && CGM.getCodeGenOpts().hasReducedDebugInfo();
581 FunctionArgList Args;
582 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs;
583 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes;
584 SmallString<256> Buffer;
585 llvm::raw_svector_ostream Out(Buffer);
586 Out << CapturedStmtInfo->getHelperName();
587 if (NeedWrapperFunction)
589 FunctionOptions FO(&S, !NeedWrapperFunction, /*RegisterCastedArgsOnly=*/false,
591 llvm::Function *F = emitOutlinedFunctionPrologue(*this, Args, LocalAddrs,
592 VLASizes, CXXThisValue, FO);
593 CodeGenFunction::OMPPrivateScope LocalScope(*this);
594 for (const auto &LocalAddrPair : LocalAddrs) {
595 if (LocalAddrPair.second.first) {
596 LocalScope.addPrivate(LocalAddrPair.second.first, [&LocalAddrPair]() {
597 return LocalAddrPair.second.second;
601 (void)LocalScope.Privatize();
602 for (const auto &VLASizePair : VLASizes)
603 VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second;
604 PGO.assignRegionCounters(GlobalDecl(CD), F);
605 CapturedStmtInfo->EmitBody(*this, CD->getBody());
606 (void)LocalScope.ForceCleanup();
607 FinishFunction(CD->getBodyRBrace());
608 if (!NeedWrapperFunction)
611 FunctionOptions WrapperFO(&S, /*UIntPtrCastRequired=*/true,
612 /*RegisterCastedArgsOnly=*/true,
613 CapturedStmtInfo->getHelperName(), Loc);
614 CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true);
615 WrapperCGF.CapturedStmtInfo = CapturedStmtInfo;
619 llvm::Function *WrapperF =
620 emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes,
621 WrapperCGF.CXXThisValue, WrapperFO);
622 llvm::SmallVector<llvm::Value *, 4> CallArgs;
623 for (const auto *Arg : Args) {
624 llvm::Value *CallArg;
625 auto I = LocalAddrs.find(Arg);
626 if (I != LocalAddrs.end()) {
627 LValue LV = WrapperCGF.MakeAddrLValue(
629 I->second.first ? I->second.first->getType() : Arg->getType(),
630 AlignmentSource::Decl);
631 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getBeginLoc());
633 auto EI = VLASizes.find(Arg);
634 if (EI != VLASizes.end()) {
635 CallArg = EI->second.second;
637 LValue LV = WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg),
639 AlignmentSource::Decl);
640 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getBeginLoc());
643 CallArgs.emplace_back(WrapperCGF.EmitFromMemory(CallArg, Arg->getType()));
645 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, Loc, F, CallArgs);
646 WrapperCGF.FinishFunction();
650 //===----------------------------------------------------------------------===//
651 // OpenMP Directive Emission
652 //===----------------------------------------------------------------------===//
653 void CodeGenFunction::EmitOMPAggregateAssign(
654 Address DestAddr, Address SrcAddr, QualType OriginalType,
655 const llvm::function_ref<void(Address, Address)> CopyGen) {
656 // Perform element-by-element initialization.
659 // Drill down to the base element type on both arrays.
660 const ArrayType *ArrayTy = OriginalType->getAsArrayTypeUnsafe();
661 llvm::Value *NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
662 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
664 llvm::Value *SrcBegin = SrcAddr.getPointer();
665 llvm::Value *DestBegin = DestAddr.getPointer();
666 // Cast from pointer to array type to pointer to single element.
667 llvm::Value *DestEnd = Builder.CreateGEP(DestBegin, NumElements);
668 // The basic structure here is a while-do loop.
669 llvm::BasicBlock *BodyBB = createBasicBlock("omp.arraycpy.body");
670 llvm::BasicBlock *DoneBB = createBasicBlock("omp.arraycpy.done");
671 llvm::Value *IsEmpty =
672 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
673 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
675 // Enter the loop body, making that address the current address.
676 llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
679 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
681 llvm::PHINode *SrcElementPHI =
682 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
683 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
684 Address SrcElementCurrent =
685 Address(SrcElementPHI,
686 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
688 llvm::PHINode *DestElementPHI =
689 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
690 DestElementPHI->addIncoming(DestBegin, EntryBB);
691 Address DestElementCurrent =
692 Address(DestElementPHI,
693 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
696 CopyGen(DestElementCurrent, SrcElementCurrent);
698 // Shift the address forward by one element.
699 llvm::Value *DestElementNext = Builder.CreateConstGEP1_32(
700 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
701 llvm::Value *SrcElementNext = Builder.CreateConstGEP1_32(
702 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
703 // Check whether we've reached the end.
705 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
706 Builder.CreateCondBr(Done, DoneBB, BodyBB);
707 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
708 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
711 EmitBlock(DoneBB, /*IsFinished=*/true);
714 void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
715 Address SrcAddr, const VarDecl *DestVD,
716 const VarDecl *SrcVD, const Expr *Copy) {
717 if (OriginalType->isArrayType()) {
718 const auto *BO = dyn_cast<BinaryOperator>(Copy);
719 if (BO && BO->getOpcode() == BO_Assign) {
720 // Perform simple memcpy for simple copying.
721 LValue Dest = MakeAddrLValue(DestAddr, OriginalType);
722 LValue Src = MakeAddrLValue(SrcAddr, OriginalType);
723 EmitAggregateAssign(Dest, Src, OriginalType);
725 // For arrays with complex element types perform element by element
727 EmitOMPAggregateAssign(
728 DestAddr, SrcAddr, OriginalType,
729 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
730 // Working with the single array element, so have to remap
731 // destination and source variables to corresponding array
733 CodeGenFunction::OMPPrivateScope Remap(*this);
734 Remap.addPrivate(DestVD, [DestElement]() { return DestElement; });
735 Remap.addPrivate(SrcVD, [SrcElement]() { return SrcElement; });
736 (void)Remap.Privatize();
737 EmitIgnoredExpr(Copy);
741 // Remap pseudo source variable to private copy.
742 CodeGenFunction::OMPPrivateScope Remap(*this);
743 Remap.addPrivate(SrcVD, [SrcAddr]() { return SrcAddr; });
744 Remap.addPrivate(DestVD, [DestAddr]() { return DestAddr; });
745 (void)Remap.Privatize();
746 // Emit copying of the whole variable.
747 EmitIgnoredExpr(Copy);
751 bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
752 OMPPrivateScope &PrivateScope) {
753 if (!HaveInsertPoint())
755 bool DeviceConstTarget =
756 getLangOpts().OpenMPIsDevice &&
757 isOpenMPTargetExecutionDirective(D.getDirectiveKind());
758 bool FirstprivateIsLastprivate = false;
759 llvm::DenseMap<const VarDecl *, OpenMPLastprivateModifier> Lastprivates;
760 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
761 for (const auto *D : C->varlists())
762 Lastprivates.try_emplace(
763 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl(),
766 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
767 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
768 getOpenMPCaptureRegions(CaptureRegions, D.getDirectiveKind());
769 // Force emission of the firstprivate copy if the directive does not emit
770 // outlined function, like omp for, omp simd, omp distribute etc.
771 bool MustEmitFirstprivateCopy =
772 CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown;
773 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
774 const auto *IRef = C->varlist_begin();
775 const auto *InitsRef = C->inits().begin();
776 for (const Expr *IInit : C->private_copies()) {
777 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
778 bool ThisFirstprivateIsLastprivate =
779 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
780 const FieldDecl *FD = CapturedStmtInfo->lookup(OrigVD);
781 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
782 if (!MustEmitFirstprivateCopy && !ThisFirstprivateIsLastprivate && FD &&
783 !FD->getType()->isReferenceType() &&
784 (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())) {
785 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
790 // Do not emit copy for firstprivate constant variables in target regions,
791 // captured by reference.
792 if (DeviceConstTarget && OrigVD->getType().isConstant(getContext()) &&
793 FD && FD->getType()->isReferenceType() &&
794 (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())) {
795 (void)CGM.getOpenMPRuntime().registerTargetFirstprivateCopy(*this,
801 FirstprivateIsLastprivate =
802 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
803 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
805 cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
807 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
808 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
809 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
812 // Check if the firstprivate variable is just a constant value.
813 ConstantEmission CE = tryEmitAsConstant(&DRE);
814 if (CE && !CE.isReference()) {
815 // Constant value, no need to create a copy.
820 if (CE && CE.isReference()) {
821 OriginalLVal = CE.getReferenceLValue(*this, &DRE);
823 assert(!CE && "Expected non-constant firstprivate.");
824 OriginalLVal = EmitLValue(&DRE);
827 OriginalLVal = EmitLValue(&DRE);
829 QualType Type = VD->getType();
830 if (Type->isArrayType()) {
831 // Emit VarDecl with copy init for arrays.
832 // Get the address of the original variable captured in current
834 IsRegistered = PrivateScope.addPrivate(
835 OrigVD, [this, VD, Type, OriginalLVal, VDInit]() {
836 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
837 const Expr *Init = VD->getInit();
838 if (!isa<CXXConstructExpr>(Init) ||
839 isTrivialInitializer(Init)) {
840 // Perform simple memcpy.
842 MakeAddrLValue(Emission.getAllocatedAddress(), Type);
843 EmitAggregateAssign(Dest, OriginalLVal, Type);
845 EmitOMPAggregateAssign(
846 Emission.getAllocatedAddress(),
847 OriginalLVal.getAddress(*this), Type,
848 [this, VDInit, Init](Address DestElement,
849 Address SrcElement) {
850 // Clean up any temporaries needed by the
852 RunCleanupsScope InitScope(*this);
853 // Emit initialization for single element.
854 setAddrOfLocalVar(VDInit, SrcElement);
855 EmitAnyExprToMem(Init, DestElement,
856 Init->getType().getQualifiers(),
857 /*IsInitializer*/ false);
858 LocalDeclMap.erase(VDInit);
861 EmitAutoVarCleanups(Emission);
862 return Emission.getAllocatedAddress();
865 Address OriginalAddr = OriginalLVal.getAddress(*this);
867 PrivateScope.addPrivate(OrigVD, [this, VDInit, OriginalAddr, VD,
868 ThisFirstprivateIsLastprivate,
869 OrigVD, &Lastprivates, IRef]() {
870 // Emit private VarDecl with copy init.
871 // Remap temp VDInit variable to the address of the original
872 // variable (for proper handling of captured global variables).
873 setAddrOfLocalVar(VDInit, OriginalAddr);
875 LocalDeclMap.erase(VDInit);
876 if (ThisFirstprivateIsLastprivate &&
877 Lastprivates[OrigVD->getCanonicalDecl()] ==
878 OMPC_LASTPRIVATE_conditional) {
879 // Create/init special variable for lastprivate conditionals.
881 CGM.getOpenMPRuntime().emitLastprivateConditionalInit(
883 llvm::Value *V = EmitLoadOfScalar(
884 MakeAddrLValue(GetAddrOfLocalVar(VD), (*IRef)->getType(),
885 AlignmentSource::Decl),
886 (*IRef)->getExprLoc());
888 MakeAddrLValue(VDAddr, (*IRef)->getType(),
889 AlignmentSource::Decl));
890 LocalDeclMap.erase(VD);
891 setAddrOfLocalVar(VD, VDAddr);
894 return GetAddrOfLocalVar(VD);
897 assert(IsRegistered &&
898 "firstprivate var already registered as private");
899 // Silence the warning about unused variable.
906 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
909 void CodeGenFunction::EmitOMPPrivateClause(
910 const OMPExecutableDirective &D,
911 CodeGenFunction::OMPPrivateScope &PrivateScope) {
912 if (!HaveInsertPoint())
914 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
915 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
916 auto IRef = C->varlist_begin();
917 for (const Expr *IInit : C->private_copies()) {
918 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
919 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
920 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
921 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, VD]() {
922 // Emit private VarDecl with copy init.
924 return GetAddrOfLocalVar(VD);
926 assert(IsRegistered && "private var already registered as private");
927 // Silence the warning about unused variable.
935 bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
936 if (!HaveInsertPoint())
938 // threadprivate_var1 = master_threadprivate_var1;
939 // operator=(threadprivate_var2, master_threadprivate_var2);
941 // __kmpc_barrier(&loc, global_tid);
942 llvm::DenseSet<const VarDecl *> CopiedVars;
943 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
944 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
945 auto IRef = C->varlist_begin();
946 auto ISrcRef = C->source_exprs().begin();
947 auto IDestRef = C->destination_exprs().begin();
948 for (const Expr *AssignOp : C->assignment_ops()) {
949 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
950 QualType Type = VD->getType();
951 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
952 // Get the address of the master variable. If we are emitting code with
953 // TLS support, the address is passed from the master as field in the
954 // captured declaration.
955 Address MasterAddr = Address::invalid();
956 if (getLangOpts().OpenMPUseTLS &&
957 getContext().getTargetInfo().isTLSSupported()) {
958 assert(CapturedStmtInfo->lookup(VD) &&
959 "Copyin threadprivates should have been captured!");
960 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(VD), true,
961 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
962 MasterAddr = EmitLValue(&DRE).getAddress(*this);
963 LocalDeclMap.erase(VD);
966 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
967 : CGM.GetAddrOfGlobal(VD),
968 getContext().getDeclAlign(VD));
970 // Get the address of the threadprivate variable.
971 Address PrivateAddr = EmitLValue(*IRef).getAddress(*this);
972 if (CopiedVars.size() == 1) {
973 // At first check if current thread is a master thread. If it is, no
974 // need to copy data.
975 CopyBegin = createBasicBlock("copyin.not.master");
976 CopyEnd = createBasicBlock("copyin.not.master.end");
977 Builder.CreateCondBr(
978 Builder.CreateICmpNE(
979 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
980 Builder.CreatePtrToInt(PrivateAddr.getPointer(),
983 EmitBlock(CopyBegin);
986 cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
988 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
989 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
997 // Exit out of copying procedure for non-master thread.
998 EmitBlock(CopyEnd, /*IsFinished=*/true);
1004 bool CodeGenFunction::EmitOMPLastprivateClauseInit(
1005 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
1006 if (!HaveInsertPoint())
1008 bool HasAtLeastOneLastprivate = false;
1009 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1010 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
1011 const auto *LoopDirective = cast<OMPLoopDirective>(&D);
1012 for (const Expr *C : LoopDirective->counters()) {
1014 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1017 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
1018 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
1019 HasAtLeastOneLastprivate = true;
1020 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
1021 !getLangOpts().OpenMPSimd)
1023 const auto *IRef = C->varlist_begin();
1024 const auto *IDestRef = C->destination_exprs().begin();
1025 for (const Expr *IInit : C->private_copies()) {
1026 // Keep the address of the original variable for future update at the end
1028 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1029 // Taskloops do not require additional initialization, it is done in
1030 // runtime support library.
1031 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
1032 const auto *DestVD =
1033 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
1034 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() {
1035 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
1036 /*RefersToEnclosingVariableOrCapture=*/
1037 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1038 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
1039 return EmitLValue(&DRE).getAddress(*this);
1041 // Check if the variable is also a firstprivate: in this case IInit is
1042 // not generated. Initialization of this variable will happen in codegen
1043 // for 'firstprivate' clause.
1044 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
1045 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
1046 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, VD, C,
1048 if (C->getKind() == OMPC_LASTPRIVATE_conditional) {
1050 CGM.getOpenMPRuntime().emitLastprivateConditionalInit(*this,
1052 setAddrOfLocalVar(VD, VDAddr);
1055 // Emit private VarDecl with copy init.
1057 return GetAddrOfLocalVar(VD);
1059 assert(IsRegistered &&
1060 "lastprivate var already registered as private");
1068 return HasAtLeastOneLastprivate;
1071 void CodeGenFunction::EmitOMPLastprivateClauseFinal(
1072 const OMPExecutableDirective &D, bool NoFinals,
1073 llvm::Value *IsLastIterCond) {
1074 if (!HaveInsertPoint())
1076 // Emit following code:
1077 // if (<IsLastIterCond>) {
1078 // orig_var1 = private_orig_var1;
1080 // orig_varn = private_orig_varn;
1082 llvm::BasicBlock *ThenBB = nullptr;
1083 llvm::BasicBlock *DoneBB = nullptr;
1084 if (IsLastIterCond) {
1085 // Emit implicit barrier if at least one lastprivate conditional is found
1086 // and this is not a simd mode.
1087 if (!getLangOpts().OpenMPSimd &&
1088 llvm::any_of(D.getClausesOfKind<OMPLastprivateClause>(),
1089 [](const OMPLastprivateClause *C) {
1090 return C->getKind() == OMPC_LASTPRIVATE_conditional;
1092 CGM.getOpenMPRuntime().emitBarrierCall(*this, D.getBeginLoc(),
1094 /*EmitChecks=*/false,
1095 /*ForceSimpleCall=*/true);
1097 ThenBB = createBasicBlock(".omp.lastprivate.then");
1098 DoneBB = createBasicBlock(".omp.lastprivate.done");
1099 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
1102 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
1103 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
1104 if (const auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
1105 auto IC = LoopDirective->counters().begin();
1106 for (const Expr *F : LoopDirective->finals()) {
1108 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
1110 AlreadyEmittedVars.insert(D);
1112 LoopCountersAndUpdates[D] = F;
1116 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
1117 auto IRef = C->varlist_begin();
1118 auto ISrcRef = C->source_exprs().begin();
1119 auto IDestRef = C->destination_exprs().begin();
1120 for (const Expr *AssignOp : C->assignment_ops()) {
1121 const auto *PrivateVD =
1122 cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1123 QualType Type = PrivateVD->getType();
1124 const auto *CanonicalVD = PrivateVD->getCanonicalDecl();
1125 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
1126 // If lastprivate variable is a loop control variable for loop-based
1127 // directive, update its value before copyin back to original
1129 if (const Expr *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
1130 EmitIgnoredExpr(FinalExpr);
1132 cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
1133 const auto *DestVD =
1134 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
1135 // Get the address of the private variable.
1136 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
1137 if (const auto *RefTy = PrivateVD->getType()->getAs<ReferenceType>())
1139 Address(Builder.CreateLoad(PrivateAddr),
1140 getNaturalTypeAlignment(RefTy->getPointeeType()));
1141 // Store the last value to the private copy in the last iteration.
1142 if (C->getKind() == OMPC_LASTPRIVATE_conditional)
1143 CGM.getOpenMPRuntime().emitLastprivateConditionalFinalUpdate(
1144 *this, MakeAddrLValue(PrivateAddr, (*IRef)->getType()), PrivateVD,
1145 (*IRef)->getExprLoc());
1146 // Get the address of the original variable.
1147 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
1148 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
1154 if (const Expr *PostUpdate = C->getPostUpdateExpr())
1155 EmitIgnoredExpr(PostUpdate);
1158 EmitBlock(DoneBB, /*IsFinished=*/true);
1161 void CodeGenFunction::EmitOMPReductionClauseInit(
1162 const OMPExecutableDirective &D,
1163 CodeGenFunction::OMPPrivateScope &PrivateScope) {
1164 if (!HaveInsertPoint())
1166 SmallVector<const Expr *, 4> Shareds;
1167 SmallVector<const Expr *, 4> Privates;
1168 SmallVector<const Expr *, 4> ReductionOps;
1169 SmallVector<const Expr *, 4> LHSs;
1170 SmallVector<const Expr *, 4> RHSs;
1171 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1172 auto IPriv = C->privates().begin();
1173 auto IRed = C->reduction_ops().begin();
1174 auto ILHS = C->lhs_exprs().begin();
1175 auto IRHS = C->rhs_exprs().begin();
1176 for (const Expr *Ref : C->varlists()) {
1177 Shareds.emplace_back(Ref);
1178 Privates.emplace_back(*IPriv);
1179 ReductionOps.emplace_back(*IRed);
1180 LHSs.emplace_back(*ILHS);
1181 RHSs.emplace_back(*IRHS);
1182 std::advance(IPriv, 1);
1183 std::advance(IRed, 1);
1184 std::advance(ILHS, 1);
1185 std::advance(IRHS, 1);
1188 ReductionCodeGen RedCG(Shareds, Privates, ReductionOps);
1190 auto ILHS = LHSs.begin();
1191 auto IRHS = RHSs.begin();
1192 auto IPriv = Privates.begin();
1193 for (const Expr *IRef : Shareds) {
1194 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
1195 // Emit private VarDecl with reduction init.
1196 RedCG.emitSharedLValue(*this, Count);
1197 RedCG.emitAggregateType(*this, Count);
1198 AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
1199 RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(),
1200 RedCG.getSharedLValue(Count),
1201 [&Emission](CodeGenFunction &CGF) {
1202 CGF.EmitAutoVarInit(Emission);
1205 EmitAutoVarCleanups(Emission);
1206 Address BaseAddr = RedCG.adjustPrivateAddress(
1207 *this, Count, Emission.getAllocatedAddress());
1208 bool IsRegistered = PrivateScope.addPrivate(
1209 RedCG.getBaseDecl(Count), [BaseAddr]() { return BaseAddr; });
1210 assert(IsRegistered && "private var already registered as private");
1211 // Silence the warning about unused variable.
1214 const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
1215 const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
1216 QualType Type = PrivateVD->getType();
1217 bool isaOMPArraySectionExpr = isa<OMPArraySectionExpr>(IRef);
1218 if (isaOMPArraySectionExpr && Type->isVariablyModifiedType()) {
1219 // Store the address of the original variable associated with the LHS
1220 // implicit variable.
1221 PrivateScope.addPrivate(LHSVD, [&RedCG, Count, this]() {
1222 return RedCG.getSharedLValue(Count).getAddress(*this);
1224 PrivateScope.addPrivate(
1225 RHSVD, [this, PrivateVD]() { return GetAddrOfLocalVar(PrivateVD); });
1226 } else if ((isaOMPArraySectionExpr && Type->isScalarType()) ||
1227 isa<ArraySubscriptExpr>(IRef)) {
1228 // Store the address of the original variable associated with the LHS
1229 // implicit variable.
1230 PrivateScope.addPrivate(LHSVD, [&RedCG, Count, this]() {
1231 return RedCG.getSharedLValue(Count).getAddress(*this);
1233 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() {
1234 return Builder.CreateElementBitCast(GetAddrOfLocalVar(PrivateVD),
1235 ConvertTypeForMem(RHSVD->getType()),
1239 QualType Type = PrivateVD->getType();
1240 bool IsArray = getContext().getAsArrayType(Type) != nullptr;
1241 Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress(*this);
1242 // Store the address of the original variable associated with the LHS
1243 // implicit variable.
1245 OriginalAddr = Builder.CreateElementBitCast(
1246 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
1248 PrivateScope.addPrivate(LHSVD, [OriginalAddr]() { return OriginalAddr; });
1249 PrivateScope.addPrivate(
1250 RHSVD, [this, PrivateVD, RHSVD, IsArray]() {
1252 ? Builder.CreateElementBitCast(
1253 GetAddrOfLocalVar(PrivateVD),
1254 ConvertTypeForMem(RHSVD->getType()), "rhs.begin")
1255 : GetAddrOfLocalVar(PrivateVD);
1265 void CodeGenFunction::EmitOMPReductionClauseFinal(
1266 const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
1267 if (!HaveInsertPoint())
1269 llvm::SmallVector<const Expr *, 8> Privates;
1270 llvm::SmallVector<const Expr *, 8> LHSExprs;
1271 llvm::SmallVector<const Expr *, 8> RHSExprs;
1272 llvm::SmallVector<const Expr *, 8> ReductionOps;
1273 bool HasAtLeastOneReduction = false;
1274 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1275 HasAtLeastOneReduction = true;
1276 Privates.append(C->privates().begin(), C->privates().end());
1277 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1278 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1279 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1281 if (HasAtLeastOneReduction) {
1282 bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
1283 isOpenMPParallelDirective(D.getDirectiveKind()) ||
1284 ReductionKind == OMPD_simd;
1285 bool SimpleReduction = ReductionKind == OMPD_simd;
1286 // Emit nowait reduction if nowait clause is present or directive is a
1287 // parallel directive (it always has implicit barrier).
1288 CGM.getOpenMPRuntime().emitReduction(
1289 *this, D.getEndLoc(), Privates, LHSExprs, RHSExprs, ReductionOps,
1290 {WithNowait, SimpleReduction, ReductionKind});
1294 static void emitPostUpdateForReductionClause(
1295 CodeGenFunction &CGF, const OMPExecutableDirective &D,
1296 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
1297 if (!CGF.HaveInsertPoint())
1299 llvm::BasicBlock *DoneBB = nullptr;
1300 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1301 if (const Expr *PostUpdate = C->getPostUpdateExpr()) {
1303 if (llvm::Value *Cond = CondGen(CGF)) {
1304 // If the first post-update expression is found, emit conditional
1305 // block if it was requested.
1306 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
1307 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1308 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1309 CGF.EmitBlock(ThenBB);
1312 CGF.EmitIgnoredExpr(PostUpdate);
1316 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1320 /// Codegen lambda for appending distribute lower and upper bounds to outlined
1321 /// parallel function. This is necessary for combined constructs such as
1322 /// 'distribute parallel for'
1323 typedef llvm::function_ref<void(CodeGenFunction &,
1324 const OMPExecutableDirective &,
1325 llvm::SmallVectorImpl<llvm::Value *> &)>
1326 CodeGenBoundParametersTy;
1327 } // anonymous namespace
1330 checkForLastprivateConditionalUpdate(CodeGenFunction &CGF,
1331 const OMPExecutableDirective &S) {
1332 if (CGF.getLangOpts().OpenMP < 50)
1334 llvm::DenseSet<CanonicalDeclPtr<const VarDecl>> PrivateDecls;
1335 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
1336 for (const Expr *Ref : C->varlists()) {
1337 if (!Ref->getType()->isScalarType())
1339 const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts());
1342 PrivateDecls.insert(cast<VarDecl>(DRE->getDecl()));
1343 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, Ref);
1346 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
1347 for (const Expr *Ref : C->varlists()) {
1348 if (!Ref->getType()->isScalarType())
1350 const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts());
1353 PrivateDecls.insert(cast<VarDecl>(DRE->getDecl()));
1354 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, Ref);
1357 for (const auto *C : S.getClausesOfKind<OMPLinearClause>()) {
1358 for (const Expr *Ref : C->varlists()) {
1359 if (!Ref->getType()->isScalarType())
1361 const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts());
1364 PrivateDecls.insert(cast<VarDecl>(DRE->getDecl()));
1365 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, Ref);
1368 // Privates should ne analyzed since they are not captured at all.
1369 // Task reductions may be skipped - tasks are ignored.
1370 // Firstprivates do not return value but may be passed by reference - no need
1371 // to check for updated lastprivate conditional.
1372 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
1373 for (const Expr *Ref : C->varlists()) {
1374 if (!Ref->getType()->isScalarType())
1376 const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts());
1379 PrivateDecls.insert(cast<VarDecl>(DRE->getDecl()));
1382 CGF.CGM.getOpenMPRuntime().checkAndEmitSharedLastprivateConditional(
1383 CGF, S, PrivateDecls);
1386 static void emitCommonOMPParallelDirective(
1387 CodeGenFunction &CGF, const OMPExecutableDirective &S,
1388 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1389 const CodeGenBoundParametersTy &CodeGenBoundParameters) {
1390 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
1391 llvm::Function *OutlinedFn =
1392 CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
1393 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
1394 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
1395 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
1396 llvm::Value *NumThreads =
1397 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1398 /*IgnoreResultAssign=*/true);
1399 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
1400 CGF, NumThreads, NumThreadsClause->getBeginLoc());
1402 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
1403 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
1404 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
1405 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getBeginLoc());
1407 const Expr *IfCond = nullptr;
1408 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1409 if (C->getNameModifier() == OMPD_unknown ||
1410 C->getNameModifier() == OMPD_parallel) {
1411 IfCond = C->getCondition();
1416 OMPParallelScope Scope(CGF, S);
1417 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
1418 // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk
1419 // lower and upper bounds with the pragma 'for' chunking mechanism.
1420 // The following lambda takes care of appending the lower and upper bound
1421 // parameters when necessary
1422 CodeGenBoundParameters(CGF, S, CapturedVars);
1423 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
1424 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getBeginLoc(), OutlinedFn,
1425 CapturedVars, IfCond);
1428 static void emitEmptyBoundParameters(CodeGenFunction &,
1429 const OMPExecutableDirective &,
1430 llvm::SmallVectorImpl<llvm::Value *> &) {}
1432 void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
1433 if (llvm::OpenMPIRBuilder *OMPBuilder = CGM.getOpenMPIRBuilder()) {
1434 // Check if we have any if clause associated with the directive.
1435 llvm::Value *IfCond = nullptr;
1436 if (const auto *C = S.getSingleClause<OMPIfClause>())
1437 IfCond = EmitScalarExpr(C->getCondition(),
1438 /*IgnoreResultAssign=*/true);
1440 llvm::Value *NumThreads = nullptr;
1441 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>())
1442 NumThreads = EmitScalarExpr(NumThreadsClause->getNumThreads(),
1443 /*IgnoreResultAssign=*/true);
1445 ProcBindKind ProcBind = OMP_PROC_BIND_default;
1446 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>())
1447 ProcBind = ProcBindClause->getProcBindKind();
1449 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
1451 // The cleanup callback that finalizes all variabels at the given location,
1452 // thus calls destructors etc.
1453 auto FiniCB = [this](InsertPointTy IP) {
1454 OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP);
1457 // Privatization callback that performs appropriate action for
1458 // shared/private/firstprivate/lastprivate/copyin/... variables.
1460 // TODO: This defaults to shared right now.
1461 auto PrivCB = [](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
1462 llvm::Value &Val, llvm::Value *&ReplVal) {
1463 // The next line is appropriate only for variables (Val) with the
1464 // data-sharing attribute "shared".
1470 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
1471 const Stmt *ParallelRegionBodyStmt = CS->getCapturedStmt();
1473 auto BodyGenCB = [ParallelRegionBodyStmt,
1474 this](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
1475 llvm::BasicBlock &ContinuationBB) {
1476 OMPBuilderCBHelpers::OutlinedRegionBodyRAII ORB(*this, AllocaIP,
1478 OMPBuilderCBHelpers::EmitOMPRegionBody(*this, ParallelRegionBodyStmt,
1479 CodeGenIP, ContinuationBB);
1482 CGCapturedStmtInfo CGSI(*CS, CR_OpenMP);
1483 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(*this, &CGSI);
1484 Builder.restoreIP(OMPBuilder->CreateParallel(Builder, BodyGenCB, PrivCB,
1485 FiniCB, IfCond, NumThreads,
1486 ProcBind, S.hasCancel()));
1490 // Emit parallel region as a standalone region.
1491 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
1493 OMPPrivateScope PrivateScope(CGF);
1494 bool Copyins = CGF.EmitOMPCopyinClause(S);
1495 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1497 // Emit implicit barrier to synchronize threads and avoid data races on
1498 // propagation master's thread values of threadprivate variables to local
1499 // instances of that variables of all other implicit threads.
1500 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1501 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
1502 /*ForceSimpleCall=*/true);
1504 CGF.EmitOMPPrivateClause(S, PrivateScope);
1505 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1506 (void)PrivateScope.Privatize();
1507 CGF.EmitStmt(S.getCapturedStmt(OMPD_parallel)->getCapturedStmt());
1508 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
1512 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
1513 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen,
1514 emitEmptyBoundParameters);
1515 emitPostUpdateForReductionClause(*this, S,
1516 [](CodeGenFunction &) { return nullptr; });
1518 // Check for outer lastprivate conditional update.
1519 checkForLastprivateConditionalUpdate(*this, S);
1522 static void emitBody(CodeGenFunction &CGF, const Stmt *S, const Stmt *NextLoop,
1523 int MaxLevel, int Level = 0) {
1524 assert(Level < MaxLevel && "Too deep lookup during loop body codegen.");
1525 const Stmt *SimplifiedS = S->IgnoreContainers();
1526 if (const auto *CS = dyn_cast<CompoundStmt>(SimplifiedS)) {
1527 PrettyStackTraceLoc CrashInfo(
1528 CGF.getContext().getSourceManager(), CS->getLBracLoc(),
1529 "LLVM IR generation of compound statement ('{}')");
1531 // Keep track of the current cleanup stack depth, including debug scopes.
1532 CodeGenFunction::LexicalScope Scope(CGF, S->getSourceRange());
1533 for (const Stmt *CurStmt : CS->body())
1534 emitBody(CGF, CurStmt, NextLoop, MaxLevel, Level);
1537 if (SimplifiedS == NextLoop) {
1538 if (const auto *For = dyn_cast<ForStmt>(SimplifiedS)) {
1541 assert(isa<CXXForRangeStmt>(SimplifiedS) &&
1542 "Expected canonical for loop or range-based for loop.");
1543 const auto *CXXFor = cast<CXXForRangeStmt>(SimplifiedS);
1544 CGF.EmitStmt(CXXFor->getLoopVarStmt());
1545 S = CXXFor->getBody();
1547 if (Level + 1 < MaxLevel) {
1548 NextLoop = OMPLoopDirective::tryToFindNextInnerLoop(
1549 S, /*TryImperfectlyNestedLoops=*/true);
1550 emitBody(CGF, S, NextLoop, MaxLevel, Level + 1);
1557 void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1558 JumpDest LoopExit) {
1559 RunCleanupsScope BodyScope(*this);
1560 // Update counters values on current iteration.
1561 for (const Expr *UE : D.updates())
1562 EmitIgnoredExpr(UE);
1563 // Update the linear variables.
1564 // In distribute directives only loop counters may be marked as linear, no
1565 // need to generate the code for them.
1566 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
1567 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
1568 for (const Expr *UE : C->updates())
1569 EmitIgnoredExpr(UE);
1573 // On a continue in the body, jump to the end.
1574 JumpDest Continue = getJumpDestInCurrentScope("omp.body.continue");
1575 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1576 for (const Expr *E : D.finals_conditions()) {
1579 // Check that loop counter in non-rectangular nest fits into the iteration
1581 llvm::BasicBlock *NextBB = createBasicBlock("omp.body.next");
1582 EmitBranchOnBoolExpr(E, NextBB, Continue.getBlock(),
1583 getProfileCount(D.getBody()));
1586 // Emit loop variables for C++ range loops.
1588 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers();
1590 emitBody(*this, Body,
1591 OMPLoopDirective::tryToFindNextInnerLoop(
1592 Body, /*TryImperfectlyNestedLoops=*/true),
1593 D.getCollapsedNumber());
1595 // The end (updates/cleanups).
1596 EmitBlock(Continue.getBlock());
1597 BreakContinueStack.pop_back();
1600 void CodeGenFunction::EmitOMPInnerLoop(
1601 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1602 const Expr *IncExpr,
1603 const llvm::function_ref<void(CodeGenFunction &)> BodyGen,
1604 const llvm::function_ref<void(CodeGenFunction &)> PostIncGen) {
1605 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
1607 // Start the loop with a block that tests the condition.
1608 auto CondBlock = createBasicBlock("omp.inner.for.cond");
1609 EmitBlock(CondBlock);
1610 const SourceRange R = S.getSourceRange();
1611 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1612 SourceLocToDebugLoc(R.getEnd()));
1614 // If there are any cleanups between here and the loop-exit scope,
1615 // create a block to stage a loop exit along.
1616 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
1617 if (RequiresCleanup)
1618 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
1620 llvm::BasicBlock *LoopBody = createBasicBlock("omp.inner.for.body");
1623 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
1624 if (ExitBlock != LoopExit.getBlock()) {
1625 EmitBlock(ExitBlock);
1626 EmitBranchThroughCleanup(LoopExit);
1629 EmitBlock(LoopBody);
1630 incrementProfileCounter(&S);
1632 // Create a block for the increment.
1633 JumpDest Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
1634 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1638 // Emit "IV = IV + 1" and a back-edge to the condition block.
1639 EmitBlock(Continue.getBlock());
1640 EmitIgnoredExpr(IncExpr);
1642 BreakContinueStack.pop_back();
1643 EmitBranch(CondBlock);
1645 // Emit the fall-through block.
1646 EmitBlock(LoopExit.getBlock());
1649 bool CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
1650 if (!HaveInsertPoint())
1652 // Emit inits for the linear variables.
1653 bool HasLinears = false;
1654 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
1655 for (const Expr *Init : C->inits()) {
1657 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
1658 if (const auto *Ref =
1659 dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
1660 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1661 const auto *OrigVD = cast<VarDecl>(Ref->getDecl());
1662 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
1663 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1664 VD->getInit()->getType(), VK_LValue,
1665 VD->getInit()->getExprLoc());
1666 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1668 /*capturedByInit=*/false);
1669 EmitAutoVarCleanups(Emission);
1674 // Emit the linear steps for the linear clauses.
1675 // If a step is not constant, it is pre-calculated before the loop.
1676 if (const auto *CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1677 if (const auto *SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
1678 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
1679 // Emit calculation of the linear step.
1680 EmitIgnoredExpr(CS);
1686 void CodeGenFunction::EmitOMPLinearClauseFinal(
1687 const OMPLoopDirective &D,
1688 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
1689 if (!HaveInsertPoint())
1691 llvm::BasicBlock *DoneBB = nullptr;
1692 // Emit the final values of the linear variables.
1693 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
1694 auto IC = C->varlist_begin();
1695 for (const Expr *F : C->finals()) {
1697 if (llvm::Value *Cond = CondGen(*this)) {
1698 // If the first post-update expression is found, emit conditional
1699 // block if it was requested.
1700 llvm::BasicBlock *ThenBB = createBasicBlock(".omp.linear.pu");
1701 DoneBB = createBasicBlock(".omp.linear.pu.done");
1702 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1706 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1707 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
1708 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1709 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
1710 Address OrigAddr = EmitLValue(&DRE).getAddress(*this);
1711 CodeGenFunction::OMPPrivateScope VarScope(*this);
1712 VarScope.addPrivate(OrigVD, [OrigAddr]() { return OrigAddr; });
1713 (void)VarScope.Privatize();
1717 if (const Expr *PostUpdate = C->getPostUpdateExpr())
1718 EmitIgnoredExpr(PostUpdate);
1721 EmitBlock(DoneBB, /*IsFinished=*/true);
1724 static void emitAlignedClause(CodeGenFunction &CGF,
1725 const OMPExecutableDirective &D) {
1726 if (!CGF.HaveInsertPoint())
1728 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
1729 llvm::APInt ClauseAlignment(64, 0);
1730 if (const Expr *AlignmentExpr = Clause->getAlignment()) {
1732 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1733 ClauseAlignment = AlignmentCI->getValue();
1735 for (const Expr *E : Clause->varlists()) {
1736 llvm::APInt Alignment(ClauseAlignment);
1737 if (Alignment == 0) {
1738 // OpenMP [2.8.1, Description]
1739 // If no optional parameter is specified, implementation-defined default
1740 // alignments for SIMD instructions on the target platforms are assumed.
1743 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1744 E->getType()->getPointeeType()))
1747 assert((Alignment == 0 || Alignment.isPowerOf2()) &&
1748 "alignment is not power of 2");
1749 if (Alignment != 0) {
1750 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1751 CGF.emitAlignmentAssumption(
1752 PtrValue, E, /*No second loc needed*/ SourceLocation(),
1753 llvm::ConstantInt::get(CGF.getLLVMContext(), Alignment));
1759 void CodeGenFunction::EmitOMPPrivateLoopCounters(
1760 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1761 if (!HaveInsertPoint())
1763 auto I = S.private_counters().begin();
1764 for (const Expr *E : S.counters()) {
1765 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1766 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
1767 // Emit var without initialization.
1768 AutoVarEmission VarEmission = EmitAutoVarAlloca(*PrivateVD);
1769 EmitAutoVarCleanups(VarEmission);
1770 LocalDeclMap.erase(PrivateVD);
1771 (void)LoopScope.addPrivate(VD, [&VarEmission]() {
1772 return VarEmission.getAllocatedAddress();
1774 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1775 VD->hasGlobalStorage()) {
1776 (void)LoopScope.addPrivate(PrivateVD, [this, VD, E]() {
1777 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(VD),
1778 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1779 E->getType(), VK_LValue, E->getExprLoc());
1780 return EmitLValue(&DRE).getAddress(*this);
1783 (void)LoopScope.addPrivate(PrivateVD, [&VarEmission]() {
1784 return VarEmission.getAllocatedAddress();
1789 // Privatize extra loop counters used in loops for ordered(n) clauses.
1790 for (const auto *C : S.getClausesOfKind<OMPOrderedClause>()) {
1791 if (!C->getNumForLoops())
1793 for (unsigned I = S.getCollapsedNumber(),
1794 E = C->getLoopNumIterations().size();
1796 const auto *DRE = cast<DeclRefExpr>(C->getLoopCounter(I));
1797 const auto *VD = cast<VarDecl>(DRE->getDecl());
1798 // Override only those variables that can be captured to avoid re-emission
1799 // of the variables declared within the loops.
1800 if (DRE->refersToEnclosingVariableOrCapture()) {
1801 (void)LoopScope.addPrivate(VD, [this, DRE, VD]() {
1802 return CreateMemTemp(DRE->getType(), VD->getName());
1809 static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1810 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1811 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
1812 if (!CGF.HaveInsertPoint())
1815 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
1816 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
1817 (void)PreCondScope.Privatize();
1818 // Get initial values of real counters.
1819 for (const Expr *I : S.inits()) {
1820 CGF.EmitIgnoredExpr(I);
1823 // Create temp loop control variables with their init values to support
1824 // non-rectangular loops.
1825 CodeGenFunction::OMPMapVars PreCondVars;
1826 for (const Expr * E: S.dependent_counters()) {
1829 assert(!E->getType().getNonReferenceType()->isRecordType() &&
1830 "dependent counter must not be an iterator.");
1831 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1832 Address CounterAddr =
1833 CGF.CreateMemTemp(VD->getType().getNonReferenceType());
1834 (void)PreCondVars.setVarAddr(CGF, VD, CounterAddr);
1836 (void)PreCondVars.apply(CGF);
1837 for (const Expr *E : S.dependent_inits()) {
1840 CGF.EmitIgnoredExpr(E);
1842 // Check that loop is executed at least one time.
1843 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1844 PreCondVars.restore(CGF);
1847 void CodeGenFunction::EmitOMPLinearClause(
1848 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1849 if (!HaveInsertPoint())
1851 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1852 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
1853 const auto *LoopDirective = cast<OMPLoopDirective>(&D);
1854 for (const Expr *C : LoopDirective->counters()) {
1856 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1859 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
1860 auto CurPrivate = C->privates().begin();
1861 for (const Expr *E : C->varlists()) {
1862 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1863 const auto *PrivateVD =
1864 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
1865 if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
1866 bool IsRegistered = PrivateScope.addPrivate(VD, [this, PrivateVD]() {
1867 // Emit private VarDecl with copy init.
1868 EmitVarDecl(*PrivateVD);
1869 return GetAddrOfLocalVar(PrivateVD);
1871 assert(IsRegistered && "linear var already registered as private");
1872 // Silence the warning about unused variable.
1875 EmitVarDecl(*PrivateVD);
1882 static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
1883 const OMPExecutableDirective &D,
1885 if (!CGF.HaveInsertPoint())
1887 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
1888 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1889 /*ignoreResult=*/true);
1890 auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1891 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1892 // In presence of finite 'safelen', it may be unsafe to mark all
1893 // the memory instructions parallel, because loop-carried
1894 // dependences of 'safelen' iterations are possible.
1896 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
1897 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
1898 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1899 /*ignoreResult=*/true);
1900 auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1901 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1902 // In presence of finite 'safelen', it may be unsafe to mark all
1903 // the memory instructions parallel, because loop-carried
1904 // dependences of 'safelen' iterations are possible.
1905 CGF.LoopStack.setParallel(/*Enable=*/false);
1909 void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1911 // Walk clauses and process safelen/lastprivate.
1912 LoopStack.setParallel(!IsMonotonic);
1913 LoopStack.setVectorizeEnable();
1914 emitSimdlenSafelenClause(*this, D, IsMonotonic);
1915 if (const auto *C = D.getSingleClause<OMPOrderClause>())
1916 if (C->getKind() == OMPC_ORDER_concurrent)
1917 LoopStack.setParallel(/*Enable=*/true);
1920 void CodeGenFunction::EmitOMPSimdFinal(
1921 const OMPLoopDirective &D,
1922 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
1923 if (!HaveInsertPoint())
1925 llvm::BasicBlock *DoneBB = nullptr;
1926 auto IC = D.counters().begin();
1927 auto IPC = D.private_counters().begin();
1928 for (const Expr *F : D.finals()) {
1929 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
1930 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1931 const auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
1932 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1933 OrigVD->hasGlobalStorage() || CED) {
1935 if (llvm::Value *Cond = CondGen(*this)) {
1936 // If the first post-update expression is found, emit conditional
1937 // block if it was requested.
1938 llvm::BasicBlock *ThenBB = createBasicBlock(".omp.final.then");
1939 DoneBB = createBasicBlock(".omp.final.done");
1940 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1944 Address OrigAddr = Address::invalid();
1947 EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress(*this);
1949 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(PrivateVD),
1950 /*RefersToEnclosingVariableOrCapture=*/false,
1951 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
1952 OrigAddr = EmitLValue(&DRE).getAddress(*this);
1954 OMPPrivateScope VarScope(*this);
1955 VarScope.addPrivate(OrigVD, [OrigAddr]() { return OrigAddr; });
1956 (void)VarScope.Privatize();
1963 EmitBlock(DoneBB, /*IsFinished=*/true);
1966 static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF,
1967 const OMPLoopDirective &S,
1968 CodeGenFunction::JumpDest LoopExit) {
1969 CGF.EmitOMPLoopBody(S, LoopExit);
1970 CGF.EmitStopPoint(&S);
1973 /// Emit a helper variable and return corresponding lvalue.
1974 static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1975 const DeclRefExpr *Helper) {
1976 auto VDecl = cast<VarDecl>(Helper->getDecl());
1977 CGF.EmitVarDecl(*VDecl);
1978 return CGF.EmitLValue(Helper);
1981 static void emitCommonSimdLoop(CodeGenFunction &CGF, const OMPLoopDirective &S,
1982 const RegionCodeGenTy &SimdInitGen,
1983 const RegionCodeGenTy &BodyCodeGen) {
1984 auto &&ThenGen = [&S, &SimdInitGen, &BodyCodeGen](CodeGenFunction &CGF,
1985 PrePostActionTy &) {
1986 CGOpenMPRuntime::NontemporalDeclsRAII NontemporalsRegion(CGF.CGM, S);
1987 CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF);
1992 auto &&ElseGen = [&BodyCodeGen](CodeGenFunction &CGF, PrePostActionTy &) {
1993 CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF);
1994 CGF.LoopStack.setVectorizeEnable(/*Enable=*/false);
1998 const Expr *IfCond = nullptr;
1999 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
2000 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2001 if (CGF.getLangOpts().OpenMP >= 50 &&
2002 (C->getNameModifier() == OMPD_unknown ||
2003 C->getNameModifier() == OMPD_simd)) {
2004 IfCond = C->getCondition();
2010 CGF.CGM.getOpenMPRuntime().emitIfClause(CGF, IfCond, ThenGen, ElseGen);
2012 RegionCodeGenTy ThenRCG(ThenGen);
2017 static void emitOMPSimdRegion(CodeGenFunction &CGF, const OMPLoopDirective &S,
2018 PrePostActionTy &Action) {
2020 assert(isOpenMPSimdDirective(S.getDirectiveKind()) &&
2021 "Expected simd directive");
2022 OMPLoopScope PreInitScope(CGF, S);
2024 // for (IV in 0..LastIteration) BODY;
2025 // <Final counter/linear vars updates>;
2028 if (isOpenMPDistributeDirective(S.getDirectiveKind()) ||
2029 isOpenMPWorksharingDirective(S.getDirectiveKind()) ||
2030 isOpenMPTaskLoopDirective(S.getDirectiveKind())) {
2031 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()));
2032 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()));
2035 // Emit: if (PreCond) - begin.
2036 // If the condition constant folds and can be elided, avoid emitting the
2039 llvm::BasicBlock *ContBlock = nullptr;
2040 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2044 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("simd.if.then");
2045 ContBlock = CGF.createBasicBlock("simd.if.end");
2046 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
2047 CGF.getProfileCount(&S));
2048 CGF.EmitBlock(ThenBlock);
2049 CGF.incrementProfileCounter(&S);
2052 // Emit the loop iteration variable.
2053 const Expr *IVExpr = S.getIterationVariable();
2054 const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
2055 CGF.EmitVarDecl(*IVDecl);
2056 CGF.EmitIgnoredExpr(S.getInit());
2058 // Emit the iterations count variable.
2059 // If it is not a variable, Sema decided to calculate iterations count on
2060 // each iteration (e.g., it is foldable into a constant).
2061 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2062 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2063 // Emit calculation of the iterations count.
2064 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
2067 emitAlignedClause(CGF, S);
2068 (void)CGF.EmitOMPLinearClauseInit(S);
2070 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2071 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
2072 CGF.EmitOMPLinearClause(S, LoopScope);
2073 CGF.EmitOMPPrivateClause(S, LoopScope);
2074 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2075 CGOpenMPRuntime::LastprivateConditionalRAII LPCRegion(
2076 CGF, S, CGF.EmitLValue(S.getIterationVariable()));
2077 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2078 (void)LoopScope.Privatize();
2079 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
2080 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
2084 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2085 CGF.EmitOMPSimdInit(S);
2087 [&S, &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) {
2088 CGF.EmitOMPInnerLoop(
2089 S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
2090 [&S](CodeGenFunction &CGF) {
2091 CGF.EmitOMPLoopBody(S, CodeGenFunction::JumpDest());
2092 CGF.EmitStopPoint(&S);
2094 [](CodeGenFunction &) {});
2096 CGF.EmitOMPSimdFinal(S, [](CodeGenFunction &) { return nullptr; });
2097 // Emit final copy of the lastprivate variables at the end of loops.
2098 if (HasLastprivateClause)
2099 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
2100 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
2101 emitPostUpdateForReductionClause(CGF, S,
2102 [](CodeGenFunction &) { return nullptr; });
2104 CGF.EmitOMPLinearClauseFinal(S, [](CodeGenFunction &) { return nullptr; });
2105 // Emit: if (PreCond) - end.
2107 CGF.EmitBranch(ContBlock);
2108 CGF.EmitBlock(ContBlock, true);
2112 void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
2113 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2114 emitOMPSimdRegion(CGF, S, Action);
2118 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
2119 OMPLexicalScope Scope(*this, S, OMPD_unknown);
2120 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2122 // Check for outer lastprivate conditional update.
2123 checkForLastprivateConditionalUpdate(*this, S);
2126 void CodeGenFunction::EmitOMPOuterLoop(
2127 bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S,
2128 CodeGenFunction::OMPPrivateScope &LoopScope,
2129 const CodeGenFunction::OMPLoopArguments &LoopArgs,
2130 const CodeGenFunction::CodeGenLoopTy &CodeGenLoop,
2131 const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) {
2132 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
2134 const Expr *IVExpr = S.getIterationVariable();
2135 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2136 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2138 JumpDest LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
2140 // Start the loop with a block that tests the condition.
2141 llvm::BasicBlock *CondBlock = createBasicBlock("omp.dispatch.cond");
2142 EmitBlock(CondBlock);
2143 const SourceRange R = S.getSourceRange();
2144 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
2145 SourceLocToDebugLoc(R.getEnd()));
2147 llvm::Value *BoolCondVal = nullptr;
2148 if (!DynamicOrOrdered) {
2149 // UB = min(UB, GlobalUB) or
2150 // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g.
2151 // 'distribute parallel for')
2152 EmitIgnoredExpr(LoopArgs.EUB);
2154 EmitIgnoredExpr(LoopArgs.Init);
2156 BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond);
2159 RT.emitForNext(*this, S.getBeginLoc(), IVSize, IVSigned, LoopArgs.IL,
2160 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST);
2163 // If there are any cleanups between here and the loop-exit scope,
2164 // create a block to stage a loop exit along.
2165 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
2166 if (LoopScope.requiresCleanups())
2167 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
2169 llvm::BasicBlock *LoopBody = createBasicBlock("omp.dispatch.body");
2170 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
2171 if (ExitBlock != LoopExit.getBlock()) {
2172 EmitBlock(ExitBlock);
2173 EmitBranchThroughCleanup(LoopExit);
2175 EmitBlock(LoopBody);
2177 // Emit "IV = LB" (in case of static schedule, we have already calculated new
2178 // LB for loop condition and emitted it above).
2179 if (DynamicOrOrdered)
2180 EmitIgnoredExpr(LoopArgs.Init);
2182 // Create a block for the increment.
2183 JumpDest Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
2184 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
2188 [&S, IsMonotonic](CodeGenFunction &CGF, PrePostActionTy &) {
2189 // Generate !llvm.loop.parallel metadata for loads and stores for loops
2190 // with dynamic/guided scheduling and without ordered clause.
2191 if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
2192 CGF.LoopStack.setParallel(!IsMonotonic);
2193 if (const auto *C = S.getSingleClause<OMPOrderClause>())
2194 if (C->getKind() == OMPC_ORDER_concurrent)
2195 CGF.LoopStack.setParallel(/*Enable=*/true);
2197 CGF.EmitOMPSimdInit(S, IsMonotonic);
2200 [&S, &LoopArgs, LoopExit, &CodeGenLoop, IVSize, IVSigned, &CodeGenOrdered,
2201 &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) {
2202 SourceLocation Loc = S.getBeginLoc();
2203 // when 'distribute' is not combined with a 'for':
2204 // while (idx <= UB) { BODY; ++idx; }
2205 // when 'distribute' is combined with a 'for'
2206 // (e.g. 'distribute parallel for')
2207 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
2208 CGF.EmitOMPInnerLoop(
2209 S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr,
2210 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
2211 CodeGenLoop(CGF, S, LoopExit);
2213 [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) {
2214 CodeGenOrdered(CGF, Loc, IVSize, IVSigned);
2218 EmitBlock(Continue.getBlock());
2219 BreakContinueStack.pop_back();
2220 if (!DynamicOrOrdered) {
2221 // Emit "LB = LB + Stride", "UB = UB + Stride".
2222 EmitIgnoredExpr(LoopArgs.NextLB);
2223 EmitIgnoredExpr(LoopArgs.NextUB);
2226 EmitBranch(CondBlock);
2228 // Emit the fall-through block.
2229 EmitBlock(LoopExit.getBlock());
2231 // Tell the runtime we are done.
2232 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
2233 if (!DynamicOrOrdered)
2234 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
2235 S.getDirectiveKind());
2237 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
2240 void CodeGenFunction::EmitOMPForOuterLoop(
2241 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
2242 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
2243 const OMPLoopArguments &LoopArgs,
2244 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
2245 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
2247 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
2248 const bool DynamicOrOrdered =
2249 Ordered || RT.isDynamic(ScheduleKind.Schedule);
2252 !RT.isStaticNonchunked(ScheduleKind.Schedule,
2253 LoopArgs.Chunk != nullptr)) &&
2254 "static non-chunked schedule does not need outer loop");
2258 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2259 // When schedule(dynamic,chunk_size) is specified, the iterations are
2260 // distributed to threads in the team in chunks as the threads request them.
2261 // Each thread executes a chunk of iterations, then requests another chunk,
2262 // until no chunks remain to be distributed. Each chunk contains chunk_size
2263 // iterations, except for the last chunk to be distributed, which may have
2264 // fewer iterations. When no chunk_size is specified, it defaults to 1.
2266 // When schedule(guided,chunk_size) is specified, the iterations are assigned
2267 // to threads in the team in chunks as the executing threads request them.
2268 // Each thread executes a chunk of iterations, then requests another chunk,
2269 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
2270 // each chunk is proportional to the number of unassigned iterations divided
2271 // by the number of threads in the team, decreasing to 1. For a chunk_size
2272 // with value k (greater than 1), the size of each chunk is determined in the
2273 // same way, with the restriction that the chunks do not contain fewer than k
2274 // iterations (except for the last chunk to be assigned, which may have fewer
2275 // than k iterations).
2277 // When schedule(auto) is specified, the decision regarding scheduling is
2278 // delegated to the compiler and/or runtime system. The programmer gives the
2279 // implementation the freedom to choose any possible mapping of iterations to
2280 // threads in the team.
2282 // When schedule(runtime) is specified, the decision regarding scheduling is
2283 // deferred until run time, and the schedule and chunk size are taken from the
2284 // run-sched-var ICV. If the ICV is set to auto, the schedule is
2285 // implementation defined
2287 // while(__kmpc_dispatch_next(&LB, &UB)) {
2289 // while (idx <= UB) { BODY; ++idx;
2290 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
2294 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2295 // When schedule(static, chunk_size) is specified, iterations are divided into
2296 // chunks of size chunk_size, and the chunks are assigned to the threads in
2297 // the team in a round-robin fashion in the order of the thread number.
2299 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
2300 // while (idx <= UB) { BODY; ++idx; } // inner loop
2306 const Expr *IVExpr = S.getIterationVariable();
2307 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2308 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2310 if (DynamicOrOrdered) {
2311 const std::pair<llvm::Value *, llvm::Value *> DispatchBounds =
2312 CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB);
2313 llvm::Value *LBVal = DispatchBounds.first;
2314 llvm::Value *UBVal = DispatchBounds.second;
2315 CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal,
2317 RT.emitForDispatchInit(*this, S.getBeginLoc(), ScheduleKind, IVSize,
2318 IVSigned, Ordered, DipatchRTInputValues);
2320 CGOpenMPRuntime::StaticRTInput StaticInit(
2321 IVSize, IVSigned, Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB,
2322 LoopArgs.ST, LoopArgs.Chunk);
2323 RT.emitForStaticInit(*this, S.getBeginLoc(), S.getDirectiveKind(),
2324 ScheduleKind, StaticInit);
2327 auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc,
2328 const unsigned IVSize,
2329 const bool IVSigned) {
2331 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize,
2336 OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
2337 LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB);
2338 OuterLoopArgs.IncExpr = S.getInc();
2339 OuterLoopArgs.Init = S.getInit();
2340 OuterLoopArgs.Cond = S.getCond();
2341 OuterLoopArgs.NextLB = S.getNextLowerBound();
2342 OuterLoopArgs.NextUB = S.getNextUpperBound();
2343 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs,
2344 emitOMPLoopBodyWithStopPoint, CodeGenOrdered);
2347 static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc,
2348 const unsigned IVSize, const bool IVSigned) {}
2350 void CodeGenFunction::EmitOMPDistributeOuterLoop(
2351 OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S,
2352 OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs,
2353 const CodeGenLoopTy &CodeGenLoopContent) {
2355 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
2358 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
2362 const Expr *IVExpr = S.getIterationVariable();
2363 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2364 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2366 CGOpenMPRuntime::StaticRTInput StaticInit(
2367 IVSize, IVSigned, /* Ordered = */ false, LoopArgs.IL, LoopArgs.LB,
2368 LoopArgs.UB, LoopArgs.ST, LoopArgs.Chunk);
2369 RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind, StaticInit);
2371 // for combined 'distribute' and 'for' the increment expression of distribute
2372 // is stored in DistInc. For 'distribute' alone, it is in Inc.
2374 if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()))
2375 IncExpr = S.getDistInc();
2377 IncExpr = S.getInc();
2379 // this routine is shared by 'omp distribute parallel for' and
2380 // 'omp distribute': select the right EUB expression depending on the
2382 OMPLoopArguments OuterLoopArgs;
2383 OuterLoopArgs.LB = LoopArgs.LB;
2384 OuterLoopArgs.UB = LoopArgs.UB;
2385 OuterLoopArgs.ST = LoopArgs.ST;
2386 OuterLoopArgs.IL = LoopArgs.IL;
2387 OuterLoopArgs.Chunk = LoopArgs.Chunk;
2388 OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2389 ? S.getCombinedEnsureUpperBound()
2390 : S.getEnsureUpperBound();
2391 OuterLoopArgs.IncExpr = IncExpr;
2392 OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2393 ? S.getCombinedInit()
2395 OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2396 ? S.getCombinedCond()
2398 OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2399 ? S.getCombinedNextLowerBound()
2400 : S.getNextLowerBound();
2401 OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2402 ? S.getCombinedNextUpperBound()
2403 : S.getNextUpperBound();
2405 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S,
2406 LoopScope, OuterLoopArgs, CodeGenLoopContent,
2410 static std::pair<LValue, LValue>
2411 emitDistributeParallelForInnerBounds(CodeGenFunction &CGF,
2412 const OMPExecutableDirective &S) {
2413 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2415 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2417 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2419 // When composing 'distribute' with 'for' (e.g. as in 'distribute
2420 // parallel for') we need to use the 'distribute'
2421 // chunk lower and upper bounds rather than the whole loop iteration
2422 // space. These are parameters to the outlined function for 'parallel'
2423 // and we copy the bounds of the previous schedule into the
2424 // the current ones.
2425 LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable());
2426 LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable());
2427 llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar(
2428 PrevLB, LS.getPrevLowerBoundVariable()->getExprLoc());
2429 PrevLBVal = CGF.EmitScalarConversion(
2430 PrevLBVal, LS.getPrevLowerBoundVariable()->getType(),
2431 LS.getIterationVariable()->getType(),
2432 LS.getPrevLowerBoundVariable()->getExprLoc());
2433 llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar(
2434 PrevUB, LS.getPrevUpperBoundVariable()->getExprLoc());
2435 PrevUBVal = CGF.EmitScalarConversion(
2436 PrevUBVal, LS.getPrevUpperBoundVariable()->getType(),
2437 LS.getIterationVariable()->getType(),
2438 LS.getPrevUpperBoundVariable()->getExprLoc());
2440 CGF.EmitStoreOfScalar(PrevLBVal, LB);
2441 CGF.EmitStoreOfScalar(PrevUBVal, UB);
2446 /// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then
2447 /// we need to use the LB and UB expressions generated by the worksharing
2448 /// code generation support, whereas in non combined situations we would
2449 /// just emit 0 and the LastIteration expression
2450 /// This function is necessary due to the difference of the LB and UB
2451 /// types for the RT emission routines for 'for_static_init' and
2452 /// 'for_dispatch_init'
2453 static std::pair<llvm::Value *, llvm::Value *>
2454 emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF,
2455 const OMPExecutableDirective &S,
2456 Address LB, Address UB) {
2457 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2458 const Expr *IVExpr = LS.getIterationVariable();
2459 // when implementing a dynamic schedule for a 'for' combined with a
2460 // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop
2461 // is not normalized as each team only executes its own assigned
2463 QualType IteratorTy = IVExpr->getType();
2464 llvm::Value *LBVal =
2465 CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy, S.getBeginLoc());
2466 llvm::Value *UBVal =
2467 CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy, S.getBeginLoc());
2468 return {LBVal, UBVal};
2471 static void emitDistributeParallelForDistributeInnerBoundParams(
2472 CodeGenFunction &CGF, const OMPExecutableDirective &S,
2473 llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) {
2474 const auto &Dir = cast<OMPLoopDirective>(S);
2476 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable()));
2477 llvm::Value *LBCast =
2478 CGF.Builder.CreateIntCast(CGF.Builder.CreateLoad(LB.getAddress(CGF)),
2479 CGF.SizeTy, /*isSigned=*/false);
2480 CapturedVars.push_back(LBCast);
2482 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable()));
2484 llvm::Value *UBCast =
2485 CGF.Builder.CreateIntCast(CGF.Builder.CreateLoad(UB.getAddress(CGF)),
2486 CGF.SizeTy, /*isSigned=*/false);
2487 CapturedVars.push_back(UBCast);
2491 emitInnerParallelForWhenCombined(CodeGenFunction &CGF,
2492 const OMPLoopDirective &S,
2493 CodeGenFunction::JumpDest LoopExit) {
2494 auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF,
2495 PrePostActionTy &Action) {
2497 bool HasCancel = false;
2498 if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
2499 if (const auto *D = dyn_cast<OMPTeamsDistributeParallelForDirective>(&S))
2500 HasCancel = D->hasCancel();
2501 else if (const auto *D = dyn_cast<OMPDistributeParallelForDirective>(&S))
2502 HasCancel = D->hasCancel();
2503 else if (const auto *D =
2504 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&S))
2505 HasCancel = D->hasCancel();
2507 CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, S.getDirectiveKind(),
2509 CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(),
2510 emitDistributeParallelForInnerBounds,
2511 emitDistributeParallelForDispatchBounds);
2514 emitCommonOMPParallelDirective(
2516 isOpenMPSimdDirective(S.getDirectiveKind()) ? OMPD_for_simd : OMPD_for,
2517 CGInlinedWorksharingLoop,
2518 emitDistributeParallelForDistributeInnerBoundParams);
2521 void CodeGenFunction::EmitOMPDistributeParallelForDirective(
2522 const OMPDistributeParallelForDirective &S) {
2523 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2524 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2527 OMPLexicalScope Scope(*this, S, OMPD_parallel);
2528 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
2531 void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
2532 const OMPDistributeParallelForSimdDirective &S) {
2533 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2534 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2537 OMPLexicalScope Scope(*this, S, OMPD_parallel);
2538 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
2541 void CodeGenFunction::EmitOMPDistributeSimdDirective(
2542 const OMPDistributeSimdDirective &S) {
2543 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2544 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
2546 OMPLexicalScope Scope(*this, S, OMPD_unknown);
2547 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2550 void CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
2551 CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S) {
2552 // Emit SPMD target parallel for region as a standalone region.
2553 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2554 emitOMPSimdRegion(CGF, S, Action);
2557 llvm::Constant *Addr;
2558 // Emit target region as a standalone region.
2559 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
2560 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
2561 assert(Fn && Addr && "Target device function emission failed.");
2564 void CodeGenFunction::EmitOMPTargetSimdDirective(
2565 const OMPTargetSimdDirective &S) {
2566 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2567 emitOMPSimdRegion(CGF, S, Action);
2569 emitCommonOMPTargetDirective(*this, S, CodeGen);
2573 struct ScheduleKindModifiersTy {
2574 OpenMPScheduleClauseKind Kind;
2575 OpenMPScheduleClauseModifier M1;
2576 OpenMPScheduleClauseModifier M2;
2577 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
2578 OpenMPScheduleClauseModifier M1,
2579 OpenMPScheduleClauseModifier M2)
2580 : Kind(Kind), M1(M1), M2(M2) {}
2584 bool CodeGenFunction::EmitOMPWorksharingLoop(
2585 const OMPLoopDirective &S, Expr *EUB,
2586 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
2587 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
2588 // Emit the loop iteration variable.
2589 const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2590 const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl());
2591 EmitVarDecl(*IVDecl);
2593 // Emit the iterations count variable.
2594 // If it is not a variable, Sema decided to calculate iterations count on each
2595 // iteration (e.g., it is foldable into a constant).
2596 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2597 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2598 // Emit calculation of the iterations count.
2599 EmitIgnoredExpr(S.getCalcLastIteration());
2602 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
2604 bool HasLastprivateClause;
2605 // Check pre-condition.
2607 OMPLoopScope PreInitScope(*this, S);
2608 // Skip the entire loop if we don't meet the precondition.
2609 // If the condition constant folds and can be elided, avoid emitting the
2612 llvm::BasicBlock *ContBlock = nullptr;
2613 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2617 llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then");
2618 ContBlock = createBasicBlock("omp.precond.end");
2619 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
2620 getProfileCount(&S));
2621 EmitBlock(ThenBlock);
2622 incrementProfileCounter(&S);
2625 RunCleanupsScope DoacrossCleanupScope(*this);
2626 bool Ordered = false;
2627 if (const auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
2628 if (OrderedClause->getNumForLoops())
2629 RT.emitDoacrossInit(*this, S, OrderedClause->getLoopNumIterations());
2634 llvm::DenseSet<const Expr *> EmittedFinals;
2635 emitAlignedClause(*this, S);
2636 bool HasLinears = EmitOMPLinearClauseInit(S);
2637 // Emit helper vars inits.
2639 std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S);
2640 LValue LB = Bounds.first;
2641 LValue UB = Bounds.second;
2643 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2645 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2647 // Emit 'then' code.
2649 OMPPrivateScope LoopScope(*this);
2650 if (EmitOMPFirstprivateClause(S, LoopScope) || HasLinears) {
2651 // Emit implicit barrier to synchronize threads and avoid data races on
2652 // initialization of firstprivate variables and post-update of
2653 // lastprivate variables.
2654 CGM.getOpenMPRuntime().emitBarrierCall(
2655 *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
2656 /*ForceSimpleCall=*/true);
2658 EmitOMPPrivateClause(S, LoopScope);
2659 CGOpenMPRuntime::LastprivateConditionalRAII LPCRegion(
2660 *this, S, EmitLValue(S.getIterationVariable()));
2661 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
2662 EmitOMPReductionClauseInit(S, LoopScope);
2663 EmitOMPPrivateLoopCounters(S, LoopScope);
2664 EmitOMPLinearClause(S, LoopScope);
2665 (void)LoopScope.Privatize();
2666 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
2667 CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(*this, S);
2669 // Detect the loop schedule kind and chunk.
2670 const Expr *ChunkExpr = nullptr;
2671 OpenMPScheduleTy ScheduleKind;
2672 if (const auto *C = S.getSingleClause<OMPScheduleClause>()) {
2673 ScheduleKind.Schedule = C->getScheduleKind();
2674 ScheduleKind.M1 = C->getFirstScheduleModifier();
2675 ScheduleKind.M2 = C->getSecondScheduleModifier();
2676 ChunkExpr = C->getChunkSize();
2678 // Default behaviour for schedule clause.
2679 CGM.getOpenMPRuntime().getDefaultScheduleAndChunk(
2680 *this, S, ScheduleKind.Schedule, ChunkExpr);
2682 bool HasChunkSizeOne = false;
2683 llvm::Value *Chunk = nullptr;
2685 Chunk = EmitScalarExpr(ChunkExpr);
2686 Chunk = EmitScalarConversion(Chunk, ChunkExpr->getType(),
2687 S.getIterationVariable()->getType(),
2689 Expr::EvalResult Result;
2690 if (ChunkExpr->EvaluateAsInt(Result, getContext())) {
2691 llvm::APSInt EvaluatedChunk = Result.Val.getInt();
2692 HasChunkSizeOne = (EvaluatedChunk.getLimitedValue() == 1);
2695 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2696 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2697 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
2698 // If the static schedule kind is specified or if the ordered clause is
2699 // specified, and if no monotonic modifier is specified, the effect will
2700 // be as if the monotonic modifier was specified.
2701 bool StaticChunkedOne = RT.isStaticChunked(ScheduleKind.Schedule,
2702 /* Chunked */ Chunk != nullptr) && HasChunkSizeOne &&
2703 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind());
2704 if ((RT.isStaticNonchunked(ScheduleKind.Schedule,
2705 /* Chunked */ Chunk != nullptr) ||
2706 StaticChunkedOne) &&
2709 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
2712 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2713 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
2714 CGF.EmitOMPSimdInit(S, /*IsMonotonic=*/true);
2715 } else if (const auto *C = S.getSingleClause<OMPOrderClause>()) {
2716 if (C->getKind() == OMPC_ORDER_concurrent)
2717 CGF.LoopStack.setParallel(/*Enable=*/true);
2720 [IVSize, IVSigned, Ordered, IL, LB, UB, ST, StaticChunkedOne, Chunk,
2721 &S, ScheduleKind, LoopExit,
2722 &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) {
2723 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2724 // When no chunk_size is specified, the iteration space is divided
2725 // into chunks that are approximately equal in size, and at most
2726 // one chunk is distributed to each thread. Note that the size of
2727 // the chunks is unspecified in this case.
2728 CGOpenMPRuntime::StaticRTInput StaticInit(
2729 IVSize, IVSigned, Ordered, IL.getAddress(CGF),
2730 LB.getAddress(CGF), UB.getAddress(CGF), ST.getAddress(CGF),
2731 StaticChunkedOne ? Chunk : nullptr);
2732 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
2733 CGF, S.getBeginLoc(), S.getDirectiveKind(), ScheduleKind,
2735 // UB = min(UB, GlobalUB);
2736 if (!StaticChunkedOne)
2737 CGF.EmitIgnoredExpr(S.getEnsureUpperBound());
2739 CGF.EmitIgnoredExpr(S.getInit());
2740 // For unchunked static schedule generate:
2742 // while (idx <= UB) {
2747 // For static schedule with chunk one:
2749 // while (IV <= PrevUB) {
2753 CGF.EmitOMPInnerLoop(
2754 S, LoopScope.requiresCleanups(),
2755 StaticChunkedOne ? S.getCombinedParForInDistCond()
2757 StaticChunkedOne ? S.getDistInc() : S.getInc(),
2758 [&S, LoopExit](CodeGenFunction &CGF) {
2759 CGF.EmitOMPLoopBody(S, LoopExit);
2760 CGF.EmitStopPoint(&S);
2762 [](CodeGenFunction &) {});
2764 EmitBlock(LoopExit.getBlock());
2765 // Tell the runtime we are done.
2766 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2767 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
2768 S.getDirectiveKind());
2770 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
2772 const bool IsMonotonic =
2773 Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static ||
2774 ScheduleKind.Schedule == OMPC_SCHEDULE_unknown ||
2775 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
2776 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
2777 // Emit the outer loop, which requests its work chunk [LB..UB] from
2778 // runtime and runs the inner loop to process it.
2779 const OMPLoopArguments LoopArguments(
2780 LB.getAddress(*this), UB.getAddress(*this), ST.getAddress(*this),
2781 IL.getAddress(*this), Chunk, EUB);
2782 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
2783 LoopArguments, CGDispatchBounds);
2785 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
2786 EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) {
2787 return CGF.Builder.CreateIsNotNull(
2788 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
2791 EmitOMPReductionClauseFinal(
2792 S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind())
2793 ? /*Parallel and Simd*/ OMPD_parallel_for_simd
2794 : /*Parallel only*/ OMPD_parallel);
2795 // Emit post-update of the reduction variables if IsLastIter != 0.
2796 emitPostUpdateForReductionClause(
2797 *this, S, [IL, &S](CodeGenFunction &CGF) {
2798 return CGF.Builder.CreateIsNotNull(
2799 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
2801 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2802 if (HasLastprivateClause)
2803 EmitOMPLastprivateClauseFinal(
2804 S, isOpenMPSimdDirective(S.getDirectiveKind()),
2805 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc())));
2807 EmitOMPLinearClauseFinal(S, [IL, &S](CodeGenFunction &CGF) {
2808 return CGF.Builder.CreateIsNotNull(
2809 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
2811 DoacrossCleanupScope.ForceCleanup();
2812 // We're now done with the loop, so jump to the continuation block.
2814 EmitBranch(ContBlock);
2815 EmitBlock(ContBlock, /*IsFinished=*/true);
2818 return HasLastprivateClause;
2821 /// The following two functions generate expressions for the loop lower
2822 /// and upper bounds in case of static and dynamic (dispatch) schedule
2823 /// of the associated 'for' or 'distribute' loop.
2824 static std::pair<LValue, LValue>
2825 emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
2826 const auto &LS = cast<OMPLoopDirective>(S);
2828 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2830 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2834 /// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
2835 /// consider the lower and upper bound expressions generated by the
2836 /// worksharing loop support, but we use 0 and the iteration space size as
2838 static std::pair<llvm::Value *, llvm::Value *>
2839 emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S,
2840 Address LB, Address UB) {
2841 const auto &LS = cast<OMPLoopDirective>(S);
2842 const Expr *IVExpr = LS.getIterationVariable();
2843 const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
2844 llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
2845 llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
2846 return {LBVal, UBVal};
2849 void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
2850 bool HasLastprivates = false;
2851 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2852 PrePostActionTy &) {
2853 OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
2854 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2856 emitDispatchForLoopBounds);
2860 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
2861 OMPLexicalScope Scope(*this, S, OMPD_unknown);
2862 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2866 // Emit an implicit barrier at the end.
2867 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates)
2868 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for);
2869 // Check for outer lastprivate conditional update.
2870 checkForLastprivateConditionalUpdate(*this, S);
2873 void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
2874 bool HasLastprivates = false;
2875 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2876 PrePostActionTy &) {
2877 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2879 emitDispatchForLoopBounds);
2883 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
2884 OMPLexicalScope Scope(*this, S, OMPD_unknown);
2885 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2888 // Emit an implicit barrier at the end.
2889 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates)
2890 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for);
2891 // Check for outer lastprivate conditional update.
2892 checkForLastprivateConditionalUpdate(*this, S);
2895 static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2897 llvm::Value *Init = nullptr) {
2898 LValue LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
2900 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
2904 void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
2905 const Stmt *CapturedStmt = S.getInnermostCapturedStmt()->getCapturedStmt();
2906 const auto *CS = dyn_cast<CompoundStmt>(CapturedStmt);
2907 bool HasLastprivates = false;
2908 auto &&CodeGen = [&S, CapturedStmt, CS,
2909 &HasLastprivates](CodeGenFunction &CGF, PrePostActionTy &) {
2910 ASTContext &C = CGF.getContext();
2911 QualType KmpInt32Ty =
2912 C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2913 // Emit helper vars inits.
2914 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2915 CGF.Builder.getInt32(0));
2916 llvm::ConstantInt *GlobalUBVal = CS != nullptr
2917 ? CGF.Builder.getInt32(CS->size() - 1)
2918 : CGF.Builder.getInt32(0);
2920 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2921 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2922 CGF.Builder.getInt32(1));
2923 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2924 CGF.Builder.getInt32(0));
2926 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
2927 OpaqueValueExpr IVRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue);
2928 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
2929 OpaqueValueExpr UBRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue);
2930 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2931 // Generate condition for loop.
2932 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
2933 OK_Ordinary, S.getBeginLoc(), FPOptions());
2934 // Increment for loop counter.
2935 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
2936 S.getBeginLoc(), true);
2937 auto &&BodyGen = [CapturedStmt, CS, &S, &IV](CodeGenFunction &CGF) {
2938 // Iterate through all sections and emit a switch construct:
2941 // <SectionStmt[0]>;
2944 // case <NumSection> - 1:
2945 // <SectionStmt[<NumSection> - 1]>;
2948 // .omp.sections.exit:
2949 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
2950 llvm::SwitchInst *SwitchStmt =
2951 CGF.Builder.CreateSwitch(CGF.EmitLoadOfScalar(IV, S.getBeginLoc()),
2952 ExitBB, CS == nullptr ? 1 : CS->size());
2954 unsigned CaseNumber = 0;
2955 for (const Stmt *SubStmt : CS->children()) {
2956 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2957 CGF.EmitBlock(CaseBB);
2958 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
2959 CGF.EmitStmt(SubStmt);
2960 CGF.EmitBranch(ExitBB);
2964 llvm::BasicBlock *CaseBB = CGF.createBasicBlock(".omp.sections.case");
2965 CGF.EmitBlock(CaseBB);
2966 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
2967 CGF.EmitStmt(CapturedStmt);
2968 CGF.EmitBranch(ExitBB);
2970 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2973 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2974 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
2975 // Emit implicit barrier to synchronize threads and avoid data races on
2976 // initialization of firstprivate variables and post-update of lastprivate
2978 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
2979 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
2980 /*ForceSimpleCall=*/true);
2982 CGF.EmitOMPPrivateClause(S, LoopScope);
2983 CGOpenMPRuntime::LastprivateConditionalRAII LPCRegion(CGF, S, IV);
2984 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2985 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2986 (void)LoopScope.Privatize();
2987 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
2988 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
2990 // Emit static non-chunked loop.
2991 OpenMPScheduleTy ScheduleKind;
2992 ScheduleKind.Schedule = OMPC_SCHEDULE_static;
2993 CGOpenMPRuntime::StaticRTInput StaticInit(
2994 /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(CGF),
2995 LB.getAddress(CGF), UB.getAddress(CGF), ST.getAddress(CGF));
2996 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
2997 CGF, S.getBeginLoc(), S.getDirectiveKind(), ScheduleKind, StaticInit);
2998 // UB = min(UB, GlobalUB);
2999 llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, S.getBeginLoc());
3000 llvm::Value *MinUBGlobalUB = CGF.Builder.CreateSelect(
3001 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
3002 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
3004 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getBeginLoc()), IV);
3005 // while (idx <= UB) { BODY; ++idx; }
3006 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
3007 [](CodeGenFunction &) {});
3008 // Tell the runtime we are done.
3009 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
3010 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
3011 S.getDirectiveKind());
3013 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
3014 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
3015 // Emit post-update of the reduction variables if IsLastIter != 0.
3016 emitPostUpdateForReductionClause(CGF, S, [IL, &S](CodeGenFunction &CGF) {
3017 return CGF.Builder.CreateIsNotNull(
3018 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
3021 // Emit final copy of the lastprivate variables if IsLastIter != 0.
3022 if (HasLastprivates)
3023 CGF.EmitOMPLastprivateClauseFinal(
3024 S, /*NoFinals=*/false,
3025 CGF.Builder.CreateIsNotNull(
3026 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())));
3029 bool HasCancel = false;
3030 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
3031 HasCancel = OSD->hasCancel();
3032 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
3033 HasCancel = OPSD->hasCancel();
3034 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
3035 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
3037 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
3038 // clause. Otherwise the barrier will be generated by the codegen for the
3040 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
3041 // Emit implicit barrier to synchronize threads and avoid data races on
3042 // initialization of firstprivate variables.
3043 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(),
3048 void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
3051 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
3052 OMPLexicalScope Scope(*this, S, OMPD_unknown);
3055 // Emit an implicit barrier at the end.
3056 if (!S.getSingleClause<OMPNowaitClause>()) {
3057 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(),
3060 // Check for outer lastprivate conditional update.
3061 checkForLastprivateConditionalUpdate(*this, S);
3064 void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
3065 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3066 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
3068 OMPLexicalScope Scope(*this, S, OMPD_unknown);
3069 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
3073 void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
3074 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
3075 llvm::SmallVector<const Expr *, 8> DestExprs;
3076 llvm::SmallVector<const Expr *, 8> SrcExprs;
3077 llvm::SmallVector<const Expr *, 8> AssignmentOps;
3078 // Check if there are any 'copyprivate' clauses associated with this
3079 // 'single' construct.
3080 // Build a list of copyprivate variables along with helper expressions
3081 // (<source>, <destination>, <destination>=<source> expressions)
3082 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
3083 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
3084 DestExprs.append(C->destination_exprs().begin(),
3085 C->destination_exprs().end());
3086 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
3087 AssignmentOps.append(C->assignment_ops().begin(),
3088 C->assignment_ops().end());
3090 // Emit code for 'single' region along with 'copyprivate' clauses
3091 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3093 OMPPrivateScope SingleScope(CGF);
3094 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
3095 CGF.EmitOMPPrivateClause(S, SingleScope);
3096 (void)SingleScope.Privatize();
3097 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
3101 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
3102 OMPLexicalScope Scope(*this, S, OMPD_unknown);
3103 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getBeginLoc(),
3104 CopyprivateVars, DestExprs,
3105 SrcExprs, AssignmentOps);
3107 // Emit an implicit barrier at the end (to avoid data race on firstprivate
3108 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
3109 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
3110 CGM.getOpenMPRuntime().emitBarrierCall(
3111 *this, S.getBeginLoc(),
3112 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
3114 // Check for outer lastprivate conditional update.
3115 checkForLastprivateConditionalUpdate(*this, S);
3118 static void emitMaster(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
3119 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3121 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
3123 CGF.CGM.getOpenMPRuntime().emitMasterRegion(CGF, CodeGen, S.getBeginLoc());
3126 void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
3127 if (llvm::OpenMPIRBuilder *OMPBuilder = CGM.getOpenMPIRBuilder()) {
3128 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
3130 const CapturedStmt *CS = S.getInnermostCapturedStmt();
3131 const Stmt *MasterRegionBodyStmt = CS->getCapturedStmt();
3133 auto FiniCB = [this](InsertPointTy IP) {
3134 OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP);
3137 auto BodyGenCB = [MasterRegionBodyStmt, this](InsertPointTy AllocaIP,
3138 InsertPointTy CodeGenIP,
3139 llvm::BasicBlock &FiniBB) {
3140 OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(*this, AllocaIP, FiniBB);
3141 OMPBuilderCBHelpers::EmitOMPRegionBody(*this, MasterRegionBodyStmt,
3145 CGCapturedStmtInfo CGSI(*CS, CR_OpenMP);
3146 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(*this, &CGSI);
3147 Builder.restoreIP(OMPBuilder->CreateMaster(Builder, BodyGenCB, FiniCB));
3151 OMPLexicalScope Scope(*this, S, OMPD_unknown);
3152 emitMaster(*this, S);
3155 void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
3156 if (llvm::OpenMPIRBuilder *OMPBuilder = CGM.getOpenMPIRBuilder()) {
3157 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
3159 const CapturedStmt *CS = S.getInnermostCapturedStmt();
3160 const Stmt *CriticalRegionBodyStmt = CS->getCapturedStmt();
3161 const Expr *Hint = nullptr;
3162 if (const auto *HintClause = S.getSingleClause<OMPHintClause>())
3163 Hint = HintClause->getHint();
3165 // TODO: This is slightly different from what's currently being done in
3166 // clang. Fix the Int32Ty to IntPtrTy (pointer width size) when everything
3167 // about typing is final.
3168 llvm::Value *HintInst = nullptr;
3171 Builder.CreateIntCast(EmitScalarExpr(Hint), CGM.Int32Ty, false);
3173 auto FiniCB = [this](InsertPointTy IP) {
3174 OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP);
3177 auto BodyGenCB = [CriticalRegionBodyStmt, this](InsertPointTy AllocaIP,
3178 InsertPointTy CodeGenIP,
3179 llvm::BasicBlock &FiniBB) {
3180 OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(*this, AllocaIP, FiniBB);
3181 OMPBuilderCBHelpers::EmitOMPRegionBody(*this, CriticalRegionBodyStmt,
3185 CGCapturedStmtInfo CGSI(*CS, CR_OpenMP);
3186 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(*this, &CGSI);
3187 Builder.restoreIP(OMPBuilder->CreateCritical(
3188 Builder, BodyGenCB, FiniCB, S.getDirectiveName().getAsString(),
3194 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3196 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
3198 const Expr *Hint = nullptr;
3199 if (const auto *HintClause = S.getSingleClause<OMPHintClause>())
3200 Hint = HintClause->getHint();
3201 OMPLexicalScope Scope(*this, S, OMPD_unknown);
3202 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
3203 S.getDirectiveName().getAsString(),
3204 CodeGen, S.getBeginLoc(), Hint);
3207 void CodeGenFunction::EmitOMPParallelForDirective(
3208 const OMPParallelForDirective &S) {
3209 // Emit directive as a combined directive that consists of two implicit
3210 // directives: 'parallel' with 'for' directive.
3211 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3213 OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
3214 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
3215 emitDispatchForLoopBounds);
3219 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
3220 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
3221 emitEmptyBoundParameters);
3223 // Check for outer lastprivate conditional update.
3224 checkForLastprivateConditionalUpdate(*this, S);
3227 void CodeGenFunction::EmitOMPParallelForSimdDirective(
3228 const OMPParallelForSimdDirective &S) {
3229 // Emit directive as a combined directive that consists of two implicit
3230 // directives: 'parallel' with 'for' directive.
3231 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3233 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
3234 emitDispatchForLoopBounds);
3238 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
3239 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen,
3240 emitEmptyBoundParameters);
3242 // Check for outer lastprivate conditional update.
3243 checkForLastprivateConditionalUpdate(*this, S);
3246 void CodeGenFunction::EmitOMPParallelMasterDirective(
3247 const OMPParallelMasterDirective &S) {
3248 // Emit directive as a combined directive that consists of two implicit
3249 // directives: 'parallel' with 'master' directive.
3250 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3252 OMPPrivateScope PrivateScope(CGF);
3253 bool Copyins = CGF.EmitOMPCopyinClause(S);
3254 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3256 // Emit implicit barrier to synchronize threads and avoid data races on
3257 // propagation master's thread values of threadprivate variables to local
3258 // instances of that variables of all other implicit threads.
3259 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
3260 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
3261 /*ForceSimpleCall=*/true);
3263 CGF.EmitOMPPrivateClause(S, PrivateScope);
3264 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
3265 (void)PrivateScope.Privatize();
3267 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
3271 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
3272 emitCommonOMPParallelDirective(*this, S, OMPD_master, CodeGen,
3273 emitEmptyBoundParameters);
3274 emitPostUpdateForReductionClause(*this, S,
3275 [](CodeGenFunction &) { return nullptr; });
3277 // Check for outer lastprivate conditional update.
3278 checkForLastprivateConditionalUpdate(*this, S);
3281 void CodeGenFunction::EmitOMPParallelSectionsDirective(
3282 const OMPParallelSectionsDirective &S) {
3283 // Emit directive as a combined directive that consists of two implicit
3284 // directives: 'parallel' with 'sections' directive.
3285 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3287 CGF.EmitSections(S);
3291 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
3292 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
3293 emitEmptyBoundParameters);
3295 // Check for outer lastprivate conditional update.
3296 checkForLastprivateConditionalUpdate(*this, S);
3299 void CodeGenFunction::EmitOMPTaskBasedDirective(
3300 const OMPExecutableDirective &S, const OpenMPDirectiveKind CapturedRegion,
3301 const RegionCodeGenTy &BodyGen, const TaskGenTy &TaskGen,
3302 OMPTaskDataTy &Data) {
3303 // Emit outlined function for task construct.
3304 const CapturedStmt *CS = S.getCapturedStmt(CapturedRegion);
3305 auto I = CS->getCapturedDecl()->param_begin();
3306 auto PartId = std::next(I);
3307 auto TaskT = std::next(I, 4);
3308 // Check if the task is final
3309 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
3310 // If the condition constant folds and can be elided, try to avoid emitting
3311 // the condition and the dead arm of the if/else.
3312 const Expr *Cond = Clause->getCondition();
3314 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
3315 Data.Final.setInt(CondConstant);
3317 Data.Final.setPointer(EvaluateExprAsBool(Cond));
3319 // By default the task is not final.
3320 Data.Final.setInt(/*IntVal=*/false);
3322 // Check if the task has 'priority' clause.
3323 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
3324 const Expr *Prio = Clause->getPriority();
3325 Data.Priority.setInt(/*IntVal=*/true);
3326 Data.Priority.setPointer(EmitScalarConversion(
3327 EmitScalarExpr(Prio), Prio->getType(),
3328 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
3329 Prio->getExprLoc()));
3331 // The first function argument for tasks is a thread id, the second one is a
3332 // part id (0 for tied tasks, >=0 for untied task).
3333 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
3334 // Get list of private variables.
3335 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
3336 auto IRef = C->varlist_begin();
3337 for (const Expr *IInit : C->private_copies()) {
3338 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
3339 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
3340 Data.PrivateVars.push_back(*IRef);
3341 Data.PrivateCopies.push_back(IInit);
3346 EmittedAsPrivate.clear();
3347 // Get list of firstprivate variables.
3348 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
3349 auto IRef = C->varlist_begin();
3350 auto IElemInitRef = C->inits().begin();
3351 for (const Expr *IInit : C->private_copies()) {
3352 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
3353 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
3354 Data.FirstprivateVars.push_back(*IRef);
3355 Data.FirstprivateCopies.push_back(IInit);
3356 Data.FirstprivateInits.push_back(*IElemInitRef);
3362 // Get list of lastprivate variables (for taskloops).
3363 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
3364 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
3365 auto IRef = C->varlist_begin();
3366 auto ID = C->destination_exprs().begin();
3367 for (const Expr *IInit : C->private_copies()) {
3368 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
3369 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
3370 Data.LastprivateVars.push_back(*IRef);
3371 Data.LastprivateCopies.push_back(IInit);
3373 LastprivateDstsOrigs.insert(
3374 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
3375 cast<DeclRefExpr>(*IRef)});
3380 SmallVector<const Expr *, 4> LHSs;
3381 SmallVector<const Expr *, 4> RHSs;
3382 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
3383 auto IPriv = C->privates().begin();
3384 auto IRed = C->reduction_ops().begin();
3385 auto ILHS = C->lhs_exprs().begin();
3386 auto IRHS = C->rhs_exprs().begin();
3387 for (const Expr *Ref : C->varlists()) {
3388 Data.ReductionVars.emplace_back(Ref);
3389 Data.ReductionCopies.emplace_back(*IPriv);