clang 22.0.0git
CGOpenMPRuntimeGPU.cpp
Go to the documentation of this file.
1//===---- CGOpenMPRuntimeGPU.cpp - Interface to OpenMP GPU Runtimes ----===//
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 provides a generalized class for OpenMP runtime code generation
10// specialized by GPU targets NVPTX, AMDGCN and SPIR-V.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGOpenMPRuntimeGPU.h"
15#include "CGDebugInfo.h"
16#include "CodeGenFunction.h"
17#include "clang/AST/Attr.h"
22#include "clang/Basic/Cuda.h"
23#include "llvm/ADT/SmallPtrSet.h"
24#include "llvm/Frontend/OpenMP/OMPDeviceConstants.h"
25#include "llvm/Frontend/OpenMP/OMPGridValues.h"
26
27using namespace clang;
28using namespace CodeGen;
29using namespace llvm::omp;
30
31namespace {
32/// Pre(post)-action for different OpenMP constructs specialized for NVPTX.
33class NVPTXActionTy final : public PrePostActionTy {
34 llvm::FunctionCallee EnterCallee = nullptr;
35 ArrayRef<llvm::Value *> EnterArgs;
36 llvm::FunctionCallee ExitCallee = nullptr;
37 ArrayRef<llvm::Value *> ExitArgs;
38 bool Conditional = false;
39 llvm::BasicBlock *ContBlock = nullptr;
40
41public:
42 NVPTXActionTy(llvm::FunctionCallee EnterCallee,
43 ArrayRef<llvm::Value *> EnterArgs,
44 llvm::FunctionCallee ExitCallee,
45 ArrayRef<llvm::Value *> ExitArgs, bool Conditional = false)
46 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
47 ExitArgs(ExitArgs), Conditional(Conditional) {}
48 void Enter(CodeGenFunction &CGF) override {
49 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
50 if (Conditional) {
51 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
52 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
53 ContBlock = CGF.createBasicBlock("omp_if.end");
54 // Generate the branch (If-stmt)
55 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
56 CGF.EmitBlock(ThenBlock);
57 }
58 }
59 void Done(CodeGenFunction &CGF) {
60 // Emit the rest of blocks/branches
61 CGF.EmitBranch(ContBlock);
62 CGF.EmitBlock(ContBlock, true);
63 }
64 void Exit(CodeGenFunction &CGF) override {
65 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
66 }
67};
68
69/// A class to track the execution mode when codegening directives within
70/// a target region. The appropriate mode (SPMD|NON-SPMD) is set on entry
71/// to the target region and used by containing directives such as 'parallel'
72/// to emit optimized code.
73class ExecutionRuntimeModesRAII {
74private:
78
79public:
80 ExecutionRuntimeModesRAII(CGOpenMPRuntimeGPU::ExecutionMode &ExecMode,
82 : ExecMode(ExecMode) {
83 SavedExecMode = ExecMode;
84 ExecMode = EntryMode;
85 }
86 ~ExecutionRuntimeModesRAII() { ExecMode = SavedExecMode; }
87};
88
89static const ValueDecl *getPrivateItem(const Expr *RefExpr) {
90 RefExpr = RefExpr->IgnoreParens();
91 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr)) {
92 const Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
93 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
94 Base = TempASE->getBase()->IgnoreParenImpCasts();
95 RefExpr = Base;
96 } else if (auto *OASE = dyn_cast<ArraySectionExpr>(RefExpr)) {
97 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
98 while (const auto *TempOASE = dyn_cast<ArraySectionExpr>(Base))
99 Base = TempOASE->getBase()->IgnoreParenImpCasts();
100 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
101 Base = TempASE->getBase()->IgnoreParenImpCasts();
102 RefExpr = Base;
103 }
104 RefExpr = RefExpr->IgnoreParenImpCasts();
105 if (const auto *DE = dyn_cast<DeclRefExpr>(RefExpr))
106 return cast<ValueDecl>(DE->getDecl()->getCanonicalDecl());
107 const auto *ME = cast<MemberExpr>(RefExpr);
108 return cast<ValueDecl>(ME->getMemberDecl()->getCanonicalDecl());
109}
110
111static RecordDecl *buildRecordForGlobalizedVars(
113 ArrayRef<const ValueDecl *> EscapedDeclsForTeams,
114 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
115 &MappedDeclsFields,
116 int BufSize) {
117 using VarsDataTy = std::pair<CharUnits /*Align*/, const ValueDecl *>;
118 if (EscapedDecls.empty() && EscapedDeclsForTeams.empty())
119 return nullptr;
120 SmallVector<VarsDataTy, 4> GlobalizedVars;
121 for (const ValueDecl *D : EscapedDecls)
122 GlobalizedVars.emplace_back(C.getDeclAlign(D), D);
123 for (const ValueDecl *D : EscapedDeclsForTeams)
124 GlobalizedVars.emplace_back(C.getDeclAlign(D), D);
125
126 // Build struct _globalized_locals_ty {
127 // /* globalized vars */[WarSize] align (decl_align)
128 // /* globalized vars */ for EscapedDeclsForTeams
129 // };
130 RecordDecl *GlobalizedRD = C.buildImplicitRecord("_globalized_locals_ty");
131 GlobalizedRD->startDefinition();
132 llvm::SmallPtrSet<const ValueDecl *, 16> SingleEscaped(llvm::from_range,
133 EscapedDeclsForTeams);
134 for (const auto &Pair : GlobalizedVars) {
135 const ValueDecl *VD = Pair.second;
136 QualType Type = VD->getType();
138 Type = C.getPointerType(Type.getNonReferenceType());
139 else
140 Type = Type.getNonReferenceType();
141 SourceLocation Loc = VD->getLocation();
142 FieldDecl *Field;
143 if (SingleEscaped.count(VD)) {
144 Field = FieldDecl::Create(
145 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
146 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
147 /*BW=*/nullptr, /*Mutable=*/false,
148 /*InitStyle=*/ICIS_NoInit);
149 Field->setAccess(AS_public);
150 if (VD->hasAttrs()) {
151 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
152 E(VD->getAttrs().end());
153 I != E; ++I)
154 Field->addAttr(*I);
155 }
156 } else {
157 if (BufSize > 1) {
158 llvm::APInt ArraySize(32, BufSize);
159 Type = C.getConstantArrayType(Type, ArraySize, nullptr,
161 }
162 Field = FieldDecl::Create(
163 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
164 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
165 /*BW=*/nullptr, /*Mutable=*/false,
166 /*InitStyle=*/ICIS_NoInit);
167 Field->setAccess(AS_public);
168 llvm::APInt Align(32, Pair.first.getQuantity());
169 Field->addAttr(AlignedAttr::CreateImplicit(
170 C, /*IsAlignmentExpr=*/true,
172 C.getIntTypeForBitwidth(32, /*Signed=*/0),
174 {}, AlignedAttr::GNU_aligned));
175 }
176 GlobalizedRD->addDecl(Field);
177 MappedDeclsFields.try_emplace(VD, Field);
178 }
179 GlobalizedRD->completeDefinition();
180 return GlobalizedRD;
181}
182
183/// Get the list of variables that can escape their declaration context.
184class CheckVarsEscapingDeclContext final
185 : public ConstStmtVisitor<CheckVarsEscapingDeclContext> {
186 CodeGenFunction &CGF;
187 llvm::SetVector<const ValueDecl *> EscapedDecls;
188 llvm::SetVector<const ValueDecl *> EscapedVariableLengthDecls;
189 llvm::SetVector<const ValueDecl *> DelayedVariableLengthDecls;
190 llvm::SmallPtrSet<const Decl *, 4> EscapedParameters;
191 RecordDecl *GlobalizedRD = nullptr;
192 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
193 bool AllEscaped = false;
194 bool IsForCombinedParallelRegion = false;
195
196 void markAsEscaped(const ValueDecl *VD) {
197 // Do not globalize declare target variables.
198 if (!isa<VarDecl>(VD) ||
199 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
200 return;
202 // Use user-specified allocation.
203 if (VD->hasAttrs() && VD->hasAttr<OMPAllocateDeclAttr>())
204 return;
205 // Variables captured by value must be globalized.
206 bool IsCaptured = false;
207 if (auto *CSI = CGF.CapturedStmtInfo) {
208 if (const FieldDecl *FD = CSI->lookup(cast<VarDecl>(VD))) {
209 // Check if need to capture the variable that was already captured by
210 // value in the outer region.
211 IsCaptured = true;
212 if (!IsForCombinedParallelRegion) {
213 if (!FD->hasAttrs())
214 return;
215 const auto *Attr = FD->getAttr<OMPCaptureKindAttr>();
216 if (!Attr)
217 return;
218 if (((Attr->getCaptureKind() != OMPC_map) &&
219 !isOpenMPPrivate(Attr->getCaptureKind())) ||
220 ((Attr->getCaptureKind() == OMPC_map) &&
221 !FD->getType()->isAnyPointerType()))
222 return;
223 }
224 if (!FD->getType()->isReferenceType()) {
225 assert(!VD->getType()->isVariablyModifiedType() &&
226 "Parameter captured by value with variably modified type");
227 EscapedParameters.insert(VD);
228 } else if (!IsForCombinedParallelRegion) {
229 return;
230 }
231 }
232 }
233 if ((!CGF.CapturedStmtInfo ||
234 (IsForCombinedParallelRegion && CGF.CapturedStmtInfo)) &&
235 VD->getType()->isReferenceType())
236 // Do not globalize variables with reference type.
237 return;
238 if (VD->getType()->isVariablyModifiedType()) {
239 // If not captured at the target region level then mark the escaped
240 // variable as delayed.
241 if (IsCaptured)
242 EscapedVariableLengthDecls.insert(VD);
243 else
244 DelayedVariableLengthDecls.insert(VD);
245 } else
246 EscapedDecls.insert(VD);
247 }
248
249 void VisitValueDecl(const ValueDecl *VD) {
250 if (VD->getType()->isLValueReferenceType())
251 markAsEscaped(VD);
252 if (const auto *VarD = dyn_cast<VarDecl>(VD)) {
253 if (!isa<ParmVarDecl>(VarD) && VarD->hasInit()) {
254 const bool SavedAllEscaped = AllEscaped;
255 AllEscaped = VD->getType()->isLValueReferenceType();
256 Visit(VarD->getInit());
257 AllEscaped = SavedAllEscaped;
258 }
259 }
260 }
261 void VisitOpenMPCapturedStmt(const CapturedStmt *S,
262 ArrayRef<OMPClause *> Clauses,
263 bool IsCombinedParallelRegion) {
264 if (!S)
265 return;
266 for (const CapturedStmt::Capture &C : S->captures()) {
267 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
268 const ValueDecl *VD = C.getCapturedVar();
269 bool SavedIsForCombinedParallelRegion = IsForCombinedParallelRegion;
270 if (IsCombinedParallelRegion) {
271 // Check if the variable is privatized in the combined construct and
272 // those private copies must be shared in the inner parallel
273 // directive.
274 IsForCombinedParallelRegion = false;
275 for (const OMPClause *C : Clauses) {
276 if (!isOpenMPPrivate(C->getClauseKind()) ||
277 C->getClauseKind() == OMPC_reduction ||
278 C->getClauseKind() == OMPC_linear ||
279 C->getClauseKind() == OMPC_private)
280 continue;
281 ArrayRef<const Expr *> Vars;
282 if (const auto *PC = dyn_cast<OMPFirstprivateClause>(C))
283 Vars = PC->getVarRefs();
284 else if (const auto *PC = dyn_cast<OMPLastprivateClause>(C))
285 Vars = PC->getVarRefs();
286 else
287 llvm_unreachable("Unexpected clause.");
288 for (const auto *E : Vars) {
289 const Decl *D =
290 cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
291 if (D == VD->getCanonicalDecl()) {
292 IsForCombinedParallelRegion = true;
293 break;
294 }
295 }
296 if (IsForCombinedParallelRegion)
297 break;
298 }
299 }
300 markAsEscaped(VD);
302 VisitValueDecl(VD);
303 IsForCombinedParallelRegion = SavedIsForCombinedParallelRegion;
304 }
305 }
306 }
307
308 void buildRecordForGlobalizedVars(bool IsInTTDRegion) {
309 assert(!GlobalizedRD &&
310 "Record for globalized variables is built already.");
311 ArrayRef<const ValueDecl *> EscapedDeclsForParallel, EscapedDeclsForTeams;
312 unsigned WarpSize = CGF.getTarget().getGridValue().GV_Warp_Size;
313 if (IsInTTDRegion)
314 EscapedDeclsForTeams = EscapedDecls.getArrayRef();
315 else
316 EscapedDeclsForParallel = EscapedDecls.getArrayRef();
317 GlobalizedRD = ::buildRecordForGlobalizedVars(
318 CGF.getContext(), EscapedDeclsForParallel, EscapedDeclsForTeams,
319 MappedDeclsFields, WarpSize);
320 }
321
322public:
323 CheckVarsEscapingDeclContext(CodeGenFunction &CGF,
324 ArrayRef<const ValueDecl *> TeamsReductions)
325 : CGF(CGF), EscapedDecls(llvm::from_range, TeamsReductions) {}
326 ~CheckVarsEscapingDeclContext() = default;
327 void VisitDeclStmt(const DeclStmt *S) {
328 if (!S)
329 return;
330 for (const Decl *D : S->decls())
331 if (const auto *VD = dyn_cast_or_null<ValueDecl>(D))
332 VisitValueDecl(VD);
333 }
334 void VisitOMPExecutableDirective(const OMPExecutableDirective *D) {
335 if (!D)
336 return;
337 if (!D->hasAssociatedStmt())
338 return;
339 if (const auto *S =
340 dyn_cast_or_null<CapturedStmt>(D->getAssociatedStmt())) {
341 // Do not analyze directives that do not actually require capturing,
342 // like `omp for` or `omp simd` directives.
343 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
344 getOpenMPCaptureRegions(CaptureRegions, D->getDirectiveKind());
345 if (CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown) {
346 VisitStmt(S->getCapturedStmt());
347 return;
348 }
349 VisitOpenMPCapturedStmt(
350 S, D->clauses(),
351 CaptureRegions.back() == OMPD_parallel &&
352 isOpenMPDistributeDirective(D->getDirectiveKind()));
353 }
354 }
355 void VisitCapturedStmt(const CapturedStmt *S) {
356 if (!S)
357 return;
358 for (const CapturedStmt::Capture &C : S->captures()) {
359 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
360 const ValueDecl *VD = C.getCapturedVar();
361 markAsEscaped(VD);
363 VisitValueDecl(VD);
364 }
365 }
366 }
367 void VisitLambdaExpr(const LambdaExpr *E) {
368 if (!E)
369 return;
370 for (const LambdaCapture &C : E->captures()) {
371 if (C.capturesVariable()) {
372 if (C.getCaptureKind() == LCK_ByRef) {
373 const ValueDecl *VD = C.getCapturedVar();
374 markAsEscaped(VD);
376 VisitValueDecl(VD);
377 }
378 }
379 }
380 }
381 void VisitBlockExpr(const BlockExpr *E) {
382 if (!E)
383 return;
384 for (const BlockDecl::Capture &C : E->getBlockDecl()->captures()) {
385 if (C.isByRef()) {
386 const VarDecl *VD = C.getVariable();
387 markAsEscaped(VD);
389 VisitValueDecl(VD);
390 }
391 }
392 }
393 void VisitCallExpr(const CallExpr *E) {
394 if (!E)
395 return;
396 for (const Expr *Arg : E->arguments()) {
397 if (!Arg)
398 continue;
399 if (Arg->isLValue()) {
400 const bool SavedAllEscaped = AllEscaped;
401 AllEscaped = true;
402 Visit(Arg);
403 AllEscaped = SavedAllEscaped;
404 } else {
405 Visit(Arg);
406 }
407 }
408 Visit(E->getCallee());
409 }
410 void VisitDeclRefExpr(const DeclRefExpr *E) {
411 if (!E)
412 return;
413 const ValueDecl *VD = E->getDecl();
414 if (AllEscaped)
415 markAsEscaped(VD);
417 VisitValueDecl(VD);
418 else if (VD->isInitCapture())
419 VisitValueDecl(VD);
420 }
421 void VisitUnaryOperator(const UnaryOperator *E) {
422 if (!E)
423 return;
424 if (E->getOpcode() == UO_AddrOf) {
425 const bool SavedAllEscaped = AllEscaped;
426 AllEscaped = true;
427 Visit(E->getSubExpr());
428 AllEscaped = SavedAllEscaped;
429 } else {
430 Visit(E->getSubExpr());
431 }
432 }
433 void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
434 if (!E)
435 return;
436 if (E->getCastKind() == CK_ArrayToPointerDecay) {
437 const bool SavedAllEscaped = AllEscaped;
438 AllEscaped = true;
439 Visit(E->getSubExpr());
440 AllEscaped = SavedAllEscaped;
441 } else {
442 Visit(E->getSubExpr());
443 }
444 }
445 void VisitExpr(const Expr *E) {
446 if (!E)
447 return;
448 bool SavedAllEscaped = AllEscaped;
449 if (!E->isLValue())
450 AllEscaped = false;
451 for (const Stmt *Child : E->children())
452 if (Child)
453 Visit(Child);
454 AllEscaped = SavedAllEscaped;
455 }
456 void VisitStmt(const Stmt *S) {
457 if (!S)
458 return;
459 for (const Stmt *Child : S->children())
460 if (Child)
461 Visit(Child);
462 }
463
464 /// Returns the record that handles all the escaped local variables and used
465 /// instead of their original storage.
466 const RecordDecl *getGlobalizedRecord(bool IsInTTDRegion) {
467 if (!GlobalizedRD)
468 buildRecordForGlobalizedVars(IsInTTDRegion);
469 return GlobalizedRD;
470 }
471
472 /// Returns the field in the globalized record for the escaped variable.
473 const FieldDecl *getFieldForGlobalizedVar(const ValueDecl *VD) const {
474 assert(GlobalizedRD &&
475 "Record for globalized variables must be generated already.");
476 return MappedDeclsFields.lookup(VD);
477 }
478
479 /// Returns the list of the escaped local variables/parameters.
480 ArrayRef<const ValueDecl *> getEscapedDecls() const {
481 return EscapedDecls.getArrayRef();
482 }
483
484 /// Checks if the escaped local variable is actually a parameter passed by
485 /// value.
486 const llvm::SmallPtrSetImpl<const Decl *> &getEscapedParameters() const {
487 return EscapedParameters;
488 }
489
490 /// Returns the list of the escaped variables with the variably modified
491 /// types.
492 ArrayRef<const ValueDecl *> getEscapedVariableLengthDecls() const {
493 return EscapedVariableLengthDecls.getArrayRef();
494 }
495
496 /// Returns the list of the delayed variables with the variably modified
497 /// types.
498 ArrayRef<const ValueDecl *> getDelayedVariableLengthDecls() const {
499 return DelayedVariableLengthDecls.getArrayRef();
500 }
501};
502} // anonymous namespace
503
505CGOpenMPRuntimeGPU::getExecutionMode() const {
506 return CurrentExecutionMode;
507}
508
510CGOpenMPRuntimeGPU::getDataSharingMode() const {
511 return CurrentDataSharingMode;
512}
513
514/// Check for inner (nested) SPMD construct, if any
516 const OMPExecutableDirective &D) {
517 const auto *CS = D.getInnermostCapturedStmt();
518 const auto *Body =
519 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
520 const Stmt *ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
521
522 if (const auto *NestedDir =
523 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
524 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
525 switch (D.getDirectiveKind()) {
526 case OMPD_target:
527 if (isOpenMPParallelDirective(DKind))
528 return true;
529 if (DKind == OMPD_teams) {
530 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
531 /*IgnoreCaptured=*/true);
532 if (!Body)
533 return false;
534 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
535 if (const auto *NND =
536 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
537 DKind = NND->getDirectiveKind();
538 if (isOpenMPParallelDirective(DKind))
539 return true;
540 }
541 }
542 return false;
543 case OMPD_target_teams:
544 return isOpenMPParallelDirective(DKind);
545 case OMPD_target_simd:
546 case OMPD_target_parallel:
547 case OMPD_target_parallel_for:
548 case OMPD_target_parallel_for_simd:
549 case OMPD_target_teams_distribute:
550 case OMPD_target_teams_distribute_simd:
551 case OMPD_target_teams_distribute_parallel_for:
552 case OMPD_target_teams_distribute_parallel_for_simd:
553 case OMPD_parallel:
554 case OMPD_for:
555 case OMPD_parallel_for:
556 case OMPD_parallel_master:
557 case OMPD_parallel_sections:
558 case OMPD_for_simd:
559 case OMPD_parallel_for_simd:
560 case OMPD_cancel:
561 case OMPD_cancellation_point:
562 case OMPD_ordered:
563 case OMPD_threadprivate:
564 case OMPD_allocate:
565 case OMPD_task:
566 case OMPD_simd:
567 case OMPD_sections:
568 case OMPD_section:
569 case OMPD_single:
570 case OMPD_master:
571 case OMPD_critical:
572 case OMPD_taskyield:
573 case OMPD_barrier:
574 case OMPD_taskwait:
575 case OMPD_taskgroup:
576 case OMPD_atomic:
577 case OMPD_flush:
578 case OMPD_depobj:
579 case OMPD_scan:
580 case OMPD_teams:
581 case OMPD_target_data:
582 case OMPD_target_exit_data:
583 case OMPD_target_enter_data:
584 case OMPD_distribute:
585 case OMPD_distribute_simd:
586 case OMPD_distribute_parallel_for:
587 case OMPD_distribute_parallel_for_simd:
588 case OMPD_teams_distribute:
589 case OMPD_teams_distribute_simd:
590 case OMPD_teams_distribute_parallel_for:
591 case OMPD_teams_distribute_parallel_for_simd:
592 case OMPD_target_update:
593 case OMPD_declare_simd:
594 case OMPD_declare_variant:
595 case OMPD_begin_declare_variant:
596 case OMPD_end_declare_variant:
597 case OMPD_declare_target:
598 case OMPD_end_declare_target:
599 case OMPD_declare_reduction:
600 case OMPD_declare_mapper:
601 case OMPD_taskloop:
602 case OMPD_taskloop_simd:
603 case OMPD_master_taskloop:
604 case OMPD_master_taskloop_simd:
605 case OMPD_parallel_master_taskloop:
606 case OMPD_parallel_master_taskloop_simd:
607 case OMPD_requires:
608 case OMPD_unknown:
609 default:
610 llvm_unreachable("Unexpected directive.");
611 }
612 }
613
614 return false;
615}
616
618 const OMPExecutableDirective &D) {
619 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
620 switch (DirectiveKind) {
621 case OMPD_target:
622 case OMPD_target_teams:
623 return hasNestedSPMDDirective(Ctx, D);
624 case OMPD_target_parallel_loop:
625 case OMPD_target_parallel:
626 case OMPD_target_parallel_for:
627 case OMPD_target_parallel_for_simd:
628 case OMPD_target_teams_distribute_parallel_for:
629 case OMPD_target_teams_distribute_parallel_for_simd:
630 case OMPD_target_simd:
631 case OMPD_target_teams_distribute_simd:
632 return true;
633 case OMPD_target_teams_distribute:
634 return false;
635 case OMPD_target_teams_loop:
636 // Whether this is true or not depends on how the directive will
637 // eventually be emitted.
638 if (auto *TTLD = dyn_cast<OMPTargetTeamsGenericLoopDirective>(&D))
639 return TTLD->canBeParallelFor();
640 return false;
641 case OMPD_parallel:
642 case OMPD_for:
643 case OMPD_parallel_for:
644 case OMPD_parallel_master:
645 case OMPD_parallel_sections:
646 case OMPD_for_simd:
647 case OMPD_parallel_for_simd:
648 case OMPD_cancel:
649 case OMPD_cancellation_point:
650 case OMPD_ordered:
651 case OMPD_threadprivate:
652 case OMPD_allocate:
653 case OMPD_task:
654 case OMPD_simd:
655 case OMPD_sections:
656 case OMPD_section:
657 case OMPD_single:
658 case OMPD_master:
659 case OMPD_critical:
660 case OMPD_taskyield:
661 case OMPD_barrier:
662 case OMPD_taskwait:
663 case OMPD_taskgroup:
664 case OMPD_atomic:
665 case OMPD_flush:
666 case OMPD_depobj:
667 case OMPD_scan:
668 case OMPD_teams:
669 case OMPD_target_data:
670 case OMPD_target_exit_data:
671 case OMPD_target_enter_data:
672 case OMPD_distribute:
673 case OMPD_distribute_simd:
674 case OMPD_distribute_parallel_for:
675 case OMPD_distribute_parallel_for_simd:
676 case OMPD_teams_distribute:
677 case OMPD_teams_distribute_simd:
678 case OMPD_teams_distribute_parallel_for:
679 case OMPD_teams_distribute_parallel_for_simd:
680 case OMPD_target_update:
681 case OMPD_declare_simd:
682 case OMPD_declare_variant:
683 case OMPD_begin_declare_variant:
684 case OMPD_end_declare_variant:
685 case OMPD_declare_target:
686 case OMPD_end_declare_target:
687 case OMPD_declare_reduction:
688 case OMPD_declare_mapper:
689 case OMPD_taskloop:
690 case OMPD_taskloop_simd:
691 case OMPD_master_taskloop:
692 case OMPD_master_taskloop_simd:
693 case OMPD_parallel_master_taskloop:
694 case OMPD_parallel_master_taskloop_simd:
695 case OMPD_requires:
696 case OMPD_unknown:
697 default:
698 break;
699 }
700 llvm_unreachable(
701 "Unknown programming model for OpenMP directive on NVPTX target.");
702}
703
704void CGOpenMPRuntimeGPU::emitNonSPMDKernel(const OMPExecutableDirective &D,
705 StringRef ParentName,
706 llvm::Function *&OutlinedFn,
707 llvm::Constant *&OutlinedFnID,
708 bool IsOffloadEntry,
709 const RegionCodeGenTy &CodeGen) {
710 ExecutionRuntimeModesRAII ModeRAII(CurrentExecutionMode, EM_NonSPMD);
711 EntryFunctionState EST;
712 WrapperFunctionsMap.clear();
713
714 [[maybe_unused]] bool IsBareKernel = D.getSingleClause<OMPXBareClause>();
715 assert(!IsBareKernel && "bare kernel should not be at generic mode");
716
717 // Emit target region as a standalone region.
718 class NVPTXPrePostActionTy : public PrePostActionTy {
719 CGOpenMPRuntimeGPU::EntryFunctionState &EST;
720 const OMPExecutableDirective &D;
721
722 public:
723 NVPTXPrePostActionTy(CGOpenMPRuntimeGPU::EntryFunctionState &EST,
724 const OMPExecutableDirective &D)
725 : EST(EST), D(D) {}
726 void Enter(CodeGenFunction &CGF) override {
727 auto &RT = static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
728 RT.emitKernelInit(D, CGF, EST, /* IsSPMD */ false);
729 // Skip target region initialization.
730 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
731 }
732 void Exit(CodeGenFunction &CGF) override {
733 auto &RT = static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
734 RT.clearLocThreadIdInsertPt(CGF);
735 RT.emitKernelDeinit(CGF, EST, /* IsSPMD */ false);
736 }
737 } Action(EST, D);
738 CodeGen.setAction(Action);
739 IsInTTDRegion = true;
740 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
741 IsOffloadEntry, CodeGen);
742 IsInTTDRegion = false;
743}
744
745void CGOpenMPRuntimeGPU::emitKernelInit(const OMPExecutableDirective &D,
746 CodeGenFunction &CGF,
747 EntryFunctionState &EST, bool IsSPMD) {
748 llvm::OpenMPIRBuilder::TargetKernelDefaultAttrs Attrs;
749 Attrs.ExecFlags =
750 IsSPMD ? llvm::omp::OMPTgtExecModeFlags::OMP_TGT_EXEC_MODE_SPMD
751 : llvm::omp::OMPTgtExecModeFlags::OMP_TGT_EXEC_MODE_GENERIC;
752 computeMinAndMaxThreadsAndTeams(D, CGF, Attrs);
753
754 CGBuilderTy &Bld = CGF.Builder;
755 Bld.restoreIP(OMPBuilder.createTargetInit(Bld, Attrs));
756 if (!IsSPMD)
757 emitGenericVarsProlog(CGF, EST.Loc);
758}
759
760void CGOpenMPRuntimeGPU::emitKernelDeinit(CodeGenFunction &CGF,
761 EntryFunctionState &EST,
762 bool IsSPMD) {
763 if (!IsSPMD)
764 emitGenericVarsEpilog(CGF);
765
766 // This is temporary until we remove the fixed sized buffer.
767 ASTContext &C = CGM.getContext();
768 RecordDecl *StaticRD = C.buildImplicitRecord(
769 "_openmp_teams_reduction_type_$_", RecordDecl::TagKind::Union);
770 StaticRD->startDefinition();
771 for (const RecordDecl *TeamReductionRec : TeamsReductions) {
772 CanQualType RecTy = C.getCanonicalTagType(TeamReductionRec);
773 auto *Field = FieldDecl::Create(
774 C, StaticRD, SourceLocation(), SourceLocation(), nullptr, RecTy,
775 C.getTrivialTypeSourceInfo(RecTy, SourceLocation()),
776 /*BW=*/nullptr, /*Mutable=*/false,
777 /*InitStyle=*/ICIS_NoInit);
778 Field->setAccess(AS_public);
779 StaticRD->addDecl(Field);
780 }
781 StaticRD->completeDefinition();
782 CanQualType StaticTy = C.getCanonicalTagType(StaticRD);
783 llvm::Type *LLVMReductionsBufferTy =
784 CGM.getTypes().ConvertTypeForMem(StaticTy);
785 const auto &DL = CGM.getModule().getDataLayout();
786 uint64_t ReductionDataSize =
787 TeamsReductions.empty()
788 ? 0
789 : DL.getTypeAllocSize(LLVMReductionsBufferTy).getFixedValue();
790 CGBuilderTy &Bld = CGF.Builder;
791 OMPBuilder.createTargetDeinit(Bld, ReductionDataSize,
792 C.getLangOpts().OpenMPCUDAReductionBufNum);
793 TeamsReductions.clear();
794}
795
796void CGOpenMPRuntimeGPU::emitSPMDKernel(const OMPExecutableDirective &D,
797 StringRef ParentName,
798 llvm::Function *&OutlinedFn,
799 llvm::Constant *&OutlinedFnID,
800 bool IsOffloadEntry,
801 const RegionCodeGenTy &CodeGen) {
802 ExecutionRuntimeModesRAII ModeRAII(CurrentExecutionMode, EM_SPMD);
803 EntryFunctionState EST;
804
805 bool IsBareKernel = D.getSingleClause<OMPXBareClause>();
806
807 // Emit target region as a standalone region.
808 class NVPTXPrePostActionTy : public PrePostActionTy {
809 CGOpenMPRuntimeGPU &RT;
810 CGOpenMPRuntimeGPU::EntryFunctionState &EST;
811 bool IsBareKernel;
812 DataSharingMode Mode;
813 const OMPExecutableDirective &D;
814
815 public:
816 NVPTXPrePostActionTy(CGOpenMPRuntimeGPU &RT,
817 CGOpenMPRuntimeGPU::EntryFunctionState &EST,
818 bool IsBareKernel, const OMPExecutableDirective &D)
819 : RT(RT), EST(EST), IsBareKernel(IsBareKernel),
820 Mode(RT.CurrentDataSharingMode), D(D) {}
821 void Enter(CodeGenFunction &CGF) override {
822 if (IsBareKernel) {
823 RT.CurrentDataSharingMode = DataSharingMode::DS_CUDA;
824 return;
825 }
826 RT.emitKernelInit(D, CGF, EST, /* IsSPMD */ true);
827 // Skip target region initialization.
828 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
829 }
830 void Exit(CodeGenFunction &CGF) override {
831 if (IsBareKernel) {
832 RT.CurrentDataSharingMode = Mode;
833 return;
834 }
835 RT.clearLocThreadIdInsertPt(CGF);
836 RT.emitKernelDeinit(CGF, EST, /* IsSPMD */ true);
837 }
838 } Action(*this, EST, IsBareKernel, D);
839 CodeGen.setAction(Action);
840 IsInTTDRegion = true;
841 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
842 IsOffloadEntry, CodeGen);
843 IsInTTDRegion = false;
844}
845
846void CGOpenMPRuntimeGPU::emitTargetOutlinedFunction(
847 const OMPExecutableDirective &D, StringRef ParentName,
848 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
849 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
850 if (!IsOffloadEntry) // Nothing to do.
851 return;
852
853 assert(!ParentName.empty() && "Invalid target region parent name!");
854
855 bool Mode = supportsSPMDExecutionMode(CGM.getContext(), D);
856 bool IsBareKernel = D.getSingleClause<OMPXBareClause>();
857 if (Mode || IsBareKernel)
858 emitSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
859 CodeGen);
860 else
861 emitNonSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
862 CodeGen);
863}
864
867 llvm::OpenMPIRBuilderConfig Config(
868 CGM.getLangOpts().OpenMPIsTargetDevice, isGPU(),
869 CGM.getLangOpts().OpenMPOffloadMandatory,
870 /*HasRequiresReverseOffload*/ false, /*HasRequiresUnifiedAddress*/ false,
871 hasRequiresUnifiedSharedMemory(), /*HasRequiresDynamicAllocators*/ false);
872 Config.setDefaultTargetAS(
873 CGM.getContext().getTargetInfo().getTargetAddressSpace(LangAS::Default));
874 OMPBuilder.setConfig(Config);
875
876 if (!CGM.getLangOpts().OpenMPIsTargetDevice)
877 llvm_unreachable("OpenMP can only handle device code.");
878
879 if (CGM.getLangOpts().OpenMPCUDAMode)
880 CurrentDataSharingMode = CGOpenMPRuntimeGPU::DS_CUDA;
881
882 llvm::OpenMPIRBuilder &OMPBuilder = getOMPBuilder();
883 if (CGM.getLangOpts().NoGPULib || CGM.getLangOpts().OMPHostIRFile.empty())
884 return;
885
886 OMPBuilder.createGlobalFlag(CGM.getLangOpts().OpenMPTargetDebug,
887 "__omp_rtl_debug_kind");
888 OMPBuilder.createGlobalFlag(CGM.getLangOpts().OpenMPTeamSubscription,
889 "__omp_rtl_assume_teams_oversubscription");
890 OMPBuilder.createGlobalFlag(CGM.getLangOpts().OpenMPThreadSubscription,
891 "__omp_rtl_assume_threads_oversubscription");
892 OMPBuilder.createGlobalFlag(CGM.getLangOpts().OpenMPNoThreadState,
893 "__omp_rtl_assume_no_thread_state");
894 OMPBuilder.createGlobalFlag(CGM.getLangOpts().OpenMPNoNestedParallelism,
895 "__omp_rtl_assume_no_nested_parallelism");
896}
897
899 ProcBindKind ProcBind,
900 SourceLocation Loc) {
901 // Nothing to do.
902}
903
905 const Expr *Message,
906 SourceLocation Loc) {
907 CGM.getDiags().Report(Loc, diag::warn_omp_gpu_unsupported_clause)
908 << getOpenMPClauseName(OMPC_message);
909 return nullptr;
910}
911
912llvm::Value *
914 SourceLocation Loc) {
915 CGM.getDiags().Report(Loc, diag::warn_omp_gpu_unsupported_clause)
916 << getOpenMPClauseName(OMPC_severity);
917 return nullptr;
918}
919
921 CodeGenFunction &CGF, llvm::Value *NumThreads, SourceLocation Loc,
923 SourceLocation SeverityLoc, const Expr *Message,
924 SourceLocation MessageLoc) {
925 if (Modifier == OMPC_NUMTHREADS_strict) {
926 CGM.getDiags().Report(Loc,
927 diag::warn_omp_gpu_unsupported_modifier_for_clause)
928 << "strict" << getOpenMPClauseName(OMPC_num_threads);
929 return;
930 }
931
932 // Nothing to do.
933}
934
936 const Expr *NumTeams,
937 const Expr *ThreadLimit,
938 SourceLocation Loc) {}
939
942 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
943 const RegionCodeGenTy &CodeGen) {
944 // Emit target region as a standalone region.
945 bool PrevIsInTTDRegion = IsInTTDRegion;
946 IsInTTDRegion = false;
947 auto *OutlinedFun =
949 CGF, D, ThreadIDVar, InnermostKind, CodeGen));
950 IsInTTDRegion = PrevIsInTTDRegion;
951 if (getExecutionMode() != CGOpenMPRuntimeGPU::EM_SPMD) {
952 llvm::Function *WrapperFun =
953 createParallelDataSharingWrapper(OutlinedFun, D);
954 WrapperFunctionsMap[OutlinedFun] = WrapperFun;
955 }
956
957 return OutlinedFun;
958}
959
960/// Get list of lastprivate variables from the teams distribute ... or
961/// teams {distribute ...} directives.
962static void
965 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
966 "expected teams directive.");
967 const OMPExecutableDirective *Dir = &D;
968 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
970 Ctx,
971 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
972 /*IgnoreCaptured=*/true))) {
973 Dir = dyn_cast_or_null<OMPExecutableDirective>(S);
974 if (Dir && !isOpenMPDistributeDirective(Dir->getDirectiveKind()))
975 Dir = nullptr;
976 }
977 }
978 if (!Dir)
979 return;
980 for (const auto *C : Dir->getClausesOfKind<OMPLastprivateClause>()) {
981 for (const Expr *E : C->getVarRefs())
982 Vars.push_back(getPrivateItem(E));
983 }
984}
985
986/// Get list of reduction variables from the teams ... directives.
987static void
990 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
991 "expected teams directive.");
992 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
993 for (const Expr *E : C->privates())
994 Vars.push_back(getPrivateItem(E));
995 }
996}
997
1000 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1001 const RegionCodeGenTy &CodeGen) {
1002 SourceLocation Loc = D.getBeginLoc();
1003
1004 const RecordDecl *GlobalizedRD = nullptr;
1005 llvm::SmallVector<const ValueDecl *, 4> LastPrivatesReductions;
1006 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
1007 unsigned WarpSize = CGM.getTarget().getGridValue().GV_Warp_Size;
1008 // Globalize team reductions variable unconditionally in all modes.
1009 if (getExecutionMode() != CGOpenMPRuntimeGPU::EM_SPMD)
1010 getTeamsReductionVars(CGM.getContext(), D, LastPrivatesReductions);
1011 if (getExecutionMode() == CGOpenMPRuntimeGPU::EM_SPMD) {
1012 getDistributeLastprivateVars(CGM.getContext(), D, LastPrivatesReductions);
1013 if (!LastPrivatesReductions.empty()) {
1014 GlobalizedRD = ::buildRecordForGlobalizedVars(
1015 CGM.getContext(), {}, LastPrivatesReductions, MappedDeclsFields,
1016 WarpSize);
1017 }
1018 } else if (!LastPrivatesReductions.empty()) {
1019 assert(!TeamAndReductions.first &&
1020 "Previous team declaration is not expected.");
1021 TeamAndReductions.first = D.getCapturedStmt(OMPD_teams)->getCapturedDecl();
1022 std::swap(TeamAndReductions.second, LastPrivatesReductions);
1023 }
1024
1025 // Emit target region as a standalone region.
1026 class NVPTXPrePostActionTy : public PrePostActionTy {
1027 SourceLocation &Loc;
1028 const RecordDecl *GlobalizedRD;
1029 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
1030 &MappedDeclsFields;
1031
1032 public:
1033 NVPTXPrePostActionTy(
1034 SourceLocation &Loc, const RecordDecl *GlobalizedRD,
1035 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
1036 &MappedDeclsFields)
1037 : Loc(Loc), GlobalizedRD(GlobalizedRD),
1038 MappedDeclsFields(MappedDeclsFields) {}
1039 void Enter(CodeGenFunction &CGF) override {
1040 auto &Rt =
1041 static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
1042 if (GlobalizedRD) {
1043 auto I = Rt.FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
1044 I->getSecond().MappedParams =
1045 std::make_unique<CodeGenFunction::OMPMapVars>();
1046 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
1047 for (const auto &Pair : MappedDeclsFields) {
1048 assert(Pair.getFirst()->isCanonicalDecl() &&
1049 "Expected canonical declaration");
1050 Data.try_emplace(Pair.getFirst());
1051 }
1052 }
1053 Rt.emitGenericVarsProlog(CGF, Loc);
1054 }
1055 void Exit(CodeGenFunction &CGF) override {
1056 static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime())
1057 .emitGenericVarsEpilog(CGF);
1058 }
1059 } Action(Loc, GlobalizedRD, MappedDeclsFields);
1060 CodeGen.setAction(Action);
1061 llvm::Function *OutlinedFun = CGOpenMPRuntime::emitTeamsOutlinedFunction(
1062 CGF, D, ThreadIDVar, InnermostKind, CodeGen);
1063
1064 return OutlinedFun;
1065}
1066
1067void CGOpenMPRuntimeGPU::emitGenericVarsProlog(CodeGenFunction &CGF,
1068 SourceLocation Loc) {
1069 if (getDataSharingMode() != CGOpenMPRuntimeGPU::DS_Generic)
1070 return;
1071
1072 CGBuilderTy &Bld = CGF.Builder;
1073
1074 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
1075 if (I == FunctionGlobalizedDecls.end())
1076 return;
1077
1078 for (auto &Rec : I->getSecond().LocalVarData) {
1079 const auto *VD = cast<VarDecl>(Rec.first);
1080 bool EscapedParam = I->getSecond().EscapedParameters.count(Rec.first);
1081 QualType VarTy = VD->getType();
1082
1083 // Get the local allocation of a firstprivate variable before sharing
1084 llvm::Value *ParValue;
1085 if (EscapedParam) {
1086 LValue ParLVal =
1087 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
1088 ParValue = CGF.EmitLoadOfScalar(ParLVal, Loc);
1089 }
1090
1091 // Allocate space for the variable to be globalized
1092 llvm::Value *AllocArgs[] = {CGF.getTypeSize(VD->getType())};
1093 llvm::CallBase *VoidPtr =
1094 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1095 CGM.getModule(), OMPRTL___kmpc_alloc_shared),
1096 AllocArgs, VD->getName());
1097 // FIXME: We should use the variables actual alignment as an argument.
1098 VoidPtr->addRetAttr(llvm::Attribute::get(
1099 CGM.getLLVMContext(), llvm::Attribute::Alignment,
1101
1102 // Cast the void pointer and get the address of the globalized variable.
1103 llvm::Value *CastedVoidPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
1104 VoidPtr, Bld.getPtrTy(0), VD->getName() + "_on_stack");
1105 LValue VarAddr =
1106 CGF.MakeNaturalAlignPointeeRawAddrLValue(CastedVoidPtr, VarTy);
1107 Rec.second.PrivateAddr = VarAddr.getAddress();
1108 Rec.second.GlobalizedVal = VoidPtr;
1109
1110 // Assign the local allocation to the newly globalized location.
1111 if (EscapedParam) {
1112 CGF.EmitStoreOfScalar(ParValue, VarAddr);
1113 I->getSecond().MappedParams->setVarAddr(CGF, VD, VarAddr.getAddress());
1114 }
1115 if (auto *DI = CGF.getDebugInfo())
1116 VoidPtr->setDebugLoc(DI->SourceLocToDebugLoc(VD->getLocation()));
1117 }
1118
1119 for (const auto *ValueD : I->getSecond().EscapedVariableLengthDecls) {
1120 const auto *VD = cast<VarDecl>(ValueD);
1121 std::pair<llvm::Value *, llvm::Value *> AddrSizePair =
1122 getKmpcAllocShared(CGF, VD);
1123 I->getSecond().EscapedVariableLengthDeclsAddrs.emplace_back(AddrSizePair);
1124 LValue Base = CGF.MakeAddrLValue(AddrSizePair.first, VD->getType(),
1125 CGM.getContext().getDeclAlign(VD),
1127 I->getSecond().MappedParams->setVarAddr(CGF, VD, Base.getAddress());
1128 }
1129 I->getSecond().MappedParams->apply(CGF);
1130}
1131
1133 const VarDecl *VD) const {
1134 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
1135 if (I == FunctionGlobalizedDecls.end())
1136 return false;
1137
1138 // Check variable declaration is delayed:
1139 return llvm::is_contained(I->getSecond().DelayedVariableLengthDecls, VD);
1140}
1141
1142std::pair<llvm::Value *, llvm::Value *>
1144 const VarDecl *VD) {
1145 CGBuilderTy &Bld = CGF.Builder;
1146
1147 // Compute size and alignment.
1148 llvm::Value *Size = CGF.getTypeSize(VD->getType());
1149 CharUnits Align = CGM.getContext().getDeclAlign(VD);
1150 Size = Bld.CreateNUWAdd(
1151 Size, llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity() - 1));
1152 llvm::Value *AlignVal =
1153 llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity());
1154 Size = Bld.CreateUDiv(Size, AlignVal);
1155 Size = Bld.CreateNUWMul(Size, AlignVal);
1156
1157 // Allocate space for this VLA object to be globalized.
1158 llvm::Value *AllocArgs[] = {Size};
1159 llvm::CallBase *VoidPtr =
1160 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1161 CGM.getModule(), OMPRTL___kmpc_alloc_shared),
1162 AllocArgs, VD->getName());
1163 VoidPtr->addRetAttr(llvm::Attribute::get(
1164 CGM.getLLVMContext(), llvm::Attribute::Alignment, Align.getQuantity()));
1165
1166 return std::make_pair(VoidPtr, Size);
1167}
1168
1170 CodeGenFunction &CGF,
1171 const std::pair<llvm::Value *, llvm::Value *> &AddrSizePair) {
1172 // Deallocate the memory for each globalized VLA object
1173 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1174 CGM.getModule(), OMPRTL___kmpc_free_shared),
1175 {AddrSizePair.first, AddrSizePair.second});
1176}
1177
1178void CGOpenMPRuntimeGPU::emitGenericVarsEpilog(CodeGenFunction &CGF) {
1179 if (getDataSharingMode() != CGOpenMPRuntimeGPU::DS_Generic)
1180 return;
1181
1182 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
1183 if (I != FunctionGlobalizedDecls.end()) {
1184 // Deallocate the memory for each globalized VLA object that was
1185 // globalized in the prolog (i.e. emitGenericVarsProlog).
1186 for (const auto &AddrSizePair :
1187 llvm::reverse(I->getSecond().EscapedVariableLengthDeclsAddrs)) {
1188 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1189 CGM.getModule(), OMPRTL___kmpc_free_shared),
1190 {AddrSizePair.first, AddrSizePair.second});
1191 }
1192 // Deallocate the memory for each globalized value
1193 for (auto &Rec : llvm::reverse(I->getSecond().LocalVarData)) {
1194 const auto *VD = cast<VarDecl>(Rec.first);
1195 I->getSecond().MappedParams->restore(CGF);
1196
1197 llvm::Value *FreeArgs[] = {Rec.second.GlobalizedVal,
1198 CGF.getTypeSize(VD->getType())};
1199 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1200 CGM.getModule(), OMPRTL___kmpc_free_shared),
1201 FreeArgs);
1202 }
1203 }
1204}
1205
1207 const OMPExecutableDirective &D,
1208 SourceLocation Loc,
1209 llvm::Function *OutlinedFn,
1210 ArrayRef<llvm::Value *> CapturedVars) {
1211 if (!CGF.HaveInsertPoint())
1212 return;
1213
1214 bool IsBareKernel = D.getSingleClause<OMPXBareClause>();
1215
1217 /*Name=*/".zero.addr");
1218 CGF.Builder.CreateStore(CGF.Builder.getInt32(/*C*/ 0), ZeroAddr);
1220 // We don't emit any thread id function call in bare kernel, but because the
1221 // outlined function has a pointer argument, we emit a nullptr here.
1222 if (IsBareKernel)
1223 OutlinedFnArgs.push_back(llvm::ConstantPointerNull::get(CGM.VoidPtrTy));
1224 else
1225 OutlinedFnArgs.push_back(emitThreadIDAddress(CGF, Loc).emitRawPointer(CGF));
1226 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
1227 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
1228 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
1229}
1230
1232 CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
1233 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond,
1234 llvm::Value *NumThreads, OpenMPNumThreadsClauseModifier NumThreadsModifier,
1235 OpenMPSeverityClauseKind Severity, const Expr *Message) {
1236 if (!CGF.HaveInsertPoint())
1237 return;
1238
1239 auto &&ParallelGen = [this, Loc, OutlinedFn, CapturedVars, IfCond,
1240 NumThreads](CodeGenFunction &CGF,
1241 PrePostActionTy &Action) {
1242 CGBuilderTy &Bld = CGF.Builder;
1243 llvm::Value *NumThreadsVal = NumThreads;
1244 llvm::Function *WFn = WrapperFunctionsMap[OutlinedFn];
1245 llvm::PointerType *FnPtrTy = llvm::PointerType::get(
1246 CGF.getLLVMContext(), CGM.getDataLayout().getProgramAddressSpace());
1247
1248 llvm::Value *ID = llvm::ConstantPointerNull::get(FnPtrTy);
1249 if (WFn)
1250 ID = Bld.CreateBitOrPointerCast(WFn, FnPtrTy);
1251
1252 llvm::Value *FnPtr = Bld.CreateBitOrPointerCast(OutlinedFn, FnPtrTy);
1253
1254 // Create a private scope that will globalize the arguments
1255 // passed from the outside of the target region.
1256 // TODO: Is that needed?
1257 CodeGenFunction::OMPPrivateScope PrivateArgScope(CGF);
1258
1259 Address CapturedVarsAddrs = CGF.CreateDefaultAlignTempAlloca(
1260 llvm::ArrayType::get(CGM.VoidPtrTy, CapturedVars.size()),
1261 "captured_vars_addrs");
1262 // There's something to share.
1263 if (!CapturedVars.empty()) {
1264 // Prepare for parallel region. Indicate the outlined function.
1265 ASTContext &Ctx = CGF.getContext();
1266 unsigned Idx = 0;
1267 for (llvm::Value *V : CapturedVars) {
1268 Address Dst = Bld.CreateConstArrayGEP(CapturedVarsAddrs, Idx);
1269 llvm::Value *PtrV;
1270 if (V->getType()->isIntegerTy())
1271 PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
1272 else
1274 CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
1275 Ctx.getPointerType(Ctx.VoidPtrTy));
1276 ++Idx;
1277 }
1278 }
1279
1280 llvm::Value *IfCondVal = nullptr;
1281 if (IfCond)
1282 IfCondVal = Bld.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.Int32Ty,
1283 /* isSigned */ false);
1284 else
1285 IfCondVal = llvm::ConstantInt::get(CGF.Int32Ty, 1);
1286
1287 if (!NumThreadsVal)
1288 NumThreadsVal = llvm::ConstantInt::get(CGF.Int32Ty, -1);
1289 else
1290 NumThreadsVal = Bld.CreateZExtOrTrunc(NumThreadsVal, CGF.Int32Ty);
1291
1292 assert(IfCondVal && "Expected a value");
1293 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
1294 llvm::Value *Args[] = {
1295 RTLoc,
1296 getThreadID(CGF, Loc),
1297 IfCondVal,
1298 NumThreadsVal,
1299 llvm::ConstantInt::get(CGF.Int32Ty, -1),
1300 FnPtr,
1301 ID,
1302 Bld.CreateBitOrPointerCast(CapturedVarsAddrs.emitRawPointer(CGF),
1303 CGF.VoidPtrPtrTy),
1304 llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size())};
1305 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1306 CGM.getModule(), OMPRTL___kmpc_parallel_51),
1307 Args);
1308 };
1309
1310 RegionCodeGenTy RCG(ParallelGen);
1311 RCG(CGF);
1312}
1313
1314void CGOpenMPRuntimeGPU::syncCTAThreads(CodeGenFunction &CGF) {
1315 // Always emit simple barriers!
1316 if (!CGF.HaveInsertPoint())
1317 return;
1318 // Build call __kmpc_barrier_simple_spmd(nullptr, 0);
1319 // This function does not use parameters, so we can emit just default values.
1320 llvm::Value *Args[] = {
1321 llvm::ConstantPointerNull::get(
1323 llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/0, /*isSigned=*/true)};
1324 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1325 CGM.getModule(), OMPRTL___kmpc_barrier_simple_spmd),
1326 Args);
1327}
1328
1330 SourceLocation Loc,
1331 OpenMPDirectiveKind Kind, bool,
1332 bool) {
1333 // Always emit simple barriers!
1334 if (!CGF.HaveInsertPoint())
1335 return;
1336 // Build call __kmpc_cancel_barrier(loc, thread_id);
1337 unsigned Flags = getDefaultFlagsForBarriers(Kind);
1338 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
1339 getThreadID(CGF, Loc)};
1340
1341 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1342 CGM.getModule(), OMPRTL___kmpc_barrier),
1343 Args);
1344}
1345
1347 CodeGenFunction &CGF, StringRef CriticalName,
1348 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
1349 const Expr *Hint) {
1350 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
1351 llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
1352 llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
1353 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
1354 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
1355
1356 auto &RT = static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
1357
1358 // Get the mask of active threads in the warp.
1359 llvm::Value *Mask = CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1360 CGM.getModule(), OMPRTL___kmpc_warp_active_thread_mask));
1361 // Fetch team-local id of the thread.
1362 llvm::Value *ThreadID = RT.getGPUThreadID(CGF);
1363
1364 // Get the width of the team.
1365 llvm::Value *TeamWidth = RT.getGPUNumThreads(CGF);
1366
1367 // Initialize the counter variable for the loop.
1368 QualType Int32Ty =
1369 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
1370 Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
1371 LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
1372 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
1373 /*isInit=*/true);
1374
1375 // Block checks if loop counter exceeds upper bound.
1376 CGF.EmitBlock(LoopBB);
1377 llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
1378 llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
1379 CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
1380
1381 // Block tests which single thread should execute region, and which threads
1382 // should go straight to synchronisation point.
1383 CGF.EmitBlock(TestBB);
1384 CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
1385 llvm::Value *CmpThreadToCounter =
1386 CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
1387 CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
1388
1389 // Block emits the body of the critical region.
1390 CGF.EmitBlock(BodyBB);
1391
1392 // Output the critical statement.
1393 CGOpenMPRuntime::emitCriticalRegion(CGF, CriticalName, CriticalOpGen, Loc,
1394 Hint);
1395
1396 // After the body surrounded by the critical region, the single executing
1397 // thread will jump to the synchronisation point.
1398 // Block waits for all threads in current team to finish then increments the
1399 // counter variable and returns to the loop.
1400 CGF.EmitBlock(SyncBB);
1401 // Reconverge active threads in the warp.
1402 (void)CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1403 CGM.getModule(), OMPRTL___kmpc_syncwarp),
1404 Mask);
1405
1406 llvm::Value *IncCounterVal =
1407 CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
1408 CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
1409 CGF.EmitBranch(LoopBB);
1410
1411 // Block that is reached when all threads in the team complete the region.
1412 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1413}
1414
1415/// Cast value to the specified type.
1416static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
1417 QualType ValTy, QualType CastTy,
1418 SourceLocation Loc) {
1419 assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
1420 "Cast type must sized.");
1421 assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
1422 "Val type must sized.");
1423 llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
1424 if (ValTy == CastTy)
1425 return Val;
1426 if (CGF.getContext().getTypeSizeInChars(ValTy) ==
1427 CGF.getContext().getTypeSizeInChars(CastTy))
1428 return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
1429 if (CastTy->isIntegerType() && ValTy->isIntegerType())
1430 return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
1432 Address CastItem = CGF.CreateMemTemp(CastTy);
1433 Address ValCastItem = CastItem.withElementType(Val->getType());
1434 CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy,
1436 TBAAAccessInfo());
1437 return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc,
1439 TBAAAccessInfo());
1440}
1441
1442///
1443/// Design of OpenMP reductions on the GPU
1444///
1445/// Consider a typical OpenMP program with one or more reduction
1446/// clauses:
1447///
1448/// float foo;
1449/// double bar;
1450/// #pragma omp target teams distribute parallel for \
1451/// reduction(+:foo) reduction(*:bar)
1452/// for (int i = 0; i < N; i++) {
1453/// foo += A[i]; bar *= B[i];
1454/// }
1455///
1456/// where 'foo' and 'bar' are reduced across all OpenMP threads in
1457/// all teams. In our OpenMP implementation on the NVPTX device an
1458/// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
1459/// within a team are mapped to CUDA threads within a threadblock.
1460/// Our goal is to efficiently aggregate values across all OpenMP
1461/// threads such that:
1462///
1463/// - the compiler and runtime are logically concise, and
1464/// - the reduction is performed efficiently in a hierarchical
1465/// manner as follows: within OpenMP threads in the same warp,
1466/// across warps in a threadblock, and finally across teams on
1467/// the NVPTX device.
1468///
1469/// Introduction to Decoupling
1470///
1471/// We would like to decouple the compiler and the runtime so that the
1472/// latter is ignorant of the reduction variables (number, data types)
1473/// and the reduction operators. This allows a simpler interface
1474/// and implementation while still attaining good performance.
1475///
1476/// Pseudocode for the aforementioned OpenMP program generated by the
1477/// compiler is as follows:
1478///
1479/// 1. Create private copies of reduction variables on each OpenMP
1480/// thread: 'foo_private', 'bar_private'
1481/// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
1482/// to it and writes the result in 'foo_private' and 'bar_private'
1483/// respectively.
1484/// 3. Call the OpenMP runtime on the GPU to reduce within a team
1485/// and store the result on the team master:
1486///
1487/// __kmpc_nvptx_parallel_reduce_nowait_v2(...,
1488/// reduceData, shuffleReduceFn, interWarpCpyFn)
1489///
1490/// where:
1491/// struct ReduceData {
1492/// double *foo;
1493/// double *bar;
1494/// } reduceData
1495/// reduceData.foo = &foo_private
1496/// reduceData.bar = &bar_private
1497///
1498/// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
1499/// auxiliary functions generated by the compiler that operate on
1500/// variables of type 'ReduceData'. They aid the runtime perform
1501/// algorithmic steps in a data agnostic manner.
1502///
1503/// 'shuffleReduceFn' is a pointer to a function that reduces data
1504/// of type 'ReduceData' across two OpenMP threads (lanes) in the
1505/// same warp. It takes the following arguments as input:
1506///
1507/// a. variable of type 'ReduceData' on the calling lane,
1508/// b. its lane_id,
1509/// c. an offset relative to the current lane_id to generate a
1510/// remote_lane_id. The remote lane contains the second
1511/// variable of type 'ReduceData' that is to be reduced.
1512/// d. an algorithm version parameter determining which reduction
1513/// algorithm to use.
1514///
1515/// 'shuffleReduceFn' retrieves data from the remote lane using
1516/// efficient GPU shuffle intrinsics and reduces, using the
1517/// algorithm specified by the 4th parameter, the two operands
1518/// element-wise. The result is written to the first operand.
1519///
1520/// Different reduction algorithms are implemented in different
1521/// runtime functions, all calling 'shuffleReduceFn' to perform
1522/// the essential reduction step. Therefore, based on the 4th
1523/// parameter, this function behaves slightly differently to
1524/// cooperate with the runtime to ensure correctness under
1525/// different circumstances.
1526///
1527/// 'InterWarpCpyFn' is a pointer to a function that transfers
1528/// reduced variables across warps. It tunnels, through CUDA
1529/// shared memory, the thread-private data of type 'ReduceData'
1530/// from lane 0 of each warp to a lane in the first warp.
1531/// 4. Call the OpenMP runtime on the GPU to reduce across teams.
1532/// The last team writes the global reduced value to memory.
1533///
1534/// ret = __kmpc_nvptx_teams_reduce_nowait(...,
1535/// reduceData, shuffleReduceFn, interWarpCpyFn,
1536/// scratchpadCopyFn, loadAndReduceFn)
1537///
1538/// 'scratchpadCopyFn' is a helper that stores reduced
1539/// data from the team master to a scratchpad array in
1540/// global memory.
1541///
1542/// 'loadAndReduceFn' is a helper that loads data from
1543/// the scratchpad array and reduces it with the input
1544/// operand.
1545///
1546/// These compiler generated functions hide address
1547/// calculation and alignment information from the runtime.
1548/// 5. if ret == 1:
1549/// The team master of the last team stores the reduced
1550/// result to the globals in memory.
1551/// foo += reduceData.foo; bar *= reduceData.bar
1552///
1553///
1554/// Warp Reduction Algorithms
1555///
1556/// On the warp level, we have three algorithms implemented in the
1557/// OpenMP runtime depending on the number of active lanes:
1558///
1559/// Full Warp Reduction
1560///
1561/// The reduce algorithm within a warp where all lanes are active
1562/// is implemented in the runtime as follows:
1563///
1564/// full_warp_reduce(void *reduce_data,
1565/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
1566/// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
1567/// ShuffleReduceFn(reduce_data, 0, offset, 0);
1568/// }
1569///
1570/// The algorithm completes in log(2, WARPSIZE) steps.
1571///
1572/// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
1573/// not used therefore we save instructions by not retrieving lane_id
1574/// from the corresponding special registers. The 4th parameter, which
1575/// represents the version of the algorithm being used, is set to 0 to
1576/// signify full warp reduction.
1577///
1578/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
1579///
1580/// #reduce_elem refers to an element in the local lane's data structure
1581/// #remote_elem is retrieved from a remote lane
1582/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
1583/// reduce_elem = reduce_elem REDUCE_OP remote_elem;
1584///
1585/// Contiguous Partial Warp Reduction
1586///
1587/// This reduce algorithm is used within a warp where only the first
1588/// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
1589/// number of OpenMP threads in a parallel region is not a multiple of
1590/// WARPSIZE. The algorithm is implemented in the runtime as follows:
1591///
1592/// void
1593/// contiguous_partial_reduce(void *reduce_data,
1594/// kmp_ShuffleReductFctPtr ShuffleReduceFn,
1595/// int size, int lane_id) {
1596/// int curr_size;
1597/// int offset;
1598/// curr_size = size;
1599/// mask = curr_size/2;
1600/// while (offset>0) {
1601/// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
1602/// curr_size = (curr_size+1)/2;
1603/// offset = curr_size/2;
1604/// }
1605/// }
1606///
1607/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
1608///
1609/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
1610/// if (lane_id < offset)
1611/// reduce_elem = reduce_elem REDUCE_OP remote_elem
1612/// else
1613/// reduce_elem = remote_elem
1614///
1615/// This algorithm assumes that the data to be reduced are located in a
1616/// contiguous subset of lanes starting from the first. When there is
1617/// an odd number of active lanes, the data in the last lane is not
1618/// aggregated with any other lane's dat but is instead copied over.
1619///
1620/// Dispersed Partial Warp Reduction
1621///
1622/// This algorithm is used within a warp when any discontiguous subset of
1623/// lanes are active. It is used to implement the reduction operation
1624/// across lanes in an OpenMP simd region or in a nested parallel region.
1625///
1626/// void
1627/// dispersed_partial_reduce(void *reduce_data,
1628/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
1629/// int size, remote_id;
1630/// int logical_lane_id = number_of_active_lanes_before_me() * 2;
1631/// do {
1632/// remote_id = next_active_lane_id_right_after_me();
1633/// # the above function returns 0 of no active lane
1634/// # is present right after the current lane.
1635/// size = number_of_active_lanes_in_this_warp();
1636/// logical_lane_id /= 2;
1637/// ShuffleReduceFn(reduce_data, logical_lane_id,
1638/// remote_id-1-threadIdx.x, 2);
1639/// } while (logical_lane_id % 2 == 0 && size > 1);
1640/// }
1641///
1642/// There is no assumption made about the initial state of the reduction.
1643/// Any number of lanes (>=1) could be active at any position. The reduction
1644/// result is returned in the first active lane.
1645///
1646/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
1647///
1648/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
1649/// if (lane_id % 2 == 0 && offset > 0)
1650/// reduce_elem = reduce_elem REDUCE_OP remote_elem
1651/// else
1652/// reduce_elem = remote_elem
1653///
1654///
1655/// Intra-Team Reduction
1656///
1657/// This function, as implemented in the runtime call
1658/// '__kmpc_nvptx_parallel_reduce_nowait_v2', aggregates data across OpenMP
1659/// threads in a team. It first reduces within a warp using the
1660/// aforementioned algorithms. We then proceed to gather all such
1661/// reduced values at the first warp.
1662///
1663/// The runtime makes use of the function 'InterWarpCpyFn', which copies
1664/// data from each of the "warp master" (zeroth lane of each warp, where
1665/// warp-reduced data is held) to the zeroth warp. This step reduces (in
1666/// a mathematical sense) the problem of reduction across warp masters in
1667/// a block to the problem of warp reduction.
1668///
1669///
1670/// Inter-Team Reduction
1671///
1672/// Once a team has reduced its data to a single value, it is stored in
1673/// a global scratchpad array. Since each team has a distinct slot, this
1674/// can be done without locking.
1675///
1676/// The last team to write to the scratchpad array proceeds to reduce the
1677/// scratchpad array. One or more workers in the last team use the helper
1678/// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
1679/// the k'th worker reduces every k'th element.
1680///
1681/// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait_v2' to
1682/// reduce across workers and compute a globally reduced value.
1683///
1687 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
1688 if (!CGF.HaveInsertPoint())
1689 return;
1690
1691 bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
1692 bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
1693
1694 ASTContext &C = CGM.getContext();
1695
1696 if (Options.SimpleReduction) {
1697 assert(!TeamsReduction && !ParallelReduction &&
1698 "Invalid reduction selection in emitReduction.");
1699 (void)ParallelReduction;
1700 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
1701 ReductionOps, Options);
1702 return;
1703 }
1704
1705 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> VarFieldMap;
1706 llvm::SmallVector<const ValueDecl *, 4> PrivatesReductions(Privates.size());
1707 int Cnt = 0;
1708 for (const Expr *DRE : Privates) {
1709 PrivatesReductions[Cnt] = cast<DeclRefExpr>(DRE)->getDecl();
1710 ++Cnt;
1711 }
1712 const RecordDecl *ReductionRec = ::buildRecordForGlobalizedVars(
1713 CGM.getContext(), PrivatesReductions, {}, VarFieldMap, 1);
1714
1715 if (TeamsReduction)
1716 TeamsReductions.push_back(ReductionRec);
1717
1718 // Source location for the ident struct
1719 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
1720
1721 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
1722 InsertPointTy AllocaIP(CGF.AllocaInsertPt->getParent(),
1723 CGF.AllocaInsertPt->getIterator());
1724 InsertPointTy CodeGenIP(CGF.Builder.GetInsertBlock(),
1725 CGF.Builder.GetInsertPoint());
1726 llvm::OpenMPIRBuilder::LocationDescription OmpLoc(
1727 CodeGenIP, CGF.SourceLocToDebugLoc(Loc));
1729
1731 unsigned Idx = 0;
1732 for (const Expr *Private : Privates) {
1733 llvm::Type *ElementType;
1734 llvm::Value *Variable;
1735 llvm::Value *PrivateVariable;
1736 llvm::OpenMPIRBuilder::ReductionGenAtomicCBTy AtomicReductionGen = nullptr;
1737 ElementType = CGF.ConvertTypeForMem(Private->getType());
1738 const auto *RHSVar =
1739 cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[Idx])->getDecl());
1740 PrivateVariable = CGF.GetAddrOfLocalVar(RHSVar).emitRawPointer(CGF);
1741 const auto *LHSVar =
1742 cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[Idx])->getDecl());
1743 Variable = CGF.GetAddrOfLocalVar(LHSVar).emitRawPointer(CGF);
1744 llvm::OpenMPIRBuilder::EvalKind EvalKind;
1745 switch (CGF.getEvaluationKind(Private->getType())) {
1746 case TEK_Scalar:
1747 EvalKind = llvm::OpenMPIRBuilder::EvalKind::Scalar;
1748 break;
1749 case TEK_Complex:
1750 EvalKind = llvm::OpenMPIRBuilder::EvalKind::Complex;
1751 break;
1752 case TEK_Aggregate:
1753 EvalKind = llvm::OpenMPIRBuilder::EvalKind::Aggregate;
1754 break;
1755 }
1756 auto ReductionGen = [&](InsertPointTy CodeGenIP, unsigned I,
1757 llvm::Value **LHSPtr, llvm::Value **RHSPtr,
1758 llvm::Function *NewFunc) {
1759 CGF.Builder.restoreIP(CodeGenIP);
1760 auto *CurFn = CGF.CurFn;
1761 CGF.CurFn = NewFunc;
1762
1763 *LHSPtr = CGF.GetAddrOfLocalVar(
1764 cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl()))
1765 .emitRawPointer(CGF);
1766 *RHSPtr = CGF.GetAddrOfLocalVar(
1767 cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl()))
1768 .emitRawPointer(CGF);
1769
1770 emitSingleReductionCombiner(CGF, ReductionOps[I], Privates[I],
1771 cast<DeclRefExpr>(LHSExprs[I]),
1772 cast<DeclRefExpr>(RHSExprs[I]));
1773
1774 CGF.CurFn = CurFn;
1775
1776 return InsertPointTy(CGF.Builder.GetInsertBlock(),
1777 CGF.Builder.GetInsertPoint());
1778 };
1779 ReductionInfos.emplace_back(llvm::OpenMPIRBuilder::ReductionInfo(
1780 ElementType, Variable, PrivateVariable, EvalKind,
1781 /*ReductionGen=*/nullptr, ReductionGen, AtomicReductionGen));
1782 Idx++;
1783 }
1784
1785 llvm::OpenMPIRBuilder::InsertPointTy AfterIP =
1786 cantFail(OMPBuilder.createReductionsGPU(
1787 OmpLoc, AllocaIP, CodeGenIP, ReductionInfos, false, TeamsReduction,
1788 llvm::OpenMPIRBuilder::ReductionGenCBKind::Clang,
1789 CGF.getTarget().getGridValue(),
1790 C.getLangOpts().OpenMPCUDAReductionBufNum, RTLoc));
1791 CGF.Builder.restoreIP(AfterIP);
1792}
1793
1794const VarDecl *
1796 const VarDecl *NativeParam) const {
1797 if (!NativeParam->getType()->isReferenceType())
1798 return NativeParam;
1799 QualType ArgType = NativeParam->getType();
1801 const Type *NonQualTy = QC.strip(ArgType);
1802 QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
1803 if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
1804 if (Attr->getCaptureKind() == OMPC_map) {
1805 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
1807 }
1808 }
1809 ArgType = CGM.getContext().getPointerType(PointeeTy);
1810 QC.addRestrict();
1811 enum { NVPTX_local_addr = 5 };
1812 QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
1813 ArgType = QC.apply(CGM.getContext(), ArgType);
1814 if (isa<ImplicitParamDecl>(NativeParam))
1816 CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
1818 return ParmVarDecl::Create(
1819 CGM.getContext(),
1820 const_cast<DeclContext *>(NativeParam->getDeclContext()),
1821 NativeParam->getBeginLoc(), NativeParam->getLocation(),
1822 NativeParam->getIdentifier(), ArgType,
1823 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
1824}
1825
1826Address
1828 const VarDecl *NativeParam,
1829 const VarDecl *TargetParam) const {
1830 assert(NativeParam != TargetParam &&
1831 NativeParam->getType()->isReferenceType() &&
1832 "Native arg must not be the same as target arg.");
1833 Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
1834 QualType NativeParamType = NativeParam->getType();
1836 const Type *NonQualTy = QC.strip(NativeParamType);
1837 QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
1838 unsigned NativePointeeAddrSpace =
1839 CGF.getTypes().getTargetAddressSpace(NativePointeeTy);
1840 QualType TargetTy = TargetParam->getType();
1841 llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(LocalAddr, /*Volatile=*/false,
1842 TargetTy, SourceLocation());
1843 // Cast to native address space.
1845 TargetAddr,
1846 llvm::PointerType::get(CGF.getLLVMContext(), NativePointeeAddrSpace));
1847 Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
1848 CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
1849 NativeParamType);
1850 return NativeParamAddr;
1851}
1852
1854 CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn,
1855 ArrayRef<llvm::Value *> Args) const {
1857 TargetArgs.reserve(Args.size());
1858 auto *FnType = OutlinedFn.getFunctionType();
1859 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
1860 if (FnType->isVarArg() && FnType->getNumParams() <= I) {
1861 TargetArgs.append(std::next(Args.begin(), I), Args.end());
1862 break;
1863 }
1864 llvm::Type *TargetType = FnType->getParamType(I);
1865 llvm::Value *NativeArg = Args[I];
1866 if (!TargetType->isPointerTy()) {
1867 TargetArgs.emplace_back(NativeArg);
1868 continue;
1869 }
1870 TargetArgs.emplace_back(
1871 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(NativeArg, TargetType));
1872 }
1873 CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
1874}
1875
1876/// Emit function which wraps the outline parallel region
1877/// and controls the arguments which are passed to this function.
1878/// The wrapper ensures that the outlined function is called
1879/// with the correct arguments when data is shared.
1880llvm::Function *CGOpenMPRuntimeGPU::createParallelDataSharingWrapper(
1881 llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
1882 ASTContext &Ctx = CGM.getContext();
1883 const auto &CS = *D.getCapturedStmt(OMPD_parallel);
1884
1885 // Create a function that takes as argument the source thread.
1886 FunctionArgList WrapperArgs;
1887 QualType Int16QTy =
1888 Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
1889 QualType Int32QTy =
1890 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
1891 ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
1892 /*Id=*/nullptr, Int16QTy,
1894 ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
1895 /*Id=*/nullptr, Int32QTy,
1897 WrapperArgs.emplace_back(&ParallelLevelArg);
1898 WrapperArgs.emplace_back(&WrapperArg);
1899
1900 const CGFunctionInfo &CGFI =
1902
1903 auto *Fn = llvm::Function::Create(
1904 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
1905 Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
1906
1907 // Ensure we do not inline the function. This is trivially true for the ones
1908 // passed to __kmpc_fork_call but the ones calles in serialized regions
1909 // could be inlined. This is not a perfect but it is closer to the invariant
1910 // we want, namely, every data environment starts with a new function.
1911 // TODO: We should pass the if condition to the runtime function and do the
1912 // handling there. Much cleaner code.
1913 Fn->addFnAttr(llvm::Attribute::NoInline);
1914
1916 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
1917 Fn->setDoesNotRecurse();
1918
1919 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
1920 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
1921 D.getBeginLoc(), D.getBeginLoc());
1922
1923 const auto *RD = CS.getCapturedRecordDecl();
1924 auto CurField = RD->field_begin();
1925
1926 Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
1927 /*Name=*/".zero.addr");
1928 CGF.Builder.CreateStore(CGF.Builder.getInt32(/*C*/ 0), ZeroAddr);
1929 // Get the array of arguments.
1931
1932 Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).emitRawPointer(CGF));
1933 Args.emplace_back(ZeroAddr.emitRawPointer(CGF));
1934
1935 CGBuilderTy &Bld = CGF.Builder;
1936 auto CI = CS.capture_begin();
1937
1938 // Use global memory for data sharing.
1939 // Handle passing of global args to workers.
1940 RawAddress GlobalArgs =
1941 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
1942 llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
1943 llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
1944 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1945 CGM.getModule(), OMPRTL___kmpc_get_shared_variables),
1946 DataSharingArgs);
1947
1948 // Retrieve the shared variables from the list of references returned
1949 // by the runtime. Pass the variables to the outlined function.
1950 Address SharedArgListAddress = Address::invalid();
1951 if (CS.capture_size() > 0 ||
1952 isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
1953 SharedArgListAddress = CGF.EmitLoadOfPointer(
1954 GlobalArgs, CGF.getContext()
1956 .castAs<PointerType>());
1957 }
1958 unsigned Idx = 0;
1959 if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
1960 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
1962 Src, Bld.getPtrTy(0), CGF.SizeTy);
1963 llvm::Value *LB = CGF.EmitLoadOfScalar(
1964 TypedAddress,
1965 /*Volatile=*/false,
1967 cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
1968 Args.emplace_back(LB);
1969 ++Idx;
1970 Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
1971 TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(Src, Bld.getPtrTy(0),
1972 CGF.SizeTy);
1973 llvm::Value *UB = CGF.EmitLoadOfScalar(
1974 TypedAddress,
1975 /*Volatile=*/false,
1977 cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
1978 Args.emplace_back(UB);
1979 ++Idx;
1980 }
1981 if (CS.capture_size() > 0) {
1982 ASTContext &CGFContext = CGF.getContext();
1983 for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
1984 QualType ElemTy = CurField->getType();
1985 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx);
1986 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
1987 Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)),
1988 CGF.ConvertTypeForMem(ElemTy));
1989 llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
1990 /*Volatile=*/false,
1991 CGFContext.getPointerType(ElemTy),
1992 CI->getLocation());
1993 if (CI->capturesVariableByCopy() &&
1994 !CI->getCapturedVar()->getType()->isAnyPointerType()) {
1995 Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
1996 CI->getLocation());
1997 }
1998 Args.emplace_back(Arg);
1999 }
2000 }
2001
2002 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedParallelFn, Args);
2003 CGF.FinishFunction();
2004 return Fn;
2005}
2006
2008 const Decl *D) {
2009 if (getDataSharingMode() != CGOpenMPRuntimeGPU::DS_Generic)
2010 return;
2011
2012 assert(D && "Expected function or captured|block decl.");
2013 assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
2014 "Function is registered already.");
2015 assert((!TeamAndReductions.first || TeamAndReductions.first == D) &&
2016 "Team is set but not processed.");
2017 const Stmt *Body = nullptr;
2018 bool NeedToDelayGlobalization = false;
2019 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2020 Body = FD->getBody();
2021 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
2022 Body = BD->getBody();
2023 } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
2024 Body = CD->getBody();
2025 NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
2026 if (NeedToDelayGlobalization &&
2027 getExecutionMode() == CGOpenMPRuntimeGPU::EM_SPMD)
2028 return;
2029 }
2030 if (!Body)
2031 return;
2032 CheckVarsEscapingDeclContext VarChecker(CGF, TeamAndReductions.second);
2033 VarChecker.Visit(Body);
2034 const RecordDecl *GlobalizedVarsRecord =
2035 VarChecker.getGlobalizedRecord(IsInTTDRegion);
2036 TeamAndReductions.first = nullptr;
2037 TeamAndReductions.second.clear();
2038 ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
2039 VarChecker.getEscapedVariableLengthDecls();
2040 ArrayRef<const ValueDecl *> DelayedVariableLengthDecls =
2041 VarChecker.getDelayedVariableLengthDecls();
2042 if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty() &&
2043 DelayedVariableLengthDecls.empty())
2044 return;
2045 auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
2046 I->getSecond().MappedParams =
2047 std::make_unique<CodeGenFunction::OMPMapVars>();
2048 I->getSecond().EscapedParameters.insert(
2049 VarChecker.getEscapedParameters().begin(),
2050 VarChecker.getEscapedParameters().end());
2051 I->getSecond().EscapedVariableLengthDecls.append(
2052 EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
2053 I->getSecond().DelayedVariableLengthDecls.append(
2054 DelayedVariableLengthDecls.begin(), DelayedVariableLengthDecls.end());
2055 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
2056 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
2057 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
2058 Data.try_emplace(VD);
2059 }
2060 if (!NeedToDelayGlobalization) {
2061 emitGenericVarsProlog(CGF, D->getBeginLoc());
2062 struct GlobalizationScope final : EHScopeStack::Cleanup {
2063 GlobalizationScope() = default;
2064
2065 void Emit(CodeGenFunction &CGF, Flags flags) override {
2066 static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime())
2067 .emitGenericVarsEpilog(CGF);
2068 }
2069 };
2070 CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
2071 }
2072}
2073
2075 const VarDecl *VD) {
2076 if (VD && VD->hasAttr<OMPAllocateDeclAttr>()) {
2077 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
2078 auto AS = LangAS::Default;
2079 switch (A->getAllocatorType()) {
2080 case OMPAllocateDeclAttr::OMPNullMemAlloc:
2081 case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
2082 case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
2083 case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
2084 break;
2085 case OMPAllocateDeclAttr::OMPThreadMemAlloc:
2086 return Address::invalid();
2087 case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
2088 // TODO: implement aupport for user-defined allocators.
2089 return Address::invalid();
2090 case OMPAllocateDeclAttr::OMPConstMemAlloc:
2092 break;
2093 case OMPAllocateDeclAttr::OMPPTeamMemAlloc:
2095 break;
2096 case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
2097 case OMPAllocateDeclAttr::OMPCGroupMemAlloc:
2098 break;
2099 }
2100 llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
2101 auto *GV = new llvm::GlobalVariable(
2102 CGM.getModule(), VarTy, /*isConstant=*/false,
2103 llvm::GlobalValue::InternalLinkage, llvm::PoisonValue::get(VarTy),
2104 VD->getName(),
2105 /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
2106 CGM.getContext().getTargetAddressSpace(AS));
2107 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2108 GV->setAlignment(Align.getAsAlign());
2109 return Address(
2111 GV, CGF.Builder.getPtrTy(CGM.getContext().getTargetAddressSpace(
2112 VD->getType().getAddressSpace()))),
2113 VarTy, Align);
2114 }
2115
2116 if (getDataSharingMode() != CGOpenMPRuntimeGPU::DS_Generic)
2117 return Address::invalid();
2118
2119 VD = VD->getCanonicalDecl();
2120 auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
2121 if (I == FunctionGlobalizedDecls.end())
2122 return Address::invalid();
2123 auto VDI = I->getSecond().LocalVarData.find(VD);
2124 if (VDI != I->getSecond().LocalVarData.end())
2125 return VDI->second.PrivateAddr;
2126 if (VD->hasAttrs()) {
2128 E(VD->attr_end());
2129 IT != E; ++IT) {
2130 auto VDI = I->getSecond().LocalVarData.find(
2131 cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
2132 ->getCanonicalDecl());
2133 if (VDI != I->getSecond().LocalVarData.end())
2134 return VDI->second.PrivateAddr;
2135 }
2136 }
2137
2138 return Address::invalid();
2139}
2140
2142 FunctionGlobalizedDecls.erase(CGF.CurFn);
2144}
2145
2147 CodeGenFunction &CGF, const OMPLoopDirective &S,
2148 OpenMPDistScheduleClauseKind &ScheduleKind,
2149 llvm::Value *&Chunk) const {
2150 auto &RT = static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
2151 if (getExecutionMode() == CGOpenMPRuntimeGPU::EM_SPMD) {
2152 ScheduleKind = OMPC_DIST_SCHEDULE_static;
2153 Chunk = CGF.EmitScalarConversion(
2154 RT.getGPUNumThreads(CGF),
2155 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
2156 S.getIterationVariable()->getType(), S.getBeginLoc());
2157 return;
2158 }
2160 CGF, S, ScheduleKind, Chunk);
2161}
2162
2164 CodeGenFunction &CGF, const OMPLoopDirective &S,
2165 OpenMPScheduleClauseKind &ScheduleKind,
2166 const Expr *&ChunkExpr) const {
2167 ScheduleKind = OMPC_SCHEDULE_static;
2168 // Chunk size is 1 in this case.
2169 llvm::APInt ChunkSize(32, 1);
2170 ChunkExpr = IntegerLiteral::Create(CGF.getContext(), ChunkSize,
2171 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
2172 SourceLocation());
2173}
2174
2176 CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
2177 assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
2178 " Expected target-based directive.");
2179 const CapturedStmt *CS = D.getCapturedStmt(OMPD_target);
2180 for (const CapturedStmt::Capture &C : CS->captures()) {
2181 // Capture variables captured by reference in lambdas for target-based
2182 // directives.
2183 if (!C.capturesVariable())
2184 continue;
2185 const VarDecl *VD = C.getCapturedVar();
2186 const auto *RD = VD->getType()
2190 if (!RD || !RD->isLambda())
2191 continue;
2192 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
2193 LValue VDLVal;
2195 VDLVal = CGF.EmitLoadOfReferenceLValue(VDAddr, VD->getType());
2196 else
2197 VDLVal = CGF.MakeAddrLValue(
2198 VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
2199 llvm::DenseMap<const ValueDecl *, FieldDecl *> Captures;
2200 FieldDecl *ThisCapture = nullptr;
2201 RD->getCaptureFields(Captures, ThisCapture);
2202 if (ThisCapture && CGF.CapturedStmtInfo->isCXXThisExprCaptured()) {
2203 LValue ThisLVal =
2204 CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
2205 llvm::Value *CXXThis = CGF.LoadCXXThis();
2206 CGF.EmitStoreOfScalar(CXXThis, ThisLVal);
2207 }
2208 for (const LambdaCapture &LC : RD->captures()) {
2209 if (LC.getCaptureKind() != LCK_ByRef)
2210 continue;
2211 const ValueDecl *VD = LC.getCapturedVar();
2212 // FIXME: For now VD is always a VarDecl because OpenMP does not support
2213 // capturing structured bindings in lambdas yet.
2214 if (!CS->capturesVariable(cast<VarDecl>(VD)))
2215 continue;
2216 auto It = Captures.find(VD);
2217 assert(It != Captures.end() && "Found lambda capture without field.");
2218 LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
2219 Address VDAddr = CGF.GetAddrOfLocalVar(cast<VarDecl>(VD));
2221 VDAddr = CGF.EmitLoadOfReferenceLValue(VDAddr,
2222 VD->getType().getCanonicalType())
2223 .getAddress();
2224 CGF.EmitStoreOfScalar(VDAddr.emitRawPointer(CGF), VarLVal);
2225 }
2226 }
2227}
2228
2230 LangAS &AS) {
2231 if (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())
2232 return false;
2233 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
2234 switch(A->getAllocatorType()) {
2235 case OMPAllocateDeclAttr::OMPNullMemAlloc:
2236 case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
2237 // Not supported, fallback to the default mem space.
2238 case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
2239 case OMPAllocateDeclAttr::OMPCGroupMemAlloc:
2240 case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
2241 case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
2242 case OMPAllocateDeclAttr::OMPThreadMemAlloc:
2243 AS = LangAS::Default;
2244 return true;
2245 case OMPAllocateDeclAttr::OMPConstMemAlloc:
2247 return true;
2248 case OMPAllocateDeclAttr::OMPPTeamMemAlloc:
2250 return true;
2251 case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
2252 llvm_unreachable("Expected predefined allocator for the variables with the "
2253 "static storage.");
2254 }
2255 return false;
2256}
2257
2258// Get current OffloadArch and ignore any unknown values
2260 if (!CGM.getTarget().hasFeature("ptx"))
2261 return OffloadArch::UNKNOWN;
2262 for (const auto &Feature : CGM.getTarget().getTargetOpts().FeatureMap) {
2263 if (Feature.getValue()) {
2266 return Arch;
2267 }
2268 }
2269 return OffloadArch::UNKNOWN;
2270}
2271
2272/// Check to see if target architecture supports unified addressing which is
2273/// a restriction for OpenMP requires clause "unified_shared_memory".
2275 for (const OMPClause *Clause : D->clauselists()) {
2276 if (Clause->getClauseKind() == OMPC_unified_shared_memory) {
2278 switch (Arch) {
2279 case OffloadArch::SM_20:
2280 case OffloadArch::SM_21:
2281 case OffloadArch::SM_30:
2283 case OffloadArch::SM_35:
2284 case OffloadArch::SM_37:
2285 case OffloadArch::SM_50:
2286 case OffloadArch::SM_52:
2287 case OffloadArch::SM_53: {
2288 SmallString<256> Buffer;
2289 llvm::raw_svector_ostream Out(Buffer);
2290 Out << "Target architecture " << OffloadArchToString(Arch)
2291 << " does not support unified addressing";
2292 CGM.Error(Clause->getBeginLoc(), Out.str());
2293 return;
2294 }
2295 case OffloadArch::SM_60:
2296 case OffloadArch::SM_61:
2297 case OffloadArch::SM_62:
2298 case OffloadArch::SM_70:
2299 case OffloadArch::SM_72:
2300 case OffloadArch::SM_75:
2301 case OffloadArch::SM_80:
2302 case OffloadArch::SM_86:
2303 case OffloadArch::SM_87:
2304 case OffloadArch::SM_89:
2305 case OffloadArch::SM_90:
2376 break;
2377 case OffloadArch::LAST:
2378 llvm_unreachable("Unexpected GPU arch.");
2379 }
2380 }
2381 }
2383}
2384
2386 CGBuilderTy &Bld = CGF.Builder;
2387 llvm::Module *M = &CGF.CGM.getModule();
2388 const char *LocSize = "__kmpc_get_hardware_num_threads_in_block";
2389 llvm::Function *F = M->getFunction(LocSize);
2390 if (!F) {
2391 F = llvm::Function::Create(llvm::FunctionType::get(CGF.Int32Ty, {}, false),
2392 llvm::GlobalVariable::ExternalLinkage, LocSize,
2393 &CGF.CGM.getModule());
2394 }
2395 return Bld.CreateCall(F, {}, "nvptx_num_threads");
2396}
2397
2400 return CGF.EmitRuntimeCall(
2401 OMPBuilder.getOrCreateRuntimeFunction(
2402 CGM.getModule(), OMPRTL___kmpc_get_hardware_thread_id_in_block),
2403 Args);
2404}
#define V(N, I)
static void getTeamsReductionVars(ASTContext &Ctx, const OMPExecutableDirective &D, llvm::SmallVectorImpl< const ValueDecl * > &Vars)
Get list of reduction variables from the teams ... directives.
static llvm::Value * castValueToType(CodeGenFunction &CGF, llvm::Value *Val, QualType ValTy, QualType CastTy, SourceLocation Loc)
Cast value to the specified type.
static void getDistributeLastprivateVars(ASTContext &Ctx, const OMPExecutableDirective &D, llvm::SmallVectorImpl< const ValueDecl * > &Vars)
Get list of lastprivate variables from the teams distribute ... or teams {distribute ....
static bool hasNestedSPMDDirective(ASTContext &Ctx, const OMPExecutableDirective &D)
Check for inner (nested) SPMD construct, if any.
static bool supportsSPMDExecutionMode(ASTContext &Ctx, const OMPExecutableDirective &D)
static OffloadArch getOffloadArch(CodeGenModule &CGM)
This file defines OpenMP nodes for declarative directives.
This file defines OpenMP AST classes for clauses.
static std::pair< ValueDecl *, bool > getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc, SourceRange &ERange, bool AllowArraySection=false, bool AllowAssumedSizeArray=false, StringRef DiagType="")
This file defines OpenMP AST classes for executable directives and clauses.
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
Definition Decl.cpp:4692
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType VoidPtrTy
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,...
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:891
Attr - This represents one attribute.
Definition Attr.h:44
ArrayRef< Capture > captures() const
Definition Decl.h:4781
const BlockDecl * getBlockDecl() const
Definition Expr.h:6570
Expr * getCallee()
Definition Expr.h:3024
arg_range arguments()
Definition Expr.h:3129
Describes the capture of either a variable, or 'this', or variable-length array type.
Definition Stmt.h:3899
This captures a statement into a function.
Definition Stmt.h:3886
bool capturesVariable(const VarDecl *Var) const
True if this variable has been captured.
Definition Stmt.cpp:1475
capture_range captures()
Definition Stmt.h:4024
CastKind getCastKind() const
Definition Expr.h:3654
Expr * getSubExpr()
Definition Expr.h:3660
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition CharUnits.h:122
llvm::Align getAsAlign() const
getAsAlign - Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit b...
Definition CharUnits.h:189
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
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
Address withElementType(llvm::Type *ElemTy) const
Return address with different element type, but same pointer and alignment.
Definition Address.h:276
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition CGBuilder.h:140
Address CreatePointerBitCastOrAddrSpaceCast(Address Addr, llvm::Type *Ty, llvm::Type *ElementTy, const llvm::Twine &Name="")
Definition CGBuilder.h:207
Address CreateConstArrayGEP(Address Addr, uint64_t Index, const llvm::Twine &Name="")
Given addr = [n x T]* ... produce name = getelementptr inbounds addr, i64 0, i64 index where i64 is a...
Definition CGBuilder.h:245
Address CreateConstInBoundsGEP(Address Addr, uint64_t Index, const llvm::Twine &Name="")
Given addr = T* ... produce name = getelementptr inbounds addr, i64 index where i64 is actually the t...
Definition CGBuilder.h:265
CGFunctionInfo - Class to encapsulate the information about a function definition.
llvm::Function * emitTeamsOutlinedFunction(CodeGenFunction &CGF, const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) override
Emits inlined function for the specified OpenMP teams.
void emitProcBindClause(CodeGenFunction &CGF, llvm::omp::ProcBindKind ProcBind, SourceLocation Loc) override
Emit call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32global_tid, int proc_bind) to generate...
void emitReduction(CodeGenFunction &CGF, SourceLocation Loc, ArrayRef< const Expr * > Privates, ArrayRef< const Expr * > LHSExprs, ArrayRef< const Expr * > RHSExprs, ArrayRef< const Expr * > ReductionOps, ReductionOptionsTy Options) override
Emit a code for reduction clause.
DataSharingMode
Target codegen is specialized based on two data-sharing modes: CUDA, in which the local variables are...
@ DS_Generic
Generic data-sharing mode.
void getDefaultDistScheduleAndChunk(CodeGenFunction &CGF, const OMPLoopDirective &S, OpenMPDistScheduleClauseKind &ScheduleKind, llvm::Value *&Chunk) const override
Choose a default value for the dist_schedule clause.
Address getAddressOfLocalVariable(CodeGenFunction &CGF, const VarDecl *VD) override
Gets the OpenMP-specific address of the local variable.
void emitFunctionProlog(CodeGenFunction &CGF, const Decl *D) override
Emits OpenMP-specific function prolog.
void getDefaultScheduleAndChunk(CodeGenFunction &CGF, const OMPLoopDirective &S, OpenMPScheduleClauseKind &ScheduleKind, const Expr *&ChunkExpr) const override
Choose a default value for the schedule clause.
void emitNumTeamsClause(CodeGenFunction &CGF, const Expr *NumTeams, const Expr *ThreadLimit, SourceLocation Loc) override
This function ought to emit, in the general case, a call to.
void emitCriticalRegion(CodeGenFunction &CGF, StringRef CriticalName, const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc, const Expr *Hint=nullptr) override
Emits a critical region.
void emitTeamsCall(CodeGenFunction &CGF, const OMPExecutableDirective &D, SourceLocation Loc, llvm::Function *OutlinedFn, ArrayRef< llvm::Value * > CapturedVars) override
Emits code for teams call of the OutlinedFn with variables captured in a record which address is stor...
bool hasAllocateAttributeForGlobalVar(const VarDecl *VD, LangAS &AS) override
Checks if the variable has associated OMPAllocateDeclAttr attribute with the predefined allocator and...
void getKmpcFreeShared(CodeGenFunction &CGF, const std::pair< llvm::Value *, llvm::Value * > &AddrSizePair) override
Get call to __kmpc_free_shared.
llvm::Function * emitParallelOutlinedFunction(CodeGenFunction &CGF, const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) override
Emits inlined function for the specified OpenMP parallel.
void functionFinished(CodeGenFunction &CGF) override
Cleans up references to the objects in finished function.
llvm::Value * getGPUThreadID(CodeGenFunction &CGF)
Get the id of the current thread on the GPU.
void processRequiresDirective(const OMPRequiresDecl *D) override
Perform check on requires decl to ensure that target architecture supports unified addressing.
bool isDelayedVariableLengthDecl(CodeGenFunction &CGF, const VarDecl *VD) const override
Declare generalized virtual functions which need to be defined by all specializations of OpenMPGPURun...
void emitOutlinedFunctionCall(CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn, ArrayRef< llvm::Value * > Args={}) const override
Emits call of the outlined function with the provided arguments, translating these arguments to corre...
Address getParameterAddress(CodeGenFunction &CGF, const VarDecl *NativeParam, const VarDecl *TargetParam) const override
Gets the address of the native argument basing on the address of the target-specific parameter.
ExecutionMode
Defines the execution mode.
@ EM_NonSPMD
Non-SPMD execution mode (1 master thread, others are workers).
@ EM_Unknown
Unknown execution mode (orphaned directive).
@ EM_SPMD
SPMD execution mode (all threads are worker threads).
void emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind Kind, bool EmitChecks=true, bool ForceSimpleCall=false) override
Emit an implicit/explicit barrier for OpenMP threads.
llvm::Value * getGPUNumThreads(CodeGenFunction &CGF)
Get the maximum number of threads in a block of the GPU.
const VarDecl * translateParameter(const FieldDecl *FD, const VarDecl *NativeParam) const override
Translates the native parameter of outlined function if this is required for target.
std::pair< llvm::Value *, llvm::Value * > getKmpcAllocShared(CodeGenFunction &CGF, const VarDecl *VD) override
Get call to __kmpc_alloc_shared.
bool isGPU() const override
Returns true if the current target is a GPU.
llvm::Value * emitSeverityClause(OpenMPSeverityClauseKind Severity, SourceLocation Loc) override
llvm::Value * emitMessageClause(CodeGenFunction &CGF, const Expr *Message, SourceLocation Loc) override
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) override
Emits code for parallel or serial call of the OutlinedFn with variables captured in a record which ad...
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()) override
Emits call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32global_tid, kmp_int32 num_threads) ...
void adjustTargetSpecificDataForLambdas(CodeGenFunction &CGF, const OMPExecutableDirective &D) const override
Adjust some parameters for the target-based directives, like addresses of the variables captured by r...
virtual Address emitThreadIDAddress(CodeGenFunction &CGF, SourceLocation Loc)
Emits address of the word in a memory where current thread id is stored.
static const Stmt * getSingleCompoundChild(ASTContext &Ctx, const Stmt *Body)
Checks if the Body is the CompoundStmt and returns its child statement iff there is only one that is ...
llvm::Value * emitUpdateLocation(CodeGenFunction &CGF, SourceLocation Loc, unsigned Flags=0, bool EmitLoc=false)
Emits object of ident_t type with info for source location.
virtual void functionFinished(CodeGenFunction &CGF)
Cleans up references to the objects in finished function.
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.
llvm::OpenMPIRBuilder OMPBuilder
An OpenMP-IR-Builder instance.
virtual void emitTargetOutlinedFunctionHelper(const OMPExecutableDirective &D, StringRef ParentName, llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID, bool IsOffloadEntry, const RegionCodeGenTy &CodeGen)
Helper to emit outlined function for 'target' directive.
bool hasRequiresUnifiedSharedMemory() const
Return whether the unified_shared_memory has been specified.
virtual void processRequiresDirective(const OMPRequiresDecl *D)
Perform check on requires decl to ensure that target architecture supports unified addressing.
llvm::Value * getThreadID(CodeGenFunction &CGF, SourceLocation Loc)
Gets thread id value for the current thread.
void computeMinAndMaxThreadsAndTeams(const OMPExecutableDirective &D, CodeGenFunction &CGF, llvm::OpenMPIRBuilder::TargetKernelDefaultAttrs &Attrs)
Helper to determine the min/max number of threads/teams for D.
static unsigned getDefaultFlagsForBarriers(OpenMPDirectiveKind Kind)
Returns default flags for the barriers depending on the directive, for which this barier is going to ...
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 getDefaultDistScheduleAndChunk(CodeGenFunction &CGF, const OMPLoopDirective &S, OpenMPDistScheduleClauseKind &ScheduleKind, llvm::Value *&Chunk) const
Choose default schedule type and chunk value for the dist_schedule clause.
llvm::Type * getIdentTyPointerTy()
Returns pointer to ident_t type.
void emitSingleReductionCombiner(CodeGenFunction &CGF, const Expr *ReductionOp, const Expr *PrivateRef, const DeclRefExpr *LHS, const DeclRefExpr *RHS)
Emits single reduction combiner.
llvm::OpenMPIRBuilder & getOMPBuilder()
virtual void emitCriticalRegion(CodeGenFunction &CGF, StringRef CriticalName, const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc, const Expr *Hint=nullptr)
Emits a critical region.
virtual void emitOutlinedFunctionCall(CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn, ArrayRef< llvm::Value * > Args={}) const
Emits call of the outlined function with the provided arguments, translating these arguments to corre...
virtual void emitReduction(CodeGenFunction &CGF, SourceLocation Loc, ArrayRef< const Expr * > Privates, ArrayRef< const Expr * > LHSExprs, ArrayRef< const Expr * > RHSExprs, ArrayRef< const Expr * > ReductionOps, ReductionOptionsTy Options)
Emit a code for reduction clause.
The scope used to remap some variables as private in the OpenMP loop body (or other captured region e...
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
LValue EmitLoadOfReferenceLValue(LValue RefLVal)
Definition CGExpr.cpp:3221
CGCapturedStmtInfo * CapturedStmtInfo
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
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:3230
LValue MakeNaturalAlignPointeeRawAddrLValue(llvm::Value *V, QualType T)
Same as MakeNaturalAlignPointeeAddrLValue except that the pointer is known to be unsigned.
llvm::AssertingVH< llvm::Instruction > AllocaInsertPt
AllocaInsertPoint - This is an instruction in the entry block before which we prefer to insert alloca...
llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Location)
Converts Location to a DebugLoc, if debug information is enabled.
RawAddress CreateDefaultAlignTempAlloca(llvm::Type *Ty, const Twine &Name="tmp")
CreateDefaultAlignedTempAlloca - This creates an alloca with the default ABI alignment of the given L...
Definition CGExpr.cpp:175
const TargetInfo & getTarget() const
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.
llvm::Value * EvaluateExprAsBool(const Expr *E)
EvaluateExprAsBool - Perform the usual unary conversions on the specified expression and compare the ...
Definition CGExpr.cpp:224
bool HaveInsertPoint() const
HaveInsertPoint - True if an insertion point is defined.
llvm::Value * getTypeSize(QualType Ty)
Returns calculated size of the specified type.
LValue EmitLValueForFieldInitialization(LValue Base, const FieldDecl *Field)
EmitLValueForFieldInitialization - Like EmitLValueForField, except that if the Field is a reference,...
Definition CGExpr.cpp:5617
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...
llvm::CallInst * EmitRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
llvm::Type * ConvertTypeForMem(QualType T)
CodeGenTypes & getTypes() const
static TypeEvaluationKind getEvaluationKind(QualType T)
getEvaluationKind - Return the TypeEvaluationKind of QualType T.
void EmitBranch(llvm::BasicBlock *Block)
EmitBranch - Emit a branch to the specified basic block from the current insert block,...
Definition CGStmt.cpp:675
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:187
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
void FinishFunction(SourceLocation EndLoc=SourceLocation())
FinishFunction - Complete IR generation of the current function.
llvm::Value * LoadCXXThis()
LoadCXXThis - Load the value of 'this'.
Address GetAddrOfLocalVar(const VarDecl *VD)
GetAddrOfLocalVar - Return the address of a local variable.
llvm::LLVMContext & getLLVMContext()
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...
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 EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition CGStmt.cpp:655
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
const TargetInfo & getTarget() const
CGOpenMPRuntime & getOpenMPRuntime()
Return a reference to the configured OpenMP runtime.
ASTContext & getContext() const
llvm::LLVMContext & getLLVMContext()
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition CGCall.cpp:1701
const CGFunctionInfo & arrangeBuiltinFunctionDeclaration(QualType resultType, const FunctionArgList &args)
A builtin function is a freestanding function using the default C conventions.
Definition CGCall.cpp:739
unsigned getTargetAddressSpace(QualType T) const
FunctionArgList - Type for representing both the decl and type of parameters to a function.
Definition CGCall.h:375
LValue - This represents an lvalue references.
Definition CGValue.h:182
Address getAddress() const
Definition CGValue.h:361
A basic class for pre|post-action for advanced codegen sequence for OpenMP region.
An abstract representation of an aligned address.
Definition Address.h:42
llvm::Value * getPointer() const
Definition Address.h:66
Class provides a way to call simple version of codegen for OpenMP region, or an advanced with possibl...
void setAction(PrePostActionTy &Action) const
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
void addDecl(Decl *D)
Add the declaration D into this context.
ValueDecl * getDecl()
Definition Expr.h:1338
decl_range decls()
Definition Stmt.h:1659
T * getAttr() const
Definition DeclBase.h:573
bool hasAttrs() const
Definition DeclBase.h:518
attr_iterator attr_end() const
Definition DeclBase.h:542
bool isCanonicalDecl() const
Whether this particular Decl is a canonical one.
Definition DeclBase.h:984
attr_iterator attr_begin() const
Definition DeclBase.h:539
SourceLocation getLocation() const
Definition DeclBase.h:439
DeclContext * getDeclContext()
Definition DeclBase.h:448
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:431
AttrVec & getAttrs()
Definition DeclBase.h:524
bool hasAttr() const
Definition DeclBase.h:577
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:978
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:831
This represents one expression.
Definition Expr.h:112
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3085
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3081
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:284
Represents a member of a struct/union/class.
Definition Decl.h:3160
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
Definition Decl.cpp:4692
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:57
static ImplicitParamDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, ImplicitParamKind ParamKind)
Create implicit parameter.
Definition Decl.cpp:5525
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition Expr.cpp:971
Describes the capture of a variable or of this, or of a C++1y init-capture.
bool isInitCapture(const LambdaCapture *Capture) const
Determine whether one of this lambda's captures is an init-capture.
Definition ExprCXX.cpp:1358
capture_range captures() const
Retrieve this lambda's captures.
Definition ExprCXX.cpp:1371
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
This is a basic class for representing single OpenMP clause.
This represents clause 'lastprivate' in the 'pragma omp ...' directives.
This represents clause 'reduction' in the 'pragma omp ...' directives.
This represents 'pragma omp requires...' directive.
Definition DeclOpenMP.h:479
clauselist_range clauselists()
Definition DeclOpenMP.h:504
This represents 'ompx_bare' clause in the 'pragma omp target teams ...' directive.
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:2946
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3328
A (possibly-)qualified type.
Definition TypeBase.h:937
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8416
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:8475
QualType getCanonicalType() const
Definition TypeBase.h:8342
A qualifier set is used to build a set of qualifiers.
Definition TypeBase.h:8230
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8237
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition Type.cpp:4660
void addAddressSpace(LangAS space)
Definition TypeBase.h:597
Represents a struct/union/class.
Definition Decl.h:4312
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition Decl.cpp:5221
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.
Stmt - This represents one statement.
Definition Stmt.h:85
child_range children()
Definition Stmt.cpp:295
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:4898
unsigned getNewAlign() const
Return the largest alignment for which a suitably-sized allocation with 'operator new(size_t)' is gua...
Definition TargetInfo.h:761
TargetOptions & getTargetOpts() const
Retrieve the target options.
Definition TargetInfo.h:323
virtual const llvm::omp::GV & getGridValue() const
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
llvm::StringMap< bool > FeatureMap
The map of which features have been enabled disabled based on the command line.
The base class of the type hierarchy.
Definition TypeBase.h:1833
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8927
bool isReferenceType() const
Definition TypeBase.h:8551
bool isLValueReferenceType() const
Definition TypeBase.h:8555
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition Type.cpp:2243
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2800
Expr * getSubExpr() const
Definition Expr.h:2285
Opcode getOpcode() const
Definition Expr.h:2280
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.cpp:5510
Represents a variable declaration or definition.
Definition Decl.h:926
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:2257
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1578
specific_attr_iterator - Iterates over a subrange of an AttrVec, only providing attributes that are o...
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
Definition CGValue.h:154
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
Definition CGValue.h:145
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:272
bool isOpenMPDistributeDirective(OpenMPDirectiveKind DKind)
Checks if the specified directive is a distribute directive.
@ LCK_ByRef
Capturing by reference.
Definition Lambda.h:37
@ Private
'private' clause, allowed on 'parallel', 'serial', 'loop', 'parallel loop', and 'serial loop' constru...
@ AS_public
Definition Specifiers.h:124
@ CR_OpenMP
bool isOpenMPParallelDirective(OpenMPDirectiveKind DKind)
Checks if the specified directive is a parallel-kind directive.
bool isOpenMPPrivate(OpenMPClauseKind Kind)
Checks if the specified clause is one of private clauses like 'private', 'firstprivate',...
@ SC_None
Definition Specifiers.h:250
OpenMPDistScheduleClauseKind
OpenMP attributes for 'dist_schedule' clause.
bool isOpenMPTargetExecutionDirective(OpenMPDirectiveKind DKind)
Checks if the specified directive is a target code offload directive.
bool isOpenMPTeamsDirective(OpenMPDirectiveKind DKind)
Checks if the specified directive is a teams-kind directive.
OffloadArch StringToOffloadArch(llvm::StringRef S)
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 ...
LangAS
Defines the address space values used by the address space qualifier of QualType.
const char * OffloadArchToString(OffloadArch A)
llvm::omp::Directive OpenMPDirectiveKind
OpenMP directives.
Definition OpenMPKinds.h:25
void getOpenMPCaptureRegions(llvm::SmallVectorImpl< OpenMPDirectiveKind > &CaptureRegions, OpenMPDirectiveKind DKind)
Return the captured regions of an OpenMP directive.
OpenMPNumThreadsClauseModifier
U cast(CodeGen::Address addr)
Definition Address.h:327
LangAS getLangASFromTargetAS(unsigned TargetAS)
@ CXXThis
Parameter for C++ 'this' argument.
Definition Decl.h:1734
@ Other
Other implicit parameter.
Definition Decl.h:1746
OpenMPScheduleClauseKind
OpenMP attributes for 'schedule' clause.
Definition OpenMPKinds.h:31
unsigned long uint64_t