clang 24.0.0git
CGStmtOpenMP.cpp
Go to the documentation of this file.
1//===--- CGStmtOpenMP.cpp - Emit LLVM Code from Statements ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This contains code to emit OpenMP nodes as LLVM code.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CGCleanup.h"
14#include "CGDebugInfo.h"
15#include "CGOpenMPRuntime.h"
16#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
18#include "CodeGenPGO.h"
19#include "TargetInfo.h"
21#include "clang/AST/Attr.h"
24#include "clang/AST/Stmt.h"
31#include "llvm/ADT/SmallSet.h"
32#include "llvm/BinaryFormat/Dwarf.h"
33#include "llvm/Frontend/OpenMP/OMPConstants.h"
34#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
35#include "llvm/IR/Constants.h"
36#include "llvm/IR/DebugInfoMetadata.h"
37#include "llvm/IR/Instructions.h"
38#include "llvm/IR/IntrinsicInst.h"
39#include "llvm/IR/Metadata.h"
40#include "llvm/Support/AtomicOrdering.h"
41#include "llvm/Support/Debug.h"
42#include <optional>
43using namespace clang;
44using namespace CodeGen;
45using namespace llvm::omp;
46
47#define TTL_CODEGEN_TYPE "target-teams-loop-codegen"
48
49static const VarDecl *getBaseDecl(const Expr *Ref);
52
53/// Whether a combined `distribute parallel for` may use the fused
54/// distr_static_chunk + static_chunkone schedule (enum 93): one
55/// for_static_init, no surrounding distribute_static_init.
57 const OMPLoopDirective &S,
58 OpenMPDirectiveKind DKind) {
59 // Reduction-only for now. Non-reduction cases might follow in the future, but
60 // need more analysis for maximum profit.
61 return CGM.getLangOpts().OpenMPIsTargetDevice && CGM.getTriple().isGPU() &&
63 S.hasClausesOfKind<OMPReductionClause>() &&
64 !S.getSingleClause<OMPDistScheduleClause>() &&
65 !S.getSingleClause<OMPScheduleClause>() &&
66 !S.getSingleClause<OMPOrderedClause>();
67}
68
69namespace {
70/// Lexical scope for OpenMP executable constructs, that handles correct codegen
71/// for captured expressions.
72class OMPLexicalScope : public CodeGenFunction::LexicalScope {
73 void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
74 for (const auto *C : S.clauses()) {
75 if (const auto *CPI = OMPClauseWithPreInit::get(C)) {
76 if (const auto *PreInit =
77 cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
78 for (const auto *I : PreInit->decls()) {
79 if (!I->hasAttr<OMPCaptureNoInitAttr>()) {
81 } else {
82 CodeGenFunction::AutoVarEmission Emission =
84 CGF.EmitAutoVarCleanups(Emission);
85 }
86 }
87 }
88 }
89 }
90 }
91 CodeGenFunction::OMPPrivateScope InlinedShareds;
92
93 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
94 return CGF.LambdaCaptureFields.lookup(VD) ||
95 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
96 (isa_and_nonnull<BlockDecl>(CGF.CurCodeDecl) &&
97 cast<BlockDecl>(CGF.CurCodeDecl)->capturesVariable(VD));
98 }
99
100public:
101 OMPLexicalScope(
102 CodeGenFunction &CGF, const OMPExecutableDirective &S,
103 const std::optional<OpenMPDirectiveKind> CapturedRegion = std::nullopt,
104 const bool EmitPreInitStmt = true)
105 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
106 InlinedShareds(CGF) {
107 if (EmitPreInitStmt)
108 emitPreInitStmt(CGF, S);
109 if (!CapturedRegion)
110 return;
111 assert(S.hasAssociatedStmt() &&
112 "Expected associated statement for inlined directive.");
113 const CapturedStmt *CS = S.getCapturedStmt(*CapturedRegion);
114 for (const auto &C : CS->captures()) {
115 if (C.capturesVariable() || C.capturesVariableByCopy()) {
116 auto *VD = C.getCapturedVar();
117 assert(VD == VD->getCanonicalDecl() &&
118 "Canonical decl must be captured.");
119 DeclRefExpr DRE(
120 CGF.getContext(), const_cast<VarDecl *>(VD),
121 isCapturedVar(CGF, VD) || (CGF.CapturedStmtInfo &&
122 InlinedShareds.isGlobalVarCaptured(VD)),
123 VD->getType().getNonReferenceType(), VK_LValue, C.getLocation());
124 InlinedShareds.addPrivate(VD, CGF.EmitLValue(&DRE).getAddress());
125 }
126 }
127 (void)InlinedShareds.Privatize();
128 }
129};
130
131/// Lexical scope for OpenMP parallel construct, that handles correct codegen
132/// for captured expressions.
133class OMPParallelScope final : public OMPLexicalScope {
134 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
136 return !(isOpenMPTargetExecutionDirective(EKind) ||
139 }
140
141public:
142 OMPParallelScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
143 : OMPLexicalScope(CGF, S, /*CapturedRegion=*/std::nullopt,
144 EmitPreInitStmt(S)) {}
145};
146
147/// Lexical scope for OpenMP teams construct, that handles correct codegen
148/// for captured expressions.
149class OMPTeamsScope final : public OMPLexicalScope {
150 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
152 return !isOpenMPTargetExecutionDirective(EKind) &&
154 }
155
156public:
157 OMPTeamsScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
158 : OMPLexicalScope(CGF, S, /*CapturedRegion=*/std::nullopt,
159 EmitPreInitStmt(S)) {}
160};
161
162/// Private scope for OpenMP loop-based directives, that supports capturing
163/// of used expression from loop statement.
164class OMPLoopScope : public CodeGenFunction::RunCleanupsScope {
165 void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopBasedDirective &S) {
166 const Stmt *PreInits;
167 CodeGenFunction::OMPMapVars PreCondVars;
168 if (auto *LD = dyn_cast<OMPLoopDirective>(&S)) {
169 // Emit init, __range, __begin and __end variables for C++ range loops.
170 (void)OMPLoopBasedDirective::doForAllLoops(
171 LD->getInnermostCapturedStmt()->getCapturedStmt(),
172 /*TryImperfectlyNestedLoops=*/true, LD->getLoopsNumber(),
173 [&CGF](unsigned Cnt, const Stmt *CurStmt) {
174 if (const auto *CXXFor = dyn_cast<CXXForRangeStmt>(CurStmt)) {
175 if (const Stmt *Init = CXXFor->getInit())
176 CGF.EmitStmt(Init);
177 CGF.EmitStmt(CXXFor->getRangeStmt());
178 CGF.EmitStmt(CXXFor->getBeginStmt());
179 CGF.EmitStmt(CXXFor->getEndStmt());
180 }
181 return false;
182 });
183 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
184 for (const auto *E : LD->counters()) {
185 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
186 EmittedAsPrivate.insert(VD->getCanonicalDecl());
187 (void)PreCondVars.setVarAddr(
188 CGF, VD, CGF.CreateMemTemp(VD->getType().getNonReferenceType()));
189 }
190 // Mark private vars as undefs.
191 for (const auto *C : LD->getClausesOfKind<OMPPrivateClause>()) {
192 for (const Expr *IRef : C->varlist()) {
193 const auto *OrigVD =
194 cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
195 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
196 QualType OrigVDTy = OrigVD->getType().getNonReferenceType();
197 (void)PreCondVars.setVarAddr(
198 CGF, OrigVD,
199 Address(llvm::UndefValue::get(CGF.ConvertTypeForMem(
200 CGF.getContext().getPointerType(OrigVDTy))),
201 CGF.ConvertTypeForMem(OrigVDTy),
202 CGF.getContext().getDeclAlign(OrigVD)));
203 }
204 }
205 }
206 (void)PreCondVars.apply(CGF);
207 PreInits = LD->getPreInits();
208 } else if (const auto *Tile = dyn_cast<OMPTileDirective>(&S)) {
209 PreInits = Tile->getPreInits();
210 } else if (const auto *Stripe = dyn_cast<OMPStripeDirective>(&S)) {
211 PreInits = Stripe->getPreInits();
212 } else if (const auto *Unroll = dyn_cast<OMPUnrollDirective>(&S)) {
213 PreInits = Unroll->getPreInits();
214 } else if (const auto *Reverse = dyn_cast<OMPReverseDirective>(&S)) {
215 PreInits = Reverse->getPreInits();
216 } else if (const auto *Split = dyn_cast<OMPSplitDirective>(&S)) {
217 PreInits = Split->getPreInits();
218 } else if (const auto *Interchange =
219 dyn_cast<OMPInterchangeDirective>(&S)) {
220 PreInits = Interchange->getPreInits();
221 } else {
222 llvm_unreachable("Unknown loop-based directive kind.");
223 }
224 doEmitPreinits(PreInits);
225 PreCondVars.restore(CGF);
226 }
227
228 void
229 emitPreInitStmt(CodeGenFunction &CGF,
231 const Stmt *PreInits;
232 if (const auto *Fuse = dyn_cast<OMPFuseDirective>(&S)) {
233 PreInits = Fuse->getPreInits();
234 } else {
235 llvm_unreachable(
236 "Unknown canonical loop sequence transform directive kind.");
237 }
238 doEmitPreinits(PreInits);
239 }
240
241 void doEmitPreinits(const Stmt *PreInits) {
242 if (PreInits) {
243 // CompoundStmts and DeclStmts are used as lists of PreInit statements and
244 // declarations. Since declarations must be visible in the the following
245 // that they initialize, unpack the CompoundStmt they are nested in.
246 SmallVector<const Stmt *> PreInitStmts;
247 if (auto *PreInitCompound = dyn_cast<CompoundStmt>(PreInits))
248 llvm::append_range(PreInitStmts, PreInitCompound->body());
249 else
250 PreInitStmts.push_back(PreInits);
251
252 for (const Stmt *S : PreInitStmts) {
253 // EmitStmt skips any OMPCapturedExprDecls, but needs to be emitted
254 // here.
255 if (auto *PreInitDecl = dyn_cast<DeclStmt>(S)) {
256 for (Decl *I : PreInitDecl->decls())
257 CGF.EmitVarDecl(cast<VarDecl>(*I));
258 continue;
259 }
260 CGF.EmitStmt(S);
261 }
262 }
263 }
264
265public:
266 OMPLoopScope(CodeGenFunction &CGF, const OMPLoopBasedDirective &S)
267 : CodeGenFunction::RunCleanupsScope(CGF) {
268 emitPreInitStmt(CGF, S);
269 }
270 OMPLoopScope(CodeGenFunction &CGF,
272 : CodeGenFunction::RunCleanupsScope(CGF) {
273 emitPreInitStmt(CGF, S);
274 }
275};
276
277class OMPSimdLexicalScope : public CodeGenFunction::LexicalScope {
278 CodeGenFunction::OMPPrivateScope InlinedShareds;
279
280 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
281 return CGF.LambdaCaptureFields.lookup(VD) ||
282 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
283 (isa_and_nonnull<BlockDecl>(CGF.CurCodeDecl) &&
284 cast<BlockDecl>(CGF.CurCodeDecl)->capturesVariable(VD));
285 }
286
287public:
288 OMPSimdLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
289 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
290 InlinedShareds(CGF) {
291 for (const auto *C : S.clauses()) {
292 if (const auto *CPI = OMPClauseWithPreInit::get(C)) {
293 if (const auto *PreInit =
294 cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
295 for (const auto *I : PreInit->decls()) {
296 if (!I->hasAttr<OMPCaptureNoInitAttr>()) {
297 CGF.EmitVarDecl(cast<VarDecl>(*I));
298 } else {
299 CodeGenFunction::AutoVarEmission Emission =
300 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
301 CGF.EmitAutoVarCleanups(Emission);
302 }
303 }
304 }
305 } else if (const auto *UDP = dyn_cast<OMPUseDevicePtrClause>(C)) {
306 for (const Expr *E : UDP->varlist()) {
307 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
308 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(D))
309 CGF.EmitVarDecl(*OED);
310 }
311 } else if (const auto *UDP = dyn_cast<OMPUseDeviceAddrClause>(C)) {
312 for (const Expr *E : UDP->varlist()) {
313 const Decl *D = getBaseDecl(E);
314 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(D))
315 CGF.EmitVarDecl(*OED);
316 }
317 }
318 }
320 CGF.EmitOMPPrivateClause(S, InlinedShareds);
321 if (const auto *TG = dyn_cast<OMPTaskgroupDirective>(&S)) {
322 if (const Expr *E = TG->getReductionRef())
323 CGF.EmitVarDecl(*cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()));
324 }
325 // Temp copy arrays for inscan reductions should not be emitted as they are
326 // not used in simd only mode.
327 llvm::DenseSet<CanonicalDeclPtr<const Decl>> CopyArrayTemps;
328 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
329 if (C->getModifier() != OMPC_REDUCTION_inscan)
330 continue;
331 for (const Expr *E : C->copy_array_temps())
332 CopyArrayTemps.insert(cast<DeclRefExpr>(E)->getDecl());
333 }
334 const auto *CS = cast_or_null<CapturedStmt>(S.getAssociatedStmt());
335 while (CS) {
336 for (auto &C : CS->captures()) {
337 if (C.capturesVariable() || C.capturesVariableByCopy()) {
338 auto *VD = C.getCapturedVar();
339 if (CopyArrayTemps.contains(VD))
340 continue;
341 assert(VD == VD->getCanonicalDecl() &&
342 "Canonical decl must be captured.");
343 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(VD),
344 isCapturedVar(CGF, VD) ||
345 (CGF.CapturedStmtInfo &&
346 InlinedShareds.isGlobalVarCaptured(VD)),
348 C.getLocation());
349 InlinedShareds.addPrivate(VD, CGF.EmitLValue(&DRE).getAddress());
350 }
351 }
352 CS = dyn_cast<CapturedStmt>(CS->getCapturedStmt());
353 }
354 (void)InlinedShareds.Privatize();
355 }
356};
357
358} // namespace
359
360// The loop directive with a bind clause will be mapped to a different
361// directive with corresponding semantics.
364 OpenMPDirectiveKind Kind = S.getDirectiveKind();
365 if (Kind != OMPD_loop)
366 return Kind;
367
369 if (const auto *C = S.getSingleClause<OMPBindClause>())
370 BindKind = C->getBindKind();
371
372 switch (BindKind) {
373 case OMPC_BIND_parallel:
374 return OMPD_for;
375 case OMPC_BIND_teams:
376 return OMPD_distribute;
377 case OMPC_BIND_thread:
378 return OMPD_simd;
379 default:
380 return OMPD_loop;
381 }
382}
383
385 const OMPExecutableDirective &S,
386 const RegionCodeGenTy &CodeGen);
387
389 if (const auto *OrigDRE = dyn_cast<DeclRefExpr>(E)) {
390 if (const auto *OrigVD = dyn_cast<VarDecl>(OrigDRE->getDecl())) {
391 OrigVD = OrigVD->getCanonicalDecl();
392 bool IsCaptured =
393 LambdaCaptureFields.lookup(OrigVD) ||
394 (CapturedStmtInfo && CapturedStmtInfo->lookup(OrigVD)) ||
395 (isa_and_nonnull<BlockDecl>(CurCodeDecl));
396 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD), IsCaptured,
397 OrigDRE->getType(), VK_LValue, OrigDRE->getExprLoc());
398 return EmitLValue(&DRE);
399 }
400 }
401 return EmitLValue(E);
402}
403
406 llvm::Value *Size = nullptr;
407 auto SizeInChars = C.getTypeSizeInChars(Ty);
408 if (SizeInChars.isZero()) {
409 // getTypeSizeInChars() returns 0 for a VLA.
410 while (const VariableArrayType *VAT = C.getAsVariableArrayType(Ty)) {
411 VlaSizePair VlaSize = getVLASize(VAT);
412 Ty = VlaSize.Type;
413 Size =
414 Size ? Builder.CreateNUWMul(Size, VlaSize.NumElts) : VlaSize.NumElts;
415 }
416 SizeInChars = C.getTypeSizeInChars(Ty);
417 if (SizeInChars.isZero())
418 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
419 return Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
420 }
421 return CGM.getSize(SizeInChars);
422}
423
425 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
426 const RecordDecl *RD = S.getCapturedRecordDecl();
427 auto CurField = RD->field_begin();
428 auto CurCap = S.captures().begin();
430 E = S.capture_init_end();
431 I != E; ++I, ++CurField, ++CurCap) {
432 if (CurField->hasCapturedVLAType()) {
433 const VariableArrayType *VAT = CurField->getCapturedVLAType();
434 llvm::Value *Val = VLASizeMap[VAT->getSizeExpr()];
435 CapturedVars.push_back(Val);
436 } else if (CurCap->capturesThis()) {
437 CapturedVars.push_back(CXXThisValue);
438 } else if (CurCap->capturesVariableByCopy()) {
439 llvm::Value *CV = EmitLoadOfScalar(EmitLValue(*I), CurCap->getLocation());
440
441 // If the field is not a pointer, we need to save the actual value
442 // and load it as a void pointer.
443 if (!CurField->getType()->isAnyPointerType()) {
444 ASTContext &Ctx = getContext();
446 Ctx.getUIntPtrType(),
447 Twine(CurCap->getCapturedVar()->getName(), ".casted"));
448 LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
449
450 llvm::Value *SrcAddrVal = EmitScalarConversion(
451 DstAddr.emitRawPointer(*this),
453 Ctx.getPointerType(CurField->getType()), CurCap->getLocation());
454 LValue SrcLV =
455 MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType());
456
457 // Store the value using the source type pointer.
459
460 // Load the value using the destination type pointer.
461 CV = EmitLoadOfScalar(DstLV, CurCap->getLocation());
462 }
463 CapturedVars.push_back(CV);
464 } else {
465 assert(CurCap->capturesVariable() && "Expected capture by reference.");
466 CapturedVars.push_back(EmitLValue(*I).getAddress().emitRawPointer(*this));
467 }
468 }
469}
470
472 QualType DstType, StringRef Name,
473 LValue AddrLV) {
474 ASTContext &Ctx = CGF.getContext();
475
476 llvm::Value *CastedPtr = CGF.EmitScalarConversion(
477 AddrLV.getAddress().emitRawPointer(CGF), Ctx.getUIntPtrType(),
478 Ctx.getPointerType(DstType), Loc);
479 // FIXME: should the pointee type (DstType) be passed?
480 Address TmpAddr =
481 CGF.MakeNaturalAlignAddrLValue(CastedPtr, DstType).getAddress();
482 return TmpAddr;
483}
484
486 if (T->isLValueReferenceType())
487 return C.getLValueReferenceType(
488 getCanonicalParamType(C, T.getNonReferenceType()),
489 /*SpelledAsLValue=*/false);
490 if (T->isPointerType())
491 return C.getPointerType(getCanonicalParamType(C, T->getPointeeType()));
492 if (const ArrayType *A = T->getAsArrayTypeUnsafe()) {
493 if (const auto *VLA = dyn_cast<VariableArrayType>(A))
494 return getCanonicalParamType(C, VLA->getElementType());
495 if (!A->isVariablyModifiedType())
496 return C.getCanonicalType(T);
497 }
498 return C.getCanonicalParamType(T);
499}
500
501namespace {
502/// Contains required data for proper outlined function codegen.
503struct FunctionOptions {
504 /// Captured statement for which the function is generated.
505 const CapturedStmt *S = nullptr;
506 /// true if cast to/from UIntPtr is required for variables captured by
507 /// value.
508 const bool UIntPtrCastRequired = true;
509 /// true if only casted arguments must be registered as local args or VLA
510 /// sizes.
511 const bool RegisterCastedArgsOnly = false;
512 /// Name of the generated function.
513 const StringRef FunctionName;
514 /// Location of the non-debug version of the outlined function.
515 SourceLocation Loc;
516 const bool IsDeviceKernel = false;
517 explicit FunctionOptions(const CapturedStmt *S, bool UIntPtrCastRequired,
518 bool RegisterCastedArgsOnly, StringRef FunctionName,
519 SourceLocation Loc, bool IsDeviceKernel)
520 : S(S), UIntPtrCastRequired(UIntPtrCastRequired),
521 RegisterCastedArgsOnly(UIntPtrCastRequired && RegisterCastedArgsOnly),
522 FunctionName(FunctionName), Loc(Loc), IsDeviceKernel(IsDeviceKernel) {}
523};
524} // namespace
525
526static llvm::Function *emitOutlinedFunctionPrologue(
528 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>>
529 &LocalAddrs,
530 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>>
531 &VLASizes,
532 llvm::Value *&CXXThisValue, const FunctionOptions &FO) {
533 const CapturedDecl *CD = FO.S->getCapturedDecl();
534 const RecordDecl *RD = FO.S->getCapturedRecordDecl();
535 assert(CD->hasBody() && "missing CapturedDecl body");
536
537 CXXThisValue = nullptr;
538 // Build the argument list.
539 CodeGenModule &CGM = CGF.CGM;
540 ASTContext &Ctx = CGM.getContext();
541 FunctionArgList TargetArgs;
542 Args.append(CD->param_begin(),
543 std::next(CD->param_begin(), CD->getContextParamPosition()));
544 TargetArgs.append(
545 CD->param_begin(),
546 std::next(CD->param_begin(), CD->getContextParamPosition()));
547 auto I = FO.S->captures().begin();
548 FunctionDecl *DebugFunctionDecl = nullptr;
549 if (!FO.UIntPtrCastRequired) {
551 QualType FunctionTy = Ctx.getFunctionType(Ctx.VoidTy, {}, EPI);
552 DebugFunctionDecl = FunctionDecl::Create(
553 Ctx, Ctx.getTranslationUnitDecl(), FO.S->getBeginLoc(),
554 SourceLocation(), DeclarationName(), FunctionTy,
555 Ctx.getTrivialTypeSourceInfo(FunctionTy), SC_Static,
556 /*UsesFPIntrin=*/false, /*isInlineSpecified=*/false,
557 /*hasWrittenPrototype=*/false);
558 }
559 for (const FieldDecl *FD : RD->fields()) {
560 QualType ArgType = FD->getType();
561 IdentifierInfo *II = nullptr;
562 VarDecl *CapVar = nullptr;
563
564 // If this is a capture by copy and the type is not a pointer, the outlined
565 // function argument type should be uintptr and the value properly casted to
566 // uintptr. This is necessary given that the runtime library is only able to
567 // deal with pointers. We can pass in the same way the VLA type sizes to the
568 // outlined function.
569 if (FO.UIntPtrCastRequired &&
570 ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
571 I->capturesVariableArrayType()))
572 ArgType = Ctx.getUIntPtrType();
573
574 if (I->capturesVariable() || I->capturesVariableByCopy()) {
575 CapVar = I->getCapturedVar();
576 II = CapVar->getIdentifier();
577 } else if (I->capturesThis()) {
578 II = &Ctx.Idents.get("this");
579 } else {
580 assert(I->capturesVariableArrayType());
581 II = &Ctx.Idents.get("vla");
582 }
583 if (ArgType->isVariablyModifiedType())
584 ArgType = getCanonicalParamType(Ctx, ArgType);
585 VarDecl *Arg;
586 if (CapVar && (CapVar->getTLSKind() != clang::VarDecl::TLS_None)) {
587 Arg = ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(),
588 II, ArgType,
590 } else if (DebugFunctionDecl && (CapVar || I->capturesThis())) {
592 Ctx, DebugFunctionDecl,
593 CapVar ? CapVar->getBeginLoc() : FD->getBeginLoc(),
594 CapVar ? CapVar->getLocation() : FD->getLocation(), II, ArgType,
595 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
596 } else {
597 Arg = ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(),
598 II, ArgType, ImplicitParamKind::Other);
599 }
600 Args.emplace_back(Arg);
601 // Do not cast arguments if we emit function with non-original types.
602 TargetArgs.emplace_back(
603 FO.UIntPtrCastRequired
604 ? Arg
605 : CGM.getOpenMPRuntime().translateParameter(FD, Arg));
606 ++I;
607 }
608 Args.append(std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
609 CD->param_end());
610 TargetArgs.append(
611 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
612 CD->param_end());
613
614 // Create the function declaration.
615 const CGFunctionInfo &FuncInfo =
616 FO.IsDeviceKernel
618 TargetArgs)
620 TargetArgs);
621 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
622
623 auto *F =
624 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
625 FO.FunctionName, &CGM.getModule());
626 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
627
628 // Adjust the calling convention for SPIR-V targets to avoid mismatches
629 // between callee and caller.
630 if (CGM.getTriple().isSPIRV() && !FO.IsDeviceKernel)
631 F->setCallingConv(llvm::CallingConv::SPIR_FUNC);
632
633 if (CD->isNothrow())
634 F->setDoesNotThrow();
635
636 // Always inline the outlined function if optimizations are enabled.
637 if (CGM.getCodeGenOpts().OptimizationLevel != 0) {
638 F->removeFnAttr(llvm::Attribute::NoInline);
639 F->addFnAttr(llvm::Attribute::AlwaysInline);
640 }
641 if (!CGM.getCodeGenOpts().SampleProfileFile.empty())
642 F->addFnAttr("sample-profile-suffix-elision-policy", "selected");
643
644 // Generate the function.
645 CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, TargetArgs,
646 FO.UIntPtrCastRequired ? FO.Loc : FO.S->getBeginLoc(),
647 FO.UIntPtrCastRequired ? FO.Loc
648 : CD->getBody()->getBeginLoc());
649 unsigned Cnt = CD->getContextParamPosition();
650 I = FO.S->captures().begin();
651 for (const FieldDecl *FD : RD->fields()) {
652 // Do not map arguments if we emit function with non-original types.
653 Address LocalAddr(Address::invalid());
654 if (!FO.UIntPtrCastRequired && Args[Cnt] != TargetArgs[Cnt]) {
655 LocalAddr = CGM.getOpenMPRuntime().getParameterAddress(CGF, Args[Cnt],
656 TargetArgs[Cnt]);
657 } else {
658 LocalAddr = CGF.GetAddrOfLocalVar(Args[Cnt]);
659 }
660 // If we are capturing a pointer by copy we don't need to do anything, just
661 // use the value that we get from the arguments.
662 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
663 const VarDecl *CurVD = I->getCapturedVar();
664 if (!FO.RegisterCastedArgsOnly)
665 LocalAddrs.insert({Args[Cnt], {CurVD, LocalAddr}});
666 ++Cnt;
667 ++I;
668 continue;
669 }
670
671 LValue ArgLVal = CGF.MakeAddrLValue(LocalAddr, Args[Cnt]->getType(),
673 if (FD->hasCapturedVLAType()) {
674 if (FO.UIntPtrCastRequired) {
675 ArgLVal = CGF.MakeAddrLValue(
676 castValueFromUintptr(CGF, I->getLocation(), FD->getType(),
677 Args[Cnt]->getName(), ArgLVal),
679 }
680 llvm::Value *ExprArg = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation());
681 const VariableArrayType *VAT = FD->getCapturedVLAType();
682 VLASizes.try_emplace(Args[Cnt], VAT->getSizeExpr(), ExprArg);
683 } else if (I->capturesVariable()) {
684 const VarDecl *Var = I->getCapturedVar();
685 QualType VarTy = Var->getType();
686 Address ArgAddr = ArgLVal.getAddress();
687 if (ArgLVal.getType()->isLValueReferenceType()) {
688 ArgAddr = CGF.EmitLoadOfReference(ArgLVal);
689 } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) {
690 assert(ArgLVal.getType()->isPointerType());
691 ArgAddr = CGF.EmitLoadOfPointer(
692 ArgAddr, ArgLVal.getType()->castAs<PointerType>());
693 }
694 if (!FO.RegisterCastedArgsOnly) {
695 LocalAddrs.insert(
696 {Args[Cnt], {Var, ArgAddr.withAlignment(Ctx.getDeclAlign(Var))}});
697 }
698 } else if (I->capturesVariableByCopy()) {
699 assert(!FD->getType()->isAnyPointerType() &&
700 "Not expecting a captured pointer.");
701 const VarDecl *Var = I->getCapturedVar();
702 LocalAddrs.insert({Args[Cnt],
703 {Var, FO.UIntPtrCastRequired
705 CGF, I->getLocation(), FD->getType(),
706 Args[Cnt]->getName(), ArgLVal)
707 : ArgLVal.getAddress()}});
708 } else {
709 // If 'this' is captured, load it into CXXThisValue.
710 assert(I->capturesThis());
711 CXXThisValue = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation());
712 LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress()}});
713 }
714 ++Cnt;
715 ++I;
716 }
717
718 return F;
719}
720
723 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>>
724 &LocalAddrs,
725 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>>
726 &VLASizes,
727 llvm::Value *&CXXThisValue, llvm::Value *&ContextV, const CapturedStmt &CS,
728 SourceLocation Loc, StringRef FunctionName) {
729 const CapturedDecl *CD = CS.getCapturedDecl();
730 const RecordDecl *RD = CS.getCapturedRecordDecl();
731
732 CXXThisValue = nullptr;
733 CodeGenModule &CGM = CGF.CGM;
734 ASTContext &Ctx = CGM.getContext();
735 Args.push_back(CD->getContextParam());
736
737 const CGFunctionInfo &FuncInfo =
739 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
740
741 auto *F =
742 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
743 FunctionName, &CGM.getModule());
744 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
745 if (CD->isNothrow())
746 F->setDoesNotThrow();
747
748 CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, Loc, Loc);
749 Address ContextAddr = CGF.GetAddrOfLocalVar(CD->getContextParam());
750 ContextV = CGF.Builder.CreateLoad(ContextAddr);
751
752 // The runtime passes arguments as an array of pointers.
753 llvm::Type *PtrTy = CGF.Builder.getPtrTy();
754 llvm::Align PtrAlign = CGM.getDataLayout().getPointerABIAlignment(0);
755 CharUnits SlotAlign = CharUnits::fromQuantity(PtrAlign.value());
756
757 for (auto [FD, C, FieldIdx] :
758 llvm::zip(RD->fields(), CS.captures(),
759 llvm::seq<unsigned>(RD->getNumFields()))) {
760 llvm::Value *SlotPtr =
761 CGF.Builder.CreateConstInBoundsGEP1_32(PtrTy, ContextV, FieldIdx);
762 llvm::Value *Slot = CGF.Builder.CreateAlignedLoad(PtrTy, SlotPtr, PtrAlign);
763
764 // Generate the appropriate load from the per-argument storage. This
765 // includes all of the user arguments as well as the implicit kernel
766 // argument pointer.
767 if (C.capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
768 const VarDecl *CurVD = C.getCapturedVar();
769 Slot->setName(CurVD->getName());
770 Address SlotAddr(Slot, PtrTy, SlotAlign);
771 LocalAddrs.insert({FD, {CurVD, SlotAddr}});
772 } else if (FD->hasCapturedVLAType()) {
773 // VLA size is stored as intptr_t directly in the slot.
774 Address SlotAddr(Slot, CGF.ConvertTypeForMem(FD->getType()), SlotAlign);
775 LValue ArgLVal =
776 CGF.MakeAddrLValue(SlotAddr, FD->getType(), AlignmentSource::Decl);
777 llvm::Value *ExprArg = CGF.EmitLoadOfScalar(ArgLVal, C.getLocation());
778 const VariableArrayType *VAT = FD->getCapturedVLAType();
779 VLASizes.try_emplace(FD, VAT->getSizeExpr(), ExprArg);
780 } else if (C.capturesVariable()) {
781 const VarDecl *Var = C.getCapturedVar();
782 QualType VarTy = Var->getType();
783
784 if (VarTy->isVariablyModifiedType() && VarTy->isPointerType()) {
785 Slot->setName(Var->getName() + ".addr");
786 Address SlotAddr(Slot, PtrTy, SlotAlign);
787 LocalAddrs.insert({FD, {Var, SlotAddr}});
788 } else {
789 llvm::Value *VarAddr = CGF.Builder.CreateAlignedLoad(
790 PtrTy, Slot, PtrAlign, Var->getName());
791 LocalAddrs.insert({FD,
792 {Var, Address(VarAddr, CGF.ConvertTypeForMem(VarTy),
793 Ctx.getDeclAlign(Var))}});
794 }
795 } else if (C.capturesVariableByCopy()) {
796 assert(!FD->getType()->isAnyPointerType() &&
797 "Not expecting a captured pointer.");
798 const VarDecl *Var = C.getCapturedVar();
799 QualType FieldTy = FD->getType();
800
801 // Scalar values are promoted and stored directly in the slot.
802 Address SlotAddr(Slot, CGF.ConvertTypeForMem(FieldTy), SlotAlign);
803 Address CopyAddr =
804 CGF.CreateMemTemp(FieldTy, Ctx.getDeclAlign(FD), Var->getName());
805 LValue SrcLVal =
806 CGF.MakeAddrLValue(SlotAddr, FieldTy, AlignmentSource::Decl);
807 LValue CopyLVal =
808 CGF.MakeAddrLValue(CopyAddr, FieldTy, AlignmentSource::Decl);
809
810 RValue ArgRVal = CGF.EmitLoadOfLValue(SrcLVal, C.getLocation());
811 CGF.EmitStoreThroughLValue(ArgRVal, CopyLVal);
812
813 LocalAddrs.insert({FD, {Var, CopyAddr}});
814 } else {
815 assert(C.capturesThis() && "Default case expected to be CXX 'this'");
816 CXXThisValue =
817 CGF.Builder.CreateAlignedLoad(PtrTy, Slot, PtrAlign, "this");
818 Address SlotAddr(Slot, PtrTy, SlotAlign);
819 LocalAddrs.insert({FD, {nullptr, SlotAddr}});
820 }
821 }
822
823 return F;
824}
825
827 const CapturedStmt &S, const OMPExecutableDirective &D) {
828 SourceLocation Loc = D.getBeginLoc();
829 assert(
831 "CapturedStmtInfo should be set when generating the captured function");
832 const CapturedDecl *CD = S.getCapturedDecl();
833 // Build the argument list.
834 bool NeedWrapperFunction =
835 getDebugInfo() && CGM.getCodeGenOpts().hasReducedDebugInfo();
836 FunctionArgList Args, WrapperArgs;
837 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs,
838 WrapperLocalAddrs;
839 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes,
840 WrapperVLASizes;
841 SmallString<256> Buffer;
842 llvm::raw_svector_ostream Out(Buffer);
843 Out << CapturedStmtInfo->getHelperName();
845 bool IsDeviceKernel = CGM.getOpenMPRuntime().isGPU() &&
847 D.getCapturedStmt(OMPD_target) == &S;
848 CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true);
849 llvm::Function *WrapperF = nullptr;
850 if (NeedWrapperFunction) {
851 // Emit the final kernel early to allow attributes to be added by the
852 // OpenMPI-IR-Builder.
853 FunctionOptions WrapperFO(&S, /*UIntPtrCastRequired=*/true,
854 /*RegisterCastedArgsOnly=*/true,
855 CapturedStmtInfo->getHelperName(), Loc,
856 IsDeviceKernel);
858 WrapperF =
859 emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes,
860 WrapperCGF.CXXThisValue, WrapperFO);
861 Out << "_debug__";
862 }
863 FunctionOptions FO(&S, !NeedWrapperFunction, /*RegisterCastedArgsOnly=*/false,
864 Out.str(), Loc, !NeedWrapperFunction && IsDeviceKernel);
865 llvm::Function *F = emitOutlinedFunctionPrologue(
866 *this, WrapperArgs, WrapperLocalAddrs, WrapperVLASizes, CXXThisValue, FO);
867 CodeGenFunction::OMPPrivateScope LocalScope(*this);
868 for (const auto &LocalAddrPair : WrapperLocalAddrs) {
869 if (LocalAddrPair.second.first) {
870 LocalScope.addPrivate(LocalAddrPair.second.first,
871 LocalAddrPair.second.second);
872 }
873 }
874 (void)LocalScope.Privatize();
875 for (const auto &VLASizePair : WrapperVLASizes)
876 VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second;
877 PGO->assignRegionCounters(GlobalDecl(CD), F);
878 CapturedStmtInfo->EmitBody(*this, CD->getBody());
879 LocalScope.ForceCleanup();
881 if (!NeedWrapperFunction)
882 return F;
883
884 // Reverse the order.
885 WrapperF->removeFromParent();
886 F->getParent()->getFunctionList().insertAfter(F->getIterator(), WrapperF);
887
889 auto *PI = F->arg_begin();
890 for (const auto *Arg : Args) {
891 llvm::Value *CallArg;
892 auto I = LocalAddrs.find(Arg);
893 if (I != LocalAddrs.end()) {
894 LValue LV = WrapperCGF.MakeAddrLValue(
895 I->second.second,
896 I->second.first ? I->second.first->getType() : Arg->getType(),
898 if (LV.getType()->isAnyComplexType())
899 LV.setAddress(LV.getAddress().withElementType(PI->getType()));
900 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getBeginLoc());
901 } else {
902 auto EI = VLASizes.find(Arg);
903 if (EI != VLASizes.end()) {
904 CallArg = EI->second.second;
905 } else {
906 LValue LV =
907 WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg),
909 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getBeginLoc());
910 }
911 }
912 CallArgs.emplace_back(WrapperCGF.EmitFromMemory(CallArg, Arg->getType()));
913 ++PI;
914 }
915 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, Loc, F, CallArgs);
916 WrapperCGF.FinishFunction();
917 return WrapperF;
918}
919
921 const CapturedStmt &S, const OMPExecutableDirective &D) {
922 SourceLocation Loc = D.getBeginLoc();
923 assert(
925 "CapturedStmtInfo should be set when generating the captured function");
926 const CapturedDecl *CD = S.getCapturedDecl();
927 const RecordDecl *RD = S.getCapturedRecordDecl();
928 StringRef FunctionName = CapturedStmtInfo->getHelperName();
929 bool NeedWrapperFunction =
930 getDebugInfo() && CGM.getCodeGenOpts().hasReducedDebugInfo();
931
932 CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true);
933 llvm::Function *WrapperF = nullptr;
934 llvm::Value *WrapperContextV = nullptr;
935 if (NeedWrapperFunction) {
937 FunctionArgList WrapperArgs;
938 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>>
939 WrapperLocalAddrs;
940 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>>
941 WrapperVLASizes;
943 WrapperCGF, WrapperArgs, WrapperLocalAddrs, WrapperVLASizes,
944 WrapperCGF.CXXThisValue, WrapperContextV, S, Loc, FunctionName);
945 }
946
947 FunctionArgList Args;
948 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs;
949 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes;
950 llvm::Function *F;
951
952 if (NeedWrapperFunction) {
953 SmallString<256> Buffer;
954 llvm::raw_svector_ostream Out(Buffer);
955 Out << FunctionName << "_debug__";
956
957 FunctionOptions FO(&S, /*UIntPtrCastRequired=*/false,
958 /*RegisterCastedArgsOnly=*/false, Out.str(), Loc,
959 /*IsDeviceKernel=*/false);
960 F = emitOutlinedFunctionPrologue(*this, Args, LocalAddrs, VLASizes,
961 CXXThisValue, FO);
962 } else {
963 llvm::Value *ContextV = nullptr;
964 F = emitOutlinedFunctionPrologueAggregate(*this, Args, LocalAddrs, VLASizes,
965 CXXThisValue, ContextV, S, Loc,
966 FunctionName);
967
968 const RecordDecl *RD = S.getCapturedRecordDecl();
969 unsigned FieldIdx = RD->getNumFields();
970 for (unsigned I = 0; I < CD->getNumParams(); ++I) {
971 const ImplicitParamDecl *Param = CD->getParam(I);
972 if (Param == CD->getContextParam())
973 continue;
974 llvm::Align PtrAlign = CGM.getDataLayout().getPointerABIAlignment(0);
975 llvm::Value *SlotPtr = Builder.CreateConstInBoundsGEP1_32(
976 Builder.getPtrTy(), ContextV, FieldIdx,
977 Twine(Param->getName()) + ".addr");
978 llvm::Value *ParamAddr =
979 Builder.CreateAlignedLoad(Builder.getPtrTy(), SlotPtr, PtrAlign);
980 llvm::Value *ParamVal = Builder.CreateAlignedLoad(
981 Builder.getPtrTy(), ParamAddr, PtrAlign, Param->getName());
982 Address ParamLocalAddr =
983 CreateMemTemp(Param->getType(), Param->getName());
984 Builder.CreateStore(ParamVal, ParamLocalAddr);
985 LocalAddrs.insert({Param, {Param, ParamLocalAddr}});
986 ++FieldIdx;
987 }
988 }
989
990 CodeGenFunction::OMPPrivateScope LocalScope(*this);
991 for (const auto &LocalAddrPair : LocalAddrs) {
992 if (LocalAddrPair.second.first)
993 LocalScope.addPrivate(LocalAddrPair.second.first,
994 LocalAddrPair.second.second);
995 }
996 (void)LocalScope.Privatize();
997 for (const auto &VLASizePair : VLASizes)
998 VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second;
999 PGO->assignRegionCounters(GlobalDecl(CD), F);
1000 CapturedStmtInfo->EmitBody(*this, CD->getBody());
1001 (void)LocalScope.ForceCleanup();
1003
1004 if (!NeedWrapperFunction)
1005 return F;
1006
1007 // Reverse the order.
1008 WrapperF->removeFromParent();
1009 F->getParent()->getFunctionList().insertAfter(F->getIterator(), WrapperF);
1010
1011 llvm::Align PtrAlign = CGM.getDataLayout().getPointerABIAlignment(0);
1013 assert(CD->getContextParamPosition() == 0 &&
1014 "Expected context param at position 0 for target regions");
1015 assert(RD->getNumFields() + 1 == F->getNumOperands() &&
1016 "Argument count mismatch");
1017
1018 for (auto [FD, InnerParam, SlotIdx] : llvm::zip(
1019 RD->fields(), F->args(), llvm::seq<unsigned>(RD->getNumFields()))) {
1020 llvm::Value *SlotPtr = WrapperCGF.Builder.CreateConstInBoundsGEP1_32(
1021 WrapperCGF.Builder.getPtrTy(), WrapperContextV, SlotIdx);
1022 llvm::Value *Slot = WrapperCGF.Builder.CreateAlignedLoad(
1023 WrapperCGF.Builder.getPtrTy(), SlotPtr, PtrAlign);
1024 llvm::Value *Val = WrapperCGF.Builder.CreateAlignedLoad(
1025 InnerParam.getType(), Slot, PtrAlign, InnerParam.getName());
1026 CallArgs.push_back(Val);
1027 }
1028
1029 // Handle the load from the implicit dyn_ptr at the end of the __context.
1030 unsigned SlotIdx = RD->getNumFields();
1031 auto InnerParam = F->arg_begin() + SlotIdx;
1032 llvm::Value *SlotPtr = WrapperCGF.Builder.CreateConstInBoundsGEP1_32(
1033 WrapperCGF.Builder.getPtrTy(), WrapperContextV, SlotIdx);
1034 llvm::Value *Slot = WrapperCGF.Builder.CreateAlignedLoad(
1035 WrapperCGF.Builder.getPtrTy(), SlotPtr, PtrAlign);
1036 llvm::Value *Val = WrapperCGF.Builder.CreateAlignedLoad(
1037 InnerParam->getType(), Slot, PtrAlign, InnerParam->getName());
1038 CallArgs.push_back(Val);
1039
1040 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, Loc, F, CallArgs);
1041 WrapperCGF.FinishFunction();
1042 return WrapperF;
1043}
1044
1045//===----------------------------------------------------------------------===//
1046// OpenMP Directive Emission
1047//===----------------------------------------------------------------------===//
1049 Address DestAddr, Address SrcAddr, QualType OriginalType,
1050 const llvm::function_ref<void(Address, Address)> CopyGen) {
1051 // Perform element-by-element initialization.
1052 QualType ElementTy;
1053
1054 // Drill down to the base element type on both arrays.
1055 const ArrayType *ArrayTy = OriginalType->getAsArrayTypeUnsafe();
1056 llvm::Value *NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
1057 SrcAddr = SrcAddr.withElementType(DestAddr.getElementType());
1058
1059 llvm::Value *SrcBegin = SrcAddr.emitRawPointer(*this);
1060 llvm::Value *DestBegin = DestAddr.emitRawPointer(*this);
1061 // Cast from pointer to array type to pointer to single element.
1062 llvm::Value *DestEnd = Builder.CreateInBoundsGEP(DestAddr.getElementType(),
1063 DestBegin, NumElements);
1064
1065 // The basic structure here is a while-do loop.
1066 llvm::BasicBlock *BodyBB = createBasicBlock("omp.arraycpy.body");
1067 llvm::BasicBlock *DoneBB = createBasicBlock("omp.arraycpy.done");
1068 llvm::Value *IsEmpty =
1069 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
1070 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
1071
1072 // Enter the loop body, making that address the current address.
1073 llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
1074 EmitBlock(BodyBB);
1075
1076 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
1077
1078 llvm::PHINode *SrcElementPHI =
1079 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
1080 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
1081 Address SrcElementCurrent =
1082 Address(SrcElementPHI, SrcAddr.getElementType(),
1083 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
1084
1085 llvm::PHINode *DestElementPHI = Builder.CreatePHI(
1086 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
1087 DestElementPHI->addIncoming(DestBegin, EntryBB);
1088 Address DestElementCurrent =
1089 Address(DestElementPHI, DestAddr.getElementType(),
1090 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
1091
1092 // Emit copy.
1093 CopyGen(DestElementCurrent, SrcElementCurrent);
1094
1095 // Shift the address forward by one element.
1096 llvm::Value *DestElementNext =
1097 Builder.CreateConstGEP1_32(DestAddr.getElementType(), DestElementPHI,
1098 /*Idx0=*/1, "omp.arraycpy.dest.element");
1099 llvm::Value *SrcElementNext =
1100 Builder.CreateConstGEP1_32(SrcAddr.getElementType(), SrcElementPHI,
1101 /*Idx0=*/1, "omp.arraycpy.src.element");
1102 // Check whether we've reached the end.
1103 llvm::Value *Done =
1104 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
1105 Builder.CreateCondBr(Done, DoneBB, BodyBB);
1106 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
1107 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
1108
1109 // Done.
1110 EmitBlock(DoneBB, /*IsFinished=*/true);
1111}
1112
1114 Address SrcAddr, const VarDecl *DestVD,
1115 const VarDecl *SrcVD, const Expr *Copy) {
1116 if (OriginalType->isArrayType()) {
1117 const auto *BO = dyn_cast<BinaryOperator>(Copy);
1118 if (BO && BO->getOpcode() == BO_Assign) {
1119 // Perform simple memcpy for simple copying.
1120 LValue Dest = MakeAddrLValue(DestAddr, OriginalType);
1121 LValue Src = MakeAddrLValue(SrcAddr, OriginalType);
1122 EmitAggregateAssign(Dest, Src, OriginalType);
1123 } else {
1124 // For arrays with complex element types perform element by element
1125 // copying.
1127 DestAddr, SrcAddr, OriginalType,
1128 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
1129 // Working with the single array element, so have to remap
1130 // destination and source variables to corresponding array
1131 // elements.
1133 Remap.addPrivate(DestVD, DestElement);
1134 Remap.addPrivate(SrcVD, SrcElement);
1135 (void)Remap.Privatize();
1137 });
1138 }
1139 } else {
1140 // Remap pseudo source variable to private copy.
1142 Remap.addPrivate(SrcVD, SrcAddr);
1143 Remap.addPrivate(DestVD, DestAddr);
1144 (void)Remap.Privatize();
1145 // Emit copying of the whole variable.
1147 }
1148}
1149
1151 OMPPrivateScope &PrivateScope) {
1152 if (!HaveInsertPoint())
1153 return false;
1155 bool DeviceConstTarget = getLangOpts().OpenMPIsTargetDevice &&
1157 bool FirstprivateIsLastprivate = false;
1158 llvm::DenseMap<const VarDecl *, OpenMPLastprivateModifier> Lastprivates;
1159 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
1160 for (const auto *D : C->varlist())
1161 Lastprivates.try_emplace(
1163 C->getKind());
1164 }
1165 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
1167 getOpenMPCaptureRegions(CaptureRegions, EKind);
1168 // Force emission of the firstprivate copy if the directive does not emit
1169 // outlined function, like omp for, omp simd, omp distribute etc.
1170 bool MustEmitFirstprivateCopy =
1171 CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown;
1172 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
1173 const auto *IRef = C->varlist_begin();
1174 const auto *InitsRef = C->inits().begin();
1175 for (const Expr *IInit : C->private_copies()) {
1176 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1177 bool ThisFirstprivateIsLastprivate =
1178 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
1179 const FieldDecl *FD = CapturedStmtInfo->lookup(OrigVD);
1180 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
1181 if (!MustEmitFirstprivateCopy && !ThisFirstprivateIsLastprivate && FD &&
1182 !FD->getType()->isReferenceType() &&
1183 (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())) {
1184 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
1185 ++IRef;
1186 ++InitsRef;
1187 continue;
1188 }
1189 // Do not emit copy for firstprivate constant variables in target regions,
1190 // captured by reference.
1191 if (DeviceConstTarget && OrigVD->getType().isConstant(getContext()) &&
1192 FD && FD->getType()->isReferenceType() &&
1193 (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())) {
1194 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
1195 ++IRef;
1196 ++InitsRef;
1197 continue;
1198 }
1199 FirstprivateIsLastprivate =
1200 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
1201 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
1202 const auto *VDInit =
1203 cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
1204 bool IsRegistered;
1205 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
1206 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
1207 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
1208 LValue OriginalLVal;
1209 if (!FD) {
1210 // Check if the firstprivate variable is just a constant value.
1212 if (CE && !CE.isReference()) {
1213 // Constant value, no need to create a copy.
1214 ++IRef;
1215 ++InitsRef;
1216 continue;
1217 }
1218 if (CE && CE.isReference()) {
1219 OriginalLVal = CE.getReferenceLValue(*this, &DRE);
1220 } else {
1221 assert(!CE && "Expected non-constant firstprivate.");
1222 OriginalLVal = EmitLValue(&DRE);
1223 }
1224 } else {
1225 OriginalLVal = EmitLValue(&DRE);
1226 }
1227 QualType Type = VD->getType();
1228 if (Type->isArrayType()) {
1229 // Emit VarDecl with copy init for arrays.
1230 // Get the address of the original variable captured in current
1231 // captured region.
1232 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1233 const Expr *Init = VD->getInit();
1235 // Perform simple memcpy.
1236 LValue Dest = MakeAddrLValue(Emission.getAllocatedAddress(), Type);
1237 EmitAggregateAssign(Dest, OriginalLVal, Type);
1238 } else {
1240 Emission.getAllocatedAddress(), OriginalLVal.getAddress(), Type,
1241 [this, VDInit, Init](Address DestElement, Address SrcElement) {
1242 // Clean up any temporaries needed by the
1243 // initialization.
1244 RunCleanupsScope InitScope(*this);
1245 // Emit initialization for single element.
1246 setAddrOfLocalVar(VDInit, SrcElement);
1247 EmitAnyExprToMem(Init, DestElement,
1248 Init->getType().getQualifiers(),
1249 /*IsInitializer*/ false);
1250 LocalDeclMap.erase(VDInit);
1251 });
1252 }
1253 EmitAutoVarCleanups(Emission);
1254 IsRegistered =
1255 PrivateScope.addPrivate(OrigVD, Emission.getAllocatedAddress());
1256 } else {
1257 Address OriginalAddr = OriginalLVal.getAddress();
1258 // Emit private VarDecl with copy init.
1259 // Remap temp VDInit variable to the address of the original
1260 // variable (for proper handling of captured global variables).
1261 setAddrOfLocalVar(VDInit, OriginalAddr);
1262 EmitDecl(*VD);
1263 LocalDeclMap.erase(VDInit);
1264 Address VDAddr = GetAddrOfLocalVar(VD);
1265 if (ThisFirstprivateIsLastprivate &&
1266 Lastprivates[OrigVD->getCanonicalDecl()] ==
1267 OMPC_LASTPRIVATE_conditional) {
1268 // Create/init special variable for lastprivate conditionals.
1269 llvm::Value *V =
1270 EmitLoadOfScalar(MakeAddrLValue(VDAddr, (*IRef)->getType(),
1272 (*IRef)->getExprLoc());
1273 VDAddr = CGM.getOpenMPRuntime().emitLastprivateConditionalInit(
1274 *this, OrigVD);
1275 EmitStoreOfScalar(V, MakeAddrLValue(VDAddr, (*IRef)->getType(),
1277 LocalDeclMap.erase(VD);
1278 setAddrOfLocalVar(VD, VDAddr);
1279 }
1280 IsRegistered = PrivateScope.addPrivate(OrigVD, VDAddr);
1281 }
1282 assert(IsRegistered &&
1283 "firstprivate var already registered as private");
1284 // Silence the warning about unused variable.
1285 (void)IsRegistered;
1286 }
1287 ++IRef;
1288 ++InitsRef;
1289 }
1290 }
1291 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
1292}
1293
1295 const OMPExecutableDirective &D,
1296 CodeGenFunction::OMPPrivateScope &PrivateScope) {
1297 if (!HaveInsertPoint())
1298 return;
1299 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
1300 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
1301 auto IRef = C->varlist_begin();
1302 for (const Expr *IInit : C->private_copies()) {
1303 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1304 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
1305 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
1306 EmitDecl(*VD);
1307 // Emit private VarDecl with copy init.
1308 bool IsRegistered =
1309 PrivateScope.addPrivate(OrigVD, GetAddrOfLocalVar(VD));
1310 assert(IsRegistered && "private var already registered as private");
1311 // Silence the warning about unused variable.
1312 (void)IsRegistered;
1313 }
1314 ++IRef;
1315 }
1316 }
1317}
1318
1320 if (!HaveInsertPoint())
1321 return false;
1322 // threadprivate_var1 = master_threadprivate_var1;
1323 // operator=(threadprivate_var2, master_threadprivate_var2);
1324 // ...
1325 // __kmpc_barrier(&loc, global_tid);
1326 llvm::DenseSet<const VarDecl *> CopiedVars;
1327 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
1328 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
1329 auto IRef = C->varlist_begin();
1330 auto ISrcRef = C->source_exprs().begin();
1331 auto IDestRef = C->destination_exprs().begin();
1332 for (const Expr *AssignOp : C->assignment_ops()) {
1333 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1334 QualType Type = VD->getType();
1335 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
1336 // Get the address of the master variable. If we are emitting code with
1337 // TLS support, the address is passed from the master as field in the
1338 // captured declaration.
1339 Address MasterAddr = Address::invalid();
1340 if (getLangOpts().OpenMPUseTLS &&
1341 getContext().getTargetInfo().isTLSSupported()) {
1342 assert(CapturedStmtInfo->lookup(VD) &&
1343 "Copyin threadprivates should have been captured!");
1344 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(VD), true,
1345 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
1346 MasterAddr = EmitLValue(&DRE).getAddress();
1347 LocalDeclMap.erase(VD);
1348 } else {
1349 MasterAddr =
1350 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
1351 : CGM.GetAddrOfGlobal(VD),
1352 CGM.getTypes().ConvertTypeForMem(VD->getType()),
1353 getContext().getDeclAlign(VD));
1354 }
1355 // Get the address of the threadprivate variable.
1356 Address PrivateAddr = EmitLValue(*IRef).getAddress();
1357 if (CopiedVars.size() == 1) {
1358 // At first check if current thread is a master thread. If it is, no
1359 // need to copy data.
1360 CopyBegin = createBasicBlock("copyin.not.master");
1361 CopyEnd = createBasicBlock("copyin.not.master.end");
1362 // TODO: Avoid ptrtoint conversion.
1363 auto *MasterAddrInt = Builder.CreatePtrToInt(
1364 MasterAddr.emitRawPointer(*this), CGM.IntPtrTy);
1365 auto *PrivateAddrInt = Builder.CreatePtrToInt(
1366 PrivateAddr.emitRawPointer(*this), CGM.IntPtrTy);
1367 Builder.CreateCondBr(
1368 Builder.CreateICmpNE(MasterAddrInt, PrivateAddrInt), CopyBegin,
1369 CopyEnd);
1370 EmitBlock(CopyBegin);
1371 }
1372 const auto *SrcVD =
1373 cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
1374 const auto *DestVD =
1375 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
1376 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
1377 }
1378 ++IRef;
1379 ++ISrcRef;
1380 ++IDestRef;
1381 }
1382 }
1383 if (CopyEnd) {
1384 // Exit out of copying procedure for non-master thread.
1385 EmitBlock(CopyEnd, /*IsFinished=*/true);
1386 return true;
1387 }
1388 return false;
1389}
1390
1392 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
1393 if (!HaveInsertPoint())
1394 return false;
1395 bool HasAtLeastOneLastprivate = false;
1397 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1398 if (isOpenMPSimdDirective(EKind)) {
1399 const auto *LoopDirective = cast<OMPLoopDirective>(&D);
1400 for (const Expr *C : LoopDirective->counters()) {
1401 SIMDLCVs.insert(
1403 }
1404 }
1405 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
1406 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
1407 HasAtLeastOneLastprivate = true;
1408 if (isOpenMPTaskLoopDirective(EKind) && !getLangOpts().OpenMPSimd)
1409 break;
1410 const auto *IRef = C->varlist_begin();
1411 const auto *IDestRef = C->destination_exprs().begin();
1412 for (const Expr *IInit : C->private_copies()) {
1413 // Keep the address of the original variable for future update at the end
1414 // of the loop.
1415 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1416 // Taskloops do not require additional initialization, it is done in
1417 // runtime support library.
1418 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
1419 const auto *DestVD =
1420 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
1421 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
1422 /*RefersToEnclosingVariableOrCapture=*/
1423 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1424 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
1425 PrivateScope.addPrivate(DestVD, EmitLValue(&DRE).getAddress());
1426 // Check if the variable is also a firstprivate: in this case IInit is
1427 // not generated. Initialization of this variable will happen in codegen
1428 // for 'firstprivate' clause.
1429 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
1430 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
1431 Address VDAddr = Address::invalid();
1432 if (C->getKind() == OMPC_LASTPRIVATE_conditional) {
1433 VDAddr = CGM.getOpenMPRuntime().emitLastprivateConditionalInit(
1434 *this, OrigVD);
1435 setAddrOfLocalVar(VD, VDAddr);
1436 } else {
1437 // Emit private VarDecl with copy init.
1438 EmitDecl(*VD);
1439 VDAddr = GetAddrOfLocalVar(VD);
1440 }
1441 bool IsRegistered = PrivateScope.addPrivate(OrigVD, VDAddr);
1442 assert(IsRegistered &&
1443 "lastprivate var already registered as private");
1444 (void)IsRegistered;
1445 }
1446 }
1447 ++IRef;
1448 ++IDestRef;
1449 }
1450 }
1451 return HasAtLeastOneLastprivate;
1452}
1453
1455 const OMPExecutableDirective &D, bool NoFinals,
1456 llvm::Value *IsLastIterCond) {
1457 if (!HaveInsertPoint())
1458 return;
1459 // Emit following code:
1460 // if (<IsLastIterCond>) {
1461 // orig_var1 = private_orig_var1;
1462 // ...
1463 // orig_varn = private_orig_varn;
1464 // }
1465 llvm::BasicBlock *ThenBB = nullptr;
1466 llvm::BasicBlock *DoneBB = nullptr;
1467 if (IsLastIterCond) {
1468 // Emit implicit barrier if at least one lastprivate conditional is found
1469 // and this is not a simd mode.
1470 if (!getLangOpts().OpenMPSimd &&
1471 llvm::any_of(D.getClausesOfKind<OMPLastprivateClause>(),
1472 [](const OMPLastprivateClause *C) {
1473 return C->getKind() == OMPC_LASTPRIVATE_conditional;
1474 })) {
1475 CGM.getOpenMPRuntime().emitBarrierCall(*this, D.getBeginLoc(),
1476 OMPD_unknown,
1477 /*EmitChecks=*/false,
1478 /*ForceSimpleCall=*/true);
1479 }
1480 ThenBB = createBasicBlock(".omp.lastprivate.then");
1481 DoneBB = createBasicBlock(".omp.lastprivate.done");
1482 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
1483 EmitBlock(ThenBB);
1484 }
1485 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
1486 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
1487 if (const auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
1488 auto IC = LoopDirective->counters().begin();
1489 for (const Expr *F : LoopDirective->finals()) {
1490 const auto *D =
1491 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
1492 if (NoFinals)
1493 AlreadyEmittedVars.insert(D);
1494 else
1495 LoopCountersAndUpdates[D] = F;
1496 ++IC;
1497 }
1498 }
1499 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
1500 auto IRef = C->varlist_begin();
1501 auto ISrcRef = C->source_exprs().begin();
1502 auto IDestRef = C->destination_exprs().begin();
1503 for (const Expr *AssignOp : C->assignment_ops()) {
1504 const auto *PrivateVD =
1505 cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1506 QualType Type = PrivateVD->getType();
1507 const auto *CanonicalVD = PrivateVD->getCanonicalDecl();
1508 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
1509 // If lastprivate variable is a loop control variable for loop-based
1510 // directive, update its value before copyin back to original
1511 // variable.
1512 if (const Expr *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
1513 EmitIgnoredExpr(FinalExpr);
1514 const auto *SrcVD =
1515 cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
1516 const auto *DestVD =
1517 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
1518 // Get the address of the private variable.
1519 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
1520 if (const auto *RefTy = PrivateVD->getType()->getAs<ReferenceType>())
1521 PrivateAddr = Address(
1522 Builder.CreateLoad(PrivateAddr),
1523 CGM.getTypes().ConvertTypeForMem(RefTy->getPointeeType()),
1524 CGM.getNaturalTypeAlignment(RefTy->getPointeeType()));
1525 // Store the last value to the private copy in the last iteration.
1526 if (C->getKind() == OMPC_LASTPRIVATE_conditional)
1527 CGM.getOpenMPRuntime().emitLastprivateConditionalFinalUpdate(
1528 *this, MakeAddrLValue(PrivateAddr, (*IRef)->getType()), PrivateVD,
1529 (*IRef)->getExprLoc());
1530 // Get the address of the original variable.
1531 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
1532 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
1533 }
1534 ++IRef;
1535 ++ISrcRef;
1536 ++IDestRef;
1537 }
1538 if (const Expr *PostUpdate = C->getPostUpdateExpr())
1539 EmitIgnoredExpr(PostUpdate);
1540 }
1541 if (IsLastIterCond)
1542 EmitBlock(DoneBB, /*IsFinished=*/true);
1543}
1544
1546 const OMPExecutableDirective &D,
1547 CodeGenFunction::OMPPrivateScope &PrivateScope, bool ForInscan) {
1548 if (!HaveInsertPoint())
1549 return;
1552 SmallVector<const Expr *, 4> ReductionOps;
1558 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1559 if (ForInscan != (C->getModifier() == OMPC_REDUCTION_inscan))
1560 continue;
1561 Shareds.append(C->varlist_begin(), C->varlist_end());
1562 Privates.append(C->privates().begin(), C->privates().end());
1563 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1564 LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1565 RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1566 if (C->getModifier() == OMPC_REDUCTION_task) {
1567 Data.ReductionVars.append(C->privates().begin(), C->privates().end());
1568 Data.ReductionOrigs.append(C->varlist_begin(), C->varlist_end());
1569 Data.ReductionCopies.append(C->privates().begin(), C->privates().end());
1570 Data.ReductionOps.append(C->reduction_ops().begin(),
1571 C->reduction_ops().end());
1572 TaskLHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1573 TaskRHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1574 }
1575 }
1576 ReductionCodeGen RedCG(Shareds, Shareds, Privates, ReductionOps);
1577 unsigned Count = 0;
1578 auto *ILHS = LHSs.begin();
1579 auto *IRHS = RHSs.begin();
1580 auto *IPriv = Privates.begin();
1581 for (const Expr *IRef : Shareds) {
1582 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
1583 // Emit private VarDecl with reduction init.
1584 RedCG.emitSharedOrigLValue(*this, Count);
1585 RedCG.emitAggregateType(*this, Count);
1586 AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
1587 RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(),
1588 RedCG.getSharedLValue(Count).getAddress(),
1589 [&Emission](CodeGenFunction &CGF) {
1590 CGF.EmitAutoVarInit(Emission);
1591 return true;
1592 });
1593 EmitAutoVarCleanups(Emission);
1594 Address BaseAddr = RedCG.adjustPrivateAddress(
1595 *this, Count, Emission.getAllocatedAddress());
1596 bool IsRegistered =
1597 PrivateScope.addPrivate(RedCG.getBaseDecl(Count), BaseAddr);
1598 assert(IsRegistered && "private var already registered as private");
1599 // Silence the warning about unused variable.
1600 (void)IsRegistered;
1601
1602 const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
1603 const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
1604 QualType Type = PrivateVD->getType();
1605 bool isaOMPArraySectionExpr = isa<ArraySectionExpr>(IRef);
1606 if (isaOMPArraySectionExpr && Type->isVariablyModifiedType()) {
1607 // Store the address of the original variable associated with the LHS
1608 // implicit variable.
1609 PrivateScope.addPrivate(LHSVD, RedCG.getSharedLValue(Count).getAddress());
1610 PrivateScope.addPrivate(RHSVD, GetAddrOfLocalVar(PrivateVD));
1611 } else if ((isaOMPArraySectionExpr && Type->isScalarType()) ||
1613 // Store the address of the original variable associated with the LHS
1614 // implicit variable.
1615 PrivateScope.addPrivate(LHSVD, RedCG.getSharedLValue(Count).getAddress());
1616 PrivateScope.addPrivate(RHSVD,
1617 GetAddrOfLocalVar(PrivateVD).withElementType(
1618 ConvertTypeForMem(RHSVD->getType())));
1619 } else {
1620 QualType Type = PrivateVD->getType();
1621 bool IsArray = getContext().getAsArrayType(Type) != nullptr;
1622 Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress();
1623 // Store the address of the original variable associated with the LHS
1624 // implicit variable.
1625 if (IsArray) {
1626 OriginalAddr =
1627 OriginalAddr.withElementType(ConvertTypeForMem(LHSVD->getType()));
1628 }
1629 PrivateScope.addPrivate(LHSVD, OriginalAddr);
1630 PrivateScope.addPrivate(
1631 RHSVD, IsArray ? GetAddrOfLocalVar(PrivateVD).withElementType(
1632 ConvertTypeForMem(RHSVD->getType()))
1633 : GetAddrOfLocalVar(PrivateVD));
1634 }
1635 ++ILHS;
1636 ++IRHS;
1637 ++IPriv;
1638 ++Count;
1639 }
1640 if (!Data.ReductionVars.empty()) {
1642 Data.IsReductionWithTaskMod = true;
1643 Data.IsWorksharingReduction = isOpenMPWorksharingDirective(EKind);
1644 llvm::Value *ReductionDesc = CGM.getOpenMPRuntime().emitTaskReductionInit(
1645 *this, D.getBeginLoc(), TaskLHSs, TaskRHSs, Data);
1646 const Expr *TaskRedRef = nullptr;
1647 switch (EKind) {
1648 case OMPD_parallel:
1649 TaskRedRef = cast<OMPParallelDirective>(D).getTaskReductionRefExpr();
1650 break;
1651 case OMPD_for:
1652 TaskRedRef = cast<OMPForDirective>(D).getTaskReductionRefExpr();
1653 break;
1654 case OMPD_sections:
1655 TaskRedRef = cast<OMPSectionsDirective>(D).getTaskReductionRefExpr();
1656 break;
1657 case OMPD_parallel_for:
1658 TaskRedRef = cast<OMPParallelForDirective>(D).getTaskReductionRefExpr();
1659 break;
1660 case OMPD_parallel_master:
1661 TaskRedRef =
1662 cast<OMPParallelMasterDirective>(D).getTaskReductionRefExpr();
1663 break;
1664 case OMPD_parallel_sections:
1665 TaskRedRef =
1666 cast<OMPParallelSectionsDirective>(D).getTaskReductionRefExpr();
1667 break;
1668 case OMPD_target_parallel:
1669 TaskRedRef =
1670 cast<OMPTargetParallelDirective>(D).getTaskReductionRefExpr();
1671 break;
1672 case OMPD_target_parallel_for:
1673 TaskRedRef =
1674 cast<OMPTargetParallelForDirective>(D).getTaskReductionRefExpr();
1675 break;
1676 case OMPD_distribute_parallel_for:
1677 TaskRedRef =
1678 cast<OMPDistributeParallelForDirective>(D).getTaskReductionRefExpr();
1679 break;
1680 case OMPD_teams_distribute_parallel_for:
1682 .getTaskReductionRefExpr();
1683 break;
1684 case OMPD_target_teams_distribute_parallel_for:
1686 .getTaskReductionRefExpr();
1687 break;
1688 case OMPD_simd:
1689 case OMPD_for_simd:
1690 case OMPD_section:
1691 case OMPD_single:
1692 case OMPD_master:
1693 case OMPD_critical:
1694 case OMPD_parallel_for_simd:
1695 case OMPD_task:
1696 case OMPD_taskyield:
1697 case OMPD_error:
1698 case OMPD_barrier:
1699 case OMPD_taskwait:
1700 case OMPD_taskgroup:
1701 case OMPD_flush:
1702 case OMPD_depobj:
1703 case OMPD_scan:
1704 case OMPD_ordered_standalone:
1705 case OMPD_ordered_blockassoc:
1706 case OMPD_atomic:
1707 case OMPD_teams:
1708 case OMPD_target:
1709 case OMPD_cancellation_point:
1710 case OMPD_cancel:
1711 case OMPD_target_data:
1712 case OMPD_target_enter_data:
1713 case OMPD_target_exit_data:
1714 case OMPD_taskloop:
1715 case OMPD_taskloop_simd:
1716 case OMPD_master_taskloop:
1717 case OMPD_master_taskloop_simd:
1718 case OMPD_parallel_master_taskloop:
1719 case OMPD_parallel_master_taskloop_simd:
1720 case OMPD_distribute:
1721 case OMPD_target_update:
1722 case OMPD_distribute_parallel_for_simd:
1723 case OMPD_distribute_simd:
1724 case OMPD_target_parallel_for_simd:
1725 case OMPD_target_simd:
1726 case OMPD_teams_distribute:
1727 case OMPD_teams_distribute_simd:
1728 case OMPD_teams_distribute_parallel_for_simd:
1729 case OMPD_target_teams:
1730 case OMPD_target_teams_distribute:
1731 case OMPD_target_teams_distribute_parallel_for_simd:
1732 case OMPD_target_teams_distribute_simd:
1733 case OMPD_declare_target:
1734 case OMPD_end_declare_target:
1735 case OMPD_threadprivate:
1736 case OMPD_allocate:
1737 case OMPD_declare_reduction:
1738 case OMPD_declare_mapper:
1739 case OMPD_declare_simd:
1740 case OMPD_requires:
1741 case OMPD_declare_variant:
1742 case OMPD_begin_declare_variant:
1743 case OMPD_end_declare_variant:
1744 case OMPD_unknown:
1745 default:
1746 llvm_unreachable("Unexpected directive with task reductions.");
1747 }
1748
1749 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(TaskRedRef)->getDecl());
1750 EmitVarDecl(*VD);
1751 EmitStoreOfScalar(ReductionDesc, GetAddrOfLocalVar(VD),
1752 /*Volatile=*/false, TaskRedRef->getType());
1753 }
1754}
1755
1757 const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
1758 if (!HaveInsertPoint())
1759 return;
1764 llvm::SmallVector<bool, 8> IsPrivateVarReduction;
1765 bool HasAtLeastOneReduction = false;
1766 bool IsReductionWithTaskMod = false;
1767 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1768 // Do not emit for inscan reductions.
1769 if (C->getModifier() == OMPC_REDUCTION_inscan)
1770 continue;
1771 HasAtLeastOneReduction = true;
1772 Privates.append(C->privates().begin(), C->privates().end());
1773 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1774 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1775 IsPrivateVarReduction.append(C->private_var_reduction_flags().begin(),
1776 C->private_var_reduction_flags().end());
1777 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1778 IsReductionWithTaskMod =
1779 IsReductionWithTaskMod || C->getModifier() == OMPC_REDUCTION_task;
1780 }
1781 if (HasAtLeastOneReduction) {
1783 if (IsReductionWithTaskMod) {
1784 CGM.getOpenMPRuntime().emitTaskReductionFini(
1785 *this, D.getBeginLoc(), isOpenMPWorksharingDirective(EKind));
1786 }
1787 bool TeamsLoopCanBeParallel = false;
1788 if (auto *TTLD = dyn_cast<OMPTargetTeamsGenericLoopDirective>(&D))
1789 TeamsLoopCanBeParallel = TTLD->canBeParallelFor();
1790 bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
1792 TeamsLoopCanBeParallel || ReductionKind == OMPD_simd;
1793 bool SimpleReduction = ReductionKind == OMPD_simd;
1794 // Emit nowait reduction if nowait clause is present or directive is a
1795 // parallel directive (it always has implicit barrier).
1796 CGM.getOpenMPRuntime().emitReduction(
1797 *this, D.getEndLoc(), Privates, LHSExprs, RHSExprs, ReductionOps,
1798 {WithNowait, SimpleReduction, IsPrivateVarReduction, ReductionKind});
1799 }
1800}
1801
1804 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
1805 if (!CGF.HaveInsertPoint())
1806 return;
1807 llvm::BasicBlock *DoneBB = nullptr;
1808 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1809 if (const Expr *PostUpdate = C->getPostUpdateExpr()) {
1810 if (!DoneBB) {
1811 if (llvm::Value *Cond = CondGen(CGF)) {
1812 // If the first post-update expression is found, emit conditional
1813 // block if it was requested.
1814 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
1815 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1816 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1817 CGF.EmitBlock(ThenBB);
1818 }
1819 }
1820 CGF.EmitIgnoredExpr(PostUpdate);
1821 }
1822 }
1823 if (DoneBB)
1824 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1825}
1826
1827namespace {
1828/// Codegen lambda for appending distribute lower and upper bounds to outlined
1829/// parallel function. This is necessary for combined constructs such as
1830/// 'distribute parallel for'
1831typedef llvm::function_ref<void(CodeGenFunction &,
1832 const OMPExecutableDirective &,
1833 llvm::SmallVectorImpl<llvm::Value *> &)>
1834 CodeGenBoundParametersTy;
1835} // anonymous namespace
1836
1837static void
1839 const OMPExecutableDirective &S) {
1840 if (CGF.getLangOpts().OpenMP < 50)
1841 return;
1842 llvm::DenseSet<CanonicalDeclPtr<const VarDecl>> PrivateDecls;
1843 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
1844 for (const Expr *Ref : C->varlist()) {
1845 if (!Ref->getType()->isScalarType())
1846 continue;
1847 const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts());
1848 if (!DRE)
1849 continue;
1850 PrivateDecls.insert(cast<VarDecl>(DRE->getDecl()));
1852 }
1853 }
1854 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
1855 for (const Expr *Ref : C->varlist()) {
1856 if (!Ref->getType()->isScalarType())
1857 continue;
1858 const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts());
1859 if (!DRE)
1860 continue;
1861 PrivateDecls.insert(cast<VarDecl>(DRE->getDecl()));
1863 }
1864 }
1865 for (const auto *C : S.getClausesOfKind<OMPLinearClause>()) {
1866 for (const Expr *Ref : C->varlist()) {
1867 if (!Ref->getType()->isScalarType())
1868 continue;
1869 const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts());
1870 if (!DRE)
1871 continue;
1872 PrivateDecls.insert(cast<VarDecl>(DRE->getDecl()));
1874 }
1875 }
1876 // Privates should ne analyzed since they are not captured at all.
1877 // Task reductions may be skipped - tasks are ignored.
1878 // Firstprivates do not return value but may be passed by reference - no need
1879 // to check for updated lastprivate conditional.
1880 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
1881 for (const Expr *Ref : C->varlist()) {
1882 if (!Ref->getType()->isScalarType())
1883 continue;
1884 const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts());
1885 if (!DRE)
1886 continue;
1887 PrivateDecls.insert(cast<VarDecl>(DRE->getDecl()));
1888 }
1889 }
1891 CGF, S, PrivateDecls);
1892}
1893
1896 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1897 const CodeGenBoundParametersTy &CodeGenBoundParameters) {
1898 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
1899 llvm::Value *NumThreads = nullptr;
1901 // OpenMP 6.0, 10.4: "If no severity clause is specified then the effect is as
1902 // if sev-level is fatal."
1903 OpenMPSeverityClauseKind Severity = OMPC_SEVERITY_fatal;
1904 clang::Expr *Message = nullptr;
1905 SourceLocation SeverityLoc = SourceLocation();
1906 SourceLocation MessageLoc = SourceLocation();
1907
1908 llvm::Function *OutlinedFn =
1910 CGF, S, *CS->getCapturedDecl()->param_begin(), InnermostKind,
1911 CodeGen);
1912
1913 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
1914 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
1915 NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads().front(),
1916 /*IgnoreResultAssign=*/true);
1917 Modifier = NumThreadsClause->getPrescriptivenessModifier();
1918 if (const auto *MessageClause = S.getSingleClause<OMPMessageClause>()) {
1919 Message = MessageClause->getMessageString();
1920 MessageLoc = MessageClause->getBeginLoc();
1921 }
1922 if (const auto *SeverityClause = S.getSingleClause<OMPSeverityClause>()) {
1923 Severity = SeverityClause->getSeverityKind();
1924 SeverityLoc = SeverityClause->getBeginLoc();
1925 }
1927 CGF, NumThreads, NumThreadsClause->getBeginLoc(), Modifier, Severity,
1928 SeverityLoc, Message, MessageLoc);
1929 }
1930 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
1931 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
1933 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getBeginLoc());
1934 }
1935 const Expr *IfCond = nullptr;
1936 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1937 if (C->getNameModifier() == OMPD_unknown ||
1938 C->getNameModifier() == OMPD_parallel) {
1939 IfCond = C->getCondition();
1940 break;
1941 }
1942 }
1943
1944 OMPParallelScope Scope(CGF, S);
1946 // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk
1947 // lower and upper bounds with the pragma 'for' chunking mechanism.
1948 // The following lambda takes care of appending the lower and upper bound
1949 // parameters when necessary
1950 CodeGenBoundParameters(CGF, S, CapturedVars);
1951 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
1952 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getBeginLoc(), OutlinedFn,
1953 CapturedVars, IfCond, NumThreads,
1954 Modifier, Severity, Message);
1955}
1956
1957static bool isAllocatableDecl(const VarDecl *VD) {
1958 const VarDecl *CVD = VD->getCanonicalDecl();
1959 if (!CVD->hasAttr<OMPAllocateDeclAttr>())
1960 return false;
1961 const auto *AA = CVD->getAttr<OMPAllocateDeclAttr>();
1962 // Use the default allocation.
1963 return !((AA->getAllocatorType() == OMPAllocateDeclAttr::OMPDefaultMemAlloc ||
1964 AA->getAllocatorType() == OMPAllocateDeclAttr::OMPNullMemAlloc) &&
1965 !AA->getAllocator());
1966}
1967
1971
1973 const OMPExecutableDirective &S) {
1974 bool Copyins = CGF.EmitOMPCopyinClause(S);
1975 if (Copyins) {
1976 // Emit implicit barrier to synchronize threads and avoid data races on
1977 // propagation master's thread values of threadprivate variables to local
1978 // instances of that variables of all other implicit threads.
1980 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
1981 /*ForceSimpleCall=*/true);
1982 }
1983}
1984
1986 CodeGenFunction &CGF, const VarDecl *VD) {
1987 CodeGenModule &CGM = CGF.CGM;
1988 auto &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
1989
1990 if (!VD)
1991 return Address::invalid();
1992 const VarDecl *CVD = VD->getCanonicalDecl();
1993 if (!isAllocatableDecl(CVD))
1994 return Address::invalid();
1995 llvm::Value *Size;
1996 CharUnits Align = CGM.getContext().getDeclAlign(CVD);
1997 if (CVD->getType()->isVariablyModifiedType()) {
1998 Size = CGF.getTypeSize(CVD->getType());
1999 // Align the size: ((size + align - 1) / align) * align
2000 Size = CGF.Builder.CreateNUWAdd(
2001 Size, CGM.getSize(Align - CharUnits::fromQuantity(1)));
2002 Size = CGF.Builder.CreateUDiv(Size, CGM.getSize(Align));
2003 Size = CGF.Builder.CreateNUWMul(Size, CGM.getSize(Align));
2004 } else {
2005 CharUnits Sz = CGM.getContext().getTypeSizeInChars(CVD->getType());
2006 Size = CGM.getSize(Sz.alignTo(Align));
2007 }
2008
2009 const auto *AA = CVD->getAttr<OMPAllocateDeclAttr>();
2010 assert(AA->getAllocator() &&
2011 "Expected allocator expression for non-default allocator.");
2012 llvm::Value *Allocator = CGF.EmitScalarExpr(AA->getAllocator());
2013 // According to the standard, the original allocator type is a enum (integer).
2014 // Convert to pointer type, if required.
2015 if (Allocator->getType()->isIntegerTy())
2016 Allocator = CGF.Builder.CreateIntToPtr(Allocator, CGM.VoidPtrTy);
2017 else if (Allocator->getType()->isPointerTy())
2018 Allocator = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Allocator,
2019 CGM.VoidPtrTy);
2020
2021 llvm::Value *Addr = OMPBuilder.createOMPAlloc(
2022 CGF.Builder, Size, Allocator,
2023 getNameWithSeparators({CVD->getName(), ".void.addr"}, ".", "."));
2024 llvm::CallInst *FreeCI =
2025 OMPBuilder.createOMPFree(CGF.Builder, Addr, Allocator);
2026
2027 CGF.EHStack.pushCleanup<OMPAllocateCleanupTy>(NormalAndEHCleanup, FreeCI);
2029 Addr,
2030 CGF.ConvertTypeForMem(CGM.getContext().getPointerType(CVD->getType())),
2031 getNameWithSeparators({CVD->getName(), ".addr"}, ".", "."));
2032 return Address(Addr, CGF.ConvertTypeForMem(CVD->getType()), Align);
2033}
2034
2036 CodeGenFunction &CGF, const VarDecl *VD, Address VDAddr,
2037 SourceLocation Loc) {
2038 CodeGenModule &CGM = CGF.CGM;
2039 if (CGM.getLangOpts().OpenMPUseTLS &&
2040 CGM.getContext().getTargetInfo().isTLSSupported())
2041 return VDAddr;
2042
2043 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
2044
2045 llvm::Type *VarTy = VDAddr.getElementType();
2046 llvm::Value *Data =
2047 CGF.Builder.CreatePointerCast(VDAddr.emitRawPointer(CGF), CGM.Int8PtrTy);
2048 llvm::ConstantInt *Size = CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy));
2049 std::string Suffix = getNameWithSeparators({"cache", ""});
2050 llvm::Twine CacheName = Twine(CGM.getMangledName(VD)).concat(Suffix);
2051
2052 llvm::CallInst *ThreadPrivateCacheCall =
2053 OMPBuilder.createCachedThreadPrivate(CGF.Builder, Data, Size, CacheName);
2054
2055 return Address(ThreadPrivateCacheCall, CGM.Int8Ty, VDAddr.getAlignment());
2056}
2057
2059 ArrayRef<StringRef> Parts, StringRef FirstSeparator, StringRef Separator) {
2060 SmallString<128> Buffer;
2061 llvm::raw_svector_ostream OS(Buffer);
2062 StringRef Sep = FirstSeparator;
2063 for (StringRef Part : Parts) {
2064 OS << Sep << Part;
2065 Sep = Separator;
2066 }
2067 return OS.str().str();
2068}
2069
2071 CodeGenFunction &CGF, const Stmt *RegionBodyStmt, InsertPointTy AllocaIP,
2072 InsertPointTy CodeGenIP, Twine RegionName) {
2074 Builder.restoreIP(CodeGenIP);
2075 llvm::BasicBlock *FiniBB = splitBBWithSuffix(Builder, /*CreateBranch=*/false,
2076 "." + RegionName + ".after");
2077
2078 {
2079 OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(CGF, AllocaIP, *FiniBB);
2080 CGF.EmitStmt(RegionBodyStmt);
2081 }
2082
2083 if (Builder.saveIP().isSet())
2084 Builder.CreateBr(FiniBB);
2085}
2086
2088 CodeGenFunction &CGF, const Stmt *RegionBodyStmt, InsertPointTy AllocaIP,
2089 InsertPointTy CodeGenIP, Twine RegionName) {
2091 Builder.restoreIP(CodeGenIP);
2092 llvm::BasicBlock *FiniBB = splitBBWithSuffix(Builder, /*CreateBranch=*/false,
2093 "." + RegionName + ".after");
2094
2095 {
2096 OMPBuilderCBHelpers::OutlinedRegionBodyRAII IRB(CGF, AllocaIP, *FiniBB);
2097 CGF.EmitStmt(RegionBodyStmt);
2098 }
2099
2100 if (Builder.saveIP().isSet())
2101 Builder.CreateBr(FiniBB);
2102}
2103
2104void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
2105 if (CGM.getLangOpts().OpenMPIRBuilder) {
2106 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
2107 // Check if we have any if clause associated with the directive.
2108 llvm::Value *IfCond = nullptr;
2109 if (const auto *C = S.getSingleClause<OMPIfClause>())
2110 IfCond = EmitScalarExpr(C->getCondition(),
2111 /*IgnoreResultAssign=*/true);
2112
2113 llvm::Value *NumThreads = nullptr;
2114 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>())
2115 NumThreads = EmitScalarExpr(NumThreadsClause->getNumThreads().front(),
2116 /*IgnoreResultAssign=*/true);
2117
2118 ProcBindKind ProcBind = OMP_PROC_BIND_default;
2119 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>())
2120 ProcBind = ProcBindClause->getProcBindKind();
2121
2122 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
2123
2124 // The cleanup callback that finalizes all variables at the given location,
2125 // thus calls destructors etc.
2126 auto FiniCB = [this](InsertPointTy IP) {
2128 return llvm::Error::success();
2129 };
2130
2131 // Privatization callback that performs appropriate action for
2132 // shared/private/firstprivate/lastprivate/copyin/... variables.
2133 //
2134 // TODO: This defaults to shared right now.
2135 auto PrivCB = [](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
2136 llvm::Value &, llvm::Value &Val, llvm::Value *&ReplVal) {
2137 // The next line is appropriate only for variables (Val) with the
2138 // data-sharing attribute "shared".
2139 ReplVal = &Val;
2140
2141 return CodeGenIP;
2142 };
2143
2144 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
2145 const Stmt *ParallelRegionBodyStmt = CS->getCapturedStmt();
2146
2147 auto BodyGenCB = [&, this](InsertPointTy AllocIP, InsertPointTy CodeGenIP,
2148 ArrayRef<llvm::BasicBlock *> DeallocBlocks) {
2150 *this, ParallelRegionBodyStmt, AllocIP, CodeGenIP, "parallel");
2151 return llvm::Error::success();
2152 };
2153
2154 CGCapturedStmtInfo CGSI(*CS, CR_OpenMP);
2155 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(*this, &CGSI);
2156 llvm::OpenMPIRBuilder::InsertPointTy AllocaIP(
2157 AllocaInsertPt->getParent(), AllocaInsertPt->getIterator());
2158 llvm::OpenMPIRBuilder::InsertPointTy AfterIP =
2159 cantFail(OMPBuilder.createParallel(
2160 Builder, AllocaIP, /*DeallocBlocks=*/{}, BodyGenCB, PrivCB, FiniCB,
2161 IfCond, NumThreads, ProcBind, S.hasCancel()));
2162 Builder.restoreIP(AfterIP);
2163 return;
2164 }
2165
2166 // Emit parallel region as a standalone region.
2167 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2168 Action.Enter(CGF);
2169 OMPPrivateScope PrivateScope(CGF);
2170 emitOMPCopyinClause(CGF, S);
2171 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
2172 CGF.EmitOMPPrivateClause(S, PrivateScope);
2173 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
2174 (void)PrivateScope.Privatize();
2175 CGF.EmitStmt(S.getCapturedStmt(OMPD_parallel)->getCapturedStmt());
2176 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
2177 };
2178 {
2179 auto LPCRegion =
2181 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen,
2184 [](CodeGenFunction &) { return nullptr; });
2185 }
2186 // Check for outer lastprivate conditional update.
2188}
2189
2193
2194namespace {
2195/// RAII to handle scopes for loop transformation directives.
2196class OMPTransformDirectiveScopeRAII {
2197 OMPLoopScope *Scope = nullptr;
2199 CodeGenFunction::CGCapturedStmtRAII *CapInfoRAII = nullptr;
2200
2201 OMPTransformDirectiveScopeRAII(const OMPTransformDirectiveScopeRAII &) =
2202 delete;
2203 OMPTransformDirectiveScopeRAII &
2204 operator=(const OMPTransformDirectiveScopeRAII &) = delete;
2205
2206public:
2207 OMPTransformDirectiveScopeRAII(CodeGenFunction &CGF, const Stmt *S) {
2208 if (const auto *Dir = dyn_cast<OMPLoopBasedDirective>(S)) {
2209 Scope = new OMPLoopScope(CGF, *Dir);
2211 CapInfoRAII = new CodeGenFunction::CGCapturedStmtRAII(CGF, CGSI);
2212 } else if (const auto *Dir =
2213 dyn_cast<OMPCanonicalLoopSequenceTransformationDirective>(
2214 S)) {
2215 // For simplicity we reuse the loop scope similarly to what we do with
2216 // OMPCanonicalLoopNestTransformationDirective do by being a subclass
2217 // of OMPLoopBasedDirective.
2218 Scope = new OMPLoopScope(CGF, *Dir);
2220 CapInfoRAII = new CodeGenFunction::CGCapturedStmtRAII(CGF, CGSI);
2221 }
2222 }
2223 ~OMPTransformDirectiveScopeRAII() {
2224 if (!Scope)
2225 return;
2226 delete CapInfoRAII;
2227 delete CGSI;
2228 delete Scope;
2229 }
2230};
2231} // namespace
2232
2233static void emitBody(CodeGenFunction &CGF, const Stmt *S, const Stmt *NextLoop,
2234 int MaxLevel, int Level = 0) {
2235 assert(Level < MaxLevel && "Too deep lookup during loop body codegen.");
2236 const Stmt *SimplifiedS = S->IgnoreContainers();
2237 if (const auto *CS = dyn_cast<CompoundStmt>(SimplifiedS)) {
2238 PrettyStackTraceLoc CrashInfo(
2239 CGF.getContext().getSourceManager(), CS->getLBracLoc(),
2240 "LLVM IR generation of compound statement ('{}')");
2241
2242 // Keep track of the current cleanup stack depth, including debug scopes.
2244 for (const Stmt *CurStmt : CS->body())
2245 emitBody(CGF, CurStmt, NextLoop, MaxLevel, Level);
2246 return;
2247 }
2248
2249 // `tryToFindNextInnerLoop` keeps the intra-tile hint wrapper around, so match
2250 // against the loop it annotates. The tile overshoot guard is emitted
2251 // separately via EmitOMPLoopBody's finals-conditions handling.
2252 if (SimplifiedS == OMPLoopBasedDirective::ignoreIntraTileHint(NextLoop)) {
2253 if (auto *Dir = dyn_cast<OMPLoopTransformationDirective>(SimplifiedS))
2254 SimplifiedS = Dir->getTransformedStmt();
2255 if (const auto *CanonLoop = dyn_cast<OMPCanonicalLoop>(SimplifiedS))
2256 SimplifiedS = CanonLoop->getLoopStmt();
2257 if (const auto *For = dyn_cast<ForStmt>(SimplifiedS)) {
2258 S = For->getBody();
2259 } else {
2260 assert(isa<CXXForRangeStmt>(SimplifiedS) &&
2261 "Expected canonical for loop or range-based for loop.");
2262 const auto *CXXFor = cast<CXXForRangeStmt>(SimplifiedS);
2263 CGF.EmitStmt(CXXFor->getLoopVarStmt());
2264 S = CXXFor->getBody();
2265 }
2266 if (Level + 1 < MaxLevel) {
2267 NextLoop = OMPLoopDirective::tryToFindNextInnerLoop(
2268 S, /*TryImperfectlyNestedLoops=*/true);
2269 emitBody(CGF, S, NextLoop, MaxLevel, Level + 1);
2270 return;
2271 }
2272 }
2273 CGF.EmitStmt(S);
2274}
2275
2278 RunCleanupsScope BodyScope(*this);
2279 // Update counters values on current iteration.
2280 for (const Expr *UE : D.updates())
2281 EmitIgnoredExpr(UE);
2282 // Update the linear variables.
2283 // In distribute directives only loop counters may be marked as linear, no
2284 // need to generate the code for them.
2286 if (!isOpenMPDistributeDirective(EKind)) {
2287 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
2288 for (const Expr *UE : C->updates())
2289 EmitIgnoredExpr(UE);
2290 }
2291 }
2292
2293 // On a continue in the body, jump to the end.
2294 JumpDest Continue = getJumpDestInCurrentScope("omp.body.continue");
2295 BreakContinueStack.push_back(BreakContinue(D, LoopExit, Continue));
2296 for (const Expr *E : D.finals_conditions()) {
2297 if (!E)
2298 continue;
2299 // Check that loop counter in non-rectangular nest fits into the iteration
2300 // space.
2301 llvm::BasicBlock *NextBB = createBasicBlock("omp.body.next");
2302 EmitBranchOnBoolExpr(E, NextBB, Continue.getBlock(),
2304 EmitBlock(NextBB);
2305 }
2306
2307 OMPPrivateScope InscanScope(*this);
2308 EmitOMPReductionClauseInit(D, InscanScope, /*ForInscan=*/true);
2309 bool IsInscanRegion = InscanScope.Privatize();
2310 if (IsInscanRegion) {
2311 // Need to remember the block before and after scan directive
2312 // to dispatch them correctly depending on the clause used in
2313 // this directive, inclusive or exclusive. For inclusive scan the natural
2314 // order of the blocks is used, for exclusive clause the blocks must be
2315 // executed in reverse order.
2316 OMPBeforeScanBlock = createBasicBlock("omp.before.scan.bb");
2317 OMPAfterScanBlock = createBasicBlock("omp.after.scan.bb");
2318 // No need to allocate inscan exit block, in simd mode it is selected in the
2319 // codegen for the scan directive.
2320 if (EKind != OMPD_simd && !getLangOpts().OpenMPSimd)
2321 OMPScanExitBlock = createBasicBlock("omp.exit.inscan.bb");
2322 OMPScanDispatch = createBasicBlock("omp.inscan.dispatch");
2325 }
2326
2327 // Emit loop variables for C++ range loops.
2328 const Stmt *Body =
2329 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers();
2330 // Emit loop body.
2331 emitBody(*this, Body,
2332 OMPLoopBasedDirective::tryToFindNextInnerLoop(
2333 Body, /*TryImperfectlyNestedLoops=*/true),
2334 D.getLoopsNumber());
2335
2336 // Jump to the dispatcher at the end of the loop body.
2337 if (IsInscanRegion)
2339
2340 // The end (updates/cleanups).
2341 EmitBlock(Continue.getBlock());
2342 BreakContinueStack.pop_back();
2343}
2344
2345using EmittedClosureTy = std::pair<llvm::Function *, llvm::Value *>;
2346
2347/// Emit a captured statement and return the function as well as its captured
2348/// closure context.
2350 const CapturedStmt *S) {
2351 LValue CapStruct = ParentCGF.InitCapturedStruct(*S);
2352 CodeGenFunction CGF(ParentCGF.CGM, /*suppressNewContext=*/true);
2353 std::unique_ptr<CodeGenFunction::CGCapturedStmtInfo> CSI =
2354 std::make_unique<CodeGenFunction::CGCapturedStmtInfo>(*S);
2355 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, CSI.get());
2356 llvm::Function *F = CGF.GenerateCapturedStmtFunction(*S);
2357
2358 return {F, CapStruct.getPointer(ParentCGF)};
2359}
2360
2361/// Emit a call to a previously captured closure.
2362static llvm::CallInst *
2365 // Append the closure context to the argument.
2366 SmallVector<llvm::Value *> EffectiveArgs;
2367 EffectiveArgs.reserve(Args.size() + 1);
2368 llvm::append_range(EffectiveArgs, Args);
2369 EffectiveArgs.push_back(Cap.second);
2370
2371 return ParentCGF.Builder.CreateCall(Cap.first, EffectiveArgs);
2372}
2373
2374llvm::CanonicalLoopInfo *
2376 assert(Depth == 1 && "Nested loops with OpenMPIRBuilder not yet implemented");
2377
2378 // The caller is processing the loop-associated directive processing the \p
2379 // Depth loops nested in \p S. Put the previous pending loop-associated
2380 // directive to the stack. If the current loop-associated directive is a loop
2381 // transformation directive, it will push its generated loops onto the stack
2382 // such that together with the loops left here they form the combined loop
2383 // nest for the parent loop-associated directive.
2384 int ParentExpectedOMPLoopDepth = ExpectedOMPLoopDepth;
2385 ExpectedOMPLoopDepth = Depth;
2386
2387 EmitStmt(S);
2388 assert(OMPLoopNestStack.size() >= (size_t)Depth && "Found too few loops");
2389
2390 // The last added loop is the outermost one.
2391 llvm::CanonicalLoopInfo *Result = OMPLoopNestStack.back();
2392
2393 // Pop the \p Depth loops requested by the call from that stack and restore
2394 // the previous context.
2395 OMPLoopNestStack.pop_back_n(Depth);
2396 ExpectedOMPLoopDepth = ParentExpectedOMPLoopDepth;
2397
2398 return Result;
2399}
2400
2401void CodeGenFunction::EmitOMPCanonicalLoop(const OMPCanonicalLoop *S) {
2402 const Stmt *SyntacticalLoop = S->getLoopStmt();
2403 if (!getLangOpts().OpenMPIRBuilder) {
2404 // Ignore if OpenMPIRBuilder is not enabled.
2405 EmitStmt(SyntacticalLoop);
2406 return;
2407 }
2408
2409 LexicalScope ForScope(*this, S->getSourceRange());
2410
2411 // Emit init statements. The Distance/LoopVar funcs may reference variable
2412 // declarations they contain.
2413 const Stmt *BodyStmt;
2414 if (const auto *For = dyn_cast<ForStmt>(SyntacticalLoop)) {
2415 if (const Stmt *InitStmt = For->getInit())
2416 EmitStmt(InitStmt);
2417 BodyStmt = For->getBody();
2418 } else if (const auto *RangeFor =
2419 dyn_cast<CXXForRangeStmt>(SyntacticalLoop)) {
2420 if (const DeclStmt *RangeStmt = RangeFor->getRangeStmt())
2421 EmitStmt(RangeStmt);
2422 if (const DeclStmt *BeginStmt = RangeFor->getBeginStmt())
2423 EmitStmt(BeginStmt);
2424 if (const DeclStmt *EndStmt = RangeFor->getEndStmt())
2425 EmitStmt(EndStmt);
2426 if (const DeclStmt *LoopVarStmt = RangeFor->getLoopVarStmt())
2427 EmitStmt(LoopVarStmt);
2428 BodyStmt = RangeFor->getBody();
2429 } else
2430 llvm_unreachable("Expected for-stmt or range-based for-stmt");
2431
2432 // Emit closure for later use. By-value captures will be captured here.
2433 const CapturedStmt *DistanceFunc = S->getDistanceFunc();
2434 EmittedClosureTy DistanceClosure = emitCapturedStmtFunc(*this, DistanceFunc);
2435 const CapturedStmt *LoopVarFunc = S->getLoopVarFunc();
2436 EmittedClosureTy LoopVarClosure = emitCapturedStmtFunc(*this, LoopVarFunc);
2437
2438 // Call the distance function to get the number of iterations of the loop to
2439 // come.
2440 QualType LogicalTy = DistanceFunc->getCapturedDecl()
2441 ->getParam(0)
2442 ->getType()
2444 RawAddress CountAddr = CreateMemTemp(LogicalTy, ".count.addr");
2445 emitCapturedStmtCall(*this, DistanceClosure, {CountAddr.getPointer()});
2446 llvm::Value *DistVal = Builder.CreateLoad(CountAddr, ".count");
2447
2448 // Emit the loop structure.
2449 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
2450 auto BodyGen = [&, this](llvm::OpenMPIRBuilder::InsertPointTy CodeGenIP,
2451 llvm::Value *IndVar) {
2452 Builder.restoreIP(CodeGenIP);
2453
2454 // Emit the loop body: Convert the logical iteration number to the loop
2455 // variable and emit the body.
2456 const DeclRefExpr *LoopVarRef = S->getLoopVarRef();
2457 LValue LCVal = EmitLValue(LoopVarRef);
2458 Address LoopVarAddress = LCVal.getAddress();
2459 emitCapturedStmtCall(*this, LoopVarClosure,
2460 {LoopVarAddress.emitRawPointer(*this), IndVar});
2461
2462 RunCleanupsScope BodyScope(*this);
2463 EmitStmt(BodyStmt);
2464 return llvm::Error::success();
2465 };
2466
2467 llvm::CanonicalLoopInfo *CL =
2468 cantFail(OMPBuilder.createCanonicalLoop(Builder, BodyGen, DistVal));
2469
2470 // Finish up the loop.
2471 Builder.restoreIP(CL->getAfterIP());
2472 ForScope.ForceCleanup();
2473
2474 // Remember the CanonicalLoopInfo for parent AST nodes consuming it.
2475 OMPLoopNestStack.push_back(CL);
2476}
2477
2479 const OMPExecutableDirective &S, bool RequiresCleanup, const Expr *LoopCond,
2480 const Expr *IncExpr,
2481 const llvm::function_ref<void(CodeGenFunction &)> BodyGen,
2482 const llvm::function_ref<void(CodeGenFunction &)> PostIncGen) {
2483 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
2484
2485 // Start the loop with a block that tests the condition.
2486 auto CondBlock = createBasicBlock("omp.inner.for.cond");
2487 EmitBlock(CondBlock);
2488 const SourceRange R = S.getSourceRange();
2489
2490 // If attributes are attached, push to the basic block with them.
2491 const auto &OMPED = cast<OMPExecutableDirective>(S);
2492 const CapturedStmt *ICS = OMPED.getInnermostCapturedStmt();
2493 const Stmt *SS = ICS->getCapturedStmt();
2494 const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(SS);
2495 OMPLoopNestStack.clear();
2496 if (AS)
2497 LoopStack.push(CondBlock, CGM.getContext(), CGM.getCodeGenOpts(),
2498 AS->getAttrs(), SourceLocToDebugLoc(R.getBegin()),
2499 SourceLocToDebugLoc(R.getEnd()));
2500 else
2501 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
2502 SourceLocToDebugLoc(R.getEnd()));
2503
2504 // If there are any cleanups between here and the loop-exit scope,
2505 // create a block to stage a loop exit along.
2506 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
2507 if (RequiresCleanup)
2508 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
2509
2510 llvm::BasicBlock *LoopBody = createBasicBlock("omp.inner.for.body");
2511
2512 // Emit condition.
2513 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
2514 if (ExitBlock != LoopExit.getBlock()) {
2515 EmitBlock(ExitBlock);
2517 }
2518
2519 EmitBlock(LoopBody);
2521
2522 // Create a block for the increment.
2523 JumpDest Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
2524 BreakContinueStack.push_back(BreakContinue(S, LoopExit, Continue));
2525
2526 BodyGen(*this);
2527
2528 // Emit "IV = IV + 1" and a back-edge to the condition block.
2529 EmitBlock(Continue.getBlock());
2530 EmitIgnoredExpr(IncExpr);
2531 PostIncGen(*this);
2532 BreakContinueStack.pop_back();
2533 EmitBranch(CondBlock);
2534 LoopStack.pop();
2535 // Emit the fall-through block.
2536 EmitBlock(LoopExit.getBlock());
2537}
2538
2540 if (!HaveInsertPoint())
2541 return false;
2542 // Emit inits for the linear variables.
2543 bool HasLinears = false;
2544 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
2545 for (const Expr *Init : C->inits()) {
2546 HasLinears = true;
2547 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
2548 if (const auto *Ref =
2549 dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
2550 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
2551 const auto *OrigVD = cast<VarDecl>(Ref->getDecl());
2552 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
2553 CapturedStmtInfo->lookup(OrigVD) != nullptr,
2554 VD->getInit()->getType(), VK_LValue,
2555 VD->getInit()->getExprLoc());
2557 &DRE, VD,
2558 MakeAddrLValue(Emission.getAllocatedAddress(), VD->getType()),
2559 /*capturedByInit=*/false);
2560 EmitAutoVarCleanups(Emission);
2561 } else {
2562 EmitVarDecl(*VD);
2563 }
2564 }
2565 // Emit the linear steps for the linear clauses.
2566 // If a step is not constant, it is pre-calculated before the loop.
2567 if (const auto *CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
2568 if (const auto *SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
2569 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
2570 // Emit calculation of the linear step.
2571 EmitIgnoredExpr(CS);
2572 }
2573 }
2574 return HasLinears;
2575}
2576
2578 const OMPLoopDirective &D,
2579 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
2580 if (!HaveInsertPoint())
2581 return;
2582 llvm::BasicBlock *DoneBB = nullptr;
2583 // Emit the final values of the linear variables.
2584 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
2585 auto IC = C->varlist_begin();
2586 for (const Expr *F : C->finals()) {
2587 if (!DoneBB) {
2588 if (llvm::Value *Cond = CondGen(*this)) {
2589 // If the first post-update expression is found, emit conditional
2590 // block if it was requested.
2591 llvm::BasicBlock *ThenBB = createBasicBlock(".omp.linear.pu");
2592 DoneBB = createBasicBlock(".omp.linear.pu.done");
2593 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
2594 EmitBlock(ThenBB);
2595 }
2596 }
2597 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
2598 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
2599 CapturedStmtInfo->lookup(OrigVD) != nullptr,
2600 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
2601 Address OrigAddr = EmitLValue(&DRE).getAddress();
2602 CodeGenFunction::OMPPrivateScope VarScope(*this);
2603 VarScope.addPrivate(OrigVD, OrigAddr);
2604 (void)VarScope.Privatize();
2605 EmitIgnoredExpr(F);
2606 ++IC;
2607 }
2608 if (const Expr *PostUpdate = C->getPostUpdateExpr())
2609 EmitIgnoredExpr(PostUpdate);
2610 }
2611 if (DoneBB)
2612 EmitBlock(DoneBB, /*IsFinished=*/true);
2613}
2614
2616 const OMPExecutableDirective &D) {
2617 if (!CGF.HaveInsertPoint())
2618 return;
2619 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
2620 llvm::APInt ClauseAlignment(64, 0);
2621 if (const Expr *AlignmentExpr = Clause->getAlignment()) {
2622 auto *AlignmentCI =
2623 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
2624 ClauseAlignment = AlignmentCI->getValue();
2625 }
2626 for (const Expr *E : Clause->varlist()) {
2627 llvm::APInt Alignment(ClauseAlignment);
2628 if (Alignment == 0) {
2629 // OpenMP [2.8.1, Description]
2630 // If no optional parameter is specified, implementation-defined default
2631 // alignments for SIMD instructions on the target platforms are assumed.
2632 Alignment =
2633 CGF.getContext()
2635 E->getType()->getPointeeType()))
2636 .getQuantity();
2637 }
2638 assert((Alignment == 0 || Alignment.isPowerOf2()) &&
2639 "alignment is not power of 2");
2640 if (Alignment != 0) {
2641 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
2643 PtrValue, E, /*No second loc needed*/ SourceLocation(),
2644 llvm::ConstantInt::get(CGF.getLLVMContext(), Alignment));
2645 }
2646 }
2647 }
2648}
2649
2652 if (!HaveInsertPoint())
2653 return;
2654 auto I = S.private_counters().begin();
2655 for (const Expr *E : S.counters()) {
2656 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2657 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
2658 // Emit var without initialization.
2659 AutoVarEmission VarEmission = EmitAutoVarAlloca(*PrivateVD);
2660 EmitAutoVarCleanups(VarEmission);
2661 LocalDeclMap.erase(PrivateVD);
2662 (void)LoopScope.addPrivate(VD, VarEmission.getAllocatedAddress());
2663 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
2664 VD->hasGlobalStorage()) {
2665 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(VD),
2666 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
2667 E->getType(), VK_LValue, E->getExprLoc());
2668 (void)LoopScope.addPrivate(PrivateVD, EmitLValue(&DRE).getAddress());
2669 } else {
2670 (void)LoopScope.addPrivate(PrivateVD, VarEmission.getAllocatedAddress());
2671 }
2672 ++I;
2673 }
2674 // Privatize extra loop counters used in loops for ordered(n) clauses.
2675 for (const auto *C : S.getClausesOfKind<OMPOrderedClause>()) {
2676 if (!C->getNumForLoops())
2677 continue;
2678 for (unsigned I = S.getLoopsNumber(), E = C->getLoopNumIterations().size();
2679 I < E; ++I) {
2680 const auto *DRE = cast<DeclRefExpr>(C->getLoopCounter(I));
2681 const auto *VD = cast<VarDecl>(DRE->getDecl());
2682 // Override only those variables that can be captured to avoid re-emission
2683 // of the variables declared within the loops.
2684 if (DRE->refersToEnclosingVariableOrCapture()) {
2685 (void)LoopScope.addPrivate(
2686 VD, CreateMemTemp(DRE->getType(), VD->getName()));
2687 }
2688 }
2689 }
2690}
2691
2693 const Expr *Cond, llvm::BasicBlock *TrueBlock,
2694 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
2695 if (!CGF.HaveInsertPoint())
2696 return;
2697 {
2698 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
2699 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
2700 (void)PreCondScope.Privatize();
2701 // Get initial values of real counters.
2702 for (const Expr *I : S.inits()) {
2703 CGF.EmitIgnoredExpr(I);
2704 }
2705 }
2706 // Create temp loop control variables with their init values to support
2707 // non-rectangular loops.
2708 CodeGenFunction::OMPMapVars PreCondVars;
2709 for (const Expr *E : S.dependent_counters()) {
2710 if (!E)
2711 continue;
2712 assert(!E->getType().getNonReferenceType()->isRecordType() &&
2713 "dependent counter must not be an iterator.");
2714 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2715 Address CounterAddr =
2717 (void)PreCondVars.setVarAddr(CGF, VD, CounterAddr);
2718 }
2719 (void)PreCondVars.apply(CGF);
2720 for (const Expr *E : S.dependent_inits()) {
2721 if (!E)
2722 continue;
2723 CGF.EmitIgnoredExpr(E);
2724 }
2725 // Check that loop is executed at least one time.
2726 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
2727 PreCondVars.restore(CGF);
2728}
2729
2731 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
2732 if (!HaveInsertPoint())
2733 return;
2734 llvm::DenseSet<const VarDecl *> SIMDLCVs;
2736 if (isOpenMPSimdDirective(EKind)) {
2737 const auto *LoopDirective = cast<OMPLoopDirective>(&D);
2738 for (const Expr *C : LoopDirective->counters()) {
2739 SIMDLCVs.insert(
2741 }
2742 }
2743 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
2744 auto CurPrivate = C->privates().begin();
2745 for (const Expr *E : C->varlist()) {
2746 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2747 const auto *PrivateVD =
2748 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
2749 if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
2750 // Emit private VarDecl with copy init.
2751 EmitVarDecl(*PrivateVD);
2752 bool IsRegistered =
2753 PrivateScope.addPrivate(VD, GetAddrOfLocalVar(PrivateVD));
2754 assert(IsRegistered && "linear var already registered as private");
2755 // Silence the warning about unused variable.
2756 (void)IsRegistered;
2757 } else {
2758 EmitVarDecl(*PrivateVD);
2759 }
2760 ++CurPrivate;
2761 }
2762 }
2763}
2764
2766 const OMPExecutableDirective &D) {
2767 if (!CGF.HaveInsertPoint())
2768 return;
2769 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
2770 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
2771 /*ignoreResult=*/true);
2772 auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
2773 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
2774 // In presence of finite 'safelen', it may be unsafe to mark all
2775 // the memory instructions parallel, because loop-carried
2776 // dependences of 'safelen' iterations are possible.
2777 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
2778 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
2779 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
2780 /*ignoreResult=*/true);
2781 auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
2782 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
2783 // In presence of finite 'safelen', it may be unsafe to mark all
2784 // the memory instructions parallel, because loop-carried
2785 // dependences of 'safelen' iterations are possible.
2786 CGF.LoopStack.setParallel(/*Enable=*/false);
2787 }
2788}
2789
2790// Check for the presence of an `OMPOrderedBlockAssocDirective`,
2791// i.e., `ordered` in `#pragma omp ordered simd`.
2792//
2793// Consider the following source code:
2794// ```
2795// __attribute__((noinline)) void omp_simd_loop(float X[ARRAY_SIZE][ARRAY_SIZE])
2796// {
2797// for (int r = 1; r < ARRAY_SIZE; ++r) {
2798// for (int c = 1; c < ARRAY_SIZE; ++c) {
2799// #pragma omp simd
2800// for (int k = 2; k < ARRAY_SIZE; ++k) {
2801// #pragma omp ordered simd
2802// X[r][k] = X[r][k - 2] + sinf((float)(r / c));
2803// }
2804// }
2805// }
2806// }
2807// ```
2808//
2809// Suppose we are in `CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective
2810// &D)`. By examining `D.dump()` we have the following AST containing
2811// `OMPOrderedBlockAssocDirective`:
2812//
2813// ```
2814// OMPSimdDirective 0x1c32950
2815// `-CapturedStmt 0x1c32028
2816// |-CapturedDecl 0x1c310e8
2817// | |-ForStmt 0x1c31e30
2818// | | |-DeclStmt 0x1c31298
2819// | | | `-VarDecl 0x1c31208 used k 'int' cinit
2820// | | | `-IntegerLiteral 0x1c31278 'int' 2
2821// | | |-<<<NULL>>>
2822// | | |-BinaryOperator 0x1c31308 'int' '<'
2823// | | | |-ImplicitCastExpr 0x1c312f0 'int' <LValueToRValue>
2824// | | | | `-DeclRefExpr 0x1c312b0 'int' lvalue Var 0x1c31208 'k' 'int'
2825// | | | `-IntegerLiteral 0x1c312d0 'int' 256
2826// | | |-UnaryOperator 0x1c31348 'int' prefix '++'
2827// | | | `-DeclRefExpr 0x1c31328 'int' lvalue Var 0x1c31208 'k' 'int'
2828// | | `-CompoundStmt 0x1c31e18
2829// | | `-OMPOrderedBlockAssocDirective 0x1c31dd8
2830// | | |-OMPSimdClause 0x1c31380
2831// | | `-CapturedStmt 0x1c31cd0
2832// ```
2833//
2834// Note the presence of `OMPOrderedBlockAssocDirective` above:
2835// It's (transitively) nested in a `CapturedStmt` representing the pragma
2836// annotated compound statement. Thus, we need to consider this nesting and
2837// include checking the `getCapturedStmt` in this case.
2840 return true;
2841
2842 if (const auto *CS = dyn_cast<CapturedStmt>(S))
2844
2845 for (const Stmt *Child : S->children()) {
2846 if (Child && hasOrderedBlockAssocDirective(Child))
2847 return true;
2848 }
2849
2850 return false;
2851}
2852
2853static void applyConservativeSimdOrderedDirective(const Stmt &AssociatedStmt,
2855 // Check for the presence of an `OMPOrderedBlockAssocDirective`
2856 // i.e., `ordered` in `#pragma omp ordered simd`
2857 bool HasOrderedDirective = hasOrderedBlockAssocDirective(&AssociatedStmt);
2858 // If present then conservatively disable loop vectorization
2859 // analogously to how `emitSimdlenSafelenClause` does.
2860 if (HasOrderedDirective)
2861 LoopStack.setParallel(/*Enable=*/false);
2862}
2863
2865 // Walk clauses and process safelen/lastprivate.
2866 LoopStack.setParallel(/*Enable=*/true);
2867 LoopStack.setVectorizeEnable();
2868 const Stmt *AssociatedStmt = D.getAssociatedStmt();
2870 emitSimdlenSafelenClause(*this, D);
2871 if (const auto *C = D.getSingleClause<OMPOrderClause>())
2872 if (C->getKind() == OMPC_ORDER_concurrent)
2873 LoopStack.setParallel(/*Enable=*/true);
2875 if ((EKind == OMPD_simd ||
2876 (getLangOpts().OpenMPSimd && isOpenMPSimdDirective(EKind))) &&
2877 llvm::any_of(D.getClausesOfKind<OMPReductionClause>(),
2878 [](const OMPReductionClause *C) {
2879 return C->getModifier() == OMPC_REDUCTION_inscan;
2880 }))
2881 // Disable parallel access in case of prefix sum.
2882 LoopStack.setParallel(/*Enable=*/false);
2883}
2884
2886 const OMPLoopDirective &D,
2887 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
2888 if (!HaveInsertPoint())
2889 return;
2890 llvm::BasicBlock *DoneBB = nullptr;
2891 auto IC = D.counters().begin();
2892 auto IPC = D.private_counters().begin();
2893 for (const Expr *F : D.finals()) {
2894 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
2895 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
2896 const auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
2897 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
2898 OrigVD->hasGlobalStorage() || CED) {
2899 if (!DoneBB) {
2900 if (llvm::Value *Cond = CondGen(*this)) {
2901 // If the first post-update expression is found, emit conditional
2902 // block if it was requested.
2903 llvm::BasicBlock *ThenBB = createBasicBlock(".omp.final.then");
2904 DoneBB = createBasicBlock(".omp.final.done");
2905 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
2906 EmitBlock(ThenBB);
2907 }
2908 }
2909 Address OrigAddr = Address::invalid();
2910 if (CED) {
2911 OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
2912 } else {
2913 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(PrivateVD),
2914 /*RefersToEnclosingVariableOrCapture=*/false,
2915 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
2916 OrigAddr = EmitLValue(&DRE).getAddress();
2917 }
2918 OMPPrivateScope VarScope(*this);
2919 VarScope.addPrivate(OrigVD, OrigAddr);
2920 (void)VarScope.Privatize();
2921 EmitIgnoredExpr(F);
2922 }
2923 ++IC;
2924 ++IPC;
2925 }
2926 if (DoneBB)
2927 EmitBlock(DoneBB, /*IsFinished=*/true);
2928}
2929
2936
2937/// Emit a helper variable and return corresponding lvalue.
2939 const DeclRefExpr *Helper) {
2940 auto VDecl = cast<VarDecl>(Helper->getDecl());
2941 CGF.EmitVarDecl(*VDecl);
2942 return CGF.EmitLValue(Helper);
2943}
2944
2946 const RegionCodeGenTy &SimdInitGen,
2947 const RegionCodeGenTy &BodyCodeGen) {
2948 auto &&ThenGen = [&S, &SimdInitGen, &BodyCodeGen](CodeGenFunction &CGF,
2949 PrePostActionTy &) {
2950 CGOpenMPRuntime::NontemporalDeclsRAII NontemporalsRegion(CGF.CGM, S);
2952 SimdInitGen(CGF);
2953
2954 BodyCodeGen(CGF);
2955 };
2956 auto &&ElseGen = [&BodyCodeGen](CodeGenFunction &CGF, PrePostActionTy &) {
2958 CGF.LoopStack.setVectorizeEnable(/*Enable=*/false);
2959
2960 BodyCodeGen(CGF);
2961 };
2962 const Expr *IfCond = nullptr;
2964 if (isOpenMPSimdDirective(EKind)) {
2965 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2966 if (CGF.getLangOpts().OpenMP >= 50 &&
2967 (C->getNameModifier() == OMPD_unknown ||
2968 C->getNameModifier() == OMPD_simd)) {
2969 IfCond = C->getCondition();
2970 break;
2971 }
2972 }
2973 }
2974 if (IfCond) {
2975 CGF.CGM.getOpenMPRuntime().emitIfClause(CGF, IfCond, ThenGen, ElseGen);
2976 } else {
2977 RegionCodeGenTy ThenRCG(ThenGen);
2978 ThenRCG(CGF);
2979 }
2980}
2981
2983 PrePostActionTy &Action) {
2984 Action.Enter(CGF);
2985 OMPLoopScope PreInitScope(CGF, S);
2986 // if (PreCond) {
2987 // for (IV in 0..LastIteration) BODY;
2988 // <Final counter/linear vars updates>;
2989 // }
2990
2991 // The presence of lower/upper bound variable depends on the actual directive
2992 // kind in the AST node. The variables must be emitted because some of the
2993 // expressions associated with the loop will use them.
2994 OpenMPDirectiveKind DKind = S.getDirectiveKind();
2995 if (isOpenMPDistributeDirective(DKind) ||
3000 }
3001
3003 // Emit: if (PreCond) - begin.
3004 // If the condition constant folds and can be elided, avoid emitting the
3005 // whole loop.
3006 bool CondConstant;
3007 llvm::BasicBlock *ContBlock = nullptr;
3008 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3009 if (!CondConstant)
3010 return;
3011 } else {
3012 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("simd.if.then");
3013 ContBlock = CGF.createBasicBlock("simd.if.end");
3014 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
3015 CGF.getProfileCount(&S));
3016 CGF.EmitBlock(ThenBlock);
3018 }
3019
3020 // Emit the loop iteration variable.
3021 const Expr *IVExpr = S.getIterationVariable();
3022 const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
3023 CGF.EmitVarDecl(*IVDecl);
3024 CGF.EmitIgnoredExpr(S.getInit());
3025
3026 // Emit the iterations count variable.
3027 // If it is not a variable, Sema decided to calculate iterations count on
3028 // each iteration (e.g., it is foldable into a constant).
3029 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
3030 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3031 // Emit calculation of the iterations count.
3033 }
3034
3035 emitAlignedClause(CGF, S);
3036 (void)CGF.EmitOMPLinearClauseInit(S);
3037 {
3038 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
3039 CGF.EmitOMPPrivateClause(S, LoopScope);
3040 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
3041 CGF.EmitOMPLinearClause(S, LoopScope);
3042 CGF.EmitOMPReductionClauseInit(S, LoopScope);
3044 CGF, S, CGF.EmitLValue(S.getIterationVariable()));
3045 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
3046 (void)LoopScope.Privatize();
3049
3051 CGF, S,
3052 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3053 CGF.EmitOMPSimdInit(S);
3054 },
3055 [&S, &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) {
3056 CGF.EmitOMPInnerLoop(
3057 S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
3058 [&S](CodeGenFunction &CGF) {
3059 emitOMPLoopBodyWithStopPoint(CGF, S,
3060 CodeGenFunction::JumpDest());
3061 },
3062 [](CodeGenFunction &) {});
3063 });
3064 CGF.EmitOMPSimdFinal(S, [](CodeGenFunction &) { return nullptr; });
3065 // Emit final copy of the lastprivate variables at the end of loops.
3066 if (HasLastprivateClause)
3067 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
3068 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
3070 [](CodeGenFunction &) { return nullptr; });
3071 LoopScope.restoreMap();
3072 CGF.EmitOMPLinearClauseFinal(S, [](CodeGenFunction &) { return nullptr; });
3073 }
3074 // Emit: if (PreCond) - end.
3075 if (ContBlock) {
3076 CGF.EmitBranch(ContBlock);
3077 CGF.EmitBlock(ContBlock, true);
3078 }
3079}
3080
3081// Pass OMPLoopDirective (instead of OMPSimdDirective) to make this function
3082// available for "loop bind(thread)", which maps to "simd".
3084 // Check for unsupported clauses
3085 for (OMPClause *C : S.clauses()) {
3086 // Currently only order, simdlen and safelen clauses are supported
3089 return false;
3090 }
3091
3092 // Check if we have a statement with the ordered-blockassoc directive.
3093 // Visit the statement hierarchy to find a compound statement
3094 // with a ordered-blockassoc directive in it.
3095 if (const auto *CanonLoop = dyn_cast<OMPCanonicalLoop>(S.getRawStmt())) {
3096 if (const Stmt *SyntacticalLoop = CanonLoop->getLoopStmt()) {
3097 for (const Stmt *SubStmt : SyntacticalLoop->children()) {
3098 if (!SubStmt)
3099 continue;
3100 if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(SubStmt)) {
3101 for (const Stmt *CSSubStmt : CS->children()) {
3102 if (!CSSubStmt)
3103 continue;
3104 if (isa<OMPOrderedBlockAssocDirective>(CSSubStmt)) {
3105 return false;
3106 }
3107 }
3108 }
3109 }
3110 }
3111 }
3112 return true;
3113}
3114
3115static llvm::MapVector<llvm::Value *, llvm::Value *>
3117 llvm::MapVector<llvm::Value *, llvm::Value *> AlignedVars;
3118 for (const auto *Clause : S.getClausesOfKind<OMPAlignedClause>()) {
3119 llvm::APInt ClauseAlignment(64, 0);
3120 if (const Expr *AlignmentExpr = Clause->getAlignment()) {
3121 auto *AlignmentCI =
3122 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
3123 ClauseAlignment = AlignmentCI->getValue();
3124 }
3125 for (const Expr *E : Clause->varlist()) {
3126 llvm::APInt Alignment(ClauseAlignment);
3127 if (Alignment == 0) {
3128 // OpenMP [2.8.1, Description]
3129 // If no optional parameter is specified, implementation-defined default
3130 // alignments for SIMD instructions on the target platforms are assumed.
3131 Alignment =
3132 CGF.getContext()
3134 E->getType()->getPointeeType()))
3135 .getQuantity();
3136 }
3137 assert((Alignment == 0 || Alignment.isPowerOf2()) &&
3138 "alignment is not power of 2");
3139 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
3140 AlignedVars[PtrValue] = CGF.Builder.getInt64(Alignment.getSExtValue());
3141 }
3142 }
3143 return AlignedVars;
3144}
3145
3146// Pass OMPLoopDirective (instead of OMPSimdDirective) to make this function
3147// available for "loop bind(thread)", which maps to "simd".
3150 bool UseOMPIRBuilder =
3151 CGM.getLangOpts().OpenMPIRBuilder && isSimdSupportedByOpenMPIRBuilder(S);
3152 if (UseOMPIRBuilder) {
3153 auto &&CodeGenIRBuilder = [&S, &CGM, UseOMPIRBuilder](CodeGenFunction &CGF,
3154 PrePostActionTy &) {
3155 // Use the OpenMPIRBuilder if enabled.
3156 if (UseOMPIRBuilder) {
3157 llvm::MapVector<llvm::Value *, llvm::Value *> AlignedVars =
3158 GetAlignedMapping(S, CGF);
3159 // Emit the associated statement and get its loop representation.
3160 const Stmt *Inner = S.getRawStmt();
3161 llvm::CanonicalLoopInfo *CLI =
3162 CGF.EmitOMPCollapsedCanonicalLoopNest(Inner, 1);
3163
3164 llvm::OpenMPIRBuilder &OMPBuilder =
3166 // Add SIMD specific metadata
3167 llvm::ConstantInt *Simdlen = nullptr;
3168 if (const auto *C = S.getSingleClause<OMPSimdlenClause>()) {
3169 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
3170 /*ignoreResult=*/true);
3171 auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
3172 Simdlen = Val;
3173 }
3174 llvm::ConstantInt *Safelen = nullptr;
3175 if (const auto *C = S.getSingleClause<OMPSafelenClause>()) {
3176 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
3177 /*ignoreResult=*/true);
3178 auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
3179 Safelen = Val;
3180 }
3181 llvm::omp::OrderKind Order = llvm::omp::OrderKind::OMP_ORDER_unknown;
3182 if (const auto *C = S.getSingleClause<OMPOrderClause>()) {
3183 if (C->getKind() == OpenMPOrderClauseKind::OMPC_ORDER_concurrent) {
3184 Order = llvm::omp::OrderKind::OMP_ORDER_concurrent;
3185 }
3186 }
3187 // Add simd metadata to the collapsed loop. Do not generate
3188 // another loop for if clause. Support for if clause is done earlier.
3189 OMPBuilder.applySimd(CLI, AlignedVars,
3190 /*IfCond*/ nullptr, Order, Simdlen, Safelen);
3191 return;
3192 }
3193 };
3194 {
3195 auto LPCRegion =
3197 OMPLexicalScope Scope(CGF, S, OMPD_unknown);
3198 CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd,
3199 CodeGenIRBuilder);
3200 }
3201 return;
3202 }
3203
3205 CGF.OMPFirstScanLoop = true;
3206 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3207 emitOMPSimdRegion(CGF, S, Action);
3208 };
3209 {
3210 auto LPCRegion =
3212 OMPLexicalScope Scope(CGF, S, OMPD_unknown);
3214 }
3215 // Check for outer lastprivate conditional update.
3217}
3218
3222
3224 // Emit the de-sugared statement.
3225 OMPTransformDirectiveScopeRAII TileScope(*this, &S);
3227}
3228
3230 // Emit the de-sugared statement.
3231 OMPTransformDirectiveScopeRAII StripeScope(*this, &S);
3233}
3234
3236 // Emit the de-sugared statement.
3237 OMPTransformDirectiveScopeRAII ReverseScope(*this, &S);
3239}
3240
3242 // Emit the de-sugared statement (the split loops).
3243 OMPTransformDirectiveScopeRAII SplitScope(*this, &S);
3245}
3246
3248 const OMPInterchangeDirective &S) {
3249 // Emit the de-sugared statement.
3250 OMPTransformDirectiveScopeRAII InterchangeScope(*this, &S);
3252}
3253
3255 // Emit the de-sugared statement
3256 OMPTransformDirectiveScopeRAII FuseScope(*this, &S);
3258}
3259
3261 bool UseOMPIRBuilder = CGM.getLangOpts().OpenMPIRBuilder;
3262
3263 if (UseOMPIRBuilder) {
3264 auto DL = SourceLocToDebugLoc(S.getBeginLoc());
3265 const Stmt *Inner = S.getRawStmt();
3266
3267 // Consume nested loop. Clear the entire remaining loop stack because a
3268 // fully unrolled loop is non-transformable. For partial unrolling the
3269 // generated outer loop is pushed back to the stack.
3270 llvm::CanonicalLoopInfo *CLI = EmitOMPCollapsedCanonicalLoopNest(Inner, 1);
3271 OMPLoopNestStack.clear();
3272
3273 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
3274
3275 bool NeedsUnrolledCLI = ExpectedOMPLoopDepth >= 1;
3276 llvm::CanonicalLoopInfo *UnrolledCLI = nullptr;
3277
3278 if (S.hasClausesOfKind<OMPFullClause>()) {
3279 assert(ExpectedOMPLoopDepth == 0);
3280 OMPBuilder.unrollLoopFull(DL, CLI);
3281 } else if (auto *PartialClause = S.getSingleClause<OMPPartialClause>()) {
3282 uint64_t Factor = 0;
3283 if (Expr *FactorExpr = PartialClause->getFactor()) {
3284 Factor = FactorExpr->EvaluateKnownConstInt(getContext()).getZExtValue();
3285 assert(Factor >= 1 && "Only positive factors are valid");
3286 }
3287 OMPBuilder.unrollLoopPartial(DL, CLI, Factor,
3288 NeedsUnrolledCLI ? &UnrolledCLI : nullptr);
3289 } else {
3290 OMPBuilder.unrollLoopHeuristic(DL, CLI);
3291 }
3292
3293 assert((!NeedsUnrolledCLI || UnrolledCLI) &&
3294 "NeedsUnrolledCLI implies UnrolledCLI to be set");
3295 if (UnrolledCLI)
3296 OMPLoopNestStack.push_back(UnrolledCLI);
3297
3298 return;
3299 }
3300
3301 // This function is only called if the unrolled loop is not consumed by any
3302 // other loop-associated construct. Such a loop-associated construct will have
3303 // used the transformed AST.
3304
3305 // Set the unroll metadata for the next emitted loop.
3306 LoopStack.setUnrollState(LoopAttributes::Enable);
3307
3308 if (S.hasClausesOfKind<OMPFullClause>()) {
3309 LoopStack.setUnrollState(LoopAttributes::Full);
3310 } else if (auto *PartialClause = S.getSingleClause<OMPPartialClause>()) {
3311 if (Expr *FactorExpr = PartialClause->getFactor()) {
3312 uint64_t Factor =
3313 FactorExpr->EvaluateKnownConstInt(getContext()).getZExtValue();
3314 assert(Factor >= 1 && "Only positive factors are valid");
3315 LoopStack.setUnrollCount(Factor);
3316 }
3317 }
3318
3319 EmitStmt(S.getAssociatedStmt());
3320}
3321
3322void CodeGenFunction::EmitOMPOuterLoop(
3323 bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S,
3325 const CodeGenFunction::OMPLoopArguments &LoopArgs,
3326 const CodeGenFunction::CodeGenLoopTy &CodeGenLoop,
3327 const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) {
3329
3330 const Expr *IVExpr = S.getIterationVariable();
3331 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3332 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3333
3334 JumpDest LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
3335
3336 // Start the loop with a block that tests the condition.
3337 llvm::BasicBlock *CondBlock = createBasicBlock("omp.dispatch.cond");
3338 EmitBlock(CondBlock);
3339 const SourceRange R = S.getSourceRange();
3340 OMPLoopNestStack.clear();
3341 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
3342 SourceLocToDebugLoc(R.getEnd()));
3343
3344 llvm::Value *BoolCondVal = nullptr;
3345 if (!DynamicOrOrdered) {
3346 // UB = min(UB, GlobalUB) or
3347 // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g.
3348 // 'distribute parallel for')
3349 EmitIgnoredExpr(LoopArgs.EUB);
3350 // IV = LB
3351 EmitIgnoredExpr(LoopArgs.Init);
3352 // IV < UB
3353 BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond);
3354 } else {
3355 BoolCondVal =
3356 RT.emitForNext(*this, S.getBeginLoc(), IVSize, IVSigned, LoopArgs.IL,
3357 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST);
3358 }
3359
3360 // If there are any cleanups between here and the loop-exit scope,
3361 // create a block to stage a loop exit along.
3362 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
3363 if (LoopScope.requiresCleanups())
3364 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
3365
3366 llvm::BasicBlock *LoopBody = createBasicBlock("omp.dispatch.body");
3367 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
3368 if (ExitBlock != LoopExit.getBlock()) {
3369 EmitBlock(ExitBlock);
3371 }
3372 EmitBlock(LoopBody);
3373
3374 // Emit "IV = LB" (in case of static schedule, we have already calculated new
3375 // LB for loop condition and emitted it above).
3376 if (DynamicOrOrdered)
3377 EmitIgnoredExpr(LoopArgs.Init);
3378
3379 // Create a block for the increment.
3380 JumpDest Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
3381 BreakContinueStack.push_back(BreakContinue(S, LoopExit, Continue));
3382
3385 *this, S,
3386 [&S, IsMonotonic, EKind](CodeGenFunction &CGF, PrePostActionTy &) {
3387 // Generate !llvm.loop.parallel metadata for loads and stores for loops
3388 // with dynamic/guided scheduling and without ordered clause.
3389 if (!isOpenMPSimdDirective(EKind)) {
3390 CGF.LoopStack.setParallel(!IsMonotonic);
3391 if (const auto *C = S.getSingleClause<OMPOrderClause>())
3392 if (C->getKind() == OMPC_ORDER_concurrent)
3393 CGF.LoopStack.setParallel(/*Enable=*/true);
3394 } else {
3395 CGF.EmitOMPSimdInit(S);
3396 }
3397 },
3398 [&S, &LoopArgs, LoopExit, &CodeGenLoop, IVSize, IVSigned, &CodeGenOrdered,
3399 &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) {
3400 SourceLocation Loc = S.getBeginLoc();
3401 // when 'distribute' is not combined with a 'for':
3402 // while (idx <= UB) { BODY; ++idx; }
3403 // when 'distribute' is combined with a 'for'
3404 // (e.g. 'distribute parallel for')
3405 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
3406 CGF.EmitOMPInnerLoop(
3407 S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr,
3408 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
3409 CodeGenLoop(CGF, S, LoopExit);
3410 },
3411 [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) {
3412 CodeGenOrdered(CGF, Loc, IVSize, IVSigned);
3413 });
3414 });
3415
3416 EmitBlock(Continue.getBlock());
3417 BreakContinueStack.pop_back();
3418 if (!DynamicOrOrdered) {
3419 // Emit "LB = LB + Stride", "UB = UB + Stride".
3420 EmitIgnoredExpr(LoopArgs.NextLB);
3421 EmitIgnoredExpr(LoopArgs.NextUB);
3422 }
3423
3424 EmitBranch(CondBlock);
3425 OMPLoopNestStack.clear();
3426 LoopStack.pop();
3427 // Emit the fall-through block.
3428 EmitBlock(LoopExit.getBlock());
3429
3430 // Tell the runtime we are done.
3431 auto &&CodeGen = [DynamicOrOrdered, &S, &LoopArgs](CodeGenFunction &CGF) {
3432 if (!DynamicOrOrdered)
3433 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
3434 LoopArgs.DKind);
3435 };
3436 OMPCancelStack.emitExit(*this, EKind, CodeGen);
3437}
3438
3439void CodeGenFunction::EmitOMPForOuterLoop(
3440 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
3441 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
3442 const OMPLoopArguments &LoopArgs,
3443 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
3444 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
3445
3446 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
3447 const bool DynamicOrOrdered = Ordered || RT.isDynamic(ScheduleKind.Schedule);
3448
3449 assert((Ordered || !RT.isStaticNonchunked(ScheduleKind.Schedule,
3450 LoopArgs.Chunk != nullptr)) &&
3451 "static non-chunked schedule does not need outer loop");
3452
3453 // Emit outer loop.
3454 //
3455 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
3456 // When schedule(dynamic,chunk_size) is specified, the iterations are
3457 // distributed to threads in the team in chunks as the threads request them.
3458 // Each thread executes a chunk of iterations, then requests another chunk,
3459 // until no chunks remain to be distributed. Each chunk contains chunk_size
3460 // iterations, except for the last chunk to be distributed, which may have
3461 // fewer iterations. When no chunk_size is specified, it defaults to 1.
3462 //
3463 // When schedule(guided,chunk_size) is specified, the iterations are assigned
3464 // to threads in the team in chunks as the executing threads request them.
3465 // Each thread executes a chunk of iterations, then requests another chunk,
3466 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
3467 // each chunk is proportional to the number of unassigned iterations divided
3468 // by the number of threads in the team, decreasing to 1. For a chunk_size
3469 // with value k (greater than 1), the size of each chunk is determined in the
3470 // same way, with the restriction that the chunks do not contain fewer than k
3471 // iterations (except for the last chunk to be assigned, which may have fewer
3472 // than k iterations).
3473 //
3474 // When schedule(auto) is specified, the decision regarding scheduling is
3475 // delegated to the compiler and/or runtime system. The programmer gives the
3476 // implementation the freedom to choose any possible mapping of iterations to
3477 // threads in the team.
3478 //
3479 // When schedule(runtime) is specified, the decision regarding scheduling is
3480 // deferred until run time, and the schedule and chunk size are taken from the
3481 // run-sched-var ICV. If the ICV is set to auto, the schedule is
3482 // implementation defined
3483 //
3484 // __kmpc_dispatch_init();
3485 // while(__kmpc_dispatch_next(&LB, &UB)) {
3486 // idx = LB;
3487 // while (idx <= UB) { BODY; ++idx;
3488 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
3489 // } // inner loop
3490 // }
3491 // __kmpc_dispatch_deinit();
3492 //
3493 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
3494 // When schedule(static, chunk_size) is specified, iterations are divided into
3495 // chunks of size chunk_size, and the chunks are assigned to the threads in
3496 // the team in a round-robin fashion in the order of the thread number.
3497 //
3498 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
3499 // while (idx <= UB) { BODY; ++idx; } // inner loop
3500 // LB = LB + ST;
3501 // UB = UB + ST;
3502 // }
3503 //
3504
3505 const Expr *IVExpr = S.getIterationVariable();
3506 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3507 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3508
3509 if (DynamicOrOrdered) {
3510 const std::pair<llvm::Value *, llvm::Value *> DispatchBounds =
3511 CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB);
3512 llvm::Value *LBVal = DispatchBounds.first;
3513 llvm::Value *UBVal = DispatchBounds.second;
3514 CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal,
3515 LoopArgs.Chunk};
3516 RT.emitForDispatchInit(*this, S.getBeginLoc(), ScheduleKind, IVSize,
3517 IVSigned, Ordered, DipatchRTInputValues);
3518 } else {
3519 CGOpenMPRuntime::StaticRTInput StaticInit(
3520 IVSize, IVSigned, Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB,
3521 LoopArgs.ST, LoopArgs.Chunk);
3523 RT.emitForStaticInit(*this, S.getBeginLoc(), EKind, ScheduleKind,
3524 StaticInit);
3525 }
3526
3527 auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc,
3528 const unsigned IVSize,
3529 const bool IVSigned) {
3530 if (Ordered) {
3531 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize,
3532 IVSigned);
3533 }
3534 };
3535
3536 OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
3537 LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB);
3538 OuterLoopArgs.IncExpr = S.getInc();
3539 OuterLoopArgs.Init = S.getInit();
3540 OuterLoopArgs.Cond = S.getCond();
3541 OuterLoopArgs.NextLB = S.getNextLowerBound();
3542 OuterLoopArgs.NextUB = S.getNextUpperBound();
3543 OuterLoopArgs.DKind = LoopArgs.DKind;
3544 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs,
3545 emitOMPLoopBodyWithStopPoint, CodeGenOrdered);
3546 if (DynamicOrOrdered) {
3547 RT.emitForDispatchDeinit(*this, S.getBeginLoc());
3548 }
3549}
3550
3552 const unsigned IVSize, const bool IVSigned) {}
3553
3554void CodeGenFunction::EmitOMPDistributeOuterLoop(
3555 OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S,
3556 OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs,
3557 const CodeGenLoopTy &CodeGenLoopContent) {
3558
3559 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
3560
3561 // Emit outer loop.
3562 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
3563 // dynamic
3564 //
3565
3566 const Expr *IVExpr = S.getIterationVariable();
3567 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3568 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3570
3571 CGOpenMPRuntime::StaticRTInput StaticInit(
3572 IVSize, IVSigned, /* Ordered = */ false, LoopArgs.IL, LoopArgs.LB,
3573 LoopArgs.UB, LoopArgs.ST, LoopArgs.Chunk);
3574 RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind, StaticInit);
3575
3576 // for combined 'distribute' and 'for' the increment expression of distribute
3577 // is stored in DistInc. For 'distribute' alone, it is in Inc.
3578 Expr *IncExpr;
3580 IncExpr = S.getDistInc();
3581 else
3582 IncExpr = S.getInc();
3583
3584 // this routine is shared by 'omp distribute parallel for' and
3585 // 'omp distribute': select the right EUB expression depending on the
3586 // directive
3587 OMPLoopArguments OuterLoopArgs;
3588 OuterLoopArgs.LB = LoopArgs.LB;
3589 OuterLoopArgs.UB = LoopArgs.UB;
3590 OuterLoopArgs.ST = LoopArgs.ST;
3591 OuterLoopArgs.IL = LoopArgs.IL;
3592 OuterLoopArgs.Chunk = LoopArgs.Chunk;
3593 OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(EKind)
3595 : S.getEnsureUpperBound();
3596 OuterLoopArgs.IncExpr = IncExpr;
3597 OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(EKind)
3598 ? S.getCombinedInit()
3599 : S.getInit();
3600 OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(EKind)
3601 ? S.getCombinedCond()
3602 : S.getCond();
3603 OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(EKind)
3605 : S.getNextLowerBound();
3606 OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(EKind)
3608 : S.getNextUpperBound();
3609 OuterLoopArgs.DKind = OMPD_distribute;
3610
3611 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S,
3612 LoopScope, OuterLoopArgs, CodeGenLoopContent,
3614}
3615
3616static std::pair<LValue, LValue>
3618 const OMPExecutableDirective &S) {
3620 LValue LB =
3622 LValue UB =
3624
3625 // When composing 'distribute' with 'for' (e.g. as in 'distribute
3626 // parallel for') we need to use the 'distribute'
3627 // chunk lower and upper bounds rather than the whole loop iteration
3628 // space. These are parameters to the outlined function for 'parallel'
3629 // and we copy the bounds of the previous schedule into the
3630 // the current ones.
3631 LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable());
3632 LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable());
3633 llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar(
3634 PrevLB, LS.getPrevLowerBoundVariable()->getExprLoc());
3635 PrevLBVal = CGF.EmitScalarConversion(
3636 PrevLBVal, LS.getPrevLowerBoundVariable()->getType(),
3639 llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar(
3640 PrevUB, LS.getPrevUpperBoundVariable()->getExprLoc());
3641 PrevUBVal = CGF.EmitScalarConversion(
3642 PrevUBVal, LS.getPrevUpperBoundVariable()->getType(),
3645
3646 CGF.EmitStoreOfScalar(PrevLBVal, LB);
3647 CGF.EmitStoreOfScalar(PrevUBVal, UB);
3648
3649 return {LB, UB};
3650}
3651
3652/// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then
3653/// we need to use the LB and UB expressions generated by the worksharing
3654/// code generation support, whereas in non combined situations we would
3655/// just emit 0 and the LastIteration expression
3656/// This function is necessary due to the difference of the LB and UB
3657/// types for the RT emission routines for 'for_static_init' and
3658/// 'for_dispatch_init'
3659static std::pair<llvm::Value *, llvm::Value *>
3661 const OMPExecutableDirective &S,
3662 Address LB, Address UB) {
3664 const Expr *IVExpr = LS.getIterationVariable();
3665 // when implementing a dynamic schedule for a 'for' combined with a
3666 // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop
3667 // is not normalized as each team only executes its own assigned
3668 // distribute chunk
3669 QualType IteratorTy = IVExpr->getType();
3670 llvm::Value *LBVal =
3671 CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy, S.getBeginLoc());
3672 llvm::Value *UBVal =
3673 CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy, S.getBeginLoc());
3674 return {LBVal, UBVal};
3675}
3676
3680 const auto &Dir = cast<OMPLoopDirective>(S);
3681 LValue LB =
3682 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable()));
3683 llvm::Value *LBCast = CGF.Builder.CreateIntCast(
3684 CGF.Builder.CreateLoad(LB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
3685 CapturedVars.push_back(LBCast);
3686 LValue UB =
3687 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable()));
3688
3689 llvm::Value *UBCast = CGF.Builder.CreateIntCast(
3690 CGF.Builder.CreateLoad(UB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
3691 CapturedVars.push_back(UBCast);
3692}
3693
3694static void
3696 const OMPLoopDirective &S,
3699 auto &&CGInlinedWorksharingLoop = [&S, EKind](CodeGenFunction &CGF,
3700 PrePostActionTy &Action) {
3701 Action.Enter(CGF);
3702 bool HasCancel = false;
3703 if (!isOpenMPSimdDirective(EKind)) {
3704 if (const auto *D = dyn_cast<OMPTeamsDistributeParallelForDirective>(&S))
3705 HasCancel = D->hasCancel();
3706 else if (const auto *D = dyn_cast<OMPDistributeParallelForDirective>(&S))
3707 HasCancel = D->hasCancel();
3708 else if (const auto *D =
3709 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&S))
3710 HasCancel = D->hasCancel();
3711 }
3712 CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, EKind, HasCancel);
3716 };
3717
3719 CGF, S, isOpenMPSimdDirective(EKind) ? OMPD_for_simd : OMPD_for,
3720 CGInlinedWorksharingLoop,
3722}
3723
3726 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3728 S.getDistInc());
3729 };
3730 OMPLexicalScope Scope(*this, S, OMPD_parallel);
3731 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
3732}
3733
3736 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3738 S.getDistInc());
3739 };
3740 OMPLexicalScope Scope(*this, S, OMPD_parallel);
3741 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
3742}
3743
3745 const OMPDistributeSimdDirective &S) {
3746 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3748 };
3749 OMPLexicalScope Scope(*this, S, OMPD_unknown);
3750 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
3751}
3752
3754 CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S) {
3755 // Emit SPMD target parallel for region as a standalone region.
3756 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3757 emitOMPSimdRegion(CGF, S, Action);
3758 };
3759 llvm::Function *Fn;
3760 llvm::Constant *Addr;
3761 // Emit target region as a standalone region.
3762 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3763 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3764 assert(Fn && Addr && "Target device function emission failed.");
3765}
3766
3768 const OMPTargetSimdDirective &S) {
3769 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3770 emitOMPSimdRegion(CGF, S, Action);
3771 };
3773}
3774
3775namespace {
3776struct ScheduleKindModifiersTy {
3780 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
3783 : Kind(Kind), M1(M1), M2(M2) {}
3784};
3785} // namespace
3786
3788 const OMPLoopDirective &S, Expr *EUB,
3789 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
3790 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
3791 // Emit the loop iteration variable.
3792 const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
3793 const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl());
3794 EmitVarDecl(*IVDecl);
3795
3796 // Emit the iterations count variable.
3797 // If it is not a variable, Sema decided to calculate iterations count on each
3798 // iteration (e.g., it is foldable into a constant).
3799 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
3800 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3801 // Emit calculation of the iterations count.
3803 }
3804
3805 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
3806
3807 bool HasLastprivateClause;
3808 // Check pre-condition.
3809 {
3810 OMPLoopScope PreInitScope(*this, S);
3811 // Skip the entire loop if we don't meet the precondition.
3812 // If the condition constant folds and can be elided, avoid emitting the
3813 // whole loop.
3814 bool CondConstant;
3815 llvm::BasicBlock *ContBlock = nullptr;
3816 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3817 if (!CondConstant)
3818 return false;
3819 } else {
3820 llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then");
3821 ContBlock = createBasicBlock("omp.precond.end");
3822 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
3823 getProfileCount(&S));
3824 EmitBlock(ThenBlock);
3826 }
3827
3828 RunCleanupsScope DoacrossCleanupScope(*this);
3829 bool Ordered = false;
3830 if (const auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
3831 if (OrderedClause->getNumForLoops())
3832 RT.emitDoacrossInit(*this, S, OrderedClause->getLoopNumIterations());
3833 else
3834 Ordered = true;
3835 }
3836
3837 emitAlignedClause(*this, S);
3838 bool HasLinears = EmitOMPLinearClauseInit(S);
3839 // Emit helper vars inits.
3840
3841 std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S);
3842 LValue LB = Bounds.first;
3843 LValue UB = Bounds.second;
3844 LValue ST =
3846 LValue IL =
3848
3849 // Emit 'then' code.
3850 {
3852 OMPPrivateScope LoopScope(*this);
3853 if (EmitOMPFirstprivateClause(S, LoopScope) || HasLinears) {
3854 // Emit implicit barrier to synchronize threads and avoid data races on
3855 // initialization of firstprivate variables and post-update of
3856 // lastprivate variables.
3857 CGM.getOpenMPRuntime().emitBarrierCall(
3858 *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
3859 /*ForceSimpleCall=*/true);
3860 }
3861 EmitOMPPrivateClause(S, LoopScope);
3863 *this, S, EmitLValue(S.getIterationVariable()));
3864 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
3865 EmitOMPReductionClauseInit(S, LoopScope);
3866 EmitOMPPrivateLoopCounters(S, LoopScope);
3867 EmitOMPLinearClause(S, LoopScope);
3868 (void)LoopScope.Privatize();
3870 CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(*this, S);
3871
3872 // Detect the loop schedule kind and chunk.
3873 const Expr *ChunkExpr = nullptr;
3874 OpenMPScheduleTy ScheduleKind;
3875 if (const auto *C = S.getSingleClause<OMPScheduleClause>()) {
3876 ScheduleKind.Schedule = C->getScheduleKind();
3877 ScheduleKind.M1 = C->getFirstScheduleModifier();
3878 ScheduleKind.M2 = C->getSecondScheduleModifier();
3879 ChunkExpr = C->getChunkSize();
3880 } else {
3881 // Default behaviour for schedule clause.
3882 CGM.getOpenMPRuntime().getDefaultScheduleAndChunk(
3883 *this, S, ScheduleKind.Schedule, ChunkExpr);
3884 }
3885 bool HasChunkSizeOne = false;
3886 llvm::Value *Chunk = nullptr;
3887 if (ChunkExpr) {
3888 Chunk = EmitScalarExpr(ChunkExpr);
3889 Chunk = EmitScalarConversion(Chunk, ChunkExpr->getType(),
3891 S.getBeginLoc());
3893 if (ChunkExpr->EvaluateAsInt(Result, getContext())) {
3894 llvm::APSInt EvaluatedChunk = Result.Val.getInt();
3895 HasChunkSizeOne = (EvaluatedChunk.getLimitedValue() == 1);
3896 }
3897 }
3898 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3899 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3900 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
3901 // If the static schedule kind is specified or if the ordered clause is
3902 // specified, and if no monotonic modifier is specified, the effect will
3903 // be as if the monotonic modifier was specified.
3904 bool StaticChunkedOne =
3905 RT.isStaticChunked(ScheduleKind.Schedule,
3906 /* Chunked */ Chunk != nullptr) &&
3907 HasChunkSizeOne && isOpenMPLoopBoundSharingDirective(EKind);
3908 // GPU combined `distribute parallel for`: emit a single
3909 // for_static_init with the fused distr_static_chunk + static_chunkone
3910 // schedule (enum 93). The surrounding EmitOMPDistributeLoop must skip
3911 // its distribute_static_init under the same conditions. Both sites are
3912 // guarded by canEmitGPUFusedDistSchedule() alone so they cannot
3913 // disagree; the assert guards the invariant that makes this safe today,
3914 // aka that the implicit GPU default schedule is always static chunk-one.
3915 ScheduleKind.UseFusedDistChunkSchedule =
3917 assert((!ScheduleKind.UseFusedDistChunkSchedule || StaticChunkedOne) &&
3918 "fused distribute schedule requires a static chunk-one schedule");
3919 bool IsMonotonic =
3920 Ordered ||
3921 (ScheduleKind.Schedule == OMPC_SCHEDULE_static &&
3922 !(ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
3923 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)) ||
3924 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
3925 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
3926 if ((RT.isStaticNonchunked(ScheduleKind.Schedule,
3927 /* Chunked */ Chunk != nullptr) ||
3928 StaticChunkedOne) &&
3929 !Ordered) {
3933 *this, S,
3934 [&S, EKind](CodeGenFunction &CGF, PrePostActionTy &) {
3935 if (isOpenMPSimdDirective(EKind)) {
3936 CGF.EmitOMPSimdInit(S);
3937 } else if (const auto *C = S.getSingleClause<OMPOrderClause>()) {
3938 if (C->getKind() == OMPC_ORDER_concurrent)
3939 CGF.LoopStack.setParallel(/*Enable=*/true);
3940 }
3941 },
3942 [IVSize, IVSigned, Ordered, IL, LB, UB, ST, StaticChunkedOne, Chunk,
3943 &S, ScheduleKind, LoopExit, EKind,
3944 &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) {
3945 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
3946 // When no chunk_size is specified, the iteration space is divided
3947 // into chunks that are approximately equal in size, and at most
3948 // one chunk is distributed to each thread. Note that the size of
3949 // the chunks is unspecified in this case.
3951 IVSize, IVSigned, Ordered, IL.getAddress(), LB.getAddress(),
3952 UB.getAddress(), ST.getAddress(),
3953 StaticChunkedOne ? Chunk : nullptr);
3955 CGF, S.getBeginLoc(), EKind, ScheduleKind, StaticInit);
3956 // UB = min(UB, GlobalUB);
3957 if (!StaticChunkedOne)
3958 CGF.EmitIgnoredExpr(S.getEnsureUpperBound());
3959 // IV = LB;
3960 CGF.EmitIgnoredExpr(S.getInit());
3961 // For unchunked static schedule generate:
3962 //
3963 // while (idx <= UB) {
3964 // BODY;
3965 // ++idx;
3966 // }
3967 //
3968 // For static schedule with chunk one:
3969 //
3970 // while (IV <= PrevUB) {
3971 // BODY;
3972 // IV += ST;
3973 // }
3974 CGF.EmitOMPInnerLoop(
3975 S, LoopScope.requiresCleanups(),
3976 StaticChunkedOne ? S.getCombinedParForInDistCond()
3977 : S.getCond(),
3978 StaticChunkedOne ? S.getDistInc() : S.getInc(),
3979 [&S, LoopExit](CodeGenFunction &CGF) {
3980 emitOMPLoopBodyWithStopPoint(CGF, S, LoopExit);
3981 },
3982 [](CodeGenFunction &) {});
3983 });
3984 EmitBlock(LoopExit.getBlock());
3985 // Tell the runtime we are done.
3986 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
3987 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
3988 OMPD_for);
3989 };
3990 OMPCancelStack.emitExit(*this, EKind, CodeGen);
3991 } else {
3992 // Emit the outer loop, which requests its work chunk [LB..UB] from
3993 // runtime and runs the inner loop to process it.
3994 OMPLoopArguments LoopArguments(LB.getAddress(), UB.getAddress(),
3995 ST.getAddress(), IL.getAddress(), Chunk,
3996 EUB);
3997 LoopArguments.DKind = OMPD_for;
3998 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
3999 LoopArguments, CGDispatchBounds);
4000 }
4001 if (isOpenMPSimdDirective(EKind)) {
4002 EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) {
4003 return CGF.Builder.CreateIsNotNull(
4004 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
4005 });
4006 }
4008 S, /*ReductionKind=*/isOpenMPSimdDirective(EKind)
4009 ? /*Parallel and Simd*/ OMPD_parallel_for_simd
4010 : /*Parallel only*/ OMPD_parallel);
4011 // Emit post-update of the reduction variables if IsLastIter != 0.
4013 *this, S, [IL, &S](CodeGenFunction &CGF) {
4014 return CGF.Builder.CreateIsNotNull(
4015 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
4016 });
4017 // Emit final copy of the lastprivate variables if IsLastIter != 0.
4018 if (HasLastprivateClause)
4020 S, isOpenMPSimdDirective(EKind),
4021 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc())));
4022 LoopScope.restoreMap();
4023 EmitOMPLinearClauseFinal(S, [IL, &S](CodeGenFunction &CGF) {
4024 return CGF.Builder.CreateIsNotNull(
4025 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
4026 });
4027 }
4028 DoacrossCleanupScope.ForceCleanup();
4029 // We're now done with the loop, so jump to the continuation block.
4030 if (ContBlock) {
4031 EmitBranch(ContBlock);
4032 EmitBlock(ContBlock, /*IsFinished=*/true);
4033 }
4034 }
4035 return HasLastprivateClause;
4036}
4037
4038/// The following two functions generate expressions for the loop lower
4039/// and upper bounds in case of static and dynamic (dispatch) schedule
4040/// of the associated 'for' or 'distribute' loop.
4041static std::pair<LValue, LValue>
4043 const auto &LS = cast<OMPLoopDirective>(S);
4044 LValue LB =
4045 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
4046 LValue UB =
4047 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
4048 return {LB, UB};
4049}
4050
4051/// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
4052/// consider the lower and upper bound expressions generated by the
4053/// worksharing loop support, but we use 0 and the iteration space size as
4054/// constants
4055static std::pair<llvm::Value *, llvm::Value *>
4057 Address LB, Address UB) {
4058 const auto &LS = cast<OMPLoopDirective>(S);
4059 const Expr *IVExpr = LS.getIterationVariable();
4060 const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
4061 llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
4062 llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
4063 return {LBVal, UBVal};
4064}
4065
4066/// Emits internal temp array declarations for the directive with inscan
4067/// reductions.
4068/// The code is the following:
4069/// \code
4070/// size num_iters = <num_iters>;
4071/// <type> buffer[num_iters];
4072/// \endcode
4074 CodeGenFunction &CGF, const OMPLoopDirective &S,
4075 llvm::function_ref<llvm::Value *(CodeGenFunction &)> NumIteratorsGen) {
4076 llvm::Value *OMPScanNumIterations = CGF.Builder.CreateIntCast(
4077 NumIteratorsGen(CGF), CGF.SizeTy, /*isSigned=*/false);
4080 SmallVector<const Expr *, 4> ReductionOps;
4081 SmallVector<const Expr *, 4> CopyArrayTemps;
4082 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
4083 assert(C->getModifier() == OMPC_REDUCTION_inscan &&
4084 "Only inscan reductions are expected.");
4085 Shareds.append(C->varlist_begin(), C->varlist_end());
4086 Privates.append(C->privates().begin(), C->privates().end());
4087 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
4088 CopyArrayTemps.append(C->copy_array_temps().begin(),
4089 C->copy_array_temps().end());
4090 }
4091 {
4092 // Emit buffers for each reduction variables.
4093 // ReductionCodeGen is required to emit correctly the code for array
4094 // reductions.
4095 ReductionCodeGen RedCG(Shareds, Shareds, Privates, ReductionOps);
4096 unsigned Count = 0;
4097 auto *ITA = CopyArrayTemps.begin();
4098 for (const Expr *IRef : Privates) {
4099 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
4100 // Emit variably modified arrays, used for arrays/array sections
4101 // reductions.
4102 if (PrivateVD->getType()->isVariablyModifiedType()) {
4103 RedCG.emitSharedOrigLValue(CGF, Count);
4104 RedCG.emitAggregateType(CGF, Count);
4105 }
4107 CGF,
4109 cast<VariableArrayType>((*ITA)->getType()->getAsArrayTypeUnsafe())
4110 ->getSizeExpr()),
4111 RValue::get(OMPScanNumIterations));
4112 // Emit temp buffer.
4113 CGF.EmitVarDecl(*cast<VarDecl>(cast<DeclRefExpr>(*ITA)->getDecl()));
4114 ++ITA;
4115 ++Count;
4116 }
4117 }
4118}
4119
4120/// Copies final inscan reductions values to the original variables.
4121/// The code is the following:
4122/// \code
4123/// <orig_var> = buffer[num_iters-1];
4124/// \endcode
4126 CodeGenFunction &CGF, const OMPLoopDirective &S,
4127 llvm::function_ref<llvm::Value *(CodeGenFunction &)> NumIteratorsGen) {
4128 llvm::Value *OMPScanNumIterations = CGF.Builder.CreateIntCast(
4129 NumIteratorsGen(CGF), CGF.SizeTy, /*isSigned=*/false);
4135 SmallVector<const Expr *, 4> CopyArrayElems;
4136 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
4137 assert(C->getModifier() == OMPC_REDUCTION_inscan &&
4138 "Only inscan reductions are expected.");
4139 Shareds.append(C->varlist_begin(), C->varlist_end());
4140 LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
4141 RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
4142 Privates.append(C->privates().begin(), C->privates().end());
4143 CopyOps.append(C->copy_ops().begin(), C->copy_ops().end());
4144 CopyArrayElems.append(C->copy_array_elems().begin(),
4145 C->copy_array_elems().end());
4146 }
4147 // Create temp var and copy LHS value to this temp value.
4148 // LHS = TMP[LastIter];
4149 llvm::Value *OMPLast = CGF.Builder.CreateNSWSub(
4150 OMPScanNumIterations,
4151 llvm::ConstantInt::get(CGF.SizeTy, 1, /*isSigned=*/false));
4152 for (unsigned I = 0, E = CopyArrayElems.size(); I < E; ++I) {
4153 const Expr *PrivateExpr = Privates[I];
4154 const Expr *OrigExpr = Shareds[I];
4155 const Expr *CopyArrayElem = CopyArrayElems[I];
4157 CGF,
4159 cast<ArraySubscriptExpr>(CopyArrayElem)->getIdx()),
4160 RValue::get(OMPLast));
4161 LValue DestLVal = CGF.EmitLValue(OrigExpr);
4162 LValue SrcLVal = CGF.EmitLValue(CopyArrayElem);
4163 CGF.EmitOMPCopy(
4164 PrivateExpr->getType(), DestLVal.getAddress(), SrcLVal.getAddress(),
4165 cast<VarDecl>(cast<DeclRefExpr>(LHSs[I])->getDecl()),
4166 cast<VarDecl>(cast<DeclRefExpr>(RHSs[I])->getDecl()), CopyOps[I]);
4167 }
4168}
4169
4170/// Emits the code for the directive with inscan reductions.
4171/// The code is the following:
4172/// \code
4173/// #pragma omp ...
4174/// for (i: 0..<num_iters>) {
4175/// <input phase>;
4176/// buffer[i] = red;
4177/// }
4178/// #pragma omp master // in parallel region
4179/// for (int k = 0; k != ceil(log2(num_iters)); ++k)
4180/// for (size cnt = last_iter; cnt >= pow(2, k); --k)
4181/// buffer[i] op= buffer[i-pow(2,k)];
4182/// #pragma omp barrier // in parallel region
4183/// #pragma omp ...
4184/// for (0..<num_iters>) {
4185/// red = InclusiveScan ? buffer[i] : buffer[i-1];
4186/// <scan phase>;
4187/// }
4188/// \endcode
4190 CodeGenFunction &CGF, const OMPLoopDirective &S,
4191 llvm::function_ref<llvm::Value *(CodeGenFunction &)> NumIteratorsGen,
4192 llvm::function_ref<void(CodeGenFunction &)> FirstGen,
4193 llvm::function_ref<void(CodeGenFunction &)> SecondGen) {
4194 llvm::Value *OMPScanNumIterations = CGF.Builder.CreateIntCast(
4195 NumIteratorsGen(CGF), CGF.SizeTy, /*isSigned=*/false);
4197 SmallVector<const Expr *, 4> ReductionOps;
4200 SmallVector<const Expr *, 4> CopyArrayElems;
4201 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
4202 assert(C->getModifier() == OMPC_REDUCTION_inscan &&
4203 "Only inscan reductions are expected.");
4204 Privates.append(C->privates().begin(), C->privates().end());
4205 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
4206 LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
4207 RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
4208 CopyArrayElems.append(C->copy_array_elems().begin(),
4209 C->copy_array_elems().end());
4210 }
4212 {
4213 // Emit loop with input phase:
4214 // #pragma omp ...
4215 // for (i: 0..<num_iters>) {
4216 // <input phase>;
4217 // buffer[i] = red;
4218 // }
4219 CGF.OMPFirstScanLoop = true;
4221 FirstGen(CGF);
4222 }
4223 // #pragma omp barrier // in parallel region
4224 auto &&CodeGen = [&S, OMPScanNumIterations, &LHSs, &RHSs, &CopyArrayElems,
4225 &ReductionOps,
4226 &Privates](CodeGenFunction &CGF, PrePostActionTy &Action) {
4227 Action.Enter(CGF);
4228 // Emit prefix reduction:
4229 // #pragma omp master // in parallel region
4230 // for (int k = 0; k <= ceil(log2(n)); ++k)
4231 llvm::BasicBlock *InputBB = CGF.Builder.GetInsertBlock();
4232 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.outer.log.scan.body");
4233 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.outer.log.scan.exit");
4234 llvm::Function *F =
4235 CGF.CGM.getIntrinsic(llvm::Intrinsic::log2, CGF.DoubleTy);
4236 llvm::Value *Arg =
4237 CGF.Builder.CreateUIToFP(OMPScanNumIterations, CGF.DoubleTy);
4238 llvm::Value *LogVal = CGF.EmitNounwindRuntimeCall(F, Arg);
4239 F = CGF.CGM.getIntrinsic(llvm::Intrinsic::ceil, CGF.DoubleTy);
4240 LogVal = CGF.EmitNounwindRuntimeCall(F, LogVal);
4241 LogVal = CGF.Builder.CreateFPToUI(LogVal, CGF.IntTy);
4242 llvm::Value *NMin1 = CGF.Builder.CreateNUWSub(
4243 OMPScanNumIterations, llvm::ConstantInt::get(CGF.SizeTy, 1));
4244 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, S.getBeginLoc());
4245 CGF.EmitBlock(LoopBB);
4246 auto *Counter = CGF.Builder.CreatePHI(CGF.IntTy, 2);
4247 // size pow2k = 1;
4248 auto *Pow2K = CGF.Builder.CreatePHI(CGF.SizeTy, 2);
4249 Counter->addIncoming(llvm::ConstantInt::get(CGF.IntTy, 0), InputBB);
4250 Pow2K->addIncoming(llvm::ConstantInt::get(CGF.SizeTy, 1), InputBB);
4251 // for (size i = n - 1; i >= 2 ^ k; --i)
4252 // tmp[i] op= tmp[i-pow2k];
4253 llvm::BasicBlock *InnerLoopBB =
4254 CGF.createBasicBlock("omp.inner.log.scan.body");
4255 llvm::BasicBlock *InnerExitBB =
4256 CGF.createBasicBlock("omp.inner.log.scan.exit");
4257 llvm::Value *CmpI = CGF.Builder.CreateICmpUGE(NMin1, Pow2K);
4258 CGF.Builder.CreateCondBr(CmpI, InnerLoopBB, InnerExitBB);
4259 CGF.EmitBlock(InnerLoopBB);
4260 auto *IVal = CGF.Builder.CreatePHI(CGF.SizeTy, 2);
4261 IVal->addIncoming(NMin1, LoopBB);
4262 {
4263 CodeGenFunction::OMPPrivateScope PrivScope(CGF);
4264 auto *ILHS = LHSs.begin();
4265 auto *IRHS = RHSs.begin();
4266 for (const Expr *CopyArrayElem : CopyArrayElems) {
4267 const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4268 const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
4269 Address LHSAddr = Address::invalid();
4270 {
4272 CGF,
4274 cast<ArraySubscriptExpr>(CopyArrayElem)->getIdx()),
4275 RValue::get(IVal));
4276 LHSAddr = CGF.EmitLValue(CopyArrayElem).getAddress();
4277 }
4278 PrivScope.addPrivate(LHSVD, LHSAddr);
4279 Address RHSAddr = Address::invalid();
4280 {
4281 llvm::Value *OffsetIVal = CGF.Builder.CreateNUWSub(IVal, Pow2K);
4283 CGF,
4285 cast<ArraySubscriptExpr>(CopyArrayElem)->getIdx()),
4286 RValue::get(OffsetIVal));
4287 RHSAddr = CGF.EmitLValue(CopyArrayElem).getAddress();
4288 }
4289 PrivScope.addPrivate(RHSVD, RHSAddr);
4290 ++ILHS;
4291 ++IRHS;
4292 }
4293 PrivScope.Privatize();
4294 CGF.CGM.getOpenMPRuntime().emitReduction(
4295 CGF, S.getEndLoc(), Privates, LHSs, RHSs, ReductionOps,
4296 {/*WithNowait=*/true, /*SimpleReduction=*/true,
4297 /*IsPrivateVarReduction*/ {}, OMPD_unknown});
4298 }
4299 llvm::Value *NextIVal =
4300 CGF.Builder.CreateNUWSub(IVal, llvm::ConstantInt::get(CGF.SizeTy, 1));
4301 IVal->addIncoming(NextIVal, CGF.Builder.GetInsertBlock());
4302 CmpI = CGF.Builder.CreateICmpUGE(NextIVal, Pow2K);
4303 CGF.Builder.CreateCondBr(CmpI, InnerLoopBB, InnerExitBB);
4304 CGF.EmitBlock(InnerExitBB);
4305 llvm::Value *Next =
4306 CGF.Builder.CreateNUWAdd(Counter, llvm::ConstantInt::get(CGF.IntTy, 1));
4307 Counter->addIncoming(Next, CGF.Builder.GetInsertBlock());
4308 // pow2k <<= 1;
4309 llvm::Value *NextPow2K =
4310 CGF.Builder.CreateShl(Pow2K, 1, "", /*HasNUW=*/true);
4311 Pow2K->addIncoming(NextPow2K, CGF.Builder.GetInsertBlock());
4312 llvm::Value *Cmp = CGF.Builder.CreateICmpNE(Next, LogVal);
4313 CGF.Builder.CreateCondBr(Cmp, LoopBB, ExitBB);
4314 auto DL1 = ApplyDebugLocation::CreateDefaultArtificial(CGF, S.getEndLoc());
4315 CGF.EmitBlock(ExitBB);
4316 };
4318 if (isOpenMPParallelDirective(EKind)) {
4319 CGF.CGM.getOpenMPRuntime().emitMasterRegion(CGF, CodeGen, S.getBeginLoc());
4321 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
4322 /*ForceSimpleCall=*/true);
4323 } else {
4324 RegionCodeGenTy RCG(CodeGen);
4325 RCG(CGF);
4326 }
4327
4328 CGF.OMPFirstScanLoop = false;
4329 SecondGen(CGF);
4330}
4331
4333 const OMPLoopDirective &S,
4334 bool HasCancel) {
4335 bool HasLastprivates;
4337 if (llvm::any_of(S.getClausesOfKind<OMPReductionClause>(),
4338 [](const OMPReductionClause *C) {
4339 return C->getModifier() == OMPC_REDUCTION_inscan;
4340 })) {
4341 const auto &&NumIteratorsGen = [&S](CodeGenFunction &CGF) {
4343 OMPLoopScope LoopScope(CGF, S);
4344 return CGF.EmitScalarExpr(S.getNumIterations());
4345 };
4346 const auto &&FirstGen = [&S, HasCancel, EKind](CodeGenFunction &CGF) {
4347 CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, EKind, HasCancel);
4351 // Emit an implicit barrier at the end.
4352 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getBeginLoc(),
4353 OMPD_for);
4354 };
4355 const auto &&SecondGen = [&S, HasCancel, EKind,
4356 &HasLastprivates](CodeGenFunction &CGF) {
4357 CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, EKind, HasCancel);
4358 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
4361 };
4362 if (!isOpenMPParallelDirective(EKind))
4363 emitScanBasedDirectiveDecls(CGF, S, NumIteratorsGen);
4364 emitScanBasedDirective(CGF, S, NumIteratorsGen, FirstGen, SecondGen);
4365 if (!isOpenMPParallelDirective(EKind))
4366 emitScanBasedDirectiveFinals(CGF, S, NumIteratorsGen);
4367 } else {
4368 CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, EKind, HasCancel);
4369 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
4372 }
4373 return HasLastprivates;
4374}
4375
4376// Pass OMPLoopDirective (instead of OMPForDirective) to make this check
4377// available for "loop bind(parallel)", which maps to "for".
4379 bool HasCancel) {
4380 if (HasCancel)
4381 return false;
4382 for (OMPClause *C : S.clauses()) {
4384 continue;
4385
4386 if (auto *SC = dyn_cast<OMPScheduleClause>(C)) {
4387 if (SC->getFirstScheduleModifier() != OMPC_SCHEDULE_MODIFIER_unknown)
4388 return false;
4389 if (SC->getSecondScheduleModifier() != OMPC_SCHEDULE_MODIFIER_unknown)
4390 return false;
4391 switch (SC->getScheduleKind()) {
4392 case OMPC_SCHEDULE_auto:
4393 case OMPC_SCHEDULE_dynamic:
4394 case OMPC_SCHEDULE_runtime:
4395 case OMPC_SCHEDULE_guided:
4396 case OMPC_SCHEDULE_static:
4397 continue;
4399 return false;
4400 }
4401 }
4402
4403 return false;
4404 }
4405
4406 return true;
4407}
4408
4409static llvm::omp::ScheduleKind
4411 switch (ScheduleClauseKind) {
4413 return llvm::omp::OMP_SCHEDULE_Default;
4414 case OMPC_SCHEDULE_auto:
4415 return llvm::omp::OMP_SCHEDULE_Auto;
4416 case OMPC_SCHEDULE_dynamic:
4417 return llvm::omp::OMP_SCHEDULE_Dynamic;
4418 case OMPC_SCHEDULE_guided:
4419 return llvm::omp::OMP_SCHEDULE_Guided;
4420 case OMPC_SCHEDULE_runtime:
4421 return llvm::omp::OMP_SCHEDULE_Runtime;
4422 case OMPC_SCHEDULE_static:
4423 return llvm::omp::OMP_SCHEDULE_Static;
4424 }
4425 llvm_unreachable("Unhandled schedule kind");
4426}
4427
4428// Pass OMPLoopDirective (instead of OMPForDirective) to make this function
4429// available for "loop bind(parallel)", which maps to "for".
4431 CodeGenModule &CGM, bool HasCancel) {
4432 bool HasLastprivates = false;
4433 bool UseOMPIRBuilder = CGM.getLangOpts().OpenMPIRBuilder &&
4434 isForSupportedByOpenMPIRBuilder(S, HasCancel);
4435 auto &&CodeGen = [&S, &CGM, HasCancel, &HasLastprivates,
4436 UseOMPIRBuilder](CodeGenFunction &CGF, PrePostActionTy &) {
4437 // Use the OpenMPIRBuilder if enabled.
4438 if (UseOMPIRBuilder) {
4439 bool NeedsBarrier = !S.getSingleClause<OMPNowaitClause>();
4440
4441 llvm::omp::ScheduleKind SchedKind = llvm::omp::OMP_SCHEDULE_Default;
4442 llvm::Value *ChunkSize = nullptr;
4443 if (auto *SchedClause = S.getSingleClause<OMPScheduleClause>()) {
4444 SchedKind =
4445 convertClauseKindToSchedKind(SchedClause->getScheduleKind());
4446 if (const Expr *ChunkSizeExpr = SchedClause->getChunkSize())
4447 ChunkSize = CGF.EmitScalarExpr(ChunkSizeExpr);
4448 }
4449
4450 // Emit the associated statement and get its loop representation.
4451 const Stmt *Inner = S.getRawStmt();
4452 llvm::CanonicalLoopInfo *CLI =
4454
4455 llvm::OpenMPIRBuilder &OMPBuilder =
4457 llvm::OpenMPIRBuilder::InsertPointTy AllocaIP(
4458 CGF.AllocaInsertPt->getParent(), CGF.AllocaInsertPt->getIterator());
4459 cantFail(OMPBuilder.applyWorkshareLoop(
4460 CGF.Builder.getCurrentDebugLocation(), CLI, AllocaIP, NeedsBarrier,
4461 SchedKind, ChunkSize, /*HasSimdModifier=*/false,
4462 /*HasMonotonicModifier=*/false, /*HasNonmonotonicModifier=*/false,
4463 /*HasOrderedClause=*/false));
4464 return;
4465 }
4466
4467 HasLastprivates = emitWorksharingDirective(CGF, S, HasCancel);
4468 };
4469 {
4470 auto LPCRegion =
4472 OMPLexicalScope Scope(CGF, S, OMPD_unknown);
4474 HasCancel);
4475 }
4476
4477 if (!UseOMPIRBuilder) {
4478 // Emit an implicit barrier at the end.
4479 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates)
4480 CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getBeginLoc(), OMPD_for);
4481 }
4482 // Check for outer lastprivate conditional update.
4484}
4485
4489
4491 bool HasLastprivates = false;
4492 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
4493 PrePostActionTy &) {
4494 HasLastprivates = emitWorksharingDirective(CGF, S, /*HasCancel=*/false);
4495 };
4496 {
4497 auto LPCRegion =
4499 OMPLexicalScope Scope(*this, S, OMPD_unknown);
4500 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
4501 }
4502
4503 // Emit an implicit barrier at the end.
4504 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates)
4505 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for);
4506 // Check for outer lastprivate conditional update.
4508}
4509
4511 const Twine &Name,
4512 llvm::Value *Init = nullptr) {
4513 LValue LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
4514 if (Init)
4515 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
4516 return LVal;
4517}
4518
4519void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
4520 const Stmt *CapturedStmt = S.getInnermostCapturedStmt()->getCapturedStmt();
4521 const auto *CS = dyn_cast<CompoundStmt>(CapturedStmt);
4522 bool HasLastprivates = false;
4524 auto &&CodeGen = [&S, CapturedStmt, CS, EKind,
4525 &HasLastprivates](CodeGenFunction &CGF, PrePostActionTy &) {
4526 const ASTContext &C = CGF.getContext();
4527 QualType KmpInt32Ty =
4528 C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
4529 // Emit helper vars inits.
4530 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
4531 CGF.Builder.getInt32(0));
4532 llvm::ConstantInt *GlobalUBVal = CS != nullptr
4533 ? CGF.Builder.getInt32(CS->size() - 1)
4534 : CGF.Builder.getInt32(0);
4535 LValue UB =
4536 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
4537 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
4538 CGF.Builder.getInt32(1));
4539 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
4540 CGF.Builder.getInt32(0));
4541 // Loop counter.
4542 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
4543 OpaqueValueExpr IVRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue);
4544 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
4545 OpaqueValueExpr UBRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue);
4546 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
4547 // Generate condition for loop.
4548 BinaryOperator *Cond = BinaryOperator::Create(
4549 C, &IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_PRValue, OK_Ordinary,
4550 S.getBeginLoc(), FPOptionsOverride());
4551 // Increment for loop counter.
4552 UnaryOperator *Inc = UnaryOperator::Create(
4553 C, &IVRefExpr, UO_PreInc, KmpInt32Ty, VK_PRValue, OK_Ordinary,
4554 S.getBeginLoc(), true, FPOptionsOverride());
4555 auto &&BodyGen = [CapturedStmt, CS, &S, &IV](CodeGenFunction &CGF) {
4556 // Iterate through all sections and emit a switch construct:
4557 // switch (IV) {
4558 // case 0:
4559 // <SectionStmt[0]>;
4560 // break;
4561 // ...
4562 // case <NumSection> - 1:
4563 // <SectionStmt[<NumSection> - 1]>;
4564 // break;
4565 // }
4566 // .omp.sections.exit:
4567 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
4568 llvm::SwitchInst *SwitchStmt =
4569 CGF.Builder.CreateSwitch(CGF.EmitLoadOfScalar(IV, S.getBeginLoc()),
4570 ExitBB, CS == nullptr ? 1 : CS->size());
4571 if (CS) {
4572 unsigned CaseNumber = 0;
4573 for (const Stmt *SubStmt : CS->children()) {
4574 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
4575 CGF.EmitBlock(CaseBB);
4576 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
4577 CGF.EmitStmt(SubStmt);
4578 CGF.EmitBranch(ExitBB);
4579 ++CaseNumber;
4580 }
4581 } else {
4582 llvm::BasicBlock *CaseBB = CGF.createBasicBlock(".omp.sections.case");
4583 CGF.EmitBlock(CaseBB);
4584 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
4585 CGF.EmitStmt(CapturedStmt);
4586 CGF.EmitBranch(ExitBB);
4587 }
4588 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
4589 };
4590
4591 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
4592 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
4593 // Emit implicit barrier to synchronize threads and avoid data races on
4594 // initialization of firstprivate variables and post-update of lastprivate
4595 // variables.
4596 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
4597 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
4598 /*ForceSimpleCall=*/true);
4599 }
4600 CGF.EmitOMPPrivateClause(S, LoopScope);
4601 CGOpenMPRuntime::LastprivateConditionalRAII LPCRegion(CGF, S, IV);
4602 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
4603 CGF.EmitOMPReductionClauseInit(S, LoopScope);
4604 (void)LoopScope.Privatize();
4606 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
4607
4608 // Emit static non-chunked loop.
4609 OpenMPScheduleTy ScheduleKind;
4610 ScheduleKind.Schedule = OMPC_SCHEDULE_static;
4611 CGOpenMPRuntime::StaticRTInput StaticInit(
4612 /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
4613 LB.getAddress(), UB.getAddress(), ST.getAddress());
4614 CGF.CGM.getOpenMPRuntime().emitForStaticInit(CGF, S.getBeginLoc(), EKind,
4615 ScheduleKind, StaticInit);
4616 // UB = min(UB, GlobalUB);
4617 llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, S.getBeginLoc());
4618 llvm::Value *MinUBGlobalUB = CGF.Builder.CreateSelect(
4619 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
4620 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
4621 // IV = LB;
4622 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getBeginLoc()), IV);
4623 // while (idx <= UB) { BODY; ++idx; }
4624 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, Cond, Inc, BodyGen,
4625 [](CodeGenFunction &) {});
4626 // Tell the runtime we are done.
4627 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
4628 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
4629 OMPD_sections);
4630 };
4631 CGF.OMPCancelStack.emitExit(CGF, EKind, CodeGen);
4632 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
4633 // Emit post-update of the reduction variables if IsLastIter != 0.
4634 emitPostUpdateForReductionClause(CGF, S, [IL, &S](CodeGenFunction &CGF) {
4635 return CGF.Builder.CreateIsNotNull(
4636 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
4637 });
4638
4639 // Emit final copy of the lastprivate variables if IsLastIter != 0.
4640 if (HasLastprivates)
4642 S, /*NoFinals=*/false,
4643 CGF.Builder.CreateIsNotNull(
4644 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())));
4645 };
4646
4647 bool HasCancel = false;
4648 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
4649 HasCancel = OSD->hasCancel();
4650 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
4651 HasCancel = OPSD->hasCancel();
4652 OMPCancelStackRAII CancelRegion(*this, EKind, HasCancel);
4653 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
4654 HasCancel);
4655 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
4656 // clause. Otherwise the barrier will be generated by the codegen for the
4657 // directive.
4658 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
4659 // Emit implicit barrier to synchronize threads and avoid data races on
4660 // initialization of firstprivate variables.
4661 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(),
4662 OMPD_unknown);
4663 }
4664}
4665
4667 {
4668 // Emit code for 'scope' region
4669 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4670 Action.Enter(CGF);
4671 OMPPrivateScope PrivateScope(CGF);
4672 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4673 CGF.EmitOMPPrivateClause(S, PrivateScope);
4674 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4675 (void)PrivateScope.Privatize();
4676 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
4677 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
4678 };
4679 auto LPCRegion =
4681 OMPLexicalScope Scope(*this, S, OMPD_unknown);
4682 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_scope, CodeGen);
4683 }
4684 // Emit an implicit barrier at the end.
4685 if (!S.getSingleClause<OMPNowaitClause>()) {
4686 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_scope);
4687 }
4688 // Check for outer lastprivate conditional update.
4690}
4691
4693 if (CGM.getLangOpts().OpenMPIRBuilder) {
4694 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
4695 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
4696 using BodyGenCallbackTy = llvm::OpenMPIRBuilder::StorableBodyGenCallbackTy;
4697
4698 auto FiniCB = [](InsertPointTy IP) {
4699 // Don't FinalizeOMPRegion because this is done inside of OMPIRBuilder for
4700 // sections.
4701 return llvm::Error::success();
4702 };
4703
4704 const CapturedStmt *ICS = S.getInnermostCapturedStmt();
4705 const Stmt *CapturedStmt = S.getInnermostCapturedStmt()->getCapturedStmt();
4706 const auto *CS = dyn_cast<CompoundStmt>(CapturedStmt);
4708 if (CS) {
4709 for (const Stmt *SubStmt : CS->children()) {
4710 auto SectionCB = [this, SubStmt](
4711 InsertPointTy AllocIP, InsertPointTy CodeGenIP,
4712 ArrayRef<llvm::BasicBlock *> DeallocBlocks) {
4713 OMPBuilderCBHelpers::EmitOMPInlinedRegionBody(*this, SubStmt, AllocIP,
4714 CodeGenIP, "section");
4715 return llvm::Error::success();
4716 };
4717 SectionCBVector.push_back(SectionCB);
4718 }
4719 } else {
4720 auto SectionCB =
4721 [this, CapturedStmt](InsertPointTy AllocIP, InsertPointTy CodeGenIP,
4722 ArrayRef<llvm::BasicBlock *> DeallocBlocks) {
4724 *this, CapturedStmt, AllocIP, CodeGenIP, "section");
4725 return llvm::Error::success();
4726 };
4727 SectionCBVector.push_back(SectionCB);
4728 }
4729
4730 // Privatization callback that performs appropriate action for
4731 // shared/private/firstprivate/lastprivate/copyin/... variables.
4732 //
4733 // TODO: This defaults to shared right now.
4734 auto PrivCB = [](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
4735 llvm::Value &, llvm::Value &Val, llvm::Value *&ReplVal) {
4736 // The next line is appropriate only for variables (Val) with the
4737 // data-sharing attribute "shared".
4738 ReplVal = &Val;
4739
4740 return CodeGenIP;
4741 };
4742
4743 CGCapturedStmtInfo CGSI(*ICS, CR_OpenMP);
4744 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(*this, &CGSI);
4745 llvm::OpenMPIRBuilder::InsertPointTy AllocaIP(
4746 AllocaInsertPt->getParent(), AllocaInsertPt->getIterator());
4747 llvm::OpenMPIRBuilder::InsertPointTy AfterIP =
4748 cantFail(OMPBuilder.createSections(
4749 Builder, AllocaIP, SectionCBVector, PrivCB, FiniCB, S.hasCancel(),
4750 S.getSingleClause<OMPNowaitClause>()));
4751 Builder.restoreIP(AfterIP);
4752 return;
4753 }
4754 {
4755 auto LPCRegion =
4757 OMPLexicalScope Scope(*this, S, OMPD_unknown);
4758 EmitSections(S);
4759 }
4760 // Emit an implicit barrier at the end.
4761 if (!S.getSingleClause<OMPNowaitClause>()) {
4762 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(),
4763 OMPD_sections);
4764 }
4765 // Check for outer lastprivate conditional update.
4767}
4768
4770 if (CGM.getLangOpts().OpenMPIRBuilder) {
4771 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
4772 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
4773
4774 const Stmt *SectionRegionBodyStmt = S.getAssociatedStmt();
4775 auto FiniCB = [this](InsertPointTy IP) {
4777 return llvm::Error::success();
4778 };
4779
4780 auto BodyGenCB = [SectionRegionBodyStmt,
4781 this](InsertPointTy AllocIP, InsertPointTy CodeGenIP,
4782 ArrayRef<llvm::BasicBlock *> DeallocBlocks) {
4784 *this, SectionRegionBodyStmt, AllocIP, CodeGenIP, "section");
4785 return llvm::Error::success();
4786 };
4787
4788 LexicalScope Scope(*this, S.getSourceRange());
4789 EmitStopPoint(&S);
4790 llvm::OpenMPIRBuilder::InsertPointTy AfterIP =
4791 cantFail(OMPBuilder.createSection(Builder, BodyGenCB, FiniCB));
4792 Builder.restoreIP(AfterIP);
4793
4794 return;
4795 }
4796 LexicalScope Scope(*this, S.getSourceRange());
4797 EmitStopPoint(&S);
4798 EmitStmt(S.getAssociatedStmt());
4799}
4800
4802 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
4806 // Check if there are any 'copyprivate' clauses associated with this
4807 // 'single' construct.
4808 // Build a list of copyprivate variables along with helper expressions
4809 // (<source>, <destination>, <destination>=<source> expressions)
4810 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
4811 CopyprivateVars.append(C->varlist_begin(), C->varlist_end());
4812 DestExprs.append(C->destination_exprs().begin(),
4813 C->destination_exprs().end());
4814 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
4815 AssignmentOps.append(C->assignment_ops().begin(),
4816 C->assignment_ops().end());
4817 }
4818 // Emit code for 'single' region along with 'copyprivate' clauses
4819 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4820 Action.Enter(CGF);
4824 (void)SingleScope.Privatize();
4825 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
4826 };
4827 {
4828 auto LPCRegion =
4830 OMPLexicalScope Scope(*this, S, OMPD_unknown);
4831 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getBeginLoc(),
4832 CopyprivateVars, DestExprs,
4833 SrcExprs, AssignmentOps);
4834 }
4835 // Emit an implicit barrier at the end (to avoid data race on firstprivate
4836 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
4837 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
4838 CGM.getOpenMPRuntime().emitBarrierCall(
4839 *this, S.getBeginLoc(),
4840 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
4841 }
4842 // Check for outer lastprivate conditional update.
4844}
4845
4847 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4848 Action.Enter(CGF);
4849 CGF.EmitStmt(S.getRawStmt());
4850 };
4851 CGF.CGM.getOpenMPRuntime().emitMasterRegion(CGF, CodeGen, S.getBeginLoc());
4852}
4853
4855 if (CGM.getLangOpts().OpenMPIRBuilder) {
4856 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
4857 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
4858
4859 const Stmt *MasterRegionBodyStmt = S.getAssociatedStmt();
4860
4861 auto FiniCB = [this](InsertPointTy IP) {
4863 return llvm::Error::success();
4864 };
4865
4866 auto BodyGenCB = [MasterRegionBodyStmt,
4867 this](InsertPointTy AllocIP, InsertPointTy CodeGenIP,
4868 ArrayRef<llvm::BasicBlock *> DeallocBlocks) {
4870 *this, MasterRegionBodyStmt, AllocIP, CodeGenIP, "master");
4871 return llvm::Error::success();
4872 };
4873
4874 LexicalScope Scope(*this, S.getSourceRange());
4875 EmitStopPoint(&S);
4876 llvm::OpenMPIRBuilder::InsertPointTy AfterIP =
4877 cantFail(OMPBuilder.createMaster(Builder, BodyGenCB, FiniCB));
4878 Builder.restoreIP(AfterIP);
4879
4880 return;
4881 }
4882 LexicalScope Scope(*this, S.getSourceRange());
4883 EmitStopPoint(&S);
4884 emitMaster(*this, S);
4885}
4886
4888 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4889 Action.Enter(CGF);
4890 CGF.EmitStmt(S.getRawStmt());
4891 };
4892 Expr *Filter = nullptr;
4893 if (const auto *FilterClause = S.getSingleClause<OMPFilterClause>())
4894 Filter = FilterClause->getThreadID();
4895 CGF.CGM.getOpenMPRuntime().emitMaskedRegion(CGF, CodeGen, S.getBeginLoc(),
4896 Filter);
4897}
4898
4900 if (CGM.getLangOpts().OpenMPIRBuilder) {
4901 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
4902 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
4903
4904 const Stmt *MaskedRegionBodyStmt = S.getAssociatedStmt();
4905 const Expr *Filter = nullptr;
4906 if (const auto *FilterClause = S.getSingleClause<OMPFilterClause>())
4907 Filter = FilterClause->getThreadID();
4908 llvm::Value *FilterVal = Filter
4909 ? EmitScalarExpr(Filter, CGM.Int32Ty)
4910 : llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/0);
4911
4912 auto FiniCB = [this](InsertPointTy IP) {
4914 return llvm::Error::success();
4915 };
4916
4917 auto BodyGenCB = [MaskedRegionBodyStmt,
4918 this](InsertPointTy AllocIP, InsertPointTy CodeGenIP,
4919 ArrayRef<llvm::BasicBlock *> DeallocBlocks) {
4921 *this, MaskedRegionBodyStmt, AllocIP, CodeGenIP, "masked");
4922 return llvm::Error::success();
4923 };
4924
4925 LexicalScope Scope(*this, S.getSourceRange());
4926 EmitStopPoint(&S);
4927 llvm::OpenMPIRBuilder::InsertPointTy AfterIP = cantFail(
4928 OMPBuilder.createMasked(Builder, BodyGenCB, FiniCB, FilterVal));
4929 Builder.restoreIP(AfterIP);
4930
4931 return;
4932 }
4933 LexicalScope Scope(*this, S.getSourceRange());
4934 EmitStopPoint(&S);
4935 emitMasked(*this, S);
4936}
4937
4939 if (CGM.getLangOpts().OpenMPIRBuilder) {
4940 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
4941 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
4942
4943 const Stmt *CriticalRegionBodyStmt = S.getAssociatedStmt();
4944 const Expr *Hint = nullptr;
4945 if (const auto *HintClause = S.getSingleClause<OMPHintClause>())
4946 Hint = HintClause->getHint();
4947
4948 // TODO: This is slightly different from what's currently being done in
4949 // clang. Fix the Int32Ty to IntPtrTy (pointer width size) when everything
4950 // about typing is final.
4951 llvm::Value *HintInst = nullptr;
4952 if (Hint)
4953 HintInst =
4954 Builder.CreateIntCast(EmitScalarExpr(Hint), CGM.Int32Ty, false);
4955
4956 auto FiniCB = [this](InsertPointTy IP) {
4958 return llvm::Error::success();
4959 };
4960
4961 auto BodyGenCB = [CriticalRegionBodyStmt,
4962 this](InsertPointTy AllocIP, InsertPointTy CodeGenIP,
4963 ArrayRef<llvm::BasicBlock *> DeallocBlocks) {
4965 *this, CriticalRegionBodyStmt, AllocIP, CodeGenIP, "critical");
4966 return llvm::Error::success();
4967 };
4968
4969 LexicalScope Scope(*this, S.getSourceRange());
4970 EmitStopPoint(&S);
4971 llvm::OpenMPIRBuilder::InsertPointTy AfterIP =
4972 cantFail(OMPBuilder.createCritical(Builder, BodyGenCB, FiniCB,
4974 HintInst));
4975 Builder.restoreIP(AfterIP);
4976
4977 return;
4978 }
4979
4980 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4981 Action.Enter(CGF);
4982 CGF.EmitStmt(S.getAssociatedStmt());
4983 };
4984 const Expr *Hint = nullptr;
4985 if (const auto *HintClause = S.getSingleClause<OMPHintClause>())
4986 Hint = HintClause->getHint();
4987 LexicalScope Scope(*this, S.getSourceRange());
4988 EmitStopPoint(&S);
4989 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
4991 CodeGen, S.getBeginLoc(), Hint);
4992}
4993
4995 const OMPParallelForDirective &S) {
4996 // Emit directive as a combined directive that consists of two implicit
4997 // directives: 'parallel' with 'for' directive.
4998 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4999 Action.Enter(CGF);
5000 emitOMPCopyinClause(CGF, S);
5001 (void)emitWorksharingDirective(CGF, S, S.hasCancel());
5002 };
5003 {
5004 const auto &&NumIteratorsGen = [&S](CodeGenFunction &CGF) {
5007 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGSI);
5008 OMPLoopScope LoopScope(CGF, S);
5009 return CGF.EmitScalarExpr(S.getNumIterations());
5010 };
5011 bool IsInscan = llvm::any_of(S.getClausesOfKind<OMPReductionClause>(),
5012 [](const OMPReductionClause *C) {
5013 return C->getModifier() == OMPC_REDUCTION_inscan;
5014 });
5015 if (IsInscan)
5016 emitScanBasedDirectiveDecls(*this, S, NumIteratorsGen);
5017 auto LPCRegion =
5019 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
5021 if (IsInscan)
5022 emitScanBasedDirectiveFinals(*this, S, NumIteratorsGen);
5023 }
5024 // Check for outer lastprivate conditional update.
5026}
5027
5029 const OMPParallelForSimdDirective &S) {
5030 // Emit directive as a combined directive that consists of two implicit
5031 // directives: 'parallel' with 'for' directive.
5032 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5033 Action.Enter(CGF);
5034 emitOMPCopyinClause(CGF, S);
5035 (void)emitWorksharingDirective(CGF, S, /*HasCancel=*/false);
5036 };
5037 {
5038 const auto &&NumIteratorsGen = [&S](CodeGenFunction &CGF) {
5041 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGSI);
5042 OMPLoopScope LoopScope(CGF, S);
5043 return CGF.EmitScalarExpr(S.getNumIterations());
5044 };
5045 bool IsInscan = llvm::any_of(S.getClausesOfKind<OMPReductionClause>(),
5046 [](const OMPReductionClause *C) {
5047 return C->getModifier() == OMPC_REDUCTION_inscan;
5048 });
5049 if (IsInscan)
5050 emitScanBasedDirectiveDecls(*this, S, NumIteratorsGen);
5051 auto LPCRegion =
5053 emitCommonOMPParallelDirective(*this, S, OMPD_for_simd, CodeGen,
5055 if (IsInscan)
5056 emitScanBasedDirectiveFinals(*this, S, NumIteratorsGen);
5057 }
5058 // Check for outer lastprivate conditional update.
5060}
5061
5063 const OMPParallelMasterDirective &S) {
5064 // Emit directive as a combined directive that consists of two implicit
5065 // directives: 'parallel' with 'master' directive.
5066 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5067 Action.Enter(CGF);
5068 OMPPrivateScope PrivateScope(CGF);
5069 emitOMPCopyinClause(CGF, S);
5070 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
5071 CGF.EmitOMPPrivateClause(S, PrivateScope);
5072 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
5073 (void)PrivateScope.Privatize();
5074 emitMaster(CGF, S);
5075 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
5076 };
5077 {
5078 auto LPCRegion =
5080 emitCommonOMPParallelDirective(*this, S, OMPD_master, CodeGen,
5083 [](CodeGenFunction &) { return nullptr; });
5084 }
5085 // Check for outer lastprivate conditional update.
5087}
5088
5090 const OMPParallelMaskedDirective &S) {
5091 // Emit directive as a combined directive that consists of two implicit
5092 // directives: 'parallel' with 'masked' directive.
5093 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5094 Action.Enter(CGF);
5095 OMPPrivateScope PrivateScope(CGF);
5096 emitOMPCopyinClause(CGF, S);
5097 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
5098 CGF.EmitOMPPrivateClause(S, PrivateScope);
5099 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
5100 (void)PrivateScope.Privatize();
5101 emitMasked(CGF, S);
5102 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
5103 };
5104 {
5105 auto LPCRegion =
5107 emitCommonOMPParallelDirective(*this, S, OMPD_masked, CodeGen,
5110 [](CodeGenFunction &) { return nullptr; });
5111 }
5112 // Check for outer lastprivate conditional update.
5114}
5115
5118 // Emit directive as a combined directive that consists of two implicit
5119 // directives: 'parallel' with 'sections' directive.
5120 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5121 Action.Enter(CGF);
5122 emitOMPCopyinClause(CGF, S);
5123 CGF.EmitSections(S);
5124 };
5125 {
5126 auto LPCRegion =
5128 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
5130 }
5131 // Check for outer lastprivate conditional update.
5133}
5134
5135namespace {
5136/// Get the list of variables declared in the context of the untied tasks.
5137class CheckVarsEscapingUntiedTaskDeclContext final
5138 : public ConstStmtVisitor<CheckVarsEscapingUntiedTaskDeclContext> {
5140
5141public:
5142 explicit CheckVarsEscapingUntiedTaskDeclContext() = default;
5143 ~CheckVarsEscapingUntiedTaskDeclContext() = default;
5144 void VisitDeclStmt(const DeclStmt *S) {
5145 if (!S)
5146 return;
5147 // Need to privatize only local vars, static locals can be processed as is.
5148 for (const Decl *D : S->decls()) {
5149 if (const auto *VD = dyn_cast_or_null<VarDecl>(D))
5150 if (VD->hasLocalStorage())
5151 PrivateDecls.push_back(VD);
5152 }
5153 }
5154 void VisitOMPExecutableDirective(const OMPExecutableDirective *) {}
5155 void VisitCapturedStmt(const CapturedStmt *) {}
5156 void VisitLambdaExpr(const LambdaExpr *) {}
5157 void VisitBlockExpr(const BlockExpr *) {}
5158 void VisitStmt(const Stmt *S) {
5159 if (!S)
5160 return;
5161 for (const Stmt *Child : S->children())
5162 if (Child)
5163 Visit(Child);
5164 }
5165
5166 /// Swaps list of vars with the provided one.
5167 ArrayRef<const VarDecl *> getPrivateDecls() const { return PrivateDecls; }
5168};
5169} // anonymous namespace
5170
5173
5174 // First look for 'omp_all_memory' and add this first.
5175 bool OmpAllMemory = false;
5176 if (llvm::any_of(
5177 S.getClausesOfKind<OMPDependClause>(), [](const OMPDependClause *C) {
5178 return C->getDependencyKind() == OMPC_DEPEND_outallmemory ||
5179 C->getDependencyKind() == OMPC_DEPEND_inoutallmemory;
5180 })) {
5181 OmpAllMemory = true;
5182 // Since both OMPC_DEPEND_outallmemory and OMPC_DEPEND_inoutallmemory are
5183 // equivalent to the runtime, always use OMPC_DEPEND_outallmemory to
5184 // simplify.
5186 Data.Dependences.emplace_back(OMPC_DEPEND_outallmemory,
5187 /*IteratorExpr=*/nullptr);
5188 // Add a nullptr Expr to simplify the codegen in emitDependData.
5189 DD.DepExprs.push_back(nullptr);
5190 }
5191 // Add remaining dependences skipping any 'out' or 'inout' if they are
5192 // overridden by 'omp_all_memory'.
5193 for (const auto *C : S.getClausesOfKind<OMPDependClause>()) {
5194 OpenMPDependClauseKind Kind = C->getDependencyKind();
5195 if (Kind == OMPC_DEPEND_outallmemory || Kind == OMPC_DEPEND_inoutallmemory)
5196 continue;
5197 if (OmpAllMemory && (Kind == OMPC_DEPEND_out || Kind == OMPC_DEPEND_inout))
5198 continue;
5200 Data.Dependences.emplace_back(C->getDependencyKind(), C->getModifier());
5201 DD.DepExprs.append(C->varlist_begin(), C->varlist_end());
5202 }
5203}
5204
5206 const OMPExecutableDirective &S, const OpenMPDirectiveKind CapturedRegion,
5207 const RegionCodeGenTy &BodyGen, const TaskGenTy &TaskGen,
5209 // Emit outlined function for task construct.
5210 const CapturedStmt *CS = S.getCapturedStmt(CapturedRegion);
5211 auto I = CS->getCapturedDecl()->param_begin();
5212 auto PartId = std::next(I);
5213 auto TaskT = std::next(I, 4);
5214 // Check if the task is final
5215 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
5216 // If the condition constant folds and can be elided, try to avoid emitting
5217 // the condition and the dead arm of the if/else.
5218 const Expr *Cond = Clause->getCondition();
5219 bool CondConstant;
5220 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
5221 Data.Final.setInt(CondConstant);
5222 else
5223 Data.Final.setPointer(EvaluateExprAsBool(Cond));
5224 } else {
5225 // By default the task is not final.
5226 Data.Final.setInt(/*IntVal=*/false);
5227 }
5228 // Check if the task has 'priority' clause.
5229 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
5230 const Expr *Prio = Clause->getPriority();
5231 Data.Priority.setInt(/*IntVal=*/true);
5232 Data.Priority.setPointer(EmitScalarConversion(
5233 EmitScalarExpr(Prio), Prio->getType(),
5234 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
5235 Prio->getExprLoc()));
5236 }
5237 // The first function argument for tasks is a thread id, the second one is a
5238 // part id (0 for tied tasks, >=0 for untied task).
5239 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
5240 // Get list of private variables.
5241 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
5242 auto IRef = C->varlist_begin();
5243 for (const Expr *IInit : C->private_copies()) {
5244 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
5245 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
5246 Data.PrivateVars.push_back(*IRef);
5247 Data.PrivateCopies.push_back(IInit);
5248 }
5249 ++IRef;
5250 }
5251 }
5252 EmittedAsPrivate.clear();
5253 // Get list of firstprivate variables.
5254 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
5255 auto IRef = C->varlist_begin();
5256 auto IElemInitRef = C->inits().begin();
5257 for (const Expr *IInit : C->private_copies()) {
5258 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
5259 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
5260 Data.FirstprivateVars.push_back(*IRef);
5261 Data.FirstprivateCopies.push_back(IInit);
5262 Data.FirstprivateInits.push_back(*IElemInitRef);
5263 }
5264 ++IRef;
5265 ++IElemInitRef;
5266 }
5267 }
5268 // Get list of lastprivate variables (for taskloops).
5269 llvm::MapVector<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
5270 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
5271 auto IRef = C->varlist_begin();
5272 auto ID = C->destination_exprs().begin();
5273 for (const Expr *IInit : C->private_copies()) {
5274 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
5275 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
5276 Data.LastprivateVars.push_back(*IRef);
5277 Data.LastprivateCopies.push_back(IInit);
5278 }
5279 LastprivateDstsOrigs.insert(
5280 std::make_pair(cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
5281 cast<DeclRefExpr>(*IRef)));
5282 ++IRef;
5283 ++ID;
5284 }
5285 }
5288 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
5289 Data.ReductionVars.append(C->varlist_begin(), C->varlist_end());
5290 Data.ReductionOrigs.append(C->varlist_begin(), C->varlist_end());
5291 Data.ReductionCopies.append(C->privates().begin(), C->privates().end());
5292 Data.ReductionOps.append(C->reduction_ops().begin(),
5293 C->reduction_ops().end());
5294 LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
5295 RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
5296 }
5297 Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit(
5298 *this, S.getBeginLoc(), LHSs, RHSs, Data);
5299 // Build list of dependences.
5301 // Get list of local vars for untied tasks.
5302 if (!Data.Tied) {
5303 CheckVarsEscapingUntiedTaskDeclContext Checker;
5304 Checker.Visit(S.getInnermostCapturedStmt()->getCapturedStmt());
5305 Data.PrivateLocals.append(Checker.getPrivateDecls().begin(),
5306 Checker.getPrivateDecls().end());
5307 }
5308 auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs,
5309 CapturedRegion](CodeGenFunction &CGF,
5310 PrePostActionTy &Action) {
5311 llvm::MapVector<CanonicalDeclPtr<const VarDecl>,
5312 std::pair<Address, Address>>
5313 UntiedLocalVars;
5314 // Set proper addresses for generated private copies.
5316 // Generate debug info for variables present in shared clause.
5317 if (auto *DI = CGF.getDebugInfo()) {
5318 llvm::SmallDenseMap<const VarDecl *, FieldDecl *> CaptureFields =
5319 CGF.CapturedStmtInfo->getCaptureFields();
5320 llvm::Value *ContextValue = CGF.CapturedStmtInfo->getContextValue();
5321 if (CaptureFields.size() && ContextValue) {
5322 unsigned CharWidth = CGF.getContext().getCharWidth();
5323 // The shared variables are packed together as members of structure.
5324 // So the address of each shared variable can be computed by adding
5325 // offset of it (within record) to the base address of record. For each
5326 // shared variable, debug intrinsic llvm.dbg.declare is generated with
5327 // appropriate expressions (DIExpression).
5328 // Ex:
5329 // %12 = load %struct.anon*, %struct.anon** %__context.addr.i
5330 // call void @llvm.dbg.declare(metadata %struct.anon* %12,
5331 // metadata !svar1,
5332 // metadata !DIExpression(DW_OP_deref))
5333 // call void @llvm.dbg.declare(metadata %struct.anon* %12,
5334 // metadata !svar2,
5335 // metadata !DIExpression(DW_OP_plus_uconst, 8, DW_OP_deref))
5336 for (auto It = CaptureFields.begin(); It != CaptureFields.end(); ++It) {
5337 const VarDecl *SharedVar = It->first;
5338 RecordDecl *CaptureRecord = It->second->getParent();
5339 const ASTRecordLayout &Layout =
5340 CGF.getContext().getASTRecordLayout(CaptureRecord);
5341 unsigned Offset =
5342 Layout.getFieldOffset(It->second->getFieldIndex()) / CharWidth;
5343 if (CGF.CGM.getCodeGenOpts().hasReducedDebugInfo())
5344 (void)DI->EmitDeclareOfAutoVariable(SharedVar, ContextValue,
5345 CGF.Builder, false);
5346 // Get the call dbg.declare instruction we just created and update
5347 // its DIExpression to add offset to base address.
5348 auto UpdateExpr = [](llvm::LLVMContext &Ctx, auto *Declare,
5349 unsigned Offset) {
5351 // Add offset to the base address if non zero.
5352 if (Offset) {
5353 Ops.push_back(llvm::dwarf::DW_OP_plus_uconst);
5354 Ops.push_back(Offset);
5355 }
5356 Ops.push_back(llvm::dwarf::DW_OP_deref);
5357 Declare->setExpression(llvm::DIExpression::get(Ctx, Ops));
5358 };
5359 llvm::Instruction &Last = CGF.Builder.GetInsertBlock()->back();
5360 if (auto DDI = dyn_cast<llvm::DbgVariableIntrinsic>(&Last))
5361 UpdateExpr(DDI->getContext(), DDI, Offset);
5362 // If we're emitting using the new debug info format into a block
5363 // without a terminator, the record will be "trailing".
5364 assert(!Last.isTerminator() && "unexpected terminator");
5365 if (auto *Marker =
5366 CGF.Builder.GetInsertBlock()->getTrailingDbgRecords()) {
5367 for (llvm::DbgVariableRecord &DVR : llvm::reverse(
5368 llvm::filterDbgVars(Marker->getDbgRecordRange()))) {
5369 UpdateExpr(Last.getContext(), &DVR, Offset);
5370 break;
5371 }
5372 }
5373 }
5374 }
5375 }
5377 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
5378 !Data.LastprivateVars.empty() || !Data.PrivateLocals.empty()) {
5379 enum { PrivatesParam = 2, CopyFnParam = 3 };
5380 llvm::Value *CopyFn = CGF.Builder.CreateLoad(
5381 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam)));
5382 llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(
5383 CS->getCapturedDecl()->getParam(PrivatesParam)));
5384 // Map privates.
5388 CallArgs.push_back(PrivatesPtr);
5389 ParamTypes.push_back(PrivatesPtr->getType());
5390 for (const Expr *E : Data.PrivateVars) {
5391 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
5392 RawAddress PrivatePtr = CGF.CreateMemTempWithoutCast(
5393 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
5394 PrivatePtrs.emplace_back(VD, PrivatePtr);
5395 CallArgs.push_back(PrivatePtr.getPointer());
5396 ParamTypes.push_back(PrivatePtr.getType());
5397 }
5398 for (const Expr *E : Data.FirstprivateVars) {
5399 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
5400 RawAddress PrivatePtr = CGF.CreateMemTempWithoutCast(
5401 CGF.getContext().getPointerType(E->getType()),
5402 ".firstpriv.ptr.addr");
5403 PrivatePtrs.emplace_back(VD, PrivatePtr);
5404 FirstprivatePtrs.emplace_back(VD, PrivatePtr);
5405 CallArgs.push_back(PrivatePtr.getPointer());
5406 ParamTypes.push_back(PrivatePtr.getType());
5407 }
5408 for (const Expr *E : Data.LastprivateVars) {
5409 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
5410 RawAddress PrivatePtr = CGF.CreateMemTempWithoutCast(
5411 CGF.getContext().getPointerType(E->getType()),
5412 ".lastpriv.ptr.addr");
5413 PrivatePtrs.emplace_back(VD, PrivatePtr);
5414 CallArgs.push_back(PrivatePtr.getPointer());
5415 ParamTypes.push_back(PrivatePtr.getType());
5416 }
5417 for (const VarDecl *VD : Data.PrivateLocals) {
5419 if (VD->getType()->isLValueReferenceType())
5420 Ty = CGF.getContext().getPointerType(Ty);
5421 if (isAllocatableDecl(VD))
5422 Ty = CGF.getContext().getPointerType(Ty);
5423 RawAddress PrivatePtr = CGF.CreateMemTempWithoutCast(
5424 CGF.getContext().getPointerType(Ty), ".local.ptr.addr");
5425 auto Result = UntiedLocalVars.insert(
5426 std::make_pair(VD, std::make_pair(PrivatePtr, Address::invalid())));
5427 // If key exists update in place.
5428 if (Result.second == false)
5429 *Result.first = std::make_pair(
5430 VD, std::make_pair(PrivatePtr, Address::invalid()));
5431 CallArgs.push_back(PrivatePtr.getPointer());
5432 ParamTypes.push_back(PrivatePtr.getType());
5433 }
5434 auto *CopyFnTy = llvm::FunctionType::get(CGF.Builder.getVoidTy(),
5435 ParamTypes, /*isVarArg=*/false);
5436 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
5437 CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs);
5438 for (const auto &Pair : LastprivateDstsOrigs) {
5439 const auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
5440 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(OrigVD),
5441 /*RefersToEnclosingVariableOrCapture=*/
5442 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
5443 Pair.second->getType(), VK_LValue,
5444 Pair.second->getExprLoc());
5445 Scope.addPrivate(Pair.first, CGF.EmitLValue(&DRE).getAddress());
5446 }
5447 for (const auto &Pair : PrivatePtrs) {
5448 Address Replacement = Address(
5449 CGF.Builder.CreateLoad(Pair.second),
5450 CGF.ConvertTypeForMem(Pair.first->getType().getNonReferenceType()),
5451 CGF.getContext().getDeclAlign(Pair.first));
5452 Scope.addPrivate(Pair.first, Replacement);
5453 if (auto *DI = CGF.getDebugInfo())
5454 if (CGF.CGM.getCodeGenOpts().hasReducedDebugInfo())
5455 (void)DI->EmitDeclareOfAutoVariable(
5456 Pair.first, Pair.second.getBasePointer(), CGF.Builder,
5457 /*UsePointerValue*/ true);
5458 }
5459 // Adjust mapping for internal locals by mapping actual memory instead of
5460 // a pointer to this memory.
5461 for (auto &Pair : UntiedLocalVars) {
5462 QualType VDType = Pair.first->getType().getNonReferenceType();
5463 if (Pair.first->getType()->isLValueReferenceType())
5464 VDType = CGF.getContext().getPointerType(VDType);
5465 if (isAllocatableDecl(Pair.first)) {
5466 llvm::Value *Ptr = CGF.Builder.CreateLoad(Pair.second.first);
5467 Address Replacement(
5468 Ptr,
5469 CGF.ConvertTypeForMem(CGF.getContext().getPointerType(VDType)),
5470 CGF.getPointerAlign());
5471 Pair.second.first = Replacement;
5472 Ptr = CGF.Builder.CreateLoad(Replacement);
5473 Replacement = Address(Ptr, CGF.ConvertTypeForMem(VDType),
5474 CGF.getContext().getDeclAlign(Pair.first));
5475 Pair.second.second = Replacement;
5476 } else {
5477 llvm::Value *Ptr = CGF.Builder.CreateLoad(Pair.second.first);
5478 Address Replacement(Ptr, CGF.ConvertTypeForMem(VDType),
5479 CGF.getContext().getDeclAlign(Pair.first));
5480 Pair.second.first = Replacement;
5481 }
5482 }
5483 }
5484 if (Data.Reductions) {
5485 OMPPrivateScope FirstprivateScope(CGF);
5486 for (const auto &Pair : FirstprivatePtrs) {
5487 Address Replacement(
5488 CGF.Builder.CreateLoad(Pair.second),
5489 CGF.ConvertTypeForMem(Pair.first->getType().getNonReferenceType()),
5490 CGF.getContext().getDeclAlign(Pair.first));
5491 FirstprivateScope.addPrivate(Pair.first, Replacement);
5492 }
5493 (void)FirstprivateScope.Privatize();
5494 OMPLexicalScope LexScope(CGF, S, CapturedRegion);
5495 ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionVars,
5496 Data.ReductionCopies, Data.ReductionOps);
5497 llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
5498 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9)));
5499 for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
5500 RedCG.emitSharedOrigLValue(CGF, Cnt);
5501 RedCG.emitAggregateType(CGF, Cnt);
5502 // FIXME: This must removed once the runtime library is fixed.
5503 // Emit required threadprivate variables for
5504 // initializer/combiner/finalizer.
5505 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
5506 RedCG, Cnt);
5507 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
5508 CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
5509 Replacement = Address(
5510 CGF.EmitScalarConversion(Replacement.emitRawPointer(CGF),
5511 CGF.getContext().VoidPtrTy,
5512 CGF.getContext().getPointerType(
5513 Data.ReductionCopies[Cnt]->getType()),
5514 Data.ReductionCopies[Cnt]->getExprLoc()),
5515 CGF.ConvertTypeForMem(Data.ReductionCopies[Cnt]->getType()),
5516 Replacement.getAlignment());
5517 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
5518 Scope.addPrivate(RedCG.getBaseDecl(Cnt), Replacement);
5519 }
5520 }
5521 // Privatize all private variables except for in_reduction items.
5522 (void)Scope.Privatize();
5526 SmallVector<const Expr *, 4> TaskgroupDescriptors;
5527 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
5528 auto IPriv = C->privates().begin();
5529 auto IRed = C->reduction_ops().begin();
5530 auto ITD = C->taskgroup_descriptors().begin();
5531 for (const Expr *Ref : C->varlist()) {
5532 InRedVars.emplace_back(Ref);
5533 InRedPrivs.emplace_back(*IPriv);
5534 InRedOps.emplace_back(*IRed);
5535 TaskgroupDescriptors.emplace_back(*ITD);
5536 std::advance(IPriv, 1);
5537 std::advance(IRed, 1);
5538 std::advance(ITD, 1);
5539 }
5540 }
5541 // Privatize in_reduction items here, because taskgroup descriptors must be
5542 // privatized earlier.
5543 OMPPrivateScope InRedScope(CGF);
5544 if (!InRedVars.empty()) {
5545 ReductionCodeGen RedCG(InRedVars, InRedVars, InRedPrivs, InRedOps);
5546 for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
5547 RedCG.emitSharedOrigLValue(CGF, Cnt);
5548 RedCG.emitAggregateType(CGF, Cnt);
5549 // The taskgroup descriptor variable is always implicit firstprivate and
5550 // privatized already during processing of the firstprivates.
5551 // FIXME: This must removed once the runtime library is fixed.
5552 // Emit required threadprivate variables for
5553 // initializer/combiner/finalizer.
5554 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
5555 RedCG, Cnt);
5556 llvm::Value *ReductionsPtr;
5557 if (const Expr *TRExpr = TaskgroupDescriptors[Cnt]) {
5558 ReductionsPtr = CGF.EmitLoadOfScalar(CGF.EmitLValue(TRExpr),
5559 TRExpr->getExprLoc());
5560 } else {
5561 ReductionsPtr = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5562 }
5563 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
5564 CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
5565 Replacement = Address(
5566 CGF.EmitScalarConversion(
5567 Replacement.emitRawPointer(CGF), CGF.getContext().VoidPtrTy,
5568 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
5569 InRedPrivs[Cnt]->getExprLoc()),
5570 CGF.ConvertTypeForMem(InRedPrivs[Cnt]->getType()),
5571 Replacement.getAlignment());
5572 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
5573 InRedScope.addPrivate(RedCG.getBaseDecl(Cnt), Replacement);
5574 }
5575 }
5576 (void)InRedScope.Privatize();
5577
5579 UntiedLocalVars);
5580 Action.Enter(CGF);
5581 BodyGen(CGF);
5582 };
5584 llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
5585 S, *I, *PartId, *TaskT, EKind, CodeGen, Data.Tied, Data.NumberOfParts);
5586 OMPLexicalScope Scope(*this, S, std::nullopt,
5587 !isOpenMPParallelDirective(EKind) &&
5588 !isOpenMPSimdDirective(EKind));
5589 TaskGen(*this, OutlinedFn, Data);
5590}
5591
5592static ImplicitParamDecl *
5594 QualType Ty, CapturedDecl *CD,
5595 SourceLocation Loc) {
5596 auto *OrigVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
5598 auto *OrigRef = DeclRefExpr::Create(
5600 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
5601 auto *PrivateVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
5603 auto *PrivateRef = DeclRefExpr::Create(
5604 C, NestedNameSpecifierLoc(), SourceLocation(), PrivateVD,
5605 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
5606 QualType ElemType = C.getBaseElementType(Ty);
5607 auto *InitVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, ElemType,
5609 auto *InitRef = DeclRefExpr::Create(
5611 /*RefersToEnclosingVariableOrCapture=*/false, Loc, ElemType, VK_LValue);
5612 PrivateVD->setInitStyle(VarDecl::CInit);
5613 PrivateVD->setInit(ImplicitCastExpr::Create(C, ElemType, CK_LValueToRValue,
5614 InitRef, /*BasePath=*/nullptr,
5616 Data.FirstprivateVars.emplace_back(OrigRef);
5617 Data.FirstprivateCopies.emplace_back(PrivateRef);
5618 Data.FirstprivateInits.emplace_back(InitRef);
5619 return OrigVD;
5620}
5621
5623 const OMPExecutableDirective &S, const RegionCodeGenTy &BodyGen,
5624 OMPTargetDataInfo &InputInfo) {
5625 // Emit outlined function for task construct.
5626 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
5627 Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
5628 CanQualType SharedsTy =
5630 auto I = CS->getCapturedDecl()->param_begin();
5631 auto PartId = std::next(I);
5632 auto TaskT = std::next(I, 4);
5634 // The task is not final.
5635 Data.Final.setInt(/*IntVal=*/false);
5636 // Get list of firstprivate variables.
5637 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
5638 auto IRef = C->varlist_begin();
5639 auto IElemInitRef = C->inits().begin();
5640 for (auto *IInit : C->private_copies()) {
5641 Data.FirstprivateVars.push_back(*IRef);
5642 Data.FirstprivateCopies.push_back(IInit);
5643 Data.FirstprivateInits.push_back(*IElemInitRef);
5644 ++IRef;
5645 ++IElemInitRef;
5646 }
5647 }
5650 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
5651 Data.ReductionVars.append(C->varlist_begin(), C->varlist_end());
5652 Data.ReductionOrigs.append(C->varlist_begin(), C->varlist_end());
5653 Data.ReductionCopies.append(C->privates().begin(), C->privates().end());
5654 Data.ReductionOps.append(C->reduction_ops().begin(),
5655 C->reduction_ops().end());
5656 LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
5657 RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
5658 }
5659 OMPPrivateScope TargetScope(*this);
5660 VarDecl *BPVD = nullptr;
5661 VarDecl *PVD = nullptr;
5662 VarDecl *SVD = nullptr;
5663 VarDecl *MVD = nullptr;
5664 if (InputInfo.NumberOfTargetItems > 0) {
5665 auto *CD = CapturedDecl::Create(
5666 getContext(), getContext().getTranslationUnitDecl(), /*NumParams=*/0);
5667 llvm::APInt ArrSize(/*numBits=*/32, InputInfo.NumberOfTargetItems);
5668 QualType BaseAndPointerAndMapperType = getContext().getConstantArrayType(
5669 getContext().VoidPtrTy, ArrSize, nullptr, ArraySizeModifier::Normal,
5670 /*IndexTypeQuals=*/0);
5672 getContext(), Data, BaseAndPointerAndMapperType, CD, S.getBeginLoc());
5674 getContext(), Data, BaseAndPointerAndMapperType, CD, S.getBeginLoc());
5676 getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1),
5677 ArrSize, nullptr, ArraySizeModifier::Normal,
5678 /*IndexTypeQuals=*/0);
5679 SVD = createImplicitFirstprivateForType(getContext(), Data, SizesType, CD,
5680 S.getBeginLoc());
5681 TargetScope.addPrivate(BPVD, InputInfo.BasePointersArray);
5682 TargetScope.addPrivate(PVD, InputInfo.PointersArray);
5683 TargetScope.addPrivate(SVD, InputInfo.SizesArray);
5684 // If there is no user-defined mapper, the mapper array will be nullptr. In
5685 // this case, we don't need to privatize it.
5686 if (!isa_and_nonnull<llvm::ConstantPointerNull>(
5687 InputInfo.MappersArray.emitRawPointer(*this))) {
5689 getContext(), Data, BaseAndPointerAndMapperType, CD, S.getBeginLoc());
5690 TargetScope.addPrivate(MVD, InputInfo.MappersArray);
5691 }
5692 }
5693 (void)TargetScope.Privatize();
5696 auto &&CodeGen = [&Data, &S, CS, &BodyGen, BPVD, PVD, SVD, MVD, EKind,
5697 &InputInfo](CodeGenFunction &CGF, PrePostActionTy &Action) {
5698 // Set proper addresses for generated private copies.
5700 if (!Data.FirstprivateVars.empty()) {
5701 enum { PrivatesParam = 2, CopyFnParam = 3 };
5702 llvm::Value *CopyFn = CGF.Builder.CreateLoad(
5703 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam)));
5704 llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(
5705 CS->getCapturedDecl()->getParam(PrivatesParam)));
5706 // Map privates.
5710 CallArgs.push_back(PrivatesPtr);
5711 ParamTypes.push_back(PrivatesPtr->getType());
5712 for (const Expr *E : Data.FirstprivateVars) {
5713 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
5714 RawAddress PrivatePtr = CGF.CreateMemTempWithoutCast(
5715 CGF.getContext().getPointerType(E->getType()),
5716 ".firstpriv.ptr.addr");
5717 PrivatePtrs.emplace_back(VD, PrivatePtr);
5718 CallArgs.push_back(PrivatePtr.getPointer());
5719 ParamTypes.push_back(PrivatePtr.getType());
5720 }
5721 auto *CopyFnTy = llvm::FunctionType::get(CGF.Builder.getVoidTy(),
5722 ParamTypes, /*isVarArg=*/false);
5723 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
5724 CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs);
5725 for (const auto &Pair : PrivatePtrs) {
5726 Address Replacement(
5727 CGF.Builder.CreateLoad(Pair.second),
5728 CGF.ConvertTypeForMem(Pair.first->getType().getNonReferenceType()),
5729 CGF.getContext().getDeclAlign(Pair.first));
5730 Scope.addPrivate(Pair.first, Replacement);
5731 }
5732 }
5733 CGF.processInReduction(S, Data, CGF, CS, Scope);
5734 if (InputInfo.NumberOfTargetItems > 0) {
5735 InputInfo.BasePointersArray = CGF.Builder.CreateConstArrayGEP(
5736 CGF.GetAddrOfLocalVar(BPVD), /*Index=*/0);
5737 InputInfo.PointersArray = CGF.Builder.CreateConstArrayGEP(
5738 CGF.GetAddrOfLocalVar(PVD), /*Index=*/0);
5739 InputInfo.SizesArray = CGF.Builder.CreateConstArrayGEP(
5740 CGF.GetAddrOfLocalVar(SVD), /*Index=*/0);
5741 // If MVD is nullptr, the mapper array is not privatized
5742 if (MVD)
5743 InputInfo.MappersArray = CGF.Builder.CreateConstArrayGEP(
5744 CGF.GetAddrOfLocalVar(MVD), /*Index=*/0);
5745 }
5746
5747 Action.Enter(CGF);
5748 OMPLexicalScope LexScope(CGF, S, OMPD_task, /*EmitPreInitStmt=*/false);
5749 auto *TL = S.getSingleClause<OMPThreadLimitClause>();
5750 if (CGF.CGM.getLangOpts().OpenMP >= 51 &&
5751 needsTaskBasedThreadLimit(EKind) && TL) {
5752 // Emit __kmpc_set_thread_limit() to set the thread_limit for the task
5753 // enclosing this target region. This will indirectly set the thread_limit
5754 // for every applicable construct within target region.
5755 CGF.CGM.getOpenMPRuntime().emitThreadLimitClause(
5756 CGF, TL->getThreadLimit().front(), S.getBeginLoc());
5757 }
5758 BodyGen(CGF);
5759 };
5760 llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
5761 S, *I, *PartId, *TaskT, EKind, CodeGen, /*Tied=*/true,
5762 Data.NumberOfParts);
5763 llvm::APInt TrueOrFalse(32, S.hasClausesOfKind<OMPNowaitClause>() ? 1 : 0);
5764 IntegerLiteral IfCond(getContext(), TrueOrFalse,
5765 getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
5766 SourceLocation());
5767 CGM.getOpenMPRuntime().emitTaskCall(*this, S.getBeginLoc(), S, OutlinedFn,
5768 SharedsTy, CapturedStruct, &IfCond, Data);
5769}
5770
5773 CodeGenFunction &CGF,
5774 const CapturedStmt *CS,
5777 if (Data.Reductions) {
5778 OpenMPDirectiveKind CapturedRegion = EKind;
5779 OMPLexicalScope LexScope(CGF, S, CapturedRegion);
5780 ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionVars,
5781 Data.ReductionCopies, Data.ReductionOps);
5782 llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
5784 for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
5785 RedCG.emitSharedOrigLValue(CGF, Cnt);
5786 RedCG.emitAggregateType(CGF, Cnt);
5787 // FIXME: This must removed once the runtime library is fixed.
5788 // Emit required threadprivate variables for
5789 // initializer/combiner/finalizer.
5790 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
5791 RedCG, Cnt);
5793 CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
5794 Replacement = Address(
5795 CGF.EmitScalarConversion(Replacement.emitRawPointer(CGF),
5796 CGF.getContext().VoidPtrTy,
5798 Data.ReductionCopies[Cnt]->getType()),
5799 Data.ReductionCopies[Cnt]->getExprLoc()),
5800 CGF.ConvertTypeForMem(Data.ReductionCopies[Cnt]->getType()),
5801 Replacement.getAlignment());
5802 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
5803 Scope.addPrivate(RedCG.getBaseDecl(Cnt), Replacement);
5804 }
5805 }
5806 (void)Scope.Privatize();
5810 SmallVector<const Expr *, 4> TaskgroupDescriptors;
5811 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
5812 auto IPriv = C->privates().begin();
5813 auto IRed = C->reduction_ops().begin();
5814 auto ITD = C->taskgroup_descriptors().begin();
5815 for (const Expr *Ref : C->varlist()) {
5816 InRedVars.emplace_back(Ref);
5817 InRedPrivs.emplace_back(*IPriv);
5818 InRedOps.emplace_back(*IRed);
5819 TaskgroupDescriptors.emplace_back(*ITD);
5820 std::advance(IPriv, 1);
5821 std::advance(IRed, 1);
5822 std::advance(ITD, 1);
5823 }
5824 }
5825 OMPPrivateScope InRedScope(CGF);
5826 if (!InRedVars.empty()) {
5827 ReductionCodeGen RedCG(InRedVars, InRedVars, InRedPrivs, InRedOps);
5828 for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
5829 RedCG.emitSharedOrigLValue(CGF, Cnt);
5830 RedCG.emitAggregateType(CGF, Cnt);
5831 // FIXME: This must removed once the runtime library is fixed.
5832 // Emit required threadprivate variables for
5833 // initializer/combiner/finalizer.
5834 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
5835 RedCG, Cnt);
5836 llvm::Value *ReductionsPtr;
5837 if (const Expr *TRExpr = TaskgroupDescriptors[Cnt]) {
5838 ReductionsPtr =
5839 CGF.EmitLoadOfScalar(CGF.EmitLValue(TRExpr), TRExpr->getExprLoc());
5840 } else {
5841 ReductionsPtr = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5842 }
5844 CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
5845 Replacement = Address(
5847 Replacement.emitRawPointer(CGF), CGF.getContext().VoidPtrTy,
5848 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
5849 InRedPrivs[Cnt]->getExprLoc()),
5850 CGF.ConvertTypeForMem(InRedPrivs[Cnt]->getType()),
5851 Replacement.getAlignment());
5852 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
5853 InRedScope.addPrivate(RedCG.getBaseDecl(Cnt), Replacement);
5854 }
5855 }
5856 (void)InRedScope.Privatize();
5857}
5858
5860 // Emit outlined function for task construct.
5861 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
5862 Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
5863 CanQualType SharedsTy =
5865 const Expr *IfCond = nullptr;
5866 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
5867 if (C->getNameModifier() == OMPD_unknown ||
5868 C->getNameModifier() == OMPD_task) {
5869 IfCond = C->getCondition();
5870 break;
5871 }
5872 }
5873
5875 // Check if we should emit tied or untied task.
5876 Data.Tied = !S.getSingleClause<OMPUntiedClause>();
5877 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
5878 CGF.EmitStmt(CS->getCapturedStmt());
5879 };
5880 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
5881 IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn,
5882 const OMPTaskDataTy &Data) {
5883 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getBeginLoc(), S, OutlinedFn,
5884 SharedsTy, CapturedStruct, IfCond,
5885 Data);
5886 };
5887 auto LPCRegion =
5889 EmitOMPTaskBasedDirective(S, OMPD_task, BodyGen, TaskGen, Data);
5890}
5891
5893 const OMPTaskyieldDirective &S) {
5894 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getBeginLoc());
5895}
5896
5898 const OMPMessageClause *MC = S.getSingleClause<OMPMessageClause>();
5899 Expr *ME = MC ? MC->getMessageString() : nullptr;
5900 const OMPSeverityClause *SC = S.getSingleClause<OMPSeverityClause>();
5901 bool IsFatal = false;
5902 if (!SC || SC->getSeverityKind() == OMPC_SEVERITY_fatal)
5903 IsFatal = true;
5904 CGM.getOpenMPRuntime().emitErrorCall(*this, S.getBeginLoc(), ME, IsFatal);
5905}
5906
5908 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_barrier);
5909}
5910
5913 // Build list of dependences
5915 Data.HasNowaitClause = S.hasClausesOfKind<OMPNowaitClause>();
5916 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getBeginLoc(), Data);
5917}
5918
5920 return T.clauses().empty();
5921}
5922
5924 const OMPTaskgroupDirective &S) {
5925 OMPLexicalScope Scope(*this, S, OMPD_unknown);
5926 if (CGM.getLangOpts().OpenMPIRBuilder && isSupportedByOpenMPIRBuilder(S)) {
5927 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
5928 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
5929 InsertPointTy AllocaIP(AllocaInsertPt->getParent(),
5930 AllocaInsertPt->getIterator());
5931
5932 auto BodyGenCB = [&, this](InsertPointTy AllocIP, InsertPointTy CodeGenIP,
5933 ArrayRef<llvm::BasicBlock *> DeallocBlocks) {
5934 Builder.restoreIP(CodeGenIP);
5935 EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
5936 return llvm::Error::success();
5937 };
5939 if (!CapturedStmtInfo)
5940 CapturedStmtInfo = &CapStmtInfo;
5941 llvm::OpenMPIRBuilder::InsertPointTy AfterIP =
5942 cantFail(OMPBuilder.createTaskgroup(Builder, AllocaIP,
5943 /*DeallocBlocks=*/{}, BodyGenCB));
5944 Builder.restoreIP(AfterIP);
5945 return;
5946 }
5947 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5948 Action.Enter(CGF);
5949 if (const Expr *E = S.getReductionRef()) {
5953 for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) {
5954 Data.ReductionVars.append(C->varlist_begin(), C->varlist_end());
5955 Data.ReductionOrigs.append(C->varlist_begin(), C->varlist_end());
5956 Data.ReductionCopies.append(C->privates().begin(), C->privates().end());
5957 Data.ReductionOps.append(C->reduction_ops().begin(),
5958 C->reduction_ops().end());
5959 LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
5960 RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
5961 }
5962 llvm::Value *ReductionDesc =
5963 CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getBeginLoc(),
5964 LHSs, RHSs, Data);
5965 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
5966 CGF.EmitVarDecl(*VD);
5967 CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD),
5968 /*Volatile=*/false, E->getType());
5969 }
5970 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
5971 };
5972 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getBeginLoc());
5973}
5974
5976 llvm::AtomicOrdering AO = S.getSingleClause<OMPFlushClause>()
5977 ? llvm::AtomicOrdering::NotAtomic
5978 : llvm::AtomicOrdering::AcquireRelease;
5979 CGM.getOpenMPRuntime().emitFlush(
5980 *this,
5981 [&S]() -> ArrayRef<const Expr *> {
5982 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>())
5983 return llvm::ArrayRef(FlushClause->varlist_begin(),
5984 FlushClause->varlist_end());
5985 return {};
5986 }(),
5987 S.getBeginLoc(), AO);
5988}
5989
5991 const auto *DO = S.getSingleClause<OMPDepobjClause>();
5992 LValue DOLVal = EmitLValue(DO->getDepobj());
5993 if (const auto *DC = S.getSingleClause<OMPDependClause>()) {
5994 // Build list and emit dependences
5997 for (auto &Dep : Data.Dependences) {
5998 Address DepAddr = CGM.getOpenMPRuntime().emitDepobjDependClause(
5999 *this, Dep, DC->getBeginLoc());
6000 EmitStoreOfScalar(DepAddr.emitRawPointer(*this), DOLVal);
6001 }
6002 return;
6003 }
6004 if (const auto *DC = S.getSingleClause<OMPDestroyClause>()) {
6005 CGM.getOpenMPRuntime().emitDestroyClause(*this, DOLVal, DC->getBeginLoc());
6006 return;
6007 }
6008 if (const auto *UC = S.getSingleClause<OMPUpdateDependObjectsClause>()) {
6009 CGM.getOpenMPRuntime().emitUpdateDependObjectsClause(
6010 *this, DOLVal, UC->getDependencyKind(), UC->getBeginLoc());
6011 return;
6012 }
6013}
6014
6017 return;
6019 bool IsInclusive = S.hasClausesOfKind<OMPInclusiveClause>();
6024 SmallVector<const Expr *, 4> ReductionOps;
6026 SmallVector<const Expr *, 4> CopyArrayTemps;
6027 SmallVector<const Expr *, 4> CopyArrayElems;
6028 for (const auto *C : ParentDir.getClausesOfKind<OMPReductionClause>()) {
6029 if (C->getModifier() != OMPC_REDUCTION_inscan)
6030 continue;
6031 Shareds.append(C->varlist_begin(), C->varlist_end());
6032 Privates.append(C->privates().begin(), C->privates().end());
6033 LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
6034 RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
6035 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
6036 CopyOps.append(C->copy_ops().begin(), C->copy_ops().end());
6037 CopyArrayTemps.append(C->copy_array_temps().begin(),
6038 C->copy_array_temps().end());
6039 CopyArrayElems.append(C->copy_array_elems().begin(),
6040 C->copy_array_elems().end());
6041 }
6042 if (ParentDir.getDirectiveKind() == OMPD_simd ||
6043 (getLangOpts().OpenMPSimd &&
6044 isOpenMPSimdDirective(ParentDir.getDirectiveKind()))) {
6045 // For simd directive and simd-based directives in simd only mode, use the
6046 // following codegen:
6047 // int x = 0;
6048 // #pragma omp simd reduction(inscan, +: x)
6049 // for (..) {
6050 // <first part>
6051 // #pragma omp scan inclusive(x)
6052 // <second part>
6053 // }
6054 // is transformed to:
6055 // int x = 0;
6056 // for (..) {
6057 // int x_priv = 0;
6058 // <first part>
6059 // x = x_priv + x;
6060 // x_priv = x;
6061 // <second part>
6062 // }
6063 // and
6064 // int x = 0;
6065 // #pragma omp simd reduction(inscan, +: x)
6066 // for (..) {
6067 // <first part>
6068 // #pragma omp scan exclusive(x)
6069 // <second part>
6070 // }
6071 // to
6072 // int x = 0;
6073 // for (..) {
6074 // int x_priv = 0;
6075 // <second part>
6076 // int temp = x;
6077 // x = x_priv + x;
6078 // x_priv = temp;
6079 // <first part>
6080 // }
6081 llvm::BasicBlock *OMPScanReduce = createBasicBlock("omp.inscan.reduce");
6082 EmitBranch(IsInclusive
6083 ? OMPScanReduce
6084 : BreakContinueStack.back().ContinueBlock.getBlock());
6086 {
6087 // New scope for correct construction/destruction of temp variables for
6088 // exclusive scan.
6089 LexicalScope Scope(*this, S.getSourceRange());
6091 EmitBlock(OMPScanReduce);
6092 if (!IsInclusive) {
6093 // Create temp var and copy LHS value to this temp value.
6094 // TMP = LHS;
6095 for (unsigned I = 0, E = CopyArrayElems.size(); I < E; ++I) {
6096 const Expr *PrivateExpr = Privates[I];
6097 const Expr *TempExpr = CopyArrayTemps[I];
6099 *cast<VarDecl>(cast<DeclRefExpr>(TempExpr)->getDecl()));
6100 LValue DestLVal = EmitLValue(TempExpr);
6101 LValue SrcLVal = EmitLValue(LHSs[I]);
6102 EmitOMPCopy(PrivateExpr->getType(), DestLVal.getAddress(),
6103 SrcLVal.getAddress(),
6104 cast<VarDecl>(cast<DeclRefExpr>(LHSs[I])->getDecl()),
6105 cast<VarDecl>(cast<DeclRefExpr>(RHSs[I])->getDecl()),
6106 CopyOps[I]);
6107 }
6108 }
6109 CGM.getOpenMPRuntime().emitReduction(
6110 *this, ParentDir.getEndLoc(), Privates, LHSs, RHSs, ReductionOps,
6111 {/*WithNowait=*/true, /*SimpleReduction=*/true,
6112 /*IsPrivateVarReduction*/ {}, OMPD_simd});
6113 for (unsigned I = 0, E = CopyArrayElems.size(); I < E; ++I) {
6114 const Expr *PrivateExpr = Privates[I];
6115 LValue DestLVal;
6116 LValue SrcLVal;
6117 if (IsInclusive) {
6118 DestLVal = EmitLValue(RHSs[I]);
6119 SrcLVal = EmitLValue(LHSs[I]);
6120 } else {
6121 const Expr *TempExpr = CopyArrayTemps[I];
6122 DestLVal = EmitLValue(RHSs[I]);
6123 SrcLVal = EmitLValue(TempExpr);
6124 }
6126 PrivateExpr->getType(), DestLVal.getAddress(), SrcLVal.getAddress(),
6127 cast<VarDecl>(cast<DeclRefExpr>(LHSs[I])->getDecl()),
6128 cast<VarDecl>(cast<DeclRefExpr>(RHSs[I])->getDecl()), CopyOps[I]);
6129 }
6130 }
6132 OMPScanExitBlock = IsInclusive
6133 ? BreakContinueStack.back().ContinueBlock.getBlock()
6134 : OMPScanReduce;
6136 return;
6137 }
6138 if (!IsInclusive) {
6139 EmitBranch(BreakContinueStack.back().ContinueBlock.getBlock());
6141 }
6142 if (OMPFirstScanLoop) {
6143 // Emit buffer[i] = red; at the end of the input phase.
6144 const auto *IVExpr = cast<OMPLoopDirective>(ParentDir)
6145 .getIterationVariable()
6146 ->IgnoreParenImpCasts();
6147 LValue IdxLVal = EmitLValue(IVExpr);
6148 llvm::Value *IdxVal = EmitLoadOfScalar(IdxLVal, IVExpr->getExprLoc());
6149 IdxVal = Builder.CreateIntCast(IdxVal, SizeTy, /*isSigned=*/false);
6150 for (unsigned I = 0, E = CopyArrayElems.size(); I < E; ++I) {
6151 const Expr *PrivateExpr = Privates[I];
6152 const Expr *OrigExpr = Shareds[I];
6153 const Expr *CopyArrayElem = CopyArrayElems[I];
6154 OpaqueValueMapping IdxMapping(
6155 *this,
6157 cast<ArraySubscriptExpr>(CopyArrayElem)->getIdx()),
6158 RValue::get(IdxVal));
6159 LValue DestLVal = EmitLValue(CopyArrayElem);
6160 LValue SrcLVal = EmitLValue(OrigExpr);
6162 PrivateExpr->getType(), DestLVal.getAddress(), SrcLVal.getAddress(),
6163 cast<VarDecl>(cast<DeclRefExpr>(LHSs[I])->getDecl()),
6164 cast<VarDecl>(cast<DeclRefExpr>(RHSs[I])->getDecl()), CopyOps[I]);
6165 }
6166 }
6167 EmitBranch(BreakContinueStack.back().ContinueBlock.getBlock());
6168 if (IsInclusive) {
6170 EmitBranch(BreakContinueStack.back().ContinueBlock.getBlock());
6171 }
6173 if (!OMPFirstScanLoop) {
6174 // Emit red = buffer[i]; at the entrance to the scan phase.
6175 const auto *IVExpr = cast<OMPLoopDirective>(ParentDir)
6176 .getIterationVariable()
6177 ->IgnoreParenImpCasts();
6178 LValue IdxLVal = EmitLValue(IVExpr);
6179 llvm::Value *IdxVal = EmitLoadOfScalar(IdxLVal, IVExpr->getExprLoc());
6180 IdxVal = Builder.CreateIntCast(IdxVal, SizeTy, /*isSigned=*/false);
6181 llvm::BasicBlock *ExclusiveExitBB = nullptr;
6182 if (!IsInclusive) {
6183 llvm::BasicBlock *ContBB = createBasicBlock("omp.exclusive.dec");
6184 ExclusiveExitBB = createBasicBlock("omp.exclusive.copy.exit");
6185 llvm::Value *Cmp = Builder.CreateIsNull(IdxVal);
6186 Builder.CreateCondBr(Cmp, ExclusiveExitBB, ContBB);
6187 EmitBlock(ContBB);
6188 // Use idx - 1 iteration for exclusive scan.
6189 IdxVal = Builder.CreateNUWSub(IdxVal, llvm::ConstantInt::get(SizeTy, 1));
6190 }
6191 for (unsigned I = 0, E = CopyArrayElems.size(); I < E; ++I) {
6192 const Expr *PrivateExpr = Privates[I];
6193 const Expr *OrigExpr = Shareds[I];
6194 const Expr *CopyArrayElem = CopyArrayElems[I];
6195 OpaqueValueMapping IdxMapping(
6196 *this,
6198 cast<ArraySubscriptExpr>(CopyArrayElem)->getIdx()),
6199 RValue::get(IdxVal));
6200 LValue SrcLVal = EmitLValue(CopyArrayElem);
6201 LValue DestLVal = EmitLValue(OrigExpr);
6203 PrivateExpr->getType(), DestLVal.getAddress(), SrcLVal.getAddress(),
6204 cast<VarDecl>(cast<DeclRefExpr>(LHSs[I])->getDecl()),
6205 cast<VarDecl>(cast<DeclRefExpr>(RHSs[I])->getDecl()), CopyOps[I]);
6206 }
6207 if (!IsInclusive) {
6208 EmitBlock(ExclusiveExitBB);
6209 }
6210 }
6214}
6215
6217 const CodeGenLoopTy &CodeGenLoop,
6218 Expr *IncExpr) {
6219 // Emit the loop iteration variable.
6220 const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
6221 const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl());
6222 EmitVarDecl(*IVDecl);
6223
6224 // Emit the iterations count variable.
6225 // If it is not a variable, Sema decided to calculate iterations count on each
6226 // iteration (e.g., it is foldable into a constant).
6227 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
6228 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
6229 // Emit calculation of the iterations count.
6231 }
6232
6233 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
6234
6235 bool HasLastprivateClause = false;
6236 // Check pre-condition.
6237 {
6238 OMPLoopScope PreInitScope(*this, S);
6239 // Skip the entire loop if we don't meet the precondition.
6240 // If the condition constant folds and can be elided, avoid emitting the
6241 // whole loop.
6242 bool CondConstant;
6243 llvm::BasicBlock *ContBlock = nullptr;
6244 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
6245 if (!CondConstant)
6246 return;
6247 } else {
6248 llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then");
6249 ContBlock = createBasicBlock("omp.precond.end");
6250 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
6251 getProfileCount(&S));
6252 EmitBlock(ThenBlock);
6254 }
6255
6256 emitAlignedClause(*this, S);
6257 // Emit 'then' code.
6258 {
6259 // Emit helper vars inits.
6260
6262 *this, cast<DeclRefExpr>(
6263 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
6265 : S.getLowerBoundVariable())));
6267 *this, cast<DeclRefExpr>(
6268 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
6270 : S.getUpperBoundVariable())));
6271 LValue ST =
6273 LValue IL =
6275
6276 OMPPrivateScope LoopScope(*this);
6277 if (EmitOMPFirstprivateClause(S, LoopScope)) {
6278 // Emit implicit barrier to synchronize threads and avoid data races
6279 // on initialization of firstprivate variables and post-update of
6280 // lastprivate variables.
6281 CGM.getOpenMPRuntime().emitBarrierCall(
6282 *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
6283 /*ForceSimpleCall=*/true);
6284 }
6285 EmitOMPPrivateClause(S, LoopScope);
6286 if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
6287 !isOpenMPParallelDirective(S.getDirectiveKind()) &&
6288 !isOpenMPTeamsDirective(S.getDirectiveKind()))
6289 EmitOMPReductionClauseInit(S, LoopScope);
6290 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
6291 EmitOMPPrivateLoopCounters(S, LoopScope);
6292 (void)LoopScope.Privatize();
6293 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
6294 CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(*this, S);
6295
6296 // Detect the distribute schedule kind and chunk.
6297 llvm::Value *Chunk = nullptr;
6299 if (const auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
6300 ScheduleKind = C->getDistScheduleKind();
6301 if (const Expr *Ch = C->getChunkSize()) {
6302 Chunk = EmitScalarExpr(Ch);
6303 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
6305 S.getBeginLoc());
6306 }
6307 } else {
6308 // Default behaviour for dist_schedule clause.
6309 CGM.getOpenMPRuntime().getDefaultDistScheduleAndChunk(
6310 *this, S, ScheduleKind, Chunk);
6311 }
6312 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
6313 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
6314
6315 // GPU fused schedule: omit the outer distribute loop and let the inner
6316 // worksharing loop schedule the flattened team/thread iteration space.
6317 if (canEmitGPUFusedDistSchedule(CGM, S, S.getDirectiveKind())) {
6320 CodeGenLoop(*this, S, LoopExit);
6321 EmitBlock(LoopExit.getBlock());
6322 } else {
6323 // OpenMP [2.10.8, distribute Construct, Description]
6324 // If dist_schedule is specified, kind must be static. If specified,
6325 // iterations are divided into chunks of size chunk_size, chunks are
6326 // assigned to the teams of the league in a round-robin fashion in the
6327 // order of the team number. When no chunk_size is specified, the
6328 // iteration space is divided into chunks that are approximately equal
6329 // in size, and at most one chunk is distributed to each team of the
6330 // league. The size of the chunks is unspecified in this case.
6331 bool StaticChunked =
6332 RT.isStaticChunked(ScheduleKind, /* Chunked */ Chunk != nullptr) &&
6333 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind());
6334 if (RT.isStaticNonchunked(ScheduleKind,
6335 /* Chunked */ Chunk != nullptr) ||
6336 StaticChunked) {
6338 IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(),
6339 LB.getAddress(), UB.getAddress(), ST.getAddress(),
6340 StaticChunked ? Chunk : nullptr);
6341 RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind,
6342 StaticInit);
6345 // UB = min(UB, GlobalUB);
6347 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
6349 : S.getEnsureUpperBound());
6350 // IV = LB;
6352 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
6353 ? S.getCombinedInit()
6354 : S.getInit());
6355
6356 const Expr *Cond =
6357 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
6358 ? S.getCombinedCond()
6359 : S.getCond();
6360
6361 if (StaticChunked)
6362 Cond = S.getCombinedDistCond();
6363
6364 // For static unchunked schedules generate:
6365 //
6366 // 1. For distribute alone, codegen
6367 // while (idx <= UB) {
6368 // BODY;
6369 // ++idx;
6370 // }
6371 //
6372 // 2. When combined with 'for' (e.g. as in 'distribute parallel for')
6373 // while (idx <= UB) {
6374 // <CodeGen rest of pragma>(LB, UB);
6375 // idx += ST;
6376 // }
6377 //
6378 // For static chunk one schedule generate:
6379 //
6380 // while (IV <= GlobalUB) {
6381 // <CodeGen rest of pragma>(LB, UB);
6382 // LB += ST;
6383 // UB += ST;
6384 // UB = min(UB, GlobalUB);
6385 // IV = LB;
6386 // }
6387 //
6389 *this, S,
6390 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
6391 if (isOpenMPSimdDirective(S.getDirectiveKind()))
6392 CGF.EmitOMPSimdInit(S);
6393 },
6394 [&S, &LoopScope, Cond, IncExpr, LoopExit, &CodeGenLoop,
6395 StaticChunked](CodeGenFunction &CGF, PrePostActionTy &) {
6396 CGF.EmitOMPInnerLoop(
6397 S, LoopScope.requiresCleanups(), Cond, IncExpr,
6398 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
6399 CodeGenLoop(CGF, S, LoopExit);
6400 },
6401 [&S, StaticChunked](CodeGenFunction &CGF) {
6402 if (StaticChunked) {
6403 CGF.EmitIgnoredExpr(S.getCombinedNextLowerBound());
6404 CGF.EmitIgnoredExpr(S.getCombinedNextUpperBound());
6405 CGF.EmitIgnoredExpr(S.getCombinedEnsureUpperBound());
6406 CGF.EmitIgnoredExpr(S.getCombinedInit());
6407 }
6408 });
6409 });
6410 EmitBlock(LoopExit.getBlock());
6411 // Tell the runtime we are done.
6412 RT.emitForStaticFinish(*this, S.getEndLoc(), OMPD_distribute);
6413 } else {
6414 // Emit the outer loop, which requests its work chunk [LB..UB] from
6415 // runtime and runs the inner loop to process it.
6416 const OMPLoopArguments LoopArguments = {
6417 LB.getAddress(), UB.getAddress(), ST.getAddress(),
6418 IL.getAddress(), Chunk};
6419 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
6420 CodeGenLoop);
6421 }
6422 }
6423 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
6424 EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) {
6425 return CGF.Builder.CreateIsNotNull(
6426 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
6427 });
6428 }
6429 if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
6430 !isOpenMPParallelDirective(S.getDirectiveKind()) &&
6431 !isOpenMPTeamsDirective(S.getDirectiveKind())) {
6432 EmitOMPReductionClauseFinal(S, OMPD_simd);
6433 // Emit post-update of the reduction variables if IsLastIter != 0.
6435 *this, S, [IL, &S](CodeGenFunction &CGF) {
6436 return CGF.Builder.CreateIsNotNull(
6437 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
6438 });
6439 }
6440 // Emit final copy of the lastprivate variables if IsLastIter != 0.
6441 if (HasLastprivateClause) {
6443 S, /*NoFinals=*/false,
6444 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc())));
6445 }
6446 }
6447
6448 // We're now done with the loop, so jump to the continuation block.
6449 if (ContBlock) {
6450 EmitBranch(ContBlock);
6451 EmitBlock(ContBlock, true);
6452 }
6453 }
6454}
6455
6456// Pass OMPLoopDirective (instead of OMPDistributeDirective) to make this
6457// function available for "loop bind(teams)", which maps to "distribute".
6459 CodeGenFunction &CGF,
6460 CodeGenModule &CGM) {
6461 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
6463 };
6464 OMPLexicalScope Scope(CGF, S, OMPD_unknown);
6465 CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute, CodeGen);
6466}
6467
6472
6473static llvm::Function *
6475 const OMPExecutableDirective &D) {
6476 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
6478 CGF.CapturedStmtInfo = &CapStmtInfo;
6479 llvm::Function *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S, D);
6480 Fn->setDoesNotRecurse();
6481 return Fn;
6482}
6483
6484template <typename T>
6485static void emitRestoreIP(CodeGenFunction &CGF, const T *C,
6486 llvm::OpenMPIRBuilder::InsertPointTy AllocaIP,
6487 llvm::OpenMPIRBuilder &OMPBuilder) {
6488
6489 unsigned NumLoops = C->getNumLoops();
6491 /*DestWidth=*/64, /*Signed=*/1);
6493 for (unsigned I = 0; I < NumLoops; I++) {
6494 const Expr *CounterVal = C->getLoopData(I);
6495 assert(CounterVal);
6496 llvm::Value *StoreValue = CGF.EmitScalarConversion(
6497 CGF.EmitScalarExpr(CounterVal), CounterVal->getType(), Int64Ty,
6498 CounterVal->getExprLoc());
6499 StoreValues.emplace_back(StoreValue);
6500 }
6501 OMPDoacrossKind<T> ODK;
6502 bool IsDependSource = ODK.isSource(C);
6503 CGF.Builder.restoreIP(
6504 OMPBuilder.createOrderedDepend(CGF.Builder, AllocaIP, NumLoops,
6505 StoreValues, ".cnt.addr", IsDependSource));
6506}
6507
6510 assert((S.hasClausesOfKind<OMPDependClause>() ||
6511 S.hasClausesOfKind<OMPDoacrossClause>()) &&
6512 "Standalone ordered directive should have either depend or doacross "
6513 "clause");
6514 // The ordered-standalone directive.
6515 assert(!S.hasAssociatedStmt() && "No associated statement must be in "
6516 "ordered depend|doacross construct.");
6517
6518 if (CGM.getLangOpts().OpenMPIRBuilder) {
6519 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
6520 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
6521
6522 InsertPointTy AllocaIP(AllocaInsertPt->getParent(),
6523 AllocaInsertPt->getIterator());
6524 for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
6525 emitRestoreIP(*this, DC, AllocaIP, OMPBuilder);
6526 for (const auto *DC : S.getClausesOfKind<OMPDoacrossClause>())
6527 emitRestoreIP(*this, DC, AllocaIP, OMPBuilder);
6528 return;
6529 }
6530
6531 if (S.hasClausesOfKind<OMPDependClause>()) {
6532 for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
6533 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
6534 } else if (S.hasClausesOfKind<OMPDoacrossClause>()) {
6535 for (const auto *DC : S.getClausesOfKind<OMPDoacrossClause>())
6536 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
6537 }
6538}
6539
6542 if (CGM.getLangOpts().OpenMPIRBuilder) {
6543 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
6544 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
6545
6546 // The ordered directive with threads or simd clause, or without clause.
6547 // Without clause, it behaves as if the threads clause is specified.
6548 const auto *C = S.getSingleClause<OMPSIMDClause>();
6549
6550 auto FiniCB = [this](InsertPointTy IP) {
6552 return llvm::Error::success();
6553 };
6554
6555 auto BodyGenCB = [&S, C, this](InsertPointTy AllocIP,
6556 InsertPointTy CodeGenIP,
6557 ArrayRef<llvm::BasicBlock *> DeallocBlocks) {
6558 Builder.restoreIP(CodeGenIP);
6559
6560 const CapturedStmt *CS = S.getInnermostCapturedStmt();
6561 if (C) {
6562 llvm::BasicBlock *FiniBB = splitBBWithSuffix(
6563 Builder, /*CreateBranch=*/false, ".ordered.after");
6565 GenerateOpenMPCapturedVars(*CS, CapturedVars);
6566 llvm::Function *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS, S);
6567 assert(S.getBeginLoc().isValid() &&
6568 "Outlined function call location must be valid.");
6569 ApplyDebugLocation::CreateDefaultArtificial(*this, S.getBeginLoc());
6570 OMPBuilderCBHelpers::EmitCaptureStmt(*this, CodeGenIP, *FiniBB,
6571 OutlinedFn, CapturedVars);
6572 } else {
6574 *this, CS->getCapturedStmt(), AllocIP, CodeGenIP, "ordered");
6575 }
6576 return llvm::Error::success();
6577 };
6578
6579 OMPLexicalScope Scope(*this, S, OMPD_unknown);
6580 llvm::OpenMPIRBuilder::InsertPointTy AfterIP = cantFail(
6581 OMPBuilder.createOrderedThreadsSimd(Builder, BodyGenCB, FiniCB, !C));
6582 Builder.restoreIP(AfterIP);
6583 return;
6584 }
6585
6586 const auto *C = S.getSingleClause<OMPSIMDClause>();
6587 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
6588 PrePostActionTy &Action) {
6589 const CapturedStmt *CS = S.getInnermostCapturedStmt();
6590 if (C) {
6592 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
6593 llvm::Function *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS, S);
6594 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getBeginLoc(),
6595 OutlinedFn, CapturedVars);
6596 } else {
6597 Action.Enter(CGF);
6598 CGF.EmitStmt(CS->getCapturedStmt());
6599 }
6600 };
6601 OMPLexicalScope Scope(*this, S, OMPD_unknown);
6602 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getBeginLoc(), !C);
6603}
6604
6605static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
6606 QualType SrcType, QualType DestType,
6607 SourceLocation Loc) {
6608 assert(CGF.hasScalarEvaluationKind(DestType) &&
6609 "DestType must have scalar evaluation kind.");
6610 assert(!Val.isAggregate() && "Must be a scalar or complex.");
6611 return Val.isScalar() ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
6612 DestType, Loc)
6614 Val.getComplexVal(), SrcType, DestType, Loc);
6615}
6616
6619 QualType DestType, SourceLocation Loc) {
6620 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
6621 "DestType must have complex evaluation kind.");
6623 if (Val.isScalar()) {
6624 // Convert the input element to the element type of the complex.
6625 QualType DestElementType =
6626 DestType->castAs<ComplexType>()->getElementType();
6627 llvm::Value *ScalarVal = CGF.EmitScalarConversion(
6628 Val.getScalarVal(), SrcType, DestElementType, Loc);
6629 ComplexVal = CodeGenFunction::ComplexPairTy(
6630 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
6631 } else {
6632 assert(Val.isComplex() && "Must be a scalar or complex.");
6633 QualType SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
6634 QualType DestElementType =
6635 DestType->castAs<ComplexType>()->getElementType();
6636 ComplexVal.first = CGF.EmitScalarConversion(
6637 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
6638 ComplexVal.second = CGF.EmitScalarConversion(
6639 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
6640 }
6641 return ComplexVal;
6642}
6643
6644static void emitSimpleAtomicStore(CodeGenFunction &CGF, llvm::AtomicOrdering AO,
6645 LValue LVal, RValue RVal) {
6646 if (LVal.isGlobalReg())
6647 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
6648 else
6649 CGF.EmitAtomicStore(RVal, LVal, AO, LVal.isVolatile(), /*isInit=*/false);
6650}
6651
6653 llvm::AtomicOrdering AO, LValue LVal,
6654 SourceLocation Loc) {
6655 if (LVal.isGlobalReg())
6656 return CGF.EmitLoadOfLValue(LVal, Loc);
6657 return CGF.EmitAtomicLoad(
6658 LVal, Loc, llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO),
6659 LVal.isVolatile());
6660}
6661
6663 QualType RValTy, SourceLocation Loc) {
6664 switch (getEvaluationKind(LVal.getType())) {
6665 case TEK_Scalar:
6667 *this, RVal, RValTy, LVal.getType(), Loc)),
6668 LVal);
6669 break;
6670 case TEK_Complex:
6672 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
6673 /*isInit=*/false);
6674 break;
6675 case TEK_Aggregate:
6676 llvm_unreachable("Must be a scalar or complex.");
6677 }
6678}
6679
6680static void emitOMPAtomicReadExpr(CodeGenFunction &CGF, llvm::AtomicOrdering AO,
6681 const Expr *X, const Expr *V,
6682 SourceLocation Loc) {
6683 // v = x;
6684 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
6685 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
6686 LValue XLValue = CGF.EmitLValue(X);
6687 LValue VLValue = CGF.EmitLValue(V);
6688 RValue Res = emitSimpleAtomicLoad(CGF, AO, XLValue, Loc);
6689 // OpenMP, 2.17.7, atomic Construct
6690 // If the read or capture clause is specified and the acquire, acq_rel, or
6691 // seq_cst clause is specified then the strong flush on exit from the atomic
6692 // operation is also an acquire flush.
6693 switch (AO) {
6694 case llvm::AtomicOrdering::Acquire:
6695 case llvm::AtomicOrdering::AcquireRelease:
6696 case llvm::AtomicOrdering::SequentiallyConsistent:
6697 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, {}, Loc,
6698 llvm::AtomicOrdering::Acquire);
6699 break;
6700 case llvm::AtomicOrdering::Monotonic:
6701 case llvm::AtomicOrdering::Release:
6702 break;
6703 case llvm::AtomicOrdering::NotAtomic:
6704 case llvm::AtomicOrdering::Unordered:
6705 llvm_unreachable("Unexpected ordering.");
6706 }
6707 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
6709}
6710
6712 llvm::AtomicOrdering AO, const Expr *X,
6713 const Expr *E, SourceLocation Loc) {
6714 // x = expr;
6715 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
6716 emitSimpleAtomicStore(CGF, AO, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
6718 // OpenMP, 2.17.7, atomic Construct
6719 // If the write, update, or capture clause is specified and the release,
6720 // acq_rel, or seq_cst clause is specified then the strong flush on entry to
6721 // the atomic operation is also a release flush.
6722 switch (AO) {
6723 case llvm::AtomicOrdering::Release:
6724 case llvm::AtomicOrdering::AcquireRelease:
6725 case llvm::AtomicOrdering::SequentiallyConsistent:
6726 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, {}, Loc,
6727 llvm::AtomicOrdering::Release);
6728 break;
6729 case llvm::AtomicOrdering::Acquire:
6730 case llvm::AtomicOrdering::Monotonic:
6731 break;
6732 case llvm::AtomicOrdering::NotAtomic:
6733 case llvm::AtomicOrdering::Unordered:
6734 llvm_unreachable("Unexpected ordering.");
6735 }
6736}
6737
6738static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
6739 RValue Update,
6741 llvm::AtomicOrdering AO,
6742 bool IsXLHSInRHSPart) {
6743 ASTContext &Context = CGF.getContext();
6744 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
6745 // expression is simple and atomic is allowed for the given type for the
6746 // target platform.
6747 if (BO == BO_Comma || !Update.isScalar() || !X.isSimple() ||
6748 (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
6749 (Update.getScalarVal()->getType() != X.getAddress().getElementType())) ||
6750 !Context.getTargetInfo().hasBuiltinAtomic(
6751 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
6752 return std::make_pair(false, RValue::get(nullptr));
6753
6754 auto &&CheckAtomicSupport = [&CGF](llvm::Type *T, BinaryOperatorKind BO) {
6755 if (T->isIntegerTy())
6756 return true;
6757
6758 if (T->isFloatingPointTy() && (BO == BO_Add || BO == BO_Sub))
6759 return llvm::isPowerOf2_64(CGF.CGM.getDataLayout().getTypeStoreSize(T));
6760
6761 return false;
6762 };
6763
6764 if (!CheckAtomicSupport(Update.getScalarVal()->getType(), BO) ||
6765 !CheckAtomicSupport(X.getAddress().getElementType(), BO))
6766 return std::make_pair(false, RValue::get(nullptr));
6767
6768 bool IsInteger = X.getAddress().getElementType()->isIntegerTy();
6769 llvm::AtomicRMWInst::BinOp RMWOp;
6770 switch (BO) {
6771 case BO_Add:
6772 RMWOp = IsInteger ? llvm::AtomicRMWInst::Add : llvm::AtomicRMWInst::FAdd;
6773 break;
6774 case BO_Sub:
6775 if (!IsXLHSInRHSPart)
6776 return std::make_pair(false, RValue::get(nullptr));
6777 RMWOp = IsInteger ? llvm::AtomicRMWInst::Sub : llvm::AtomicRMWInst::FSub;
6778 break;
6779 case BO_And:
6780 RMWOp = llvm::AtomicRMWInst::And;
6781 break;
6782 case BO_Or:
6783 RMWOp = llvm::AtomicRMWInst::Or;
6784 break;
6785 case BO_Xor:
6786 RMWOp = llvm::AtomicRMWInst::Xor;
6787 break;
6788 case BO_LT:
6789 if (IsInteger)
6790 RMWOp = X.getType()->hasSignedIntegerRepresentation()
6791 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
6792 : llvm::AtomicRMWInst::Max)
6793 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
6794 : llvm::AtomicRMWInst::UMax);
6795 else
6796 RMWOp = IsXLHSInRHSPart ? llvm::AtomicRMWInst::FMin
6797 : llvm::AtomicRMWInst::FMax;
6798 break;
6799 case BO_GT:
6800 if (IsInteger)
6801 RMWOp = X.getType()->hasSignedIntegerRepresentation()
6802 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
6803 : llvm::AtomicRMWInst::Min)
6804 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
6805 : llvm::AtomicRMWInst::UMin);
6806 else
6807 RMWOp = IsXLHSInRHSPart ? llvm::AtomicRMWInst::FMax
6808 : llvm::AtomicRMWInst::FMin;
6809 break;
6810 case BO_Assign:
6811 RMWOp = llvm::AtomicRMWInst::Xchg;
6812 break;
6813 case BO_Mul:
6814 case BO_Div:
6815 case BO_Rem:
6816 case BO_Shl:
6817 case BO_Shr:
6818 case BO_LAnd:
6819 case BO_LOr:
6820 return std::make_pair(false, RValue::get(nullptr));
6821 case BO_PtrMemD:
6822 case BO_PtrMemI:
6823 case BO_LE:
6824 case BO_GE:
6825 case BO_EQ:
6826 case BO_NE:
6827 case BO_Cmp:
6828 case BO_AddAssign:
6829 case BO_SubAssign:
6830 case BO_AndAssign:
6831 case BO_OrAssign:
6832 case BO_XorAssign:
6833 case BO_MulAssign:
6834 case BO_DivAssign:
6835 case BO_RemAssign:
6836 case BO_ShlAssign:
6837 case BO_ShrAssign:
6838 case BO_Comma:
6839 llvm_unreachable("Unsupported atomic update operation");
6840 }
6841 llvm::Value *UpdateVal = Update.getScalarVal();
6842 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
6843 if (IsInteger)
6844 UpdateVal = CGF.Builder.CreateIntCast(
6845 IC, X.getAddress().getElementType(),
6846 X.getType()->hasSignedIntegerRepresentation());
6847 else
6848 UpdateVal = CGF.Builder.CreateCast(llvm::Instruction::CastOps::UIToFP, IC,
6849 X.getAddress().getElementType());
6850 }
6851 llvm::AtomicRMWInst *Res =
6852 CGF.emitAtomicRMWInst(RMWOp, X.getAddress(), UpdateVal, AO);
6853 return std::make_pair(true, RValue::get(Res));
6854}
6855
6857 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
6858 llvm::AtomicOrdering AO, SourceLocation Loc,
6859 const llvm::function_ref<RValue(RValue)> CommonGen) {
6860 // Update expressions are allowed to have the following forms:
6861 // x binop= expr; -> xrval + expr;
6862 // x++, ++x -> xrval + 1;
6863 // x--, --x -> xrval - 1;
6864 // x = x binop expr; -> xrval binop expr
6865 // x = expr Op x; - > expr binop xrval;
6866 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
6867 if (!Res.first) {
6868 if (X.isGlobalReg()) {
6869 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
6870 // 'xrval'.
6871 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
6872 } else {
6873 // Perform compare-and-swap procedure.
6874 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
6875 }
6876 }
6877 return Res;
6878}
6879
6881 llvm::AtomicOrdering AO, const Expr *X,
6882 const Expr *E, const Expr *UE,
6883 bool IsXLHSInRHSPart, SourceLocation Loc) {
6884 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
6885 "Update expr in 'atomic update' must be a binary operator.");
6886 const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
6887 // Update expressions are allowed to have the following forms:
6888 // x binop= expr; -> xrval + expr;
6889 // x++, ++x -> xrval + 1;
6890 // x--, --x -> xrval - 1;
6891 // x = x binop expr; -> xrval binop expr
6892 // x = expr Op x; - > expr binop xrval;
6893 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
6894 LValue XLValue = CGF.EmitLValue(X);
6895 RValue ExprRValue = CGF.EmitAnyExpr(E);
6896 const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
6897 const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
6898 const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
6899 const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
6900 auto &&Gen = [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) {
6901 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
6902 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
6903 return CGF.EmitAnyExpr(UE);
6904 };
6906 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
6908 // OpenMP, 2.17.7, atomic Construct
6909 // If the write, update, or capture clause is specified and the release,
6910 // acq_rel, or seq_cst clause is specified then the strong flush on entry to
6911 // the atomic operation is also a release flush.
6912 switch (AO) {
6913 case llvm::AtomicOrdering::Release:
6914 case llvm::AtomicOrdering::AcquireRelease:
6915 case llvm::AtomicOrdering::SequentiallyConsistent:
6916 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, {}, Loc,
6917 llvm::AtomicOrdering::Release);
6918 break;
6919 case llvm::AtomicOrdering::Acquire:
6920 case llvm::AtomicOrdering::Monotonic:
6921 break;
6922 case llvm::AtomicOrdering::NotAtomic:
6923 case llvm::AtomicOrdering::Unordered:
6924 llvm_unreachable("Unexpected ordering.");
6925 }
6926}
6927
6929 QualType SourceType, QualType ResType,
6930 SourceLocation Loc) {
6931 switch (CGF.getEvaluationKind(ResType)) {
6932 case TEK_Scalar:
6933 return RValue::get(
6934 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
6935 case TEK_Complex: {
6936 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
6937 return RValue::getComplex(Res.first, Res.second);
6938 }
6939 case TEK_Aggregate:
6940 break;
6941 }
6942 llvm_unreachable("Must be a scalar or complex.");
6943}
6944
6946 llvm::AtomicOrdering AO,
6947 bool IsPostfixUpdate, const Expr *V,
6948 const Expr *X, const Expr *E,
6949 const Expr *UE, bool IsXLHSInRHSPart,
6950 SourceLocation Loc) {
6951 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
6952 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
6953 RValue NewVVal;
6954 LValue VLValue = CGF.EmitLValue(V);
6955 LValue XLValue = CGF.EmitLValue(X);
6956 RValue ExprRValue = CGF.EmitAnyExpr(E);
6957 QualType NewVValType;
6958 if (UE) {
6959 // 'x' is updated with some additional value.
6960 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
6961 "Update expr in 'atomic capture' must be a binary operator.");
6962 const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
6963 // Update expressions are allowed to have the following forms:
6964 // x binop= expr; -> xrval + expr;
6965 // x++, ++x -> xrval + 1;
6966 // x--, --x -> xrval - 1;
6967 // x = x binop expr; -> xrval binop expr
6968 // x = expr Op x; - > expr binop xrval;
6969 const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
6970 const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
6971 const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
6972 NewVValType = XRValExpr->getType();
6973 const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
6974 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
6975 IsPostfixUpdate](RValue XRValue) {
6976 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
6977 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
6978 RValue Res = CGF.EmitAnyExpr(UE);
6979 NewVVal = IsPostfixUpdate ? XRValue : Res;
6980 return Res;
6981 };
6982 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
6983 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
6985 if (Res.first) {
6986 // 'atomicrmw' instruction was generated.
6987 if (IsPostfixUpdate) {
6988 // Use old value from 'atomicrmw'.
6989 NewVVal = Res.second;
6990 } else {
6991 // 'atomicrmw' does not provide new value, so evaluate it using old
6992 // value of 'x'.
6993 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
6994 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
6995 NewVVal = CGF.EmitAnyExpr(UE);
6996 }
6997 }
6998 } else {
6999 // 'x' is simply rewritten with some 'expr'.
7000 NewVValType = X->getType().getNonReferenceType();
7001 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
7002 X->getType().getNonReferenceType(), Loc);
7003 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) {
7004 NewVVal = XRValue;
7005 return ExprRValue;
7006 };
7007 // Try to perform atomicrmw xchg, otherwise simple exchange.
7008 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
7009 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
7010 Loc, Gen);
7012 if (Res.first) {
7013 // 'atomicrmw' instruction was generated.
7014 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
7015 }
7016 }
7017 // Emit post-update store to 'v' of old/new 'x' value.
7018 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
7020 // OpenMP 5.1 removes the required flush for capture clause.
7021 if (CGF.CGM.getLangOpts().OpenMP < 51) {
7022 // OpenMP, 2.17.7, atomic Construct
7023 // If the write, update, or capture clause is specified and the release,
7024 // acq_rel, or seq_cst clause is specified then the strong flush on entry to
7025 // the atomic operation is also a release flush.
7026 // If the read or capture clause is specified and the acquire, acq_rel, or
7027 // seq_cst clause is specified then the strong flush on exit from the atomic
7028 // operation is also an acquire flush.
7029 switch (AO) {
7030 case llvm::AtomicOrdering::Release:
7031 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, {}, Loc,
7032 llvm::AtomicOrdering::Release);
7033 break;
7034 case llvm::AtomicOrdering::Acquire:
7035 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, {}, Loc,
7036 llvm::AtomicOrdering::Acquire);
7037 break;
7038 case llvm::AtomicOrdering::AcquireRelease:
7039 case llvm::AtomicOrdering::SequentiallyConsistent:
7041 CGF, {}, Loc, llvm::AtomicOrdering::AcquireRelease);
7042 break;
7043 case llvm::AtomicOrdering::Monotonic:
7044 break;
7045 case llvm::AtomicOrdering::NotAtomic:
7046 case llvm::AtomicOrdering::Unordered:
7047 llvm_unreachable("Unexpected ordering.");
7048 }
7049 }
7050}
7051
7053 CodeGenFunction &CGF, llvm::AtomicOrdering AO, llvm::AtomicOrdering FailAO,
7054 const Expr *X, const Expr *V, const Expr *R, const Expr *E, const Expr *D,
7055 const Expr *CE, bool IsXBinopExpr, bool IsPostfixUpdate, bool IsFailOnly,
7056 SourceLocation Loc) {
7057 llvm::OpenMPIRBuilder &OMPBuilder =
7059
7060 OMPAtomicCompareOp Op;
7061 assert(isa<BinaryOperator>(CE) && "CE is not a BinaryOperator");
7062 switch (cast<BinaryOperator>(CE)->getOpcode()) {
7063 case BO_EQ:
7064 Op = OMPAtomicCompareOp::EQ;
7065 break;
7066 case BO_LT:
7067 Op = OMPAtomicCompareOp::MIN;
7068 break;
7069 case BO_GT:
7070 Op = OMPAtomicCompareOp::MAX;
7071 break;
7072 default:
7073 llvm_unreachable("unsupported atomic compare binary operator");
7074 }
7075
7076 LValue XLVal = CGF.EmitLValue(X);
7077 Address XAddr = XLVal.getAddress();
7078
7079 auto EmitRValueWithCastIfNeeded = [&CGF, Loc](const Expr *X, const Expr *E) {
7080 if (X->getType() == E->getType())
7081 return CGF.EmitScalarExpr(E);
7082 const Expr *NewE = E->IgnoreImplicitAsWritten();
7083 llvm::Value *V = CGF.EmitScalarExpr(NewE);
7084 if (NewE->getType() == X->getType())
7085 return V;
7086 return CGF.EmitScalarConversion(V, NewE->getType(), X->getType(), Loc);
7087 };
7088
7089 llvm::Value *EVal = EmitRValueWithCastIfNeeded(X, E);
7090 llvm::Value *DVal = D ? EmitRValueWithCastIfNeeded(X, D) : nullptr;
7091 if (auto *CI = dyn_cast<llvm::ConstantInt>(EVal))
7092 EVal = CGF.Builder.CreateIntCast(
7093 CI, XLVal.getAddress().getElementType(),
7095 if (DVal)
7096 if (auto *CI = dyn_cast<llvm::ConstantInt>(DVal))
7097 DVal = CGF.Builder.CreateIntCast(
7098 CI, XLVal.getAddress().getElementType(),
7100
7101 llvm::OpenMPIRBuilder::AtomicOpValue XOpVal{
7102 XAddr.emitRawPointer(CGF), XAddr.getElementType(),
7103 X->getType()->hasSignedIntegerRepresentation(),
7104 X->getType().isVolatileQualified()};
7105 llvm::OpenMPIRBuilder::AtomicOpValue VOpVal, ROpVal;
7106 if (V) {
7107 LValue LV = CGF.EmitLValue(V);
7108 Address Addr = LV.getAddress();
7109 VOpVal = {Addr.emitRawPointer(CGF), Addr.getElementType(),
7110 V->getType()->hasSignedIntegerRepresentation(),
7111 V->getType().isVolatileQualified()};
7112 }
7113 if (R) {
7114 LValue LV = CGF.EmitLValue(R);
7115 Address Addr = LV.getAddress();
7116 ROpVal = {Addr.emitRawPointer(CGF), Addr.getElementType(),
7117 R->getType()->hasSignedIntegerRepresentation(),
7118 R->getType().isVolatileQualified()};
7119 }
7120
7121 if (FailAO == llvm::AtomicOrdering::NotAtomic) {
7122 // fail clause was not mentioned on the
7123 // "#pragma omp atomic compare" construct.
7124 CGF.Builder.restoreIP(OMPBuilder.createAtomicCompare(
7125 CGF.Builder, XOpVal, VOpVal, ROpVal, EVal, DVal, AO, Op, IsXBinopExpr,
7126 IsPostfixUpdate, IsFailOnly));
7127 } else
7128 CGF.Builder.restoreIP(OMPBuilder.createAtomicCompare(
7129 CGF.Builder, XOpVal, VOpVal, ROpVal, EVal, DVal, AO, Op, IsXBinopExpr,
7130 IsPostfixUpdate, IsFailOnly, FailAO));
7131}
7132
7134 llvm::AtomicOrdering AO,
7135 llvm::AtomicOrdering FailAO, bool IsPostfixUpdate,
7136 const Expr *X, const Expr *V, const Expr *R,
7137 const Expr *E, const Expr *UE, const Expr *D,
7138 const Expr *CE, bool IsXLHSInRHSPart,
7139 bool IsFailOnly, SourceLocation Loc) {
7140 switch (Kind) {
7141 case OMPC_read:
7142 emitOMPAtomicReadExpr(CGF, AO, X, V, Loc);
7143 break;
7144 case OMPC_write:
7145 emitOMPAtomicWriteExpr(CGF, AO, X, E, Loc);
7146 break;
7147 case OMPC_unknown:
7148 case OMPC_update:
7149 emitOMPAtomicUpdateExpr(CGF, AO, X, E, UE, IsXLHSInRHSPart, Loc);
7150 break;
7151 case OMPC_capture:
7152 emitOMPAtomicCaptureExpr(CGF, AO, IsPostfixUpdate, V, X, E, UE,
7153 IsXLHSInRHSPart, Loc);
7154 break;
7155 case OMPC_compare: {
7156 emitOMPAtomicCompareExpr(CGF, AO, FailAO, X, V, R, E, D, CE,
7157 IsXLHSInRHSPart, IsPostfixUpdate, IsFailOnly, Loc);
7158 break;
7159 }
7160 default:
7161 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
7162 }
7163}
7164
7166 llvm::AtomicOrdering AO = CGM.getOpenMPRuntime().getDefaultMemoryOrdering();
7167 // Fail Memory Clause Ordering.
7168 llvm::AtomicOrdering FailAO = llvm::AtomicOrdering::NotAtomic;
7169 bool MemOrderingSpecified = false;
7170 if (S.getSingleClause<OMPSeqCstClause>()) {
7171 AO = llvm::AtomicOrdering::SequentiallyConsistent;
7172 MemOrderingSpecified = true;
7173 } else if (S.getSingleClause<OMPAcqRelClause>()) {
7174 AO = llvm::AtomicOrdering::AcquireRelease;
7175 MemOrderingSpecified = true;
7176 } else if (S.getSingleClause<OMPAcquireClause>()) {
7177 AO = llvm::AtomicOrdering::Acquire;
7178 MemOrderingSpecified = true;
7179 } else if (S.getSingleClause<OMPReleaseClause>()) {
7180 AO = llvm::AtomicOrdering::Release;
7181 MemOrderingSpecified = true;
7182 } else if (S.getSingleClause<OMPRelaxedClause>()) {
7183 AO = llvm::AtomicOrdering::Monotonic;
7184 MemOrderingSpecified = true;
7185 }
7186 llvm::SmallSet<OpenMPClauseKind, 2> KindsEncountered;
7187 OpenMPClauseKind Kind = OMPC_unknown;
7188 for (const OMPClause *C : S.clauses()) {
7189 // Find first clause (skip seq_cst|acq_rel|aqcuire|release|relaxed clause,
7190 // if it is first).
7191 OpenMPClauseKind K = C->getClauseKind();
7192 // TBD
7193 if (K == OMPC_weak)
7194 return;
7195 if (K == OMPC_seq_cst || K == OMPC_acq_rel || K == OMPC_acquire ||
7196 K == OMPC_release || K == OMPC_relaxed || K == OMPC_hint)
7197 continue;
7198 Kind = K;
7199 KindsEncountered.insert(K);
7200 }
7201 // We just need to correct Kind here. No need to set a bool saying it is
7202 // actually compare capture because we can tell from whether V and R are
7203 // nullptr.
7204 if (KindsEncountered.contains(OMPC_compare) &&
7205 KindsEncountered.contains(OMPC_capture))
7206 Kind = OMPC_compare;
7207 if (!MemOrderingSpecified) {
7208 llvm::AtomicOrdering DefaultOrder =
7209 CGM.getOpenMPRuntime().getDefaultMemoryOrdering();
7210 if (DefaultOrder == llvm::AtomicOrdering::Monotonic ||
7211 DefaultOrder == llvm::AtomicOrdering::SequentiallyConsistent ||
7212 (DefaultOrder == llvm::AtomicOrdering::AcquireRelease &&
7213 Kind == OMPC_capture)) {
7214 AO = DefaultOrder;
7215 } else if (DefaultOrder == llvm::AtomicOrdering::AcquireRelease) {
7216 if (Kind == OMPC_unknown || Kind == OMPC_update || Kind == OMPC_write) {
7217 AO = llvm::AtomicOrdering::Release;
7218 } else if (Kind == OMPC_read) {
7219 assert(Kind == OMPC_read && "Unexpected atomic kind.");
7220 AO = llvm::AtomicOrdering::Acquire;
7221 }
7222 }
7223 }
7224
7225 if (KindsEncountered.contains(OMPC_compare) &&
7226 KindsEncountered.contains(OMPC_fail)) {
7227 Kind = OMPC_compare;
7228 const auto *FailClause = S.getSingleClause<OMPFailClause>();
7229 if (FailClause) {
7230 OpenMPClauseKind FailParameter = FailClause->getFailParameter();
7231 if (FailParameter == llvm::omp::OMPC_relaxed)
7232 FailAO = llvm::AtomicOrdering::Monotonic;
7233 else if (FailParameter == llvm::omp::OMPC_acquire)
7234 FailAO = llvm::AtomicOrdering::Acquire;
7235 else if (FailParameter == llvm::omp::OMPC_seq_cst)
7236 FailAO = llvm::AtomicOrdering::SequentiallyConsistent;
7237 }
7238 }
7239
7240 LexicalScope Scope(*this, S.getSourceRange());
7241 EmitStopPoint(S.getAssociatedStmt());
7242 emitOMPAtomicExpr(*this, Kind, AO, FailAO, S.isPostfixUpdate(), S.getX(),
7243 S.getV(), S.getR(), S.getExpr(), S.getUpdateExpr(),
7244 S.getD(), S.getCondExpr(), S.isXLHSInRHSPart(),
7245 S.isFailOnly(), S.getBeginLoc());
7246}
7247
7249 const OMPExecutableDirective &S,
7250 const RegionCodeGenTy &CodeGen) {
7251 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
7252 CodeGenModule &CGM = CGF.CGM;
7253
7254 // On device emit this construct as inlined code.
7255 if (CGM.getLangOpts().OpenMPIsTargetDevice) {
7256 OMPLexicalScope Scope(CGF, S, OMPD_target);
7258 CGF, OMPD_target, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
7259 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
7260 });
7261 return;
7262 }
7263
7265 llvm::Function *Fn = nullptr;
7266 llvm::Constant *FnID = nullptr;
7267
7268 const Expr *IfCond = nullptr;
7269 // Check for the at most one if clause associated with the target region.
7270 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
7271 if (C->getNameModifier() == OMPD_unknown ||
7272 C->getNameModifier() == OMPD_target) {
7273 IfCond = C->getCondition();
7274 break;
7275 }
7276 }
7277
7278 // Check if we have any device clause associated with the directive.
7279 llvm::PointerIntPair<const Expr *, 2, OpenMPDeviceClauseModifier> Device(
7280 nullptr, OMPC_DEVICE_unknown);
7281 if (auto *C = S.getSingleClause<OMPDeviceClause>())
7282 Device.setPointerAndInt(C->getDevice(), C->getModifier());
7283
7284 // Check if we have an if clause whose conditional always evaluates to false
7285 // or if we do not have any targets specified. If so the target region is not
7286 // an offload entry point.
7287 bool IsOffloadEntry = true;
7288 if (IfCond) {
7289 bool Val;
7290 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
7291 IsOffloadEntry = false;
7292 }
7293 if (CGM.getLangOpts().OMPTargetTriples.empty())
7294 IsOffloadEntry = false;
7295
7296 if (CGM.getLangOpts().OpenMPOffloadMandatory && !IsOffloadEntry) {
7297 CGM.getDiags().Report(diag::err_missing_mandatory_offloading);
7298 }
7299
7300 assert(CGF.CurFuncDecl && "No parent declaration for target region!");
7301 StringRef ParentName;
7302 // In case we have Ctors/Dtors we use the complete type variant to produce
7303 // the mangling of the device outlined kernel.
7304 if (const auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
7305 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
7306 else if (const auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
7307 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
7308 else
7309 ParentName =
7311
7312 // Emit target region as a standalone region.
7313 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
7314 IsOffloadEntry, CodeGen);
7315 OMPLexicalScope Scope(CGF, S, OMPD_task);
7316 auto &&SizeEmitter =
7317 [IsOffloadEntry](CodeGenFunction &CGF,
7318 const OMPLoopDirective &D) -> llvm::Value * {
7319 if (IsOffloadEntry) {
7320 OMPLoopScope PreInitScope(CGF, D);
7321 // Emit calculation of the iterations count.
7322 llvm::Value *NumIterations = CGF.EmitScalarExpr(D.getNumIterations());
7323 NumIterations = CGF.Builder.CreateIntCast(NumIterations, CGF.Int64Ty,
7324 /*isSigned=*/false);
7325 return NumIterations;
7326 }
7327 return nullptr;
7328 };
7329 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device,
7330 SizeEmitter);
7331}
7332
7334 PrePostActionTy &Action) {
7335 Action.Enter(CGF);
7336 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
7337 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
7338 CGF.EmitOMPPrivateClause(S, PrivateScope);
7339 (void)PrivateScope.Privatize();
7340 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
7342
7343 CGF.EmitStmt(S.getCapturedStmt(OMPD_target)->getCapturedStmt());
7344 CGF.EnsureInsertPoint();
7345}
7346
7348 StringRef ParentName,
7349 const OMPTargetDirective &S) {
7350 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7351 emitTargetRegion(CGF, S, Action);
7352 };
7353 llvm::Function *Fn;
7354 llvm::Constant *Addr;
7355 // Emit target region as a standalone region.
7356 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
7357 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
7358 assert(Fn && Addr && "Target device function emission failed.");
7359}
7360
7362 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7363 emitTargetRegion(CGF, S, Action);
7364 };
7366}
7367
7369 const OMPExecutableDirective &S,
7370 OpenMPDirectiveKind InnermostKind,
7371 const RegionCodeGenTy &CodeGen) {
7372 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
7373 llvm::Function *OutlinedFn =
7375 CGF, S, *CS->getCapturedDecl()->param_begin(), InnermostKind,
7376 CodeGen);
7377
7378 OMPTeamsScope Scope(CGF, S);
7379 auto ParallelLeague = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
7380 const auto *NT = S.getSingleClause<OMPNumTeamsClause>();
7381 const auto *TL = S.getSingleClause<OMPThreadLimitClause>();
7382 if (NT || TL) {
7383 const Expr *NumTeams = NT ? NT->getNumTeams().front() : nullptr;
7384 const Expr *ThreadLimit = TL ? TL->getThreadLimit().front() : nullptr;
7385
7386 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
7387 S.getBeginLoc());
7388 }
7389 };
7390
7391 const Expr *IfCond = nullptr;
7392 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
7393 if (C->getNameModifier() == OMPD_unknown ||
7394 C->getNameModifier() == OMPD_teams) {
7395 IfCond = C->getCondition();
7396 break;
7397 }
7398 }
7399 if (IfCond && CGF.CGM.getLangOpts().OpenMP >= 52) {
7400 auto SerialLeague = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
7401 // OpenMP 5.2, 10.2, teams Construct
7402 // When an if clause is present on a teams construct and the if clause
7403 // expression evaluates to false, the number of created teams is one.
7404 const llvm::APInt One(32, 1);
7405 IntegerLiteral NumTeams(
7406 CGF.getContext(), One,
7407 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
7408 SourceLocation());
7409 // The thread_limit clause is unaffected by the if clause.
7410 const auto *TL = S.getSingleClause<OMPThreadLimitClause>();
7411 const Expr *ThreadLimit = TL ? TL->getThreadLimit().front() : nullptr;
7412 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, &NumTeams, ThreadLimit,
7413 S.getBeginLoc());
7414 };
7415 CGF.CGM.getOpenMPRuntime().emitIfClause(CGF, IfCond, ParallelLeague,
7416 SerialLeague);
7417 } else {
7418 const RegionCodeGenTy ThenRCG(ParallelLeague);
7419 ThenRCG(CGF);
7420 }
7421
7423 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
7424 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getBeginLoc(), OutlinedFn,
7425 CapturedVars);
7426}
7427
7429 // Emit teams region as a standalone region.
7430 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7431 Action.Enter(CGF);
7432 OMPPrivateScope PrivateScope(CGF);
7433 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
7434 CGF.EmitOMPPrivateClause(S, PrivateScope);
7435 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
7436 (void)PrivateScope.Privatize();
7437 CGF.EmitStmt(S.getCapturedStmt(OMPD_teams)->getCapturedStmt());
7438 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
7439 };
7440 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
7442 [](CodeGenFunction &) { return nullptr; });
7443}
7444
7446 const OMPTargetTeamsDirective &S) {
7447 auto *CS = S.getCapturedStmt(OMPD_teams);
7448 Action.Enter(CGF);
7449 // Emit teams region as a standalone region.
7450 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
7451 Action.Enter(CGF);
7452 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
7453 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
7454 CGF.EmitOMPPrivateClause(S, PrivateScope);
7455 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
7456 (void)PrivateScope.Privatize();
7457 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
7459 CGF.EmitStmt(CS->getCapturedStmt());
7460 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
7461 };
7462 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
7464 [](CodeGenFunction &) { return nullptr; });
7465}
7466
7468 CodeGenModule &CGM, StringRef ParentName,
7469 const OMPTargetTeamsDirective &S) {
7470 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7471 emitTargetTeamsRegion(CGF, Action, S);
7472 };
7473 llvm::Function *Fn;
7474 llvm::Constant *Addr;
7475 // Emit target region as a standalone region.
7476 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
7477 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
7478 assert(Fn && Addr && "Target device function emission failed.");
7479}
7480
7482 const OMPTargetTeamsDirective &S) {
7483 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7484 emitTargetTeamsRegion(CGF, Action, S);
7485 };
7487}
7488
7489static void
7492 Action.Enter(CGF);
7493 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
7495 };
7496
7497 // Emit teams region as a standalone region.
7498 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
7499 PrePostActionTy &Action) {
7500 Action.Enter(CGF);
7501 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
7502 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
7503 (void)PrivateScope.Privatize();
7504 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
7505 CodeGenDistribute);
7506 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
7507 };
7508 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute, CodeGen);
7510 [](CodeGenFunction &) { return nullptr; });
7511}
7512
7514 CodeGenModule &CGM, StringRef ParentName,
7516 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7517 emitTargetTeamsDistributeRegion(CGF, Action, S);
7518 };
7519 llvm::Function *Fn;
7520 llvm::Constant *Addr;
7521 // Emit target region as a standalone region.
7522 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
7523 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
7524 assert(Fn && Addr && "Target device function emission failed.");
7525}
7526
7529 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7530 emitTargetTeamsDistributeRegion(CGF, Action, S);
7531 };
7533}
7534
7536 CodeGenFunction &CGF, PrePostActionTy &Action,
7538 Action.Enter(CGF);
7539 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
7541 };
7542
7543 // Emit teams region as a standalone region.
7544 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
7545 PrePostActionTy &Action) {
7546 Action.Enter(CGF);
7547 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
7548 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
7549 (void)PrivateScope.Privatize();
7550 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
7551 CodeGenDistribute);
7552 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
7553 };
7554 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_simd, CodeGen);
7556 [](CodeGenFunction &) { return nullptr; });
7557}
7558
7560 CodeGenModule &CGM, StringRef ParentName,
7562 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7564 };
7565 llvm::Function *Fn;
7566 llvm::Constant *Addr;
7567 // Emit target region as a standalone region.
7568 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
7569 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
7570 assert(Fn && Addr && "Target device function emission failed.");
7571}
7572
7575 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7577 };
7579}
7580
7582 const OMPTeamsDistributeDirective &S) {
7583
7584 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
7586 };
7587
7588 // Emit teams region as a standalone region.
7589 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
7590 PrePostActionTy &Action) {
7591 Action.Enter(CGF);
7592 OMPPrivateScope PrivateScope(CGF);
7593 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
7594 (void)PrivateScope.Privatize();
7595 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
7596 CodeGenDistribute);
7597 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
7598 };
7599 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
7601 [](CodeGenFunction &) { return nullptr; });
7602}
7603
7606 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
7608 };
7609
7610 // Emit teams region as a standalone region.
7611 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
7612 PrePostActionTy &Action) {
7613 Action.Enter(CGF);
7614 OMPPrivateScope PrivateScope(CGF);
7615 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
7616 (void)PrivateScope.Privatize();
7617 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd,
7618 CodeGenDistribute);
7619 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
7620 };
7621 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_simd, CodeGen);
7623 [](CodeGenFunction &) { return nullptr; });
7624}
7625
7628 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
7630 S.getDistInc());
7631 };
7632
7633 // Emit teams region as a standalone region.
7634 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
7635 PrePostActionTy &Action) {
7636 Action.Enter(CGF);
7637 OMPPrivateScope PrivateScope(CGF);
7638 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
7639 (void)PrivateScope.Privatize();
7640 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
7641 CodeGenDistribute);
7642 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
7643 };
7644 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
7646 [](CodeGenFunction &) { return nullptr; });
7647}
7648
7651 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
7653 S.getDistInc());
7654 };
7655
7656 // Emit teams region as a standalone region.
7657 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
7658 PrePostActionTy &Action) {
7659 Action.Enter(CGF);
7660 OMPPrivateScope PrivateScope(CGF);
7661 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
7662 (void)PrivateScope.Privatize();
7664 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
7665 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
7666 };
7667 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for_simd,
7668 CodeGen);
7670 [](CodeGenFunction &) { return nullptr; });
7671}
7672
7674 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
7675 llvm::Value *Device = nullptr;
7676 llvm::Value *NumDependences = nullptr;
7677 llvm::Value *DependenceList = nullptr;
7678
7679 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
7680 Device = EmitScalarExpr(C->getDevice());
7681
7682 // Build list and emit dependences
7685 if (!Data.Dependences.empty()) {
7686 Address DependenciesArray = Address::invalid();
7687 std::tie(NumDependences, DependenciesArray) =
7688 CGM.getOpenMPRuntime().emitDependClause(*this, Data.Dependences,
7689 S.getBeginLoc());
7690 DependenceList = DependenciesArray.emitRawPointer(*this);
7691 }
7692 Data.HasNowaitClause = S.hasClausesOfKind<OMPNowaitClause>();
7693
7694 assert(!(Data.HasNowaitClause && !(S.getSingleClause<OMPInitClause>() ||
7695 S.getSingleClause<OMPDestroyClause>() ||
7696 S.getSingleClause<OMPUseClause>())) &&
7697 "OMPNowaitClause clause is used separately in OMPInteropDirective.");
7698
7699 auto ItOMPInitClause = S.getClausesOfKind<OMPInitClause>();
7700 if (!ItOMPInitClause.empty()) {
7701 // Look at the multiple init clauses
7702 for (const OMPInitClause *C : ItOMPInitClause) {
7703 llvm::Value *InteropvarPtr =
7704 EmitLValue(C->getInteropVar()).getPointer(*this);
7705 llvm::omp::OMPInteropType InteropType =
7706 llvm::omp::OMPInteropType::Unknown;
7707 if (C->getIsTarget()) {
7708 InteropType = llvm::omp::OMPInteropType::Target;
7709 } else {
7710 assert(C->getIsTargetSync() &&
7711 "Expected interop-type target/targetsync");
7712 InteropType = llvm::omp::OMPInteropType::TargetSync;
7713 }
7714 OMPBuilder.createOMPInteropInit(Builder, InteropvarPtr, InteropType,
7715 Device, NumDependences, DependenceList,
7716 Data.HasNowaitClause);
7717 }
7718 }
7719 auto ItOMPDestroyClause = S.getClausesOfKind<OMPDestroyClause>();
7720 if (!ItOMPDestroyClause.empty()) {
7721 // Look at the multiple destroy clauses
7722 for (const OMPDestroyClause *C : ItOMPDestroyClause) {
7723 llvm::Value *InteropvarPtr =
7724 EmitLValue(C->getInteropVar()).getPointer(*this);
7725 OMPBuilder.createOMPInteropDestroy(Builder, InteropvarPtr, Device,
7726 NumDependences, DependenceList,
7727 Data.HasNowaitClause);
7728 }
7729 }
7730 auto ItOMPUseClause = S.getClausesOfKind<OMPUseClause>();
7731 if (!ItOMPUseClause.empty()) {
7732 // Look at the multiple use clauses
7733 for (const OMPUseClause *C : ItOMPUseClause) {
7734 llvm::Value *InteropvarPtr =
7735 EmitLValue(C->getInteropVar()).getPointer(*this);
7736 OMPBuilder.createOMPInteropUse(Builder, InteropvarPtr, Device,
7737 NumDependences, DependenceList,
7738 Data.HasNowaitClause);
7739 }
7740 }
7741}
7742
7745 PrePostActionTy &Action) {
7746 Action.Enter(CGF);
7747 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
7749 S.getDistInc());
7750 };
7751
7752 // Emit teams region as a standalone region.
7753 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
7754 PrePostActionTy &Action) {
7755 Action.Enter(CGF);
7756 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
7757 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
7758 (void)PrivateScope.Privatize();
7760 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
7761 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
7762 };
7763
7764 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for,
7765 CodeGenTeams);
7767 [](CodeGenFunction &) { return nullptr; });
7768}
7769
7771 CodeGenModule &CGM, StringRef ParentName,
7773 // Emit SPMD target teams distribute parallel for region as a standalone
7774 // region.
7775 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7777 };
7778 llvm::Function *Fn;
7779 llvm::Constant *Addr;
7780 // Emit target region as a standalone region.
7781 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
7782 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
7783 assert(Fn && Addr && "Target device function emission failed.");
7784}
7785
7793
7795 CodeGenFunction &CGF,
7797 PrePostActionTy &Action) {
7798 Action.Enter(CGF);
7799 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
7801 S.getDistInc());
7802 };
7803
7804 // Emit teams region as a standalone region.
7805 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
7806 PrePostActionTy &Action) {
7807 Action.Enter(CGF);
7808 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
7809 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
7810 (void)PrivateScope.Privatize();
7812 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
7813 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
7814 };
7815
7816 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for_simd,
7817 CodeGenTeams);
7819 [](CodeGenFunction &) { return nullptr; });
7820}
7821
7823 CodeGenModule &CGM, StringRef ParentName,
7825 // Emit SPMD target teams distribute parallel for simd region as a standalone
7826 // region.
7827 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7829 };
7830 llvm::Function *Fn;
7831 llvm::Constant *Addr;
7832 // Emit target region as a standalone region.
7833 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
7834 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
7835 assert(Fn && Addr && "Target device function emission failed.");
7836}
7837
7845
7848 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getBeginLoc(),
7849 S.getCancelRegion());
7850}
7851
7853 const Expr *IfCond = nullptr;
7854 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
7855 if (C->getNameModifier() == OMPD_unknown ||
7856 C->getNameModifier() == OMPD_cancel) {
7857 IfCond = C->getCondition();
7858 break;
7859 }
7860 }
7861 if (CGM.getLangOpts().OpenMPIRBuilder) {
7862 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
7863 // TODO: This check is necessary as we only generate `omp parallel` through
7864 // the OpenMPIRBuilder for now.
7865 if (S.getCancelRegion() == OMPD_parallel ||
7866 S.getCancelRegion() == OMPD_sections ||
7867 S.getCancelRegion() == OMPD_section) {
7868 llvm::Value *IfCondition = nullptr;
7869 if (IfCond)
7870 IfCondition = EmitScalarExpr(IfCond,
7871 /*IgnoreResultAssign=*/true);
7872 llvm::OpenMPIRBuilder::InsertPointTy AfterIP = cantFail(
7873 OMPBuilder.createCancel(Builder, IfCondition, S.getCancelRegion()));
7874 return Builder.restoreIP(AfterIP);
7875 }
7876 }
7877
7878 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getBeginLoc(), IfCond,
7879 S.getCancelRegion());
7880}
7881
7884 if (Kind == OMPD_parallel || Kind == OMPD_task ||
7885 Kind == OMPD_target_parallel || Kind == OMPD_taskloop ||
7886 Kind == OMPD_master_taskloop || Kind == OMPD_parallel_master_taskloop)
7887 return ReturnBlock;
7888 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
7889 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
7890 Kind == OMPD_distribute_parallel_for ||
7891 Kind == OMPD_target_parallel_for ||
7892 Kind == OMPD_teams_distribute_parallel_for ||
7893 Kind == OMPD_target_teams_distribute_parallel_for);
7894 return OMPCancelStack.getExitBlock();
7895}
7896
7898 const OMPUseDevicePtrClause &C, OMPPrivateScope &PrivateScope,
7899 const llvm::DenseMap<const ValueDecl *, llvm::Value *>
7900 CaptureDeviceAddrMap) {
7901 llvm::SmallDenseSet<CanonicalDeclPtr<const Decl>, 4> Processed;
7902 for (const Expr *OrigVarIt : C.varlist()) {
7903 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(OrigVarIt)->getDecl());
7904 if (!Processed.insert(OrigVD).second)
7905 continue;
7906
7907 // In order to identify the right initializer we need to match the
7908 // declaration used by the mapping logic. In some cases we may get
7909 // OMPCapturedExprDecl that refers to the original declaration.
7910 const ValueDecl *MatchingVD = OrigVD;
7911 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
7912 // OMPCapturedExprDecl are used to privative fields of the current
7913 // structure.
7914 const auto *ME = cast<MemberExpr>(OED->getInit());
7915 assert(isa<CXXThisExpr>(ME->getBase()->IgnoreImpCasts()) &&
7916 "Base should be the current struct!");
7917 MatchingVD = ME->getMemberDecl();
7918 }
7919
7920 // If we don't have information about the current list item, move on to
7921 // the next one.
7922 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
7923 if (InitAddrIt == CaptureDeviceAddrMap.end())
7924 continue;
7925
7926 llvm::Type *Ty = ConvertTypeForMem(OrigVD->getType().getNonReferenceType());
7927
7928 // Return the address of the private variable.
7929 bool IsRegistered = PrivateScope.addPrivate(
7930 OrigVD,
7931 Address(InitAddrIt->second, Ty,
7932 getContext().getTypeAlignInChars(getContext().VoidPtrTy)));
7933 assert(IsRegistered && "firstprivate var already registered as private");
7934 // Silence the warning about unused variable.
7935 (void)IsRegistered;
7936 }
7937}
7938
7939static const VarDecl *getBaseDecl(const Expr *Ref) {
7940 const Expr *Base = Ref->IgnoreParenImpCasts();
7941 while (const auto *OASE = dyn_cast<ArraySectionExpr>(Base))
7942 Base = OASE->getBase()->IgnoreParenImpCasts();
7943 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Base))
7944 Base = ASE->getBase()->IgnoreParenImpCasts();
7945 return cast<VarDecl>(cast<DeclRefExpr>(Base)->getDecl());
7946}
7947
7949 const OMPUseDeviceAddrClause &C, OMPPrivateScope &PrivateScope,
7950 const llvm::DenseMap<const ValueDecl *, llvm::Value *>
7951 CaptureDeviceAddrMap) {
7952 llvm::SmallDenseSet<CanonicalDeclPtr<const Decl>, 4> Processed;
7953 for (const Expr *Ref : C.varlist()) {
7954 const VarDecl *OrigVD = getBaseDecl(Ref);
7955 if (!Processed.insert(OrigVD).second)
7956 continue;
7957 // In order to identify the right initializer we need to match the
7958 // declaration used by the mapping logic. In some cases we may get
7959 // OMPCapturedExprDecl that refers to the original declaration.
7960 const ValueDecl *MatchingVD = OrigVD;
7961 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
7962 // OMPCapturedExprDecl are used to privative fields of the current
7963 // structure.
7964 const auto *ME = cast<MemberExpr>(OED->getInit());
7965 assert(isa<CXXThisExpr>(ME->getBase()) &&
7966 "Base should be the current struct!");
7967 MatchingVD = ME->getMemberDecl();
7968 }
7969
7970 // If we don't have information about the current list item, move on to
7971 // the next one.
7972 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
7973 if (InitAddrIt == CaptureDeviceAddrMap.end())
7974 continue;
7975
7976 llvm::Type *Ty = ConvertTypeForMem(OrigVD->getType().getNonReferenceType());
7977
7978 Address PrivAddr =
7979 Address(InitAddrIt->second, Ty,
7980 getContext().getTypeAlignInChars(getContext().VoidPtrTy));
7981 // For declrefs and variable length array need to load the pointer for
7982 // correct mapping, since the pointer to the data was passed to the runtime.
7983 if (isa<DeclRefExpr>(Ref->IgnoreParenImpCasts()) ||
7984 MatchingVD->getType()->isArrayType()) {
7986 OrigVD->getType().getNonReferenceType());
7987 PrivAddr =
7989 PtrTy->castAs<PointerType>());
7990 }
7991
7992 (void)PrivateScope.addPrivate(OrigVD, PrivAddr);
7993 }
7994}
7995
7996// Generate the instructions for '#pragma omp target data' directive.
7998 const OMPTargetDataDirective &S) {
7999 // Emit vtable only from host for target data directive.
8000 if (!CGM.getLangOpts().OpenMPIsTargetDevice)
8001 CGM.getOpenMPRuntime().registerVTable(S);
8002
8003 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true,
8004 /*SeparateBeginEndCalls=*/true);
8005
8006 // Create a pre/post action to signal the privatization of the device pointer.
8007 // This action can be replaced by the OpenMP runtime code generation to
8008 // deactivate privatization.
8009 bool PrivatizeDevicePointers = false;
8010 class DevicePointerPrivActionTy : public PrePostActionTy {
8011 bool &PrivatizeDevicePointers;
8012
8013 public:
8014 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
8015 : PrivatizeDevicePointers(PrivatizeDevicePointers) {}
8016 void Enter(CodeGenFunction &CGF) override {
8017 PrivatizeDevicePointers = true;
8018 }
8019 };
8020 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
8021
8022 auto &&CodeGen = [&](CodeGenFunction &CGF, PrePostActionTy &Action) {
8023 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
8024 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
8025 };
8026
8027 // Codegen that selects whether to generate the privatization code or not.
8028 auto &&PrivCodeGen = [&](CodeGenFunction &CGF, PrePostActionTy &Action) {
8029 RegionCodeGenTy RCG(InnermostCodeGen);
8030 PrivatizeDevicePointers = false;
8031
8032 // Call the pre-action to change the status of PrivatizeDevicePointers if
8033 // needed.
8034 Action.Enter(CGF);
8035
8036 if (PrivatizeDevicePointers) {
8037 OMPPrivateScope PrivateScope(CGF);
8038 // Emit all instances of the use_device_ptr clause.
8039 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
8040 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
8042 for (const auto *C : S.getClausesOfKind<OMPUseDeviceAddrClause>())
8043 CGF.EmitOMPUseDeviceAddrClause(*C, PrivateScope,
8045 (void)PrivateScope.Privatize();
8046 RCG(CGF);
8047 } else {
8048 // If we don't have target devices, don't bother emitting the data
8049 // mapping code.
8050 std::optional<OpenMPDirectiveKind> CaptureRegion;
8051 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
8052 // Emit helper decls of the use_device_ptr/use_device_addr clauses.
8053 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
8054 for (const Expr *E : C->varlist()) {
8055 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
8056 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(D))
8057 CGF.EmitVarDecl(*OED);
8058 }
8059 for (const auto *C : S.getClausesOfKind<OMPUseDeviceAddrClause>())
8060 for (const Expr *E : C->varlist()) {
8061 const Decl *D = getBaseDecl(E);
8062 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(D))
8063 CGF.EmitVarDecl(*OED);
8064 }
8065 } else {
8066 CaptureRegion = OMPD_unknown;
8067 }
8068
8069 OMPLexicalScope Scope(CGF, S, CaptureRegion);
8070 RCG(CGF);
8071 }
8072 };
8073
8074 // Forward the provided action to the privatization codegen.
8075 RegionCodeGenTy PrivRCG(PrivCodeGen);
8076 PrivRCG.setAction(Action);
8077
8078 // Notwithstanding the body of the region is emitted as inlined directive,
8079 // we don't use an inline scope as changes in the references inside the
8080 // region are expected to be visible outside, so we do not privative them.
8081 OMPLexicalScope Scope(CGF, S);
8082 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
8083 PrivRCG);
8084 };
8085
8087
8088 // If we don't have target devices, don't bother emitting the data mapping
8089 // code.
8090 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
8091 RCG(*this);
8092 return;
8093 }
8094
8095 // Check if we have any if clause associated with the directive.
8096 const Expr *IfCond = nullptr;
8097 if (const auto *C = S.getSingleClause<OMPIfClause>())
8098 IfCond = C->getCondition();
8099
8100 // Check if we have any device clause associated with the directive.
8101 const Expr *Device = nullptr;
8102 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
8103 Device = C->getDevice();
8104
8105 // Set the action to signal privatization of device pointers.
8106 RCG.setAction(PrivAction);
8107
8108 // Emit region code.
8109 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
8110 Info);
8111}
8112
8114 const OMPTargetEnterDataDirective &S) {
8115 // If we don't have target devices, don't bother emitting the data mapping
8116 // code.
8117 if (CGM.getLangOpts().OMPTargetTriples.empty())
8118 return;
8119
8120 // Check if we have any if clause associated with the directive.
8121 const Expr *IfCond = nullptr;
8122 if (const auto *C = S.getSingleClause<OMPIfClause>())
8123 IfCond = C->getCondition();
8124
8125 // Check if we have any device clause associated with the directive.
8126 const Expr *Device = nullptr;
8127 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
8128 Device = C->getDevice();
8129
8130 OMPLexicalScope Scope(*this, S, OMPD_task);
8131 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
8132}
8133
8135 const OMPTargetExitDataDirective &S) {
8136 // If we don't have target devices, don't bother emitting the data mapping
8137 // code.
8138 if (CGM.getLangOpts().OMPTargetTriples.empty())
8139 return;
8140
8141 // Check if we have any if clause associated with the directive.
8142 const Expr *IfCond = nullptr;
8143 if (const auto *C = S.getSingleClause<OMPIfClause>())
8144 IfCond = C->getCondition();
8145
8146 // Check if we have any device clause associated with the directive.
8147 const Expr *Device = nullptr;
8148 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
8149 Device = C->getDevice();
8150
8151 OMPLexicalScope Scope(*this, S, OMPD_task);
8152 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
8153}
8154
8157 PrePostActionTy &Action) {
8158 // Get the captured statement associated with the 'parallel' region.
8159 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
8160 Action.Enter(CGF);
8161 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
8162 Action.Enter(CGF);
8163 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
8164 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
8165 CGF.EmitOMPPrivateClause(S, PrivateScope);
8166 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
8167 (void)PrivateScope.Privatize();
8168 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
8170 // TODO: Add support for clauses.
8171 CGF.EmitStmt(CS->getCapturedStmt());
8172 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
8173 };
8174 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
8177 [](CodeGenFunction &) { return nullptr; });
8178}
8179
8181 CodeGenModule &CGM, StringRef ParentName,
8182 const OMPTargetParallelDirective &S) {
8183 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
8184 emitTargetParallelRegion(CGF, S, Action);
8185 };
8186 llvm::Function *Fn;
8187 llvm::Constant *Addr;
8188 // Emit target region as a standalone region.
8189 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
8190 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
8191 assert(Fn && Addr && "Target device function emission failed.");
8192}
8193
8195 const OMPTargetParallelDirective &S) {
8196 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
8197 emitTargetParallelRegion(CGF, S, Action);
8198 };
8200}
8201
8204 PrePostActionTy &Action) {
8205 Action.Enter(CGF);
8206 // Emit directive as a combined directive that consists of two implicit
8207 // directives: 'parallel' with 'for' directive.
8208 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
8209 Action.Enter(CGF);
8211 CGF, OMPD_target_parallel_for, S.hasCancel());
8214 };
8215 emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen,
8217}
8218
8220 CodeGenModule &CGM, StringRef ParentName,
8222 // Emit SPMD target parallel for region as a standalone region.
8223 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
8224 emitTargetParallelForRegion(CGF, S, Action);
8225 };
8226 llvm::Function *Fn;
8227 llvm::Constant *Addr;
8228 // Emit target region as a standalone region.
8229 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
8230 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
8231 assert(Fn && Addr && "Target device function emission failed.");
8232}
8233
8236 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
8237 emitTargetParallelForRegion(CGF, S, Action);
8238 };
8240}
8241
8242static void
8245 PrePostActionTy &Action) {
8246 Action.Enter(CGF);
8247 // Emit directive as a combined directive that consists of two implicit
8248 // directives: 'parallel' with 'for' directive.
8249 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
8250 Action.Enter(CGF);
8253 };
8254 emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen,
8256}
8257
8259 CodeGenModule &CGM, StringRef ParentName,
8261 // Emit SPMD target parallel for region as a standalone region.
8262 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
8263 emitTargetParallelForSimdRegion(CGF, S, Action);
8264 };
8265 llvm::Function *Fn;
8266 llvm::Constant *Addr;
8267 // Emit target region as a standalone region.
8268 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
8269 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
8270 assert(Fn && Addr && "Target device function emission failed.");
8271}
8272
8275 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
8276 emitTargetParallelForSimdRegion(CGF, S, Action);
8277 };
8279}
8280
8281/// Emit a helper variable and return corresponding lvalue.
8282static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
8283 const ImplicitParamDecl *PVD,
8285 const auto *VDecl = cast<VarDecl>(Helper->getDecl());
8286 Privates.addPrivate(VDecl, CGF.GetAddrOfLocalVar(PVD));
8287}
8288
8290 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
8291 // Emit outlined function for task construct.
8292 const CapturedStmt *CS = S.getCapturedStmt(OMPD_taskloop);
8293 Address CapturedStruct = Address::invalid();
8294 {
8295 OMPLexicalScope Scope(*this, S, OMPD_taskloop, /*EmitPreInitStmt=*/false);
8296 CapturedStruct = GenerateCapturedStmtArgument(*CS);
8297 }
8298 CanQualType SharedsTy =
8300 const Expr *IfCond = nullptr;
8301 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
8302 if (C->getNameModifier() == OMPD_unknown ||
8303 C->getNameModifier() == OMPD_taskloop) {
8304 IfCond = C->getCondition();
8305 break;
8306 }
8307 }
8308
8310 // Check if taskloop must be emitted without taskgroup.
8311 Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
8312 // TODO: Check if we should emit tied or untied task.
8313 Data.Tied = true;
8314 // Set scheduling for taskloop
8315 if (const auto *Clause = S.getSingleClause<OMPGrainsizeClause>()) {
8316 // grainsize clause
8317 Data.Schedule.setInt(/*IntVal=*/false);
8318 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
8319 Data.HasModifier =
8320 (Clause->getModifier() == OMPC_GRAINSIZE_strict) ? true : false;
8321 } else if (const auto *Clause = S.getSingleClause<OMPNumTasksClause>()) {
8322 // num_tasks clause
8323 Data.Schedule.setInt(/*IntVal=*/true);
8324 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
8325 Data.HasModifier =
8326 (Clause->getModifier() == OMPC_NUMTASKS_strict) ? true : false;
8327 }
8328
8329 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
8330 // if (PreCond) {
8331 // for (IV in 0..LastIteration) BODY;
8332 // <Final counter/linear vars updates>;
8333 // }
8334 //
8335
8336 // Emit: if (PreCond) - begin.
8337 // If the condition constant folds and can be elided, avoid emitting the
8338 // whole loop.
8339 bool CondConstant;
8340 llvm::BasicBlock *ContBlock = nullptr;
8341 OMPLoopScope PreInitScope(CGF, S);
8342 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
8343 if (!CondConstant)
8344 return;
8345 } else {
8346 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
8347 ContBlock = CGF.createBasicBlock("taskloop.if.end");
8348 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
8349 CGF.getProfileCount(&S));
8350 CGF.EmitBlock(ThenBlock);
8351 CGF.incrementProfileCounter(&S);
8352 }
8353
8354 (void)CGF.EmitOMPLinearClauseInit(S);
8355
8356 OMPPrivateScope LoopScope(CGF);
8357 // Emit helper vars inits.
8358 enum { LowerBound = 5, UpperBound, Stride, LastIter };
8359 auto *I = CS->getCapturedDecl()->param_begin();
8360 auto *LBP = std::next(I, LowerBound);
8361 auto *UBP = std::next(I, UpperBound);
8362 auto *STP = std::next(I, Stride);
8363 auto *LIP = std::next(I, LastIter);
8365 LoopScope);
8367 LoopScope);
8368 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
8370 LoopScope);
8371 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
8372 CGF.EmitOMPLinearClause(S, LoopScope);
8373 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
8374 (void)LoopScope.Privatize();
8375 // Emit the loop iteration variable.
8376 const Expr *IVExpr = S.getIterationVariable();
8377 const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
8378 CGF.EmitVarDecl(*IVDecl);
8379 CGF.EmitIgnoredExpr(S.getInit());
8380
8381 // Emit the iterations count variable.
8382 // If it is not a variable, Sema decided to calculate iterations count on
8383 // each iteration (e.g., it is foldable into a constant).
8384 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
8385 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
8386 // Emit calculation of the iterations count.
8387 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
8388 }
8389
8390 {
8391 OMPLexicalScope Scope(CGF, S, OMPD_taskloop, /*EmitPreInitStmt=*/false);
8393 CGF, S,
8394 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
8395 if (isOpenMPSimdDirective(S.getDirectiveKind()))
8396 CGF.EmitOMPSimdInit(S);
8397 },
8398 [&S, &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) {
8399 CGF.EmitOMPInnerLoop(
8400 S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
8401 [&S](CodeGenFunction &CGF) {
8402 emitOMPLoopBodyWithStopPoint(CGF, S,
8403 CodeGenFunction::JumpDest());
8404 },
8405 [](CodeGenFunction &) {});
8406 });
8407 }
8408 // Emit: if (PreCond) - end.
8409 if (ContBlock) {
8410 CGF.EmitBranch(ContBlock);
8411 CGF.EmitBlock(ContBlock, true);
8412 }
8413 // Emit final copy of the lastprivate variables if IsLastIter != 0.
8414 if (HasLastprivateClause) {
8415 CGF.EmitOMPLastprivateClauseFinal(
8416 S, isOpenMPSimdDirective(S.getDirectiveKind()),
8417 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
8418 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
8419 (*LIP)->getType(), S.getBeginLoc())));
8420 }
8421 LoopScope.restoreMap();
8422 CGF.EmitOMPLinearClauseFinal(S, [LIP, &S](CodeGenFunction &CGF) {
8423 return CGF.Builder.CreateIsNotNull(
8424 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
8425 (*LIP)->getType(), S.getBeginLoc()));
8426 });
8427 };
8428 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
8429 IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn,
8430 const OMPTaskDataTy &Data) {
8431 auto &&CodeGen = [&S, OutlinedFn, SharedsTy, CapturedStruct, IfCond,
8432 &Data](CodeGenFunction &CGF, PrePostActionTy &) {
8433 OMPLoopScope PreInitScope(CGF, S);
8434 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getBeginLoc(), S,
8435 OutlinedFn, SharedsTy,
8436 CapturedStruct, IfCond, Data);
8437 };
8438 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
8439 CodeGen);
8440 };
8441 if (Data.Nogroup) {
8442 EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen, Data);
8443 } else {
8444 CGM.getOpenMPRuntime().emitTaskgroupRegion(
8445 *this,
8446 [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF,
8447 PrePostActionTy &Action) {
8448 Action.Enter(CGF);
8449 CGF.EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen,
8450 Data);
8451 },
8452 S.getBeginLoc());
8453 }
8454}
8455
8461
8463 const OMPTaskLoopSimdDirective &S) {
8464 auto LPCRegion =
8466 OMPLexicalScope Scope(*this, S);
8468}
8469
8471 const OMPMasterTaskLoopDirective &S) {
8472 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
8473 Action.Enter(CGF);
8475 };
8476 auto LPCRegion =
8478 OMPLexicalScope Scope(*this, S, std::nullopt, /*EmitPreInitStmt=*/false);
8479 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc());
8480}
8481
8483 const OMPMaskedTaskLoopDirective &S) {
8484 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
8485 Action.Enter(CGF);
8487 };
8488 auto LPCRegion =
8490 OMPLexicalScope Scope(*this, S, std::nullopt, /*EmitPreInitStmt=*/false);
8491 CGM.getOpenMPRuntime().emitMaskedRegion(*this, CodeGen, S.getBeginLoc());
8492}
8493
8496 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
8497 Action.Enter(CGF);
8499 };
8500 auto LPCRegion =
8502 OMPLexicalScope Scope(*this, S);
8503 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc());
8504}
8505
8508 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
8509 Action.Enter(CGF);
8511 };
8512 auto LPCRegion =
8514 OMPLexicalScope Scope(*this, S);
8515 CGM.getOpenMPRuntime().emitMaskedRegion(*this, CodeGen, S.getBeginLoc());
8516}
8517
8520 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
8521 auto &&TaskLoopCodeGen = [&S](CodeGenFunction &CGF,
8522 PrePostActionTy &Action) {
8523 Action.Enter(CGF);
8525 };
8526 OMPLexicalScope Scope(CGF, S, OMPD_parallel, /*EmitPreInitStmt=*/false);
8527 CGM.getOpenMPRuntime().emitMasterRegion(CGF, TaskLoopCodeGen,
8528 S.getBeginLoc());
8529 };
8530 auto LPCRegion =
8532 emitCommonOMPParallelDirective(*this, S, OMPD_master_taskloop, CodeGen,
8534}
8535
8538 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
8539 auto &&TaskLoopCodeGen = [&S](CodeGenFunction &CGF,
8540 PrePostActionTy &Action) {
8541 Action.Enter(CGF);
8543 };
8544 OMPLexicalScope Scope(CGF, S, OMPD_parallel, /*EmitPreInitStmt=*/false);
8545 CGM.getOpenMPRuntime().emitMaskedRegion(CGF, TaskLoopCodeGen,
8546 S.getBeginLoc());
8547 };
8548 auto LPCRegion =
8550 emitCommonOMPParallelDirective(*this, S, OMPD_masked_taskloop, CodeGen,
8552}
8553
8556 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
8557 auto &&TaskLoopCodeGen = [&S](CodeGenFunction &CGF,
8558 PrePostActionTy &Action) {
8559 Action.Enter(CGF);
8561 };
8562 OMPLexicalScope Scope(CGF, S, OMPD_parallel, /*EmitPreInitStmt=*/false);
8563 CGM.getOpenMPRuntime().emitMasterRegion(CGF, TaskLoopCodeGen,
8564 S.getBeginLoc());
8565 };
8566 auto LPCRegion =
8568 emitCommonOMPParallelDirective(*this, S, OMPD_master_taskloop_simd, CodeGen,
8570}
8571
8574 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
8575 auto &&TaskLoopCodeGen = [&S](CodeGenFunction &CGF,
8576 PrePostActionTy &Action) {
8577 Action.Enter(CGF);
8579 };
8580 OMPLexicalScope Scope(CGF, S, OMPD_parallel, /*EmitPreInitStmt=*/false);
8581 CGM.getOpenMPRuntime().emitMaskedRegion(CGF, TaskLoopCodeGen,
8582 S.getBeginLoc());
8583 };
8584 auto LPCRegion =
8586 emitCommonOMPParallelDirective(*this, S, OMPD_masked_taskloop_simd, CodeGen,
8588}
8589
8590// Generate the instructions for '#pragma omp target update' directive.
8592 const OMPTargetUpdateDirective &S) {
8593 // If we don't have target devices, don't bother emitting the data mapping
8594 // code.
8595 if (CGM.getLangOpts().OMPTargetTriples.empty())
8596 return;
8597
8598 // Check if we have any if clause associated with the directive.
8599 const Expr *IfCond = nullptr;
8600 if (const auto *C = S.getSingleClause<OMPIfClause>())
8601 IfCond = C->getCondition();
8602
8603 // Check if we have any device clause associated with the directive.
8604 const Expr *Device = nullptr;
8605 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
8606 Device = C->getDevice();
8607
8608 OMPLexicalScope Scope(*this, S, OMPD_task);
8609 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
8610}
8611
8613 const OMPGenericLoopDirective &S) {
8614 // Always expect a bind clause on the loop directive. It it wasn't
8615 // in the source, it should have been added in sema.
8616
8618 if (const auto *C = S.getSingleClause<OMPBindClause>())
8619 BindKind = C->getBindKind();
8620
8621 switch (BindKind) {
8622 case OMPC_BIND_parallel: // for
8623 return emitOMPForDirective(S, *this, CGM, /*HasCancel=*/false);
8624 case OMPC_BIND_teams: // distribute
8625 return emitOMPDistributeDirective(S, *this, CGM);
8626 case OMPC_BIND_thread: // simd
8627 return emitOMPSimdDirective(S, *this, CGM);
8628 case OMPC_BIND_unknown:
8629 break;
8630 }
8631
8632 // Unimplemented, just inline the underlying statement for now.
8633 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
8634 // Emit the loop iteration variable.
8635 const Stmt *CS =
8636 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
8637 const auto *ForS = dyn_cast<ForStmt>(CS);
8638 if (ForS && !isa<DeclStmt>(ForS->getInit())) {
8639 OMPPrivateScope LoopScope(CGF);
8640 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
8641 (void)LoopScope.Privatize();
8642 CGF.EmitStmt(CS);
8643 LoopScope.restoreMap();
8644 } else {
8645 CGF.EmitStmt(CS);
8646 }
8647 };
8648 OMPLexicalScope Scope(*this, S, OMPD_unknown);
8649 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_loop, CodeGen);
8650}
8651
8653 const OMPLoopDirective &S) {
8654 // Emit combined directive as if its constituent constructs are 'parallel'
8655 // and 'for'.
8656 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
8657 Action.Enter(CGF);
8658 emitOMPCopyinClause(CGF, S);
8659 (void)emitWorksharingDirective(CGF, S, /*HasCancel=*/false);
8660 };
8661 {
8662 auto LPCRegion =
8664 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
8666 }
8667 // Check for outer lastprivate conditional update.
8669}
8670
8673 // To be consistent with current behavior of 'target teams loop', emit
8674 // 'teams loop' as if its constituent constructs are 'teams' and 'distribute'.
8675 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
8677 };
8678
8679 // Emit teams region as a standalone region.
8680 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
8681 PrePostActionTy &Action) {
8682 Action.Enter(CGF);
8683 OMPPrivateScope PrivateScope(CGF);
8684 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
8685 (void)PrivateScope.Privatize();
8686 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
8687 CodeGenDistribute);
8688 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
8689 };
8690 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
8692 [](CodeGenFunction &) { return nullptr; });
8693}
8694
8695#ifndef NDEBUG
8697 std::string StatusMsg,
8698 const OMPExecutableDirective &D) {
8699 bool IsDevice = CGF.CGM.getLangOpts().OpenMPIsTargetDevice;
8700 if (IsDevice)
8701 StatusMsg += ": DEVICE";
8702 else
8703 StatusMsg += ": HOST";
8704 SourceLocation L = D.getBeginLoc();
8705 auto &SM = CGF.getContext().getSourceManager();
8706 PresumedLoc PLoc = SM.getPresumedLoc(L);
8707 const char *FileName = PLoc.isValid() ? PLoc.getFilename() : nullptr;
8708 unsigned LineNo =
8709 PLoc.isValid() ? PLoc.getLine() : SM.getExpansionLineNumber(L);
8710 llvm::dbgs() << StatusMsg << ": " << FileName << ": " << LineNo << "\n";
8711}
8712#endif
8713
8715 CodeGenFunction &CGF, PrePostActionTy &Action,
8717 Action.Enter(CGF);
8718 // Emit 'teams loop' as if its constituent constructs are 'distribute,
8719 // 'parallel, and 'for'.
8720 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
8722 S.getDistInc());
8723 };
8724
8725 // Emit teams region as a standalone region.
8726 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
8727 PrePostActionTy &Action) {
8728 Action.Enter(CGF);
8729 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
8730 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
8731 (void)PrivateScope.Privatize();
8733 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
8734 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
8735 };
8736 DEBUG_WITH_TYPE(TTL_CODEGEN_TYPE,
8738 CGF, TTL_CODEGEN_TYPE " as parallel for", S));
8739 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for,
8740 CodeGenTeams);
8742 [](CodeGenFunction &) { return nullptr; });
8743}
8744
8746 CodeGenFunction &CGF, PrePostActionTy &Action,
8748 Action.Enter(CGF);
8749 // Emit 'teams loop' as if its constituent construct is 'distribute'.
8750 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
8752 };
8753
8754 // Emit teams region as a standalone region.
8755 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
8756 PrePostActionTy &Action) {
8757 Action.Enter(CGF);
8758 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
8759 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
8760 (void)PrivateScope.Privatize();
8762 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
8763 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
8764 };
8765 DEBUG_WITH_TYPE(TTL_CODEGEN_TYPE,
8767 CGF, TTL_CODEGEN_TYPE " as distribute", S));
8768 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute, CodeGen);
8770 [](CodeGenFunction &) { return nullptr; });
8771}
8772
8775 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
8776 if (S.canBeParallelFor())
8778 else
8780 };
8782}
8783
8785 CodeGenModule &CGM, StringRef ParentName,
8787 // Emit SPMD target parallel loop region as a standalone region.
8788 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
8789 if (S.canBeParallelFor())
8791 else
8793 };
8794 llvm::Function *Fn;
8795 llvm::Constant *Addr;
8796 // Emit target region as a standalone region.
8797 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
8798 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
8799 assert(Fn && Addr &&
8800 "Target device function emission failed for 'target teams loop'.");
8801}
8802
8805 PrePostActionTy &Action) {
8806 Action.Enter(CGF);
8807 // Emit as 'parallel for'.
8808 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
8809 Action.Enter(CGF);
8811 CGF, OMPD_target_parallel_loop, /*hasCancel=*/false);
8814 };
8815 emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen,
8817}
8818
8820 CodeGenModule &CGM, StringRef ParentName,
8822 // Emit target parallel loop region as a standalone region.
8823 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
8825 };
8826 llvm::Function *Fn;
8827 llvm::Constant *Addr;
8828 // Emit target region as a standalone region.
8829 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
8830 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
8831 assert(Fn && Addr && "Target device function emission failed.");
8832}
8833
8834/// Emit combined directive 'target parallel loop' as if its constituent
8835/// constructs are 'target', 'parallel', and 'for'.
8838 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
8840 };
8842}
8843
8845 const OMPExecutableDirective &D) {
8846 if (const auto *SD = dyn_cast<OMPScanDirective>(&D)) {
8848 return;
8849 }
8850 if (!D.hasAssociatedStmt() || !D.getAssociatedStmt())
8851 return;
8852 auto &&CodeGen = [&D](CodeGenFunction &CGF, PrePostActionTy &Action) {
8853 OMPPrivateScope GlobalsScope(CGF);
8854 if (isOpenMPTaskingDirective(D.getDirectiveKind())) {
8855 // Capture global firstprivates to avoid crash.
8856 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
8857 for (const Expr *Ref : C->varlist()) {
8858 const auto *DRE = cast<DeclRefExpr>(Ref->IgnoreParenImpCasts());
8859 if (!DRE)
8860 continue;
8861 const auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
8862 if (!VD || VD->hasLocalStorage())
8863 continue;
8864 if (!CGF.LocalDeclMap.count(VD)) {
8865 LValue GlobLVal = CGF.EmitLValue(Ref);
8866 GlobalsScope.addPrivate(VD, GlobLVal.getAddress());
8867 }
8868 }
8869 }
8870 }
8871 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
8872 (void)GlobalsScope.Privatize();
8873 ParentLoopDirectiveForScanRegion ScanRegion(CGF, D);
8875 } else {
8876 if (const auto *LD = dyn_cast<OMPLoopDirective>(&D)) {
8877 for (const Expr *E : LD->counters()) {
8878 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
8879 if (!VD->hasLocalStorage() && !CGF.LocalDeclMap.count(VD)) {
8880 LValue GlobLVal = CGF.EmitLValue(E);
8881 GlobalsScope.addPrivate(VD, GlobLVal.getAddress());
8882 }
8883 if (isa<OMPCapturedExprDecl>(VD)) {
8884 // Emit only those that were not explicitly referenced in clauses.
8885 if (!CGF.LocalDeclMap.count(VD))
8886 CGF.EmitVarDecl(*VD);
8887 }
8888 }
8889 for (const auto *C : D.getClausesOfKind<OMPOrderedClause>()) {
8890 if (!C->getNumForLoops())
8891 continue;
8892 for (unsigned I = LD->getLoopsNumber(),
8893 E = C->getLoopNumIterations().size();
8894 I < E; ++I) {
8895 if (const auto *VD = dyn_cast<OMPCapturedExprDecl>(
8896 cast<DeclRefExpr>(C->getLoopCounter(I))->getDecl())) {
8897 // Emit only those that were not explicitly referenced in clauses.
8898 if (!CGF.LocalDeclMap.count(VD))
8899 CGF.EmitVarDecl(*VD);
8900 }
8901 }
8902 }
8903 }
8904 (void)GlobalsScope.Privatize();
8905 CGF.EmitStmt(D.getInnermostCapturedStmt()->getCapturedStmt());
8906 }
8907 };
8908 if (D.getDirectiveKind() == OMPD_atomic ||
8909 D.getDirectiveKind() == OMPD_critical ||
8910 D.getDirectiveKind() == OMPD_section ||
8911 D.getDirectiveKind() == OMPD_master ||
8912 D.getDirectiveKind() == OMPD_masked ||
8913 D.getDirectiveKind() == OMPD_unroll ||
8914 D.getDirectiveKind() == OMPD_assume) {
8915 EmitStmt(D.getAssociatedStmt());
8916 } else {
8917 auto LPCRegion =
8919 OMPSimdLexicalScope Scope(*this, D);
8920 CGM.getOpenMPRuntime().emitInlinedDirective(
8921 *this,
8922 isOpenMPSimdDirective(D.getDirectiveKind()) ? OMPD_simd
8923 : D.getDirectiveKind(),
8924 CodeGen);
8925 }
8926 // Check for outer lastprivate conditional update.
8928}
8929
8931 for (const auto *C : S.getClausesOfKind<OMPHoldsClause>()) {
8932 const Expr *E = C->getExpr();
8933 assert(E && "holds clause requires an expression");
8934 if (!E->HasSideEffects(getContext()))
8935 Builder.CreateAssumption(EvaluateExprAsBool(E));
8936 }
8937 EmitStmt(S.getAssociatedStmt());
8938}
Defines the clang::ASTContext interface.
#define V(N, I)
static bool isAllocatableDecl(const VarDecl *VD)
static const VarDecl * getBaseDecl(const Expr *Ref, const DeclRefExpr *&DE)
static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S, PrePostActionTy &Action)
static void emitOMPSimdRegion(CodeGenFunction &CGF, const OMPLoopDirective &S, PrePostActionTy &Action)
static const VarDecl * getBaseDecl(const Expr *Ref)
static void emitTargetTeamsGenericLoopRegionAsParallel(CodeGenFunction &CGF, PrePostActionTy &Action, const OMPTargetTeamsGenericLoopDirective &S)
static void emitOMPAtomicReadExpr(CodeGenFunction &CGF, llvm::AtomicOrdering AO, const Expr *X, const Expr *V, SourceLocation Loc)
static void emitOMPAtomicCaptureExpr(CodeGenFunction &CGF, llvm::AtomicOrdering AO, bool IsPostfixUpdate, const Expr *V, const Expr *X, const Expr *E, const Expr *UE, bool IsXLHSInRHSPart, SourceLocation Loc)
static void emitScanBasedDirective(CodeGenFunction &CGF, const OMPLoopDirective &S, llvm::function_ref< llvm::Value *(CodeGenFunction &)> NumIteratorsGen, llvm::function_ref< void(CodeGenFunction &)> FirstGen, llvm::function_ref< void(CodeGenFunction &)> SecondGen)
Emits the code for the directive with inscan reductions.
static void emitSimpleAtomicStore(CodeGenFunction &CGF, llvm::AtomicOrdering AO, LValue LVal, RValue RVal)
static bool isSupportedByOpenMPIRBuilder(const OMPTaskgroupDirective &T)
static Address castValueFromUintptr(CodeGenFunction &CGF, SourceLocation Loc, QualType DstType, StringRef Name, LValue AddrLV)
static bool canEmitGPUFusedDistSchedule(const CodeGenModule &CGM, const OMPLoopDirective &S, OpenMPDirectiveKind DKind)
Whether a combined distribute parallel for may use the fused distr_static_chunk + static_chunkone sch...
static void emitDistributeParallelForDistributeInnerBoundParams(CodeGenFunction &CGF, const OMPExecutableDirective &S, llvm::SmallVectorImpl< llvm::Value * > &CapturedVars)
static void emitScanBasedDirectiveFinals(CodeGenFunction &CGF, const OMPLoopDirective &S, llvm::function_ref< llvm::Value *(CodeGenFunction &)> NumIteratorsGen)
Copies final inscan reductions values to the original variables.
static void checkForLastprivateConditionalUpdate(CodeGenFunction &CGF, const OMPExecutableDirective &S)
static std::pair< LValue, LValue > emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S)
The following two functions generate expressions for the loop lower and upper bounds in case of stati...
static void emitTargetParallelForRegion(CodeGenFunction &CGF, const OMPTargetParallelForDirective &S, PrePostActionTy &Action)
static llvm::Function * emitOutlinedFunctionPrologueAggregate(CodeGenFunction &CGF, FunctionArgList &Args, llvm::MapVector< const Decl *, std::pair< const VarDecl *, Address > > &LocalAddrs, llvm::DenseMap< const Decl *, std::pair< const Expr *, llvm::Value * > > &VLASizes, llvm::Value *&CXXThisValue, llvm::Value *&ContextV, const CapturedStmt &CS, SourceLocation Loc, StringRef FunctionName)
static LValue EmitOMPHelperVar(CodeGenFunction &CGF, const DeclRefExpr *Helper)
Emit a helper variable and return corresponding lvalue.
static void emitOMPAtomicUpdateExpr(CodeGenFunction &CGF, llvm::AtomicOrdering AO, const Expr *X, const Expr *E, const Expr *UE, bool IsXLHSInRHSPart, SourceLocation Loc)
static llvm::Value * convertToScalarValue(CodeGenFunction &CGF, RValue Val, QualType SrcType, QualType DestType, SourceLocation Loc)
static llvm::Function * emitOutlinedOrderedFunction(CodeGenModule &CGM, const CapturedStmt *S, const OMPExecutableDirective &D)
static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S, const Expr *Cond, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock, uint64_t TrueCount)
static std::pair< bool, RValue > emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X, RValue Update, BinaryOperatorKind BO, llvm::AtomicOrdering AO, bool IsXLHSInRHSPart)
static std::pair< LValue, LValue > emitDistributeParallelForInnerBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S)
static void emitTargetTeamsGenericLoopRegionAsDistribute(CodeGenFunction &CGF, PrePostActionTy &Action, const OMPTargetTeamsGenericLoopDirective &S)
static void emitTargetParallelRegion(CodeGenFunction &CGF, const OMPTargetParallelDirective &S, PrePostActionTy &Action)
static std::pair< llvm::Value *, llvm::Value * > emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S, Address LB, Address UB)
When dealing with dispatch schedules (e.g.
static void emitMaster(CodeGenFunction &CGF, const OMPExecutableDirective &S)
static void emitRestoreIP(CodeGenFunction &CGF, const T *C, llvm::OpenMPIRBuilder::InsertPointTy AllocaIP, llvm::OpenMPIRBuilder &OMPBuilder)
static void emitCommonOMPTargetDirective(CodeGenFunction &CGF, const OMPExecutableDirective &S, const RegionCodeGenTy &CodeGen)
static void emitSimdlenSafelenClause(CodeGenFunction &CGF, const OMPExecutableDirective &D)
static void emitAlignedClause(CodeGenFunction &CGF, const OMPExecutableDirective &D)
static bool isSimdSupportedByOpenMPIRBuilder(const OMPLoopDirective &S)
static void emitCommonOMPParallelDirective(CodeGenFunction &CGF, const OMPExecutableDirective &S, OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen, const CodeGenBoundParametersTy &CodeGenBoundParameters)
static void applyConservativeSimdOrderedDirective(const Stmt &AssociatedStmt, LoopInfoStack &LoopStack)
static bool emitWorksharingDirective(CodeGenFunction &CGF, const OMPLoopDirective &S, bool HasCancel)
static void emitPostUpdateForReductionClause(CodeGenFunction &CGF, const OMPExecutableDirective &D, const llvm::function_ref< llvm::Value *(CodeGenFunction &)> CondGen)
static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc, const unsigned IVSize, const bool IVSigned)
static void emitTargetTeamsLoopCodegenStatus(CodeGenFunction &CGF, std::string StatusMsg, const OMPExecutableDirective &D)
static bool isForSupportedByOpenMPIRBuilder(const OMPLoopDirective &S, bool HasCancel)
static RValue emitSimpleAtomicLoad(CodeGenFunction &CGF, llvm::AtomicOrdering AO, LValue LVal, SourceLocation Loc)
static std::pair< llvm::Value *, llvm::Value * > emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S, Address LB, Address UB)
if the 'for' loop has a dispatch schedule (e.g.
static bool hasOrderedBlockAssocDirective(const Stmt *S)
static void emitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind, llvm::AtomicOrdering AO, llvm::AtomicOrdering FailAO, bool IsPostfixUpdate, const Expr *X, const Expr *V, const Expr *R, const Expr *E, const Expr *UE, const Expr *D, const Expr *CE, bool IsXLHSInRHSPart, bool IsFailOnly, SourceLocation Loc)
#define TTL_CODEGEN_TYPE
static CodeGenFunction::ComplexPairTy convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType, QualType DestType, SourceLocation Loc)
static ImplicitParamDecl * createImplicitFirstprivateForType(ASTContext &C, OMPTaskDataTy &Data, QualType Ty, CapturedDecl *CD, SourceLocation Loc)
static EmittedClosureTy emitCapturedStmtFunc(CodeGenFunction &ParentCGF, const CapturedStmt *S)
Emit a captured statement and return the function as well as its captured closure context.
static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF, const OMPLoopDirective &S, CodeGenFunction::JumpDest LoopExit)
static void emitOMPDistributeDirective(const OMPLoopDirective &S, CodeGenFunction &CGF, CodeGenModule &CGM)
static void emitOMPCopyinClause(CodeGenFunction &CGF, const OMPExecutableDirective &S)
static void emitTargetTeamsDistributeParallelForRegion(CodeGenFunction &CGF, const OMPTargetTeamsDistributeParallelForDirective &S, PrePostActionTy &Action)
static llvm::CallInst * emitCapturedStmtCall(CodeGenFunction &ParentCGF, EmittedClosureTy Cap, llvm::ArrayRef< llvm::Value * > Args)
Emit a call to a previously captured closure.
static void emitMasked(CodeGenFunction &CGF, const OMPExecutableDirective &S)
static void emitBody(CodeGenFunction &CGF, const Stmt *S, const Stmt *NextLoop, int MaxLevel, int Level=0)
static void emitOMPForDirective(const OMPLoopDirective &S, CodeGenFunction &CGF, CodeGenModule &CGM, bool HasCancel)
static void emitEmptyBoundParameters(CodeGenFunction &, const OMPExecutableDirective &, llvm::SmallVectorImpl< llvm::Value * > &)
static void emitTargetParallelForSimdRegion(CodeGenFunction &CGF, const OMPTargetParallelForSimdDirective &S, PrePostActionTy &Action)
static void emitOMPSimdDirective(const OMPLoopDirective &S, CodeGenFunction &CGF, CodeGenModule &CGM)
static void emitOMPAtomicCompareExpr(CodeGenFunction &CGF, llvm::AtomicOrdering AO, llvm::AtomicOrdering FailAO, const Expr *X, const Expr *V, const Expr *R, const Expr *E, const Expr *D, const Expr *CE, bool IsXBinopExpr, bool IsPostfixUpdate, bool IsFailOnly, SourceLocation Loc)
std::pair< llvm::Function *, llvm::Value * > EmittedClosureTy
static OpenMPDirectiveKind getEffectiveDirectiveKind(const OMPExecutableDirective &S)
static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action, const OMPTargetTeamsDirective &S)
static void buildDependences(const OMPExecutableDirective &S, OMPTaskDataTy &Data)
static RValue convertToType(CodeGenFunction &CGF, RValue Value, QualType SourceType, QualType ResType, SourceLocation Loc)
static void emitScanBasedDirectiveDecls(CodeGenFunction &CGF, const OMPLoopDirective &S, llvm::function_ref< llvm::Value *(CodeGenFunction &)> NumIteratorsGen)
Emits internal temp array declarations for the directive with inscan reductions.
static void emitTargetTeamsDistributeParallelForSimdRegion(CodeGenFunction &CGF, const OMPTargetTeamsDistributeParallelForSimdDirective &S, PrePostActionTy &Action)
static void emitTargetTeamsDistributeSimdRegion(CodeGenFunction &CGF, PrePostActionTy &Action, const OMPTargetTeamsDistributeSimdDirective &S)
static llvm::MapVector< llvm::Value *, llvm::Value * > GetAlignedMapping(const OMPLoopDirective &S, CodeGenFunction &CGF)
static llvm::omp::ScheduleKind convertClauseKindToSchedKind(OpenMPScheduleClauseKind ScheduleClauseKind)
static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper, const ImplicitParamDecl *PVD, CodeGenFunction::OMPPrivateScope &Privates)
Emit a helper variable and return corresponding lvalue.
static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF, const OMPExecutableDirective &S, OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen)
static void emitTargetParallelGenericLoopRegion(CodeGenFunction &CGF, const OMPTargetParallelGenericLoopDirective &S, PrePostActionTy &Action)
static QualType getCanonicalParamType(ASTContext &C, QualType T)
static void emitCommonSimdLoop(CodeGenFunction &CGF, const OMPLoopDirective &S, const RegionCodeGenTy &SimdInitGen, const RegionCodeGenTy &BodyCodeGen)
static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty, const Twine &Name, llvm::Value *Init=nullptr)
static void emitOMPAtomicWriteExpr(CodeGenFunction &CGF, llvm::AtomicOrdering AO, const Expr *X, const Expr *E, SourceLocation Loc)
static llvm::Function * emitOutlinedFunctionPrologue(CodeGenFunction &CGF, FunctionArgList &Args, llvm::MapVector< const Decl *, std::pair< const VarDecl *, Address > > &LocalAddrs, llvm::DenseMap< const Decl *, std::pair< const Expr *, llvm::Value * > > &VLASizes, llvm::Value *&CXXThisValue, const FunctionOptions &FO)
static void emitInnerParallelForWhenCombined(CodeGenFunction &CGF, const OMPLoopDirective &S, CodeGenFunction::JumpDest LoopExit)
static void emitTargetTeamsDistributeRegion(CodeGenFunction &CGF, PrePostActionTy &Action, const OMPTargetTeamsDistributeDirective &S)
This file defines OpenMP nodes for declarative directives.
TokenType getType() const
Returns the token's type, e.g.
FormatToken * Next
The next token in the unwrapped line.
static const Decl * getCanonicalDecl(const Decl *D)
#define X(type, name)
Definition Value.h:97
This file defines OpenMP AST classes for clauses.
Defines some OpenMP-specific enums and functions.
Defines the PrettyStackTraceEntry class, which is used to make crashes give more contextual informati...
Defines the SourceManager interface.
This file defines OpenMP AST classes for executable directives and clauses.
This represents clause 'aligned' in the 'pragma omp ...' directives.
This represents 'pragma omp atomic' directive.
Expr * getR()
Get 'r' part of the associated expression/statement.
Expr * getX()
Get 'x' part of the associated expression/statement.
bool isFailOnly() const
Return true if 'v' is updated only when the condition is evaluated false (compare capture only).
bool isPostfixUpdate() const
Return true if 'v' expression must be updated to original value of 'x', false if 'v' must be updated ...
Expr * getExpr()
Get 'expr' part of the associated expression/statement.
Expr * getV()
Get 'v' part of the associated expression/statement.
bool isXLHSInRHSPart() const
Return true if helper update expression has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' and...
Expr * getD()
Get 'd' part of the associated expression/statement.
Expr * getUpdateExpr()
Get helper expression of the form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 'OpaqueValueExp...
Expr * getCondExpr()
Get the 'cond' part of the source atomic expression.
This represents 'pragma omp barrier' directive.
This represents 'bind' clause in the 'pragma omp ...' directives.
This represents 'pragma omp cancel' directive.
OpenMPDirectiveKind getCancelRegion() const
Get cancellation region for the current cancellation point.
This represents 'pragma omp cancellation point' directive.
OpenMPDirectiveKind getCancelRegion() const
Get cancellation region for the current cancellation point.
The base class for all transformation directives of canonical loop sequences (currently only 'fuse')
This represents clause 'copyin' in the 'pragma omp ...' directives.
This represents clause 'copyprivate' in the 'pragma omp ...' directives.
This represents 'pragma omp critical' directive.
DeclarationNameInfo getDirectiveName() const
Return name of the directive.
This represents implicit clause 'depend' for the 'pragma omp task' directive.
This represents implicit clause 'depobj' for the 'pragma omp depobj' directive. This clause does not ...
This represents 'pragma omp depobj' directive.
This represents 'destroy' clause in the 'pragma omp depobj' directive or the 'pragma omp interop' dir...
This represents 'device' clause in the 'pragma omp ...' directive.
This represents 'dist_schedule' clause in the 'pragma omp ...' directive.
This represents 'pragma omp distribute' directive.
This represents 'pragma omp distribute parallel for' composite directive.
This represents 'pragma omp distribute parallel for simd' composite directive.
This represents 'pragma omp distribute simd' composite directive.
This represents the 'doacross' clause for the 'pragma omp ordered' directive.
This represents 'pragma omp error' directive.
This represents 'filter' clause in the 'pragma omp ...' directive.
This represents implicit clause 'flush' for the 'pragma omp flush' directive. This clause does not ex...
This represents 'pragma omp flush' directive.
This represents 'pragma omp for' directive.
bool hasCancel() const
Return true if current directive has inner cancel directive.
This represents 'pragma omp for simd' directive.
Represents the 'pragma omp fuse' loop transformation directive.
Stmt * getTransformedStmt() const
Gets the associated loops after the transformation.
This represents 'pragma omp loop' directive.
This represents 'grainsize' clause in the 'pragma omp ...' directive.
This represents 'hint' clause in the 'pragma omp ...' directive.
This represents clause 'inclusive' in the 'pragma omp scan' directive.
This represents the 'init' clause in 'pragma omp ...' directives.
Represents the 'pragma omp interchange' loop transformation directive.
Stmt * getTransformedStmt() const
Gets the associated loops after the transformation.
This represents 'pragma omp interop' directive.
This is a common base class for loop directives ('omp simd', 'omp for', 'omp for simd' etc....
Expr * getCombinedUpperBoundVariable() const
Expr * getPreCond() const
Expr * getPrevUpperBoundVariable() const
Expr * getIsLastIterVariable() const
Expr * getCombinedLowerBoundVariable() const
Expr * getCombinedCond() const
Expr * getCombinedInit() const
Expr * getLowerBoundVariable() const
Expr * getCombinedNextLowerBound() const
ArrayRef< Expr * > finals_conditions()
ArrayRef< Expr * > counters()
Expr * getInc() const
ArrayRef< Expr * > private_counters()
Expr * getUpperBoundVariable() const
Expr * getCombinedDistCond() const
Expr * getPrevLowerBoundVariable() const
ArrayRef< Expr * > dependent_inits()
Expr * getNextLowerBound() const
Expr * getDistInc() const
ArrayRef< Expr * > updates()
Expr * getCond() const
Expr * getNextUpperBound() const
Expr * getLastIteration() const
Expr * getEnsureUpperBound() const
Expr * getCalcLastIteration() const
Expr * getCombinedNextUpperBound() const
Expr * getIterationVariable() const
Expr * getStrideVariable() const
Expr * getNumIterations() const
Expr * getInit() const
ArrayRef< Expr * > finals()
Expr * getPrevEnsureUpperBound() const
Expr * getCombinedEnsureUpperBound() const
ArrayRef< Expr * > dependent_counters()
ArrayRef< Expr * > inits()
This represents 'pragma omp masked' directive.
This represents 'pragma omp masked taskloop' directive.
This represents 'pragma omp masked taskloop simd' directive.
This represents 'pragma omp master' directive.
This represents 'pragma omp master taskloop' directive.
This represents 'pragma omp master taskloop simd' directive.
This represents 'pragma omp metadirective' directive.
Stmt * getIfStmt() const
This represents 'nogroup' clause in the 'pragma omp ...' directive.
This represents 'num_tasks' clause in the 'pragma omp ...' directive.
This represents 'num_teams' clause in the 'pragma omp ...' directive.
This represents 'order' clause in the 'pragma omp ...' directive.
This represents block-associated 'pragma omp ordered' directive.
This represents standalone 'pragma omp ordered' directive.
This represents 'pragma omp parallel for' directive.
bool hasCancel() const
Return true if current directive has inner cancel directive.
This represents 'pragma omp parallel for simd' directive.
This represents 'pragma omp parallel masked' directive.
This represents 'pragma omp parallel masked taskloop' directive.
This represents 'pragma omp parallel masked taskloop simd' directive.
This represents 'pragma omp parallel master' directive.
This represents 'pragma omp parallel master taskloop' directive.
This represents 'pragma omp parallel master taskloop simd' directive.
This represents 'pragma omp parallel sections' directive.
This represents 'priority' clause in the 'pragma omp ...' directive.
Represents the 'pragma omp reverse' loop transformation directive.
Stmt * getTransformedStmt() const
Gets/sets the associated loops after the transformation, i.e.
This represents 'simd' clause in the 'pragma omp ...' directive.
This represents 'pragma omp scan' directive.
This represents 'pragma omp scope' directive.
This represents 'pragma omp section' directive.
This represents 'pragma omp sections' directive.
bool hasCancel() const
Return true if current directive has inner cancel directive.
This represents 'pragma omp simd' directive.
This represents 'pragma omp single' directive.
Represents the 'pragma omp split' loop transformation directive.
Stmt * getTransformedStmt() const
Gets/sets the associated loops after the transformation, i.e.
This represents the 'pragma omp stripe' loop transformation directive.
Stmt * getTransformedStmt() const
Gets/sets the associated loops after striping.
This represents 'pragma omp target data' directive.
This represents 'pragma omp target' directive.
This represents 'pragma omp target enter data' directive.
This represents 'pragma omp target exit data' directive.
This represents 'pragma omp target parallel' directive.
This represents 'pragma omp target parallel for' directive.
bool hasCancel() const
Return true if current directive has inner cancel directive.
This represents 'pragma omp target parallel for simd' directive.
This represents 'pragma omp target parallel loop' directive.
This represents 'pragma omp target simd' directive.
This represents 'pragma omp target teams' directive.
This represents 'pragma omp target teams distribute' combined directive.
This represents 'pragma omp target teams distribute parallel for' combined directive.
This represents 'pragma omp target teams distribute parallel for simd' combined directive.
This represents 'pragma omp target teams distribute simd' combined directive.
This represents 'pragma omp target teams loop' directive.
bool canBeParallelFor() const
Return true if current loop directive's associated loop can be a parallel for.
This represents 'pragma omp target update' directive.
This represents 'pragma omp task' directive.
This represents 'pragma omp taskloop' directive.
This represents 'pragma omp taskloop simd' directive.
This represents 'pragma omp taskgroup' directive.
const Expr * getReductionRef() const
Returns reference to the task_reduction return variable.
This represents 'pragma omp taskwait' directive.
This represents 'pragma omp taskyield' directive.
This represents 'pragma omp teams' directive.
This represents 'pragma omp teams distribute' directive.
This represents 'pragma omp teams distribute parallel for' composite directive.
This represents 'pragma omp teams distribute parallel for simd' composite directive.
This represents 'pragma omp teams distribute simd' combined directive.
This represents 'pragma omp teams loop' directive.
This represents 'thread_limit' clause in the 'pragma omp ...' directive.
This represents the 'pragma omp tile' loop transformation directive.
Stmt * getTransformedStmt() const
Gets/sets the associated loops after tiling.
This represents the 'pragma omp unroll' loop transformation directive.
This represents the 'use' clause in 'pragma omp ...' directives.
This represents clause 'use_device_addr' in the 'pragma omp ...' directives.
This represents clause 'use_device_ptr' in the 'pragma omp ...' directives.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:239
SourceManager & getSourceManager()
Definition ASTContext.h:907
TranslationUnitDecl * getTranslationUnitDecl() const
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType VoidPtrTy
IdentifierTable & Idents
Definition ASTContext.h:846
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
QualType getUIntPtrType() const
Return a type compatible with "uintptr_t" (C99 7.18.1.4), as defined by the target.
QualType getIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
getIntTypeForBitwidth - sets integer QualTy according to specified details: bitwidth,...
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
unsigned getOpenMPDefaultSimdAlign(QualType T) const
Get default simd alignment of the specified complete type in bits.
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType getCanonicalTagType(const TagDecl *TD) const
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3800
Represents an attribute applied to a statement.
Definition Stmt.h:2215
ArrayRef< const Attr * > getAttrs() const
Definition Stmt.h:2247
static BinaryOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures)
Definition Expr.cpp:5131
Represents the body of a CapturedStmt, and serves as its DeclContext.
Definition Decl.h:5079
unsigned getNumParams() const
Definition Decl.h:5117
ImplicitParamDecl * getContextParam() const
Retrieve the parameter containing captured variables.
Definition Decl.h:5137
unsigned getContextParamPosition() const
Definition Decl.h:5146
bool isNothrow() const
Definition Decl.cpp:5773
static CapturedDecl * Create(ASTContext &C, DeclContext *DC, unsigned NumParams)
Definition Decl.cpp:5758
param_iterator param_end() const
Retrieve an iterator one past the last parameter decl.
Definition Decl.h:5154
param_iterator param_begin() const
Retrieve an iterator pointing to the first parameter decl.
Definition Decl.h:5152
Stmt * getBody() const override
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
Definition Decl.cpp:5770
ImplicitParamDecl * getParam(unsigned i) const
Definition Decl.h:5119
This captures a statement into a function.
Definition Stmt.h:3949
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.h:4148
CapturedDecl * getCapturedDecl()
Retrieve the outlined function declaration.
Definition Stmt.cpp:1493
child_range children()
Definition Stmt.cpp:1484
const RecordDecl * getCapturedRecordDecl() const
Retrieve the record declaration for captured variables.
Definition Stmt.h:4070
Stmt * getCapturedStmt()
Retrieve the statement being captured.
Definition Stmt.h:4053
capture_init_iterator capture_init_begin()
Retrieve the first initialization argument.
Definition Stmt.h:4126
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.h:4144
capture_init_iterator capture_init_end()
Retrieve the iterator pointing one past the last initialization argument.
Definition Stmt.h:4136
capture_range captures()
Definition Stmt.h:4087
Expr *const * const_capture_init_iterator
Const iterator that walks over the capture initialization arguments.
Definition Stmt.h:4113
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
CharUnits alignmentOfArrayElement(CharUnits elementSize) const
Given that this is the alignment of the first element of an array, return the minimum alignment of an...
Definition CharUnits.h:214
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
CharUnits alignTo(const CharUnits &Align) const
alignTo - Returns the next integer (mod 2**64) that is greater than or equal to this quantity and is ...
Definition CharUnits.h:201
std::string SampleProfileFile
Name of the profile file to use with -fprofile-sample-use.
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
Definition Address.h:128
static Address invalid()
Definition Address.h:176
llvm::Value * emitRawPointer(CodeGenFunction &CGF) const
Return the pointer contained in this class after authenticating it and adding offset to it if necessa...
Definition Address.h:253
CharUnits getAlignment() const
Definition Address.h:194
llvm::Type * getElementType() const
Return the type of the values stored in this address.
Definition Address.h:209
Address withElementType(llvm::Type *ElemTy) const
Return address with different element type, but same pointer and alignment.
Definition Address.h:276
Address withAlignment(CharUnits NewAlignment) const
Return address with different alignment, but same pointer and element type.
Definition Address.h:269
llvm::PointerType * getType() const
Return the type of the pointer value.
Definition Address.h:204
static AggValueSlot ignored()
ignored - Returns an aggregate value slot indicating that the aggregate value is being ignored.
Definition CGValue.h:619
static ApplyDebugLocation CreateDefaultArtificial(CodeGenFunction &CGF, SourceLocation TemporaryLocation)
Apply TemporaryLocation if it is valid.
Address CreatePointerBitCastOrAddrSpaceCast(Address Addr, llvm::Type *Ty, llvm::Type *ElementTy, const llvm::Twine &Name="")
Definition CGBuilder.h:213
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition CGBuilder.h:118
llvm::LoadInst * CreateAlignedLoad(llvm::Type *Ty, llvm::Value *Addr, CharUnits Align, const llvm::Twine &Name="")
Definition CGBuilder.h:138
CGFunctionInfo - Class to encapsulate the information about a function definition.
Manages list of lastprivate conditional decls for the specified directive.
static LastprivateConditionalRAII disable(CodeGenFunction &CGF, const OMPExecutableDirective &S)
Manages list of nontemporal decls for the specified directive.
Struct that keeps all the relevant information that should be kept throughout a 'target data' region.
llvm::DenseMap< const ValueDecl *, llvm::Value * > CaptureDeviceAddrMap
Map between the a declaration of a capture and the corresponding new llvm address where the runtime r...
Manages list of nontemporal decls for the specified directive.
virtual void emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc, const OMPExecutableDirective &D, llvm::Function *TaskFunction, QualType SharedsTy, Address Shareds, const Expr *IfCond, const OMPTaskDataTy &Data)
Emit task region for the task directive.
virtual llvm::Value * emitForNext(CodeGenFunction &CGF, SourceLocation Loc, unsigned IVSize, bool IVSigned, Address IL, Address LB, Address UB, Address ST)
Call __kmpc_dispatch_next( ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter, kmp_int[32|64] *p_lowe...
virtual void emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn, ArrayRef< llvm::Value * > CapturedVars, const Expr *IfCond, llvm::Value *NumThreads, OpenMPNumThreadsClauseModifier NumThreadsModifier=OMPC_NUMTHREADS_unknown, OpenMPSeverityClauseKind Severity=OMPC_SEVERITY_fatal, const Expr *Message=nullptr)
Emits code for parallel or serial call of the OutlinedFn with variables captured in a record which ad...
virtual void emitNumThreadsClause(CodeGenFunction &CGF, llvm::Value *NumThreads, SourceLocation Loc, OpenMPNumThreadsClauseModifier Modifier=OMPC_NUMTHREADS_unknown, OpenMPSeverityClauseKind Severity=OMPC_SEVERITY_fatal, SourceLocation SeverityLoc=SourceLocation(), const Expr *Message=nullptr, SourceLocation MessageLoc=SourceLocation())
Emits call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32global_tid, kmp_int32 num_threads) ...
virtual Address getTaskReductionItem(CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *ReductionsPtr, LValue SharedLVal)
Get the address of void * type of the privatue copy of the reduction item specified by the SharedLVal...
virtual void emitForDispatchDeinit(CodeGenFunction &CGF, SourceLocation Loc)
This is used for non static scheduled types and when the ordered clause is present on the loop constr...
virtual void emitTeamsCall(CodeGenFunction &CGF, const OMPExecutableDirective &D, SourceLocation Loc, llvm::Function *OutlinedFn, ArrayRef< llvm::Value * > CapturedVars)
Emits code for teams call of the OutlinedFn with variables captured in a record which address is stor...
virtual const VarDecl * translateParameter(const FieldDecl *FD, const VarDecl *NativeParam) const
Translates the native parameter of outlined function if this is required for target.
virtual llvm::Function * emitTeamsOutlinedFunction(CodeGenFunction &CGF, const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen)
Emits outlined function for the specified OpenMP teams directive D.
virtual void emitDoacrossInit(CodeGenFunction &CGF, const OMPLoopDirective &D, ArrayRef< Expr * > NumIterations)
Emit initialization for doacross loop nesting support.
virtual void adjustTargetSpecificDataForLambdas(CodeGenFunction &CGF, const OMPExecutableDirective &D) const
Adjust some parameters for the target-based directives, like addresses of the variables captured by r...
virtual Address getParameterAddress(CodeGenFunction &CGF, const VarDecl *NativeParam, const VarDecl *TargetParam) const
Gets the address of the native argument basing on the address of the target-specific parameter.
virtual void emitNumTeamsClause(CodeGenFunction &CGF, const Expr *NumTeams, const Expr *ThreadLimit, SourceLocation Loc)
Emits call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32global_tid, kmp_int32 num_teams,...
virtual llvm::Value * emitTaskReductionInit(CodeGenFunction &CGF, SourceLocation Loc, ArrayRef< const Expr * > LHSExprs, ArrayRef< const Expr * > RHSExprs, const OMPTaskDataTy &Data)
Emit a code for initialization of task reduction clause.
virtual void emitFlush(CodeGenFunction &CGF, ArrayRef< const Expr * > Vars, SourceLocation Loc, llvm::AtomicOrdering AO)
Emit flush of the variables specified in 'omp flush' directive.
virtual void emitProcBindClause(CodeGenFunction &CGF, llvm::omp::ProcBindKind ProcBind, SourceLocation Loc)
Emit call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32global_tid, int proc_bind) to generate...
virtual void emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind Kind, bool EmitChecks=true, bool ForceSimpleCall=false)
Emit an implicit/explicit barrier for OpenMP threads.
virtual void emitDistributeStaticInit(CodeGenFunction &CGF, SourceLocation Loc, OpenMPDistScheduleClauseKind SchedKind, const StaticRTInput &Values)
virtual void emitForStaticFinish(CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind)
Call the appropriate runtime routine to notify that we finished all the work with current loop.
void emitIfClause(CodeGenFunction &CGF, const Expr *Cond, const RegionCodeGenTy &ThenGen, const RegionCodeGenTy &ElseGen)
Emits code for OpenMP 'if' clause using specified CodeGen function.
virtual llvm::Function * emitParallelOutlinedFunction(CodeGenFunction &CGF, const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen)
Emits outlined function for the specified OpenMP parallel directive D.
virtual void emitForStaticInit(CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind, const OpenMPScheduleTy &ScheduleKind, const StaticRTInput &Values)
Call the appropriate runtime routine to initialize it before start of loop.
virtual bool isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind, bool Chunked) const
Check if the specified ScheduleKind is static non-chunked.
virtual void emitMasterRegion(CodeGenFunction &CGF, const RegionCodeGenTy &MasterOpGen, SourceLocation Loc)
Emits a master region.
virtual void emitTaskReductionFixups(CodeGenFunction &CGF, SourceLocation Loc, ReductionCodeGen &RCG, unsigned N)
Required to resolve existing problems in the runtime.
virtual void checkAndEmitLastprivateConditional(CodeGenFunction &CGF, const Expr *LHS)
Checks if the provided LVal is lastprivate conditional and emits the code to update the value of the ...
llvm::OpenMPIRBuilder & getOMPBuilder()
virtual void emitTargetOutlinedFunction(const OMPExecutableDirective &D, StringRef ParentName, llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID, bool IsOffloadEntry, const RegionCodeGenTy &CodeGen)
Emit outilined function for 'target' directive.
virtual void emitForOrderedIterationEnd(CodeGenFunction &CGF, SourceLocation Loc, unsigned IVSize, bool IVSigned)
Call the appropriate runtime routine to notify that we finished iteration of the ordered loop with th...
virtual void checkAndEmitSharedLastprivateConditional(CodeGenFunction &CGF, const OMPExecutableDirective &D, const llvm::DenseSet< CanonicalDeclPtr< const VarDecl > > &IgnoredDecls)
Checks if the lastprivate conditional was updated in inner region and writes the value.
virtual void emitInlinedDirective(CodeGenFunction &CGF, OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen, bool HasCancel=false)
Emit code for the directive that does not require outlining.
virtual bool isStaticChunked(OpenMPScheduleClauseKind ScheduleKind, bool Chunked) const
Check if the specified ScheduleKind is static chunked.
virtual void emitTargetCall(CodeGenFunction &CGF, const OMPExecutableDirective &D, llvm::Function *OutlinedFn, llvm::Value *OutlinedFnID, const Expr *IfCond, llvm::PointerIntPair< const Expr *, 2, OpenMPDeviceClauseModifier > Device, llvm::function_ref< llvm::Value *(CodeGenFunction &CGF, const OMPLoopDirective &D)> SizeEmitter)
Emit the target offloading code associated with D.
virtual bool isDynamic(OpenMPScheduleClauseKind ScheduleKind) const
Check if the specified ScheduleKind is dynamic.
virtual void emitMaskedRegion(CodeGenFunction &CGF, const RegionCodeGenTy &MaskedOpGen, SourceLocation Loc, const Expr *Filter=nullptr)
Emits a masked region.
virtual void emitForDispatchInit(CodeGenFunction &CGF, SourceLocation Loc, const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned, bool Ordered, const DispatchRTInput &DispatchValues)
Call the appropriate runtime routine to initialize it before start of loop.
Address getAllocatedAddress() const
Returns the raw, allocated address, which is not necessarily the address of the object itself.
API for captured statement code generation.
virtual const FieldDecl * lookup(const VarDecl *VD) const
Lookup the captured field decl for a variable.
RAII for correct setting/restoring of CapturedStmtInfo.
LValue getReferenceLValue(CodeGenFunction &CGF, const Expr *RefExpr) const
void ForceCleanup()
Force the emission of cleanups now, instead of waiting until this object is destroyed.
RAII for preserving necessary info during inlined region body codegen.
RAII for preserving necessary info during Outlined region body codegen.
Controls insertion of cancellation exit blocks in worksharing constructs.
Save/restore original map of previously emitted local vars in case when we need to duplicate emission...
The class used to assign some variables some temporarily addresses.
bool apply(CodeGenFunction &CGF)
Applies new addresses to the list of the variables.
void restore(CodeGenFunction &CGF)
Restores original addresses of the variables.
bool setVarAddr(CodeGenFunction &CGF, const VarDecl *LocalVD, Address TempAddr)
Sets the address of the variable LocalVD to be TempAddr in function CGF.
The scope used to remap some variables as private in the OpenMP loop body (or other captured region e...
void restoreMap()
Restore all mapped variables w/o clean up.
bool Privatize()
Privatizes local variables previously registered as private.
bool addPrivate(const VarDecl *LocalVD, Address Addr)
Registers LocalVD variable as a private with Addr as the address of the corresponding private variabl...
An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
Enters a new scope for capturing cleanups, all of which will be executed once the scope is exited.
void ForceCleanup(std::initializer_list< llvm::Value ** > ValuesToReload={})
Force the emission of cleanups now, instead of waiting until this object is destroyed.
bool requiresCleanups() const
Determine whether this scope requires any cleanups.
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
void EmitOMPParallelMaskedTaskLoopDirective(const OMPParallelMaskedTaskLoopDirective &S)
void EmitOMPParallelMaskedDirective(const OMPParallelMaskedDirective &S)
void EmitOMPTaskyieldDirective(const OMPTaskyieldDirective &S)
void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock, uint64_t TrueCount, Stmt::Likelihood LH=Stmt::LH_None, const Expr *ConditionalOp=nullptr, const VarDecl *ConditionalDecl=nullptr)
EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g.
void EmitOMPLastprivateClauseFinal(const OMPExecutableDirective &D, bool NoFinals, llvm::Value *IsLastIterCond=nullptr)
Emit final copying of lastprivate values to original variables at the end of the worksharing or simd ...
void processInReduction(const OMPExecutableDirective &S, OMPTaskDataTy &Data, CodeGenFunction &CGF, const CapturedStmt *CS, OMPPrivateScope &Scope)
JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target)
The given basic block lies in the current EH scope, but may be a target of a potentially scope-crossi...
void EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S)
void emitOMPSimpleStore(LValue LVal, RValue RVal, QualType RValTy, SourceLocation Loc)
static void EmitOMPTargetParallelDeviceFunction(CodeGenModule &CGM, StringRef ParentName, const OMPTargetParallelDirective &S)
void EmitOMPCanonicalLoop(const OMPCanonicalLoop *S)
Emit an OMPCanonicalLoop using the OpenMPIRBuilder.
void EmitOMPGenericLoopDirective(const OMPGenericLoopDirective &S)
void EmitOMPScanDirective(const OMPScanDirective &S)
static bool hasScalarEvaluationKind(QualType T)
llvm::function_ref< std::pair< llvm::Value *, llvm::Value * >(CodeGenFunction &, const OMPExecutableDirective &S, Address LB, Address UB)> CodeGenDispatchBoundsTy
LValue InitCapturedStruct(const CapturedStmt &S)
Definition CGStmt.cpp:3433
CGCapturedStmtInfo * CapturedStmtInfo
void EmitOMPDistributeDirective(const OMPDistributeDirective &S)
void EmitOMPParallelForDirective(const OMPParallelForDirective &S)
void EmitOMPMasterDirective(const OMPMasterDirective &S)
void EmitOMPParallelMasterTaskLoopSimdDirective(const OMPParallelMasterTaskLoopSimdDirective &S)
void EmitOMPSimdInit(const OMPLoopDirective &D)
Helpers for the OpenMP loop directives.
const OMPExecutableDirective * OMPParentLoopDirectiveForScan
Parent loop-based directive for scan directive.
void EmitOMPFlushDirective(const OMPFlushDirective &S)
static void EmitOMPTargetDeviceFunction(CodeGenModule &CGM, StringRef ParentName, const OMPTargetDirective &S)
Emit device code for the target directive.
bool EmitOMPFirstprivateClause(const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope)
void EmitOMPTaskgroupDirective(const OMPTaskgroupDirective &S)
void EmitOMPTargetTeamsDistributeParallelForSimdDirective(const OMPTargetTeamsDistributeParallelForSimdDirective &S)
static void EmitOMPTargetTeamsDeviceFunction(CodeGenModule &CGM, StringRef ParentName, const OMPTargetTeamsDirective &S)
Emit device code for the target teams directive.
void EmitOMPReductionClauseInit(const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope, bool ForInscan=false)
Emit initial code for reduction variables.
void EmitOMPDistributeSimdDirective(const OMPDistributeSimdDirective &S)
void EmitAutoVarDecl(const VarDecl &D)
EmitAutoVarDecl - Emit an auto variable declaration.
Definition CGDecl.cpp:1356
static void EmitOMPTargetTeamsDistributeDeviceFunction(CodeGenModule &CGM, StringRef ParentName, const OMPTargetTeamsDistributeDirective &S)
Emit device code for the target teams distribute directive.
llvm::Function * GenerateOpenMPCapturedStmtFunctionAggregate(const CapturedStmt &S, const OMPExecutableDirective &D)
void EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S)
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
void EmitOMPTargetParallelForDirective(const OMPTargetParallelForDirective &S)
const LangOptions & getLangOpts() const
LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
AutoVarEmission EmitAutoVarAlloca(const VarDecl &var)
EmitAutoVarAlloca - Emit the alloca and debug information for a local variable.
Definition CGDecl.cpp:1490
void EmitAtomicUpdate(LValue LVal, llvm::AtomicOrdering AO, const llvm::function_ref< RValue(RValue)> &UpdateOp, bool IsVolatile)
Address EmitLoadOfPointer(Address Ptr, const PointerType *PtrTy, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
Load a pointer with type PtrTy stored at address Ptr.
Definition CGExpr.cpp:3442
void EmitOMPSplitDirective(const OMPSplitDirective &S)
void EmitBranchThroughCleanup(JumpDest Dest)
EmitBranchThroughCleanup - Emit a branch from the current insert block through the normal cleanup han...
void EmitOMPReductionClauseFinal(const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind)
Emit final update of reduction values to original variables at the end of the directive.
void EmitOMPLoopBody(const OMPLoopDirective &D, JumpDest LoopExit)
Helper for the OpenMP loop directives.
void EmitOMPScopeDirective(const OMPScopeDirective &S)
const Decl * CurCodeDecl
CurCodeDecl - This is the inner-most code context, which includes blocks.
llvm::AssertingVH< llvm::Instruction > AllocaInsertPt
AllocaInsertPoint - This is an instruction in the entry block before which we prefer to insert alloca...
void EmitAggregateAssign(LValue Dest, LValue Src, QualType EltTy)
Emit an aggregate assignment.
JumpDest ReturnBlock
ReturnBlock - Unified return block.
void EmitOMPTargetTeamsDistributeSimdDirective(const OMPTargetTeamsDistributeSimdDirective &S)
const llvm::function_ref< void(CodeGenFunction &, llvm::Function *, const OMPTaskDataTy &)> TaskGenTy
llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Location)
Converts Location to a DebugLoc, if debug information is enabled.
bool EmitOMPCopyinClause(const OMPExecutableDirective &D)
Emit code for copyin clause in D directive.
void EmitOMPLinearClause(const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope)
Emit initial code for linear clauses.
llvm::BasicBlock * OMPBeforeScanBlock
void EmitOMPInterchangeDirective(const OMPInterchangeDirective &S)
void EmitOMPPrivateLoopCounters(const OMPLoopDirective &S, OMPPrivateScope &LoopScope)
Emit initial code for loop counters of loop-based directives.
void GenerateOpenMPCapturedVars(const CapturedStmt &S, SmallVectorImpl< llvm::Value * > &CapturedVars)
void EmitOMPDepobjDirective(const OMPDepobjDirective &S)
void EmitOMPMetaDirective(const OMPMetaDirective &S)
void EmitOMPCriticalDirective(const OMPCriticalDirective &S)
void EmitIgnoredExpr(const Expr *E)
EmitIgnoredExpr - Emit an expression in a context which ignores the result.
Definition CGExpr.cpp:260
void EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S)
RValue EmitLoadOfLValue(LValue V, SourceLocation Loc)
EmitLoadOfLValue - Given an expression that represents a value lvalue, this method emits the address ...
Definition CGExpr.cpp:2538
void EmitOMPCancelDirective(const OMPCancelDirective &S)
void EmitOMPBarrierDirective(const OMPBarrierDirective &S)
llvm::Value * EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy, QualType DstTy, SourceLocation Loc)
Emit a conversion from the specified complex type to the specified destination type,...
bool EmitOMPWorksharingLoop(const OMPLoopDirective &S, Expr *EUB, const CodeGenLoopBoundsTy &CodeGenLoopBounds, const CodeGenDispatchBoundsTy &CGDispatchBounds)
Emit code for the worksharing loop-based directive.
LValue EmitOMPSharedLValue(const Expr *E)
Emits the lvalue for the expression with possibly captured variable.
llvm::CanonicalLoopInfo * EmitOMPCollapsedCanonicalLoopNest(const Stmt *S, int Depth)
Emit the Stmt S and return its topmost canonical loop, if any.
void EmitOMPSectionsDirective(const OMPSectionsDirective &S)
void StartFunction(GlobalDecl GD, QualType RetTy, llvm::Function *Fn, const CGFunctionInfo &FnInfo, const FunctionArgList &Args, SourceLocation Loc=SourceLocation(), SourceLocation StartLoc=SourceLocation())
Emit code for the start of a function.
void EmitOMPInteropDirective(const OMPInteropDirective &S)
void EmitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &S)
void EmitOMPTargetParallelDirective(const OMPTargetParallelDirective &S)
void EmitOMPCopy(QualType OriginalType, Address DestAddr, Address SrcAddr, const VarDecl *DestVD, const VarDecl *SrcVD, const Expr *Copy)
Emit proper copying of data from one variable to another.
llvm::Value * EvaluateExprAsBool(const Expr *E)
EvaluateExprAsBool - Perform the usual unary conversions on the specified expression and compare the ...
Definition CGExpr.cpp:241
JumpDest getOMPCancelDestination(OpenMPDirectiveKind Kind)
void EmitOMPTargetParallelForSimdDirective(const OMPTargetParallelForSimdDirective &S)
void EmitOMPTargetParallelGenericLoopDirective(const OMPTargetParallelGenericLoopDirective &S)
Emit combined directive 'target parallel loop' as if its constituent constructs are 'target',...
void EmitOMPUseDeviceAddrClause(const OMPUseDeviceAddrClause &C, OMPPrivateScope &PrivateScope, const llvm::DenseMap< const ValueDecl *, llvm::Value * > CaptureDeviceAddrMap)
void EmitOMPTeamsDistributeParallelForSimdDirective(const OMPTeamsDistributeParallelForSimdDirective &S)
void EmitOMPMaskedDirective(const OMPMaskedDirective &S)
llvm::Value * emitArrayLength(const ArrayType *arrayType, QualType &baseType, Address &addr)
emitArrayLength - Compute the length of an array, even if it's a VLA, and drill down to the base elem...
void EmitOMPAggregateAssign(Address DestAddr, Address SrcAddr, QualType OriginalType, const llvm::function_ref< void(Address, Address)> CopyGen)
Perform element by element copying of arrays with type OriginalType from SrcAddr to DestAddr using co...
bool HaveInsertPoint() const
HaveInsertPoint - True if an insertion point is defined.
void EmitOMPTeamsDistributeSimdDirective(const OMPTeamsDistributeSimdDirective &S)
RValue EmitAtomicLoad(LValue LV, SourceLocation SL, AggValueSlot Slot=AggValueSlot::ignored())
void EmitOMPOrderedBlockAssocDirective(const OMPOrderedBlockAssocDirective &S)
void EmitOMPDistributeLoop(const OMPLoopDirective &S, const CodeGenLoopTy &CodeGenLoop, Expr *IncExpr)
Emit code for the distribute loop-based directive.
void EmitOMPMasterTaskLoopDirective(const OMPMasterTaskLoopDirective &S)
void EmitOMPReverseDirective(const OMPReverseDirective &S)
llvm::Value * getTypeSize(QualType Ty)
Returns calculated size of the specified type.
void EmitOMPCancellationPointDirective(const OMPCancellationPointDirective &S)
void EmitOMPTargetTeamsDistributeParallelForDirective(const OMPTargetTeamsDistributeParallelForDirective &S)
void EmitOMPMaskedTaskLoopDirective(const OMPMaskedTaskLoopDirective &S)
llvm::function_ref< std::pair< LValue, LValue >(CodeGenFunction &, const OMPExecutableDirective &S)> CodeGenLoopBoundsTy
void EmitOMPTargetExitDataDirective(const OMPTargetExitDataDirective &S)
RawAddress CreateMemTempWithoutCast(QualType T, const Twine &Name="tmp")
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen without...
Definition CGExpr.cpp:233
void EmitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective &S)
void EmitOMPMaskedTaskLoopSimdDirective(const OMPMaskedTaskLoopSimdDirective &S)
std::pair< bool, RValue > EmitOMPAtomicSimpleUpdateExpr(LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart, llvm::AtomicOrdering AO, SourceLocation Loc, const llvm::function_ref< RValue(RValue)> CommonGen)
Emit atomic update code for constructs: X = X BO E or X = E BO E.
VlaSizePair getVLASize(const VariableArrayType *vla)
Returns an LLVM value that corresponds to the size, in non-variably-sized elements,...
void EmitOMPParallelDirective(const OMPParallelDirective &S)
void EmitOMPTaskDirective(const OMPTaskDirective &S)
void EmitOMPMasterTaskLoopSimdDirective(const OMPMasterTaskLoopSimdDirective &S)
void EmitOMPDistributeParallelForDirective(const OMPDistributeParallelForDirective &S)
void EmitOMPAssumeDirective(const OMPAssumeDirective &S)
int ExpectedOMPLoopDepth
Number of nested loop to be consumed by the last surrounding loop-associated directive.
void EmitOMPPrivateClause(const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope)
void EmitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective &S)
void EmitStopPoint(const Stmt *S)
EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
Definition CGStmt.cpp:48
void EmitOMPTargetUpdateDirective(const OMPTargetUpdateDirective &S)
llvm::Value * EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty, SourceLocation Loc, AlignmentSource Source=AlignmentSource::Type, bool isNontemporal=false)
EmitLoadOfScalar - Load a scalar value from an address, taking care to appropriately convert from the...
void EmitOMPTargetTeamsGenericLoopDirective(const OMPTargetTeamsGenericLoopDirective &S)
void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit)
EmitStoreOfComplex - Store a complex number into the specified l-value.
const Decl * CurFuncDecl
CurFuncDecl - Holds the Decl for the current outermost non-closure context.
void EmitAutoVarCleanups(const AutoVarEmission &emission)
Definition CGDecl.cpp:2225
void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit=false)
EmitStoreThroughLValue - Store the specified rvalue into the specified lvalue, where both are guarant...
Definition CGExpr.cpp:2790
SmallVector< llvm::CanonicalLoopInfo *, 4 > OMPLoopNestStack
List of recently emitted OMPCanonicalLoops.
void EmitOMPTeamsDistributeParallelForDirective(const OMPTeamsDistributeParallelForDirective &S)
llvm::AtomicRMWInst * emitAtomicRMWInst(llvm::AtomicRMWInst::BinOp Op, Address Addr, llvm::Value *Val, llvm::AtomicOrdering Order=llvm::AtomicOrdering::SequentiallyConsistent, llvm::SyncScope::ID SSID=llvm::SyncScope::System, const AtomicExpr *AE=nullptr)
Emit an atomicrmw instruction, and applying relevant metadata when applicable.
void EmitOMPFuseDirective(const OMPFuseDirective &S)
void EmitOMPTargetTeamsDistributeDirective(const OMPTargetTeamsDistributeDirective &S)
void EmitOMPUseDevicePtrClause(const OMPUseDevicePtrClause &C, OMPPrivateScope &PrivateScope, const llvm::DenseMap< const ValueDecl *, llvm::Value * > CaptureDeviceAddrMap)
RValue EmitAnyExpr(const Expr *E, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
EmitAnyExpr - Emit code to compute the specified expression which can have any type.
Definition CGExpr.cpp:282
void EmitStmt(const Stmt *S, ArrayRef< const Attr * > Attrs={})
EmitStmt - Emit the code for the statement.
Definition CGStmt.cpp:58
llvm::DenseMap< const ValueDecl *, FieldDecl * > LambdaCaptureFields
void EmitOMPParallelForSimdDirective(const OMPParallelForSimdDirective &S)
llvm::Type * ConvertTypeForMem(QualType T)
void EmitOMPInnerLoop(const OMPExecutableDirective &S, bool RequiresCleanup, const Expr *LoopCond, const Expr *IncExpr, const llvm::function_ref< void(CodeGenFunction &)> BodyGen, const llvm::function_ref< void(CodeGenFunction &)> PostIncGen)
Emit inner loop of the worksharing/simd construct.
void EmitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective &S)
static void EmitOMPTargetTeamsDistributeParallelForDeviceFunction(CodeGenModule &CGM, StringRef ParentName, const OMPTargetTeamsDistributeParallelForDirective &S)
void EmitOMPTargetDirective(const OMPTargetDirective &S)
static void EmitOMPTargetParallelForSimdDeviceFunction(CodeGenModule &CGM, StringRef ParentName, const OMPTargetParallelForSimdDirective &S)
Emit device code for the target parallel for simd directive.
static TypeEvaluationKind getEvaluationKind(QualType T)
getEvaluationKind - Return the TypeEvaluationKind of QualType T.
void EmitOMPTeamsDirective(const OMPTeamsDirective &S)
void EmitSimpleOMPExecutableDirective(const OMPExecutableDirective &D)
Emit simple code for OpenMP directives in Simd-only mode.
void EmitOMPErrorDirective(const OMPErrorDirective &S)
void EmitOMPTargetTaskBasedDirective(const OMPExecutableDirective &S, const RegionCodeGenTy &BodyGen, OMPTargetDataInfo &InputInfo)
void EmitOMPParallelMaskedTaskLoopSimdDirective(const OMPParallelMaskedTaskLoopSimdDirective &S)
void EmitOMPTargetTeamsDirective(const OMPTargetTeamsDirective &S)
void EmitOMPTargetDataDirective(const OMPTargetDataDirective &S)
Address GenerateCapturedStmtArgument(const CapturedStmt &S)
Definition CGStmt.cpp:3474
bool EmitOMPLastprivateClauseInit(const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope)
Emit initial code for lastprivate variables.
static void EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(CodeGenModule &CGM, StringRef ParentName, const OMPTargetTeamsDistributeParallelForSimdDirective &S)
Emit device code for the target teams distribute parallel for simd directive.
void EmitBranch(llvm::BasicBlock *Block)
EmitBranch - Emit a branch to the specified basic block from the current insert block,...
Definition CGStmt.cpp:671
llvm::Function * GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S, const OMPExecutableDirective &D)
void EmitOMPSimdDirective(const OMPSimdDirective &S)
RawAddress CreateMemTemp(QualType T, const Twine &Name="tmp", RawAddress *Alloca=nullptr)
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen and cas...
Definition CGExpr.cpp:197
Address EmitLoadOfReference(LValue RefLVal, LValueBaseInfo *PointeeBaseInfo=nullptr, TBAAAccessInfo *PointeeTBAAInfo=nullptr)
Definition CGExpr.cpp:3400
void EmitOMPParallelGenericLoopDirective(const OMPLoopDirective &S)
void EmitOMPTargetSimdDirective(const OMPTargetSimdDirective &S)
void EmitOMPTeamsGenericLoopDirective(const OMPTeamsGenericLoopDirective &S)
void EmitOMPOrderedStandaloneDirective(const OMPOrderedStandaloneDirective &S)
void EmitVarDecl(const VarDecl &D)
EmitVarDecl - Emit a local variable declaration.
Definition CGDecl.cpp:211
bool EmitOMPLinearClauseInit(const OMPLoopDirective &D)
Emit initial code for linear variables.
static void EmitOMPTargetParallelGenericLoopDeviceFunction(CodeGenModule &CGM, StringRef ParentName, const OMPTargetParallelGenericLoopDirective &S)
Emit device code for the target parallel loop directive.
void EmitOMPUnrollDirective(const OMPUnrollDirective &S)
void EmitOMPStripeDirective(const OMPStripeDirective &S)
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type,...
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
void EmitOMPSingleDirective(const OMPSingleDirective &S)
void FinishFunction(SourceLocation EndLoc=SourceLocation())
FinishFunction - Complete IR generation of the current function.
llvm::function_ref< void(CodeGenFunction &, SourceLocation, const unsigned, const bool)> CodeGenOrderedTy
void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit)
llvm::Value * EmitFromMemory(llvm::Value *Value, QualType Ty)
EmitFromMemory - Change a scalar value from its memory representation to its value representation.
Definition CGExpr.cpp:2297
static void EmitOMPTargetSimdDeviceFunction(CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S)
Emit device code for the target simd directive.
llvm::Function * GenerateCapturedStmtFunction(const CapturedStmt &S)
Creates the outlined function for a CapturedStmt.
Definition CGStmt.cpp:3481
static void EmitOMPTargetParallelForDeviceFunction(CodeGenModule &CGM, StringRef ParentName, const OMPTargetParallelForDirective &S)
Emit device code for the target parallel for directive.
uint64_t getProfileCount(const Stmt *S)
Get the profiler's count for the given statement.
Address GetAddrOfLocalVar(const VarDecl *VD)
GetAddrOfLocalVar - Return the address of a local variable.
bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result, bool AllowLabels=false)
ConstantFoldsToSimpleInteger - If the specified expression does not fold to a constant,...
static void EmitOMPTargetTeamsGenericLoopDeviceFunction(CodeGenModule &CGM, StringRef ParentName, const OMPTargetTeamsGenericLoopDirective &S)
Emit device code for the target teams loop directive.
void EmitOMPTileDirective(const OMPTileDirective &S)
void EmitDecl(const Decl &D, bool EvaluateConditionDecl=false)
EmitDecl - Emit a declaration.
Definition CGDecl.cpp:52
void EmitOMPAtomicDirective(const OMPAtomicDirective &S)
std::pair< llvm::Value *, llvm::Value * > ComplexPairTy
ConstantEmission tryEmitAsConstant(const DeclRefExpr *RefExpr)
Try to emit a reference to the given value without producing it as an l-value.
Definition CGExpr.cpp:1960
LValue EmitLValue(const Expr *E, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitLValue - Emit code to compute a designator that specifies the location of the expression.
Definition CGExpr.cpp:1733
void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst)
Store of global named registers are always calls to intrinsics.
Definition CGExpr.cpp:3240
void EmitOMPParallelMasterTaskLoopDirective(const OMPParallelMasterTaskLoopDirective &S)
void EmitOMPDistributeParallelForSimdDirective(const OMPDistributeParallelForSimdDirective &S)
void EmitOMPSectionDirective(const OMPSectionDirective &S)
void EnsureInsertPoint()
EnsureInsertPoint - Ensure that an insertion point is defined so that emitted IR has a place to go.
void EmitOMPForSimdDirective(const OMPForSimdDirective &S)
llvm::LLVMContext & getLLVMContext()
void incrementProfileCounter(const Stmt *S, llvm::Value *StepV=nullptr)
Increment the profiler's counter for the given statement by StepV.
void emitAlignmentAssumption(llvm::Value *PtrValue, QualType Ty, SourceLocation Loc, SourceLocation AssumptionLoc, llvm::Value *Alignment, llvm::Value *OffsetValue=nullptr)
static void EmitOMPTargetTeamsDistributeSimdDeviceFunction(CodeGenModule &CGM, StringRef ParentName, const OMPTargetTeamsDistributeSimdDirective &S)
Emit device code for the target teams distribute simd directive.
llvm::function_ref< void(CodeGenFunction &, const OMPLoopDirective &, JumpDest)> CodeGenLoopTy
llvm::Value * EmitScalarConversion(llvm::Value *Src, QualType SrcTy, QualType DstTy, SourceLocation Loc)
Emit a conversion from the specified type to the specified destination type, both of which are LLVM s...
bool isTrivialInitializer(const Expr *Init)
Determine whether the given initializer is trivial in the sense that it requires no code to be genera...
Definition CGDecl.cpp:1830
void EmitOMPParallelMasterDirective(const OMPParallelMasterDirective &S)
void EmitOMPTaskBasedDirective(const OMPExecutableDirective &S, const OpenMPDirectiveKind CapturedRegion, const RegionCodeGenTy &BodyGen, const TaskGenTy &TaskGen, OMPTaskDataTy &Data)
void EmitStoreOfScalar(llvm::Value *Value, Address Addr, bool Volatile, QualType Ty, AlignmentSource Source=AlignmentSource::Type, bool isInit=false, bool isNontemporal=false)
EmitStoreOfScalar - Store a scalar value to an address, taking care to appropriately convert from the...
void EmitOMPForDirective(const OMPForDirective &S)
void EmitOMPLinearClauseFinal(const OMPLoopDirective &D, const llvm::function_ref< llvm::Value *(CodeGenFunction &)> CondGen)
Emit final code for linear clauses.
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition CGStmt.cpp:651
void EmitExprAsInit(const Expr *init, const ValueDecl *D, LValue lvalue, bool capturedByInit)
EmitExprAsInit - Emits the code necessary to initialize a location in memory with the given initializ...
Definition CGDecl.cpp:2115
void EmitOMPSimdFinal(const OMPLoopDirective &D, const llvm::function_ref< llvm::Value *(CodeGenFunction &)> CondGen)
This class organizes the cross-function state that is used while generating LLVM code.
void SetInternalFunctionAttributes(GlobalDecl GD, llvm::Function *F, const CGFunctionInfo &FI)
Set the attributes on the LLVM function for the given decl and function info.
llvm::Module & getModule() const
DiagnosticsEngine & getDiags() const
const LangOptions & getLangOpts() const
const llvm::DataLayout & getDataLayout() const
CGOpenMPRuntime & getOpenMPRuntime()
Return a reference to the configured OpenMP runtime.
const llvm::Triple & getTriple() const
ASTContext & getContext() const
const CodeGenOptions & getCodeGenOpts() const
StringRef getMangledName(GlobalDecl GD)
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition CGCall.cpp:2051
const CGFunctionInfo & arrangeBuiltinFunctionDeclaration(QualType resultType, const FunctionArgList &args)
A builtin function is a freestanding function using the default C conventions.
Definition CGCall.cpp:780
const CGFunctionInfo & arrangeDeviceKernelCallerDeclaration(QualType resultType, const FunctionArgList &args)
A device kernel caller function is an offload device entry point function with a target device depend...
Definition CGCall.cpp:796
FunctionArgList - Type for representing both the decl and type of parameters to a function.
Definition CGCall.h:378
LValue - This represents an lvalue references.
Definition CGValue.h:183
llvm::Value * getPointer(CodeGenFunction &CGF) const
Address getAddress() const
Definition CGValue.h:373
QualType getType() const
Definition CGValue.h:303
void setAddress(Address address)
Definition CGValue.h:375
A stack of loop information corresponding to loop nesting levels.
Definition CGLoopInfo.h:210
void setVectorizeWidth(unsigned W)
Set the vectorize width for the next loop pushed.
Definition CGLoopInfo.h:280
void setParallel(bool Enable=true)
Set the next pushed loop as parallel.
Definition CGLoopInfo.h:245
void push(llvm::BasicBlock *Header, const llvm::DebugLoc &StartLoc, const llvm::DebugLoc &EndLoc)
Begin a new structured loop.
void setVectorizeEnable(bool Enable=true)
Set the next pushed loop 'vectorize.enable'.
Definition CGLoopInfo.h:248
A basic class for pre|post-action for advanced codegen sequence for OpenMP region.
virtual void Enter(CodeGenFunction &CGF)
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
Definition CGValue.h:42
bool isScalar() const
Definition CGValue.h:64
static RValue get(llvm::Value *V)
Definition CGValue.h:99
static RValue getComplex(llvm::Value *V1, llvm::Value *V2)
Definition CGValue.h:109
bool isAggregate() const
Definition CGValue.h:66
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
Definition CGValue.h:72
bool isComplex() const
Definition CGValue.h:65
std::pair< llvm::Value *, llvm::Value * > getComplexVal() const
getComplexVal - Return the real/imag components of this complex value.
Definition CGValue.h:79
An abstract representation of an aligned address.
Definition Address.h:42
llvm::PointerType * getType() const
Return the type of the pointer value.
Definition Address.h:72
llvm::Value * getPointer() const
Definition Address.h:66
Class intended to support codegen of all kind of the reduction clauses.
LValue getSharedLValue(unsigned N) const
Returns LValue for the reduction item.
void emitAggregateType(CodeGenFunction &CGF, unsigned N)
Emits the code for the variable-modified type, if required.
const VarDecl * getBaseDecl(unsigned N) const
Returns the base declaration of the reduction item.
void emitSharedOrigLValue(CodeGenFunction &CGF, unsigned N)
Emits lvalue for the shared and original reduction item.
void emitInitialization(CodeGenFunction &CGF, unsigned N, Address PrivateAddr, Address SharedAddr, llvm::function_ref< bool(CodeGenFunction &)> DefaultInit)
Performs initialization of the private copy for the reduction item.
Address adjustPrivateAddress(CodeGenFunction &CGF, unsigned N, Address PrivateAddr)
Adjusts PrivatedAddr for using instead of the original variable address in normal operations.
Class provides a way to call simple version of codegen for OpenMP region, or an advanced with possibl...
void setAction(PrePostActionTy &Action) const
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3355
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1752
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2126
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1290
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition Expr.cpp:494
ValueDecl * getDecl()
Definition Expr.h:1358
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1643
decl_range decls()
Definition Stmt.h:1691
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
T * getAttr() const
Definition DeclBase.h:581
SourceLocation getBodyRBrace() const
getBodyRBrace - Gets the right brace of the body, if a body exists.
virtual bool hasBody() const
Returns true if this Decl represents a declaration for a body of code, such as a function or method d...
Definition DeclBase.h:1110
SourceLocation getLocation() const
Definition DeclBase.h:447
bool hasAttr() const
Definition DeclBase.h:585
The name of a declaration.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:832
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
This represents one expression.
Definition Expr.h:113
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3123
Expr * IgnoreImplicitAsWritten() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3115
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition Expr.cpp:3722
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3103
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:145
Represents difference between two FPOptions values.
Represents a member of a struct/union/class.
Definition Decl.h:3295
Represents a function declaration or definition.
Definition Decl.h:2059
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin=false, bool isInlineSpecified=false, bool hasWrittenPrototype=true, ConstexprSpecKind ConstexprKind=ConstexprSpecKind::Unspecified, const AssociatedConstraint &TrailingRequiresClause={})
Definition Decl.h:2303
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:60
One of these records is kept for each identifier that is lexed.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2103
static ImplicitParamDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, ImplicitParamKind ParamKind)
Create implicit parameter.
Definition Decl.cpp:5669
std::vector< llvm::Triple > OMPTargetTriples
Triples of the OpenMP targets that the host code codegen should take into account in order to generat...
Represents a point when we exit a loop.
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:296
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:302
A C++ nested-name-specifier augmented with source location information.
This is a basic class for representing single OpenMP clause.
This represents 'final' clause in the 'pragma omp ...' directive.
Representation of the 'full' clause of the 'pragma omp unroll' directive.
This represents 'if' clause in the 'pragma omp ...' directive.
This represents 'num_threads' clause in the 'pragma omp ...' directive.
Representation of the 'partial' clause of the 'pragma omp unroll' directive.
This represents 'safelen' clause in the 'pragma omp ...' directive.
This represents 'simdlen' clause in the 'pragma omp ...' directive.
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1198
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition Decl.cpp:2945
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3396
Represents an unpacked "presumed" location which can be presented to the user.
const char * getFilename() const
Return the presumed filename of this location.
unsigned getLine() const
Return the presumed line number of this location.
If a crash happens while one of these objects are live, the message is printed out along with the spe...
A (possibly-)qualified type.
Definition TypeBase.h:938
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8603
Represents a struct/union/class.
Definition Decl.h:4460
unsigned getNumFields() const
Returns the number of fields (non-static data members) in this record.
Definition Decl.h:4676
field_range fields() const
Definition Decl.h:4663
field_iterator field_begin() const
Definition Decl.cpp:5342
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3658
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
Encodes a location in the source.
A trivial tuple used to represent a source range.
Stmt - This represents one statement.
Definition Stmt.h:85
child_range children()
Definition Stmt.cpp:304
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
Stmt * IgnoreContainers(bool IgnoreCaptured=false)
Skip no-op (attributed, compound) container stmts and skip captured stmt at the top,...
Definition Stmt.cpp:210
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
bool isArrayType() const
Definition TypeBase.h:8754
bool isPointerType() const
Definition TypeBase.h:8655
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9321
bool isReferenceType() const
Definition TypeBase.h:8679
bool isLValueReferenceType() const
Definition TypeBase.h:8683
bool isAnyComplexType() const
Definition TypeBase.h:8790
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition Type.cpp:2340
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2877
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9307
static UnaryOperator * Create(const ASTContext &C, Expr *input, Opcode opc, QualType type, ExprValueKind VK, ExprObjectKind OK, SourceLocation l, bool CanOverflow, FPOptionsOverride FPFeatures)
Definition Expr.cpp:5188
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:713
QualType getType() const
Definition Decl.h:724
Represents a variable declaration or definition.
Definition Decl.h:933
TLSKind getTLSKind() const
Definition Decl.cpp:2150
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:2239
@ CInit
C-style initialization with assignment.
Definition Decl.h:938
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1248
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1215
const Expr * getInit() const
Definition Decl.h:1392
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1191
@ TLS_None
Not a TLS variable.
Definition Decl.h:953
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4044
Expr * getSizeExpr() const
Definition TypeBase.h:4058
Definition SPIR.cpp:35
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
Definition CGValue.h:155
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
Definition CGValue.h:146
@ Address
A pointer to a ValueDecl.
Definition Primitives.h:28
bool Inc(InterpState &S, CodePtr OpPC, bool CanOverflow)
1) Pops a pointer from the stack 2) Load the value from the pointer 3) Writes the value increased by ...
Definition Interp.h:986
CharSourceRange getSourceRange(const SourceRange &Range)
Returns the token CharSourceRange corresponding to Range.
Definition FixIt.h:32
Top level wrappers for InstallAPI frontend operations.
bool isOpenMPWorksharingDirective(OpenMPDirectiveKind DKind)
Checks if the specified directive is a worksharing directive.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool needsTaskBasedThreadLimit(OpenMPDirectiveKind DKind)
Checks if the specified target directive, combined or not, needs task based thread_limit.
@ Ctor_Complete
Complete object ctor.
Definition ABI.h:25
Privates[]
This class represents the 'transparent' clause in the 'pragma omp task' directive.
bool isa(CodeGen::Address addr)
Definition Address.h:330
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:152
bool isOpenMPDistributeDirective(OpenMPDirectiveKind DKind)
Checks if the specified directive is a distribute directive.
@ Tile
'tile' clause, allowed on 'loop' and Combined constructs.
OpenMPScheduleClauseModifier
OpenMP modifiers for 'schedule' clause.
Definition OpenMPKinds.h:39
@ OMPC_SCHEDULE_MODIFIER_unknown
Definition OpenMPKinds.h:40
@ CR_OpenMP
bool isOpenMPParallelDirective(OpenMPDirectiveKind DKind)
Checks if the specified directive is a parallel-kind directive.
@ SC_Static
Definition Specifiers.h:253
@ SC_None
Definition Specifiers.h:251
OpenMPDistScheduleClauseKind
OpenMP attributes for 'dist_schedule' clause.
@ OMPC_DIST_SCHEDULE_unknown
bool isOpenMPTaskingDirective(OpenMPDirectiveKind Kind)
Checks if the specified directive kind is one of tasking directives - task, taskloop,...
bool isOpenMPTargetExecutionDirective(OpenMPDirectiveKind DKind)
Checks if the specified directive is a target code offload directive.
@ Result
The result type of a method or function.
Definition TypeBase.h:906
bool isOpenMPTeamsDirective(OpenMPDirectiveKind DKind)
Checks if the specified directive is a teams-kind directive.
bool isOpenMPGenericLoopDirective(OpenMPDirectiveKind DKind)
Checks if the specified directive constitutes a 'loop' directive in the outermost nest.
OpenMPBindClauseKind
OpenMP bindings for the 'bind' clause.
@ OMPC_BIND_unknown
const FunctionProtoType * T
OpenMPDependClauseKind
OpenMP attributes for 'depend' clause.
Definition OpenMPKinds.h:55
@ Dtor_Complete
Complete object dtor.
Definition ABI.h:36
OpenMPSeverityClauseKind
OpenMP attributes for 'severity' clause.
bool isOpenMPLoopBoundSharingDirective(OpenMPDirectiveKind Kind)
Checks if the specified directive kind is one of the composite or combined directives that need loop ...
llvm::omp::Directive OpenMPDirectiveKind
OpenMP directives.
Definition OpenMPKinds.h:25
bool isOpenMPSimdDirective(OpenMPDirectiveKind DKind)
Checks if the specified directive is a simd directive.
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:140
void getOpenMPCaptureRegions(llvm::SmallVectorImpl< OpenMPDirectiveKind > &CaptureRegions, OpenMPDirectiveKind DKind)
Return the captured regions of an OpenMP directive.
OpenMPNumThreadsClauseModifier
@ OMPC_NUMTHREADS_unknown
U cast(CodeGen::Address addr)
Definition Address.h:327
@ OMPC_DEVICE_unknown
Definition OpenMPKinds.h:51
llvm::omp::Clause OpenMPClauseKind
OpenMP clauses.
Definition OpenMPKinds.h:28
@ ThreadPrivateVar
Parameter for Thread private variable.
Definition Decl.h:1772
@ Other
Other implicit parameter.
Definition Decl.h:1775
OpenMPScheduleClauseKind
OpenMP attributes for 'schedule' clause.
Definition OpenMPKinds.h:31
@ OMPC_SCHEDULE_unknown
Definition OpenMPKinds.h:35
bool isOpenMPTaskLoopDirective(OpenMPDirectiveKind DKind)
Checks if the specified directive is a taskloop directive.
#define true
Definition stdbool.h:25
Struct with the values to be passed to the static runtime function.
QualType getType() const
Definition CGCall.h:251
A jump destination is an abstract label, branching to which may require a jump out through normal cle...
static Address getAddrOfThreadPrivate(CodeGenFunction &CGF, const VarDecl *VD, Address VDAddr, SourceLocation Loc)
Returns address of the threadprivate variable for the current thread.
llvm::OpenMPIRBuilder::InsertPointTy InsertPointTy
static void EmitOMPOutlinedRegionBody(CodeGenFunction &CGF, const Stmt *RegionBodyStmt, InsertPointTy AllocaIP, InsertPointTy CodeGenIP, Twine RegionName)
Emit the body of an OMP region that will be outlined in OpenMPIRBuilder::finalize().
static Address getAddressOfLocalVariable(CodeGenFunction &CGF, const VarDecl *VD)
Gets the OpenMP-specific address of the local variable /p VD.
static void EmitCaptureStmt(CodeGenFunction &CGF, InsertPointTy CodeGenIP, llvm::BasicBlock &FiniBB, llvm::Function *Fn, ArrayRef< llvm::Value * > Args)
static std::string getNameWithSeparators(ArrayRef< StringRef > Parts, StringRef FirstSeparator=".", StringRef Separator=".")
Get the platform-specific name separator.
static void FinalizeOMPRegion(CodeGenFunction &CGF, InsertPointTy IP)
Emit the Finalization for an OMP region.
static void EmitOMPInlinedRegionBody(CodeGenFunction &CGF, const Stmt *RegionBodyStmt, InsertPointTy AllocaIP, InsertPointTy CodeGenIP, Twine RegionName)
Emit the body of an OMP region.
SmallVector< const Expr *, 4 > DepExprs
std::string getAsString() const
getAsString - Retrieve the human-readable string for this name.
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:666
Extra information about a function prototype.
Definition TypeBase.h:5470
Scheduling data for loop-based OpenMP directives.
bool UseFusedDistChunkSchedule
Request the fused distr_static_chunk + static_chunkone runtime schedule in for_static_init.
OpenMPScheduleClauseModifier M2
OpenMPScheduleClauseModifier M1
OpenMPScheduleClauseKind Schedule