1 //===----- CGOpenMPRuntime.cpp - Interface to OpenMP Runtimes -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This provides a class for OpenMP runtime code generation.
12 //===----------------------------------------------------------------------===//
15 #include "CGCleanup.h"
16 #include "CGOpenMPRuntime.h"
17 #include "CodeGenFunction.h"
18 #include "clang/CodeGen/ConstantInitBuilder.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/StmtOpenMP.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/Bitcode/BitcodeReader.h"
23 #include "llvm/IR/CallSite.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/GlobalValue.h"
26 #include "llvm/IR/Value.h"
27 #include "llvm/Support/Format.h"
28 #include "llvm/Support/raw_ostream.h"
31 using namespace clang;
32 using namespace CodeGen;
35 /// \brief Base class for handling code generation inside OpenMP regions.
36 class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
38 /// \brief Kinds of OpenMP regions used in codegen.
39 enum CGOpenMPRegionKind {
40 /// \brief Region with outlined function for standalone 'parallel'
42 ParallelOutlinedRegion,
43 /// \brief Region with outlined function for standalone 'task' directive.
45 /// \brief Region for constructs that do not require function outlining,
46 /// like 'for', 'sections', 'atomic' etc. directives.
48 /// \brief Region with outlined function for standalone 'target' directive.
52 CGOpenMPRegionInfo(const CapturedStmt &CS,
53 const CGOpenMPRegionKind RegionKind,
54 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
56 : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
57 CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {}
59 CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
60 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
62 : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen),
63 Kind(Kind), HasCancel(HasCancel) {}
65 /// \brief Get a variable or parameter for storing global thread id
66 /// inside OpenMP construct.
67 virtual const VarDecl *getThreadIDVariable() const = 0;
69 /// \brief Emit the captured statement body.
70 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
72 /// \brief Get an LValue for the current ThreadID variable.
73 /// \return LValue for thread id variable. This LValue always has type int32*.
74 virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
76 virtual void emitUntiedSwitch(CodeGenFunction & /*CGF*/) {}
78 CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
80 OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
82 bool hasCancel() const { return HasCancel; }
84 static bool classof(const CGCapturedStmtInfo *Info) {
85 return Info->getKind() == CR_OpenMP;
88 ~CGOpenMPRegionInfo() override = default;
91 CGOpenMPRegionKind RegionKind;
92 RegionCodeGenTy CodeGen;
93 OpenMPDirectiveKind Kind;
97 /// \brief API for captured statement code generation in OpenMP constructs.
98 class CGOpenMPOutlinedRegionInfo final : public CGOpenMPRegionInfo {
100 CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
101 const RegionCodeGenTy &CodeGen,
102 OpenMPDirectiveKind Kind, bool HasCancel,
103 StringRef HelperName)
104 : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind,
106 ThreadIDVar(ThreadIDVar), HelperName(HelperName) {
107 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
110 /// \brief Get a variable or parameter for storing global thread id
111 /// inside OpenMP construct.
112 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
114 /// \brief Get the name of the capture helper.
115 StringRef getHelperName() const override { return HelperName; }
117 static bool classof(const CGCapturedStmtInfo *Info) {
118 return CGOpenMPRegionInfo::classof(Info) &&
119 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
120 ParallelOutlinedRegion;
124 /// \brief A variable or parameter storing global thread id for OpenMP
126 const VarDecl *ThreadIDVar;
127 StringRef HelperName;
130 /// \brief API for captured statement code generation in OpenMP constructs.
131 class CGOpenMPTaskOutlinedRegionInfo final : public CGOpenMPRegionInfo {
133 class UntiedTaskActionTy final : public PrePostActionTy {
135 const VarDecl *PartIDVar;
136 const RegionCodeGenTy UntiedCodeGen;
137 llvm::SwitchInst *UntiedSwitch = nullptr;
140 UntiedTaskActionTy(bool Tied, const VarDecl *PartIDVar,
141 const RegionCodeGenTy &UntiedCodeGen)
142 : Untied(!Tied), PartIDVar(PartIDVar), UntiedCodeGen(UntiedCodeGen) {}
143 void Enter(CodeGenFunction &CGF) override {
145 // Emit task switching point.
146 auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
147 CGF.GetAddrOfLocalVar(PartIDVar),
148 PartIDVar->getType()->castAs<PointerType>());
149 auto *Res = CGF.EmitLoadOfScalar(PartIdLVal, SourceLocation());
150 auto *DoneBB = CGF.createBasicBlock(".untied.done.");
151 UntiedSwitch = CGF.Builder.CreateSwitch(Res, DoneBB);
152 CGF.EmitBlock(DoneBB);
153 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
154 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
155 UntiedSwitch->addCase(CGF.Builder.getInt32(0),
156 CGF.Builder.GetInsertBlock());
157 emitUntiedSwitch(CGF);
160 void emitUntiedSwitch(CodeGenFunction &CGF) const {
162 auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
163 CGF.GetAddrOfLocalVar(PartIDVar),
164 PartIDVar->getType()->castAs<PointerType>());
165 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
168 CodeGenFunction::JumpDest CurPoint =
169 CGF.getJumpDestInCurrentScope(".untied.next.");
170 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
171 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
172 UntiedSwitch->addCase(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
173 CGF.Builder.GetInsertBlock());
174 CGF.EmitBranchThroughCleanup(CurPoint);
175 CGF.EmitBlock(CurPoint.getBlock());
178 unsigned getNumberOfParts() const { return UntiedSwitch->getNumCases(); }
180 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
181 const VarDecl *ThreadIDVar,
182 const RegionCodeGenTy &CodeGen,
183 OpenMPDirectiveKind Kind, bool HasCancel,
184 const UntiedTaskActionTy &Action)
185 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel),
186 ThreadIDVar(ThreadIDVar), Action(Action) {
187 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
190 /// \brief Get a variable or parameter for storing global thread id
191 /// inside OpenMP construct.
192 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
194 /// \brief Get an LValue for the current ThreadID variable.
195 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
197 /// \brief Get the name of the capture helper.
198 StringRef getHelperName() const override { return ".omp_outlined."; }
200 void emitUntiedSwitch(CodeGenFunction &CGF) override {
201 Action.emitUntiedSwitch(CGF);
204 static bool classof(const CGCapturedStmtInfo *Info) {
205 return CGOpenMPRegionInfo::classof(Info) &&
206 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
211 /// \brief A variable or parameter storing global thread id for OpenMP
213 const VarDecl *ThreadIDVar;
214 /// Action for emitting code for untied tasks.
215 const UntiedTaskActionTy &Action;
218 /// \brief API for inlined captured statement code generation in OpenMP
220 class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
222 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
223 const RegionCodeGenTy &CodeGen,
224 OpenMPDirectiveKind Kind, bool HasCancel)
225 : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel),
227 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
229 // \brief Retrieve the value of the context parameter.
230 llvm::Value *getContextValue() const override {
232 return OuterRegionInfo->getContextValue();
233 llvm_unreachable("No context value for inlined OpenMP region");
236 void setContextValue(llvm::Value *V) override {
237 if (OuterRegionInfo) {
238 OuterRegionInfo->setContextValue(V);
241 llvm_unreachable("No context value for inlined OpenMP region");
244 /// \brief Lookup the captured field decl for a variable.
245 const FieldDecl *lookup(const VarDecl *VD) const override {
247 return OuterRegionInfo->lookup(VD);
248 // If there is no outer outlined region,no need to lookup in a list of
249 // captured variables, we can use the original one.
253 FieldDecl *getThisFieldDecl() const override {
255 return OuterRegionInfo->getThisFieldDecl();
259 /// \brief Get a variable or parameter for storing global thread id
260 /// inside OpenMP construct.
261 const VarDecl *getThreadIDVariable() const override {
263 return OuterRegionInfo->getThreadIDVariable();
267 /// \brief Get the name of the capture helper.
268 StringRef getHelperName() const override {
269 if (auto *OuterRegionInfo = getOldCSI())
270 return OuterRegionInfo->getHelperName();
271 llvm_unreachable("No helper name for inlined OpenMP construct");
274 void emitUntiedSwitch(CodeGenFunction &CGF) override {
276 OuterRegionInfo->emitUntiedSwitch(CGF);
279 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
281 static bool classof(const CGCapturedStmtInfo *Info) {
282 return CGOpenMPRegionInfo::classof(Info) &&
283 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
286 ~CGOpenMPInlinedRegionInfo() override = default;
289 /// \brief CodeGen info about outer OpenMP region.
290 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
291 CGOpenMPRegionInfo *OuterRegionInfo;
294 /// \brief API for captured statement code generation in OpenMP target
295 /// constructs. For this captures, implicit parameters are used instead of the
296 /// captured fields. The name of the target region has to be unique in a given
297 /// application so it is provided by the client, because only the client has
298 /// the information to generate that.
299 class CGOpenMPTargetRegionInfo final : public CGOpenMPRegionInfo {
301 CGOpenMPTargetRegionInfo(const CapturedStmt &CS,
302 const RegionCodeGenTy &CodeGen, StringRef HelperName)
303 : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target,
304 /*HasCancel=*/false),
305 HelperName(HelperName) {}
307 /// \brief This is unused for target regions because each starts executing
308 /// with a single thread.
309 const VarDecl *getThreadIDVariable() const override { return nullptr; }
311 /// \brief Get the name of the capture helper.
312 StringRef getHelperName() const override { return HelperName; }
314 static bool classof(const CGCapturedStmtInfo *Info) {
315 return CGOpenMPRegionInfo::classof(Info) &&
316 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion;
320 StringRef HelperName;
323 static void EmptyCodeGen(CodeGenFunction &, PrePostActionTy &) {
324 llvm_unreachable("No codegen for expressions");
326 /// \brief API for generation of expressions captured in a innermost OpenMP
328 class CGOpenMPInnerExprInfo final : public CGOpenMPInlinedRegionInfo {
330 CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS)
331 : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen,
333 /*HasCancel=*/false),
335 // Make sure the globals captured in the provided statement are local by
336 // using the privatization logic. We assume the same variable is not
337 // captured more than once.
338 for (auto &C : CS.captures()) {
339 if (!C.capturesVariable() && !C.capturesVariableByCopy())
342 const VarDecl *VD = C.getCapturedVar();
343 if (VD->isLocalVarDeclOrParm())
346 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
347 /*RefersToEnclosingVariableOrCapture=*/false,
348 VD->getType().getNonReferenceType(), VK_LValue,
350 PrivScope.addPrivate(VD, [&CGF, &DRE]() -> Address {
351 return CGF.EmitLValue(&DRE).getAddress();
354 (void)PrivScope.Privatize();
357 /// \brief Lookup the captured field decl for a variable.
358 const FieldDecl *lookup(const VarDecl *VD) const override {
359 if (auto *FD = CGOpenMPInlinedRegionInfo::lookup(VD))
364 /// \brief Emit the captured statement body.
365 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override {
366 llvm_unreachable("No body for expressions");
369 /// \brief Get a variable or parameter for storing global thread id
370 /// inside OpenMP construct.
371 const VarDecl *getThreadIDVariable() const override {
372 llvm_unreachable("No thread id for expressions");
375 /// \brief Get the name of the capture helper.
376 StringRef getHelperName() const override {
377 llvm_unreachable("No helper name for expressions");
380 static bool classof(const CGCapturedStmtInfo *Info) { return false; }
383 /// Private scope to capture global variables.
384 CodeGenFunction::OMPPrivateScope PrivScope;
387 /// \brief RAII for emitting code of OpenMP constructs.
388 class InlinedOpenMPRegionRAII {
389 CodeGenFunction &CGF;
390 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
391 FieldDecl *LambdaThisCaptureField = nullptr;
394 /// \brief Constructs region for combined constructs.
395 /// \param CodeGen Code generation sequence for combined directives. Includes
396 /// a list of functions used for code generation of implicitly inlined
398 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
399 OpenMPDirectiveKind Kind, bool HasCancel)
401 // Start emission for the construct.
402 CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
403 CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
404 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
405 LambdaThisCaptureField = CGF.LambdaThisCaptureField;
406 CGF.LambdaThisCaptureField = nullptr;
409 ~InlinedOpenMPRegionRAII() {
410 // Restore original CapturedStmtInfo only if we're done with code emission.
412 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
413 delete CGF.CapturedStmtInfo;
414 CGF.CapturedStmtInfo = OldCSI;
415 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
416 CGF.LambdaThisCaptureField = LambdaThisCaptureField;
420 /// \brief Values for bit flags used in the ident_t to describe the fields.
421 /// All enumeric elements are named and described in accordance with the code
422 /// from http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
423 enum OpenMPLocationFlags {
424 /// \brief Use trampoline for internal microtask.
425 OMP_IDENT_IMD = 0x01,
426 /// \brief Use c-style ident structure.
427 OMP_IDENT_KMPC = 0x02,
428 /// \brief Atomic reduction option for kmpc_reduce.
429 OMP_ATOMIC_REDUCE = 0x10,
430 /// \brief Explicit 'barrier' directive.
431 OMP_IDENT_BARRIER_EXPL = 0x20,
432 /// \brief Implicit barrier in code.
433 OMP_IDENT_BARRIER_IMPL = 0x40,
434 /// \brief Implicit barrier in 'for' directive.
435 OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
436 /// \brief Implicit barrier in 'sections' directive.
437 OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
438 /// \brief Implicit barrier in 'single' directive.
439 OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140
442 /// \brief Describes ident structure that describes a source location.
443 /// All descriptions are taken from
444 /// http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
445 /// Original structure:
446 /// typedef struct ident {
447 /// kmp_int32 reserved_1; /**< might be used in Fortran;
449 /// kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags;
450 /// KMP_IDENT_KMPC identifies this union
452 /// kmp_int32 reserved_2; /**< not really used in Fortran any more;
455 /// /* but currently used for storing
456 /// region-specific ITT */
457 /// /* contextual information. */
458 ///#endif /* USE_ITT_BUILD */
459 /// kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for
461 /// char const *psource; /**< String describing the source location.
462 /// The string is composed of semi-colon separated
463 // fields which describe the source file,
464 /// the function and a pair of line numbers that
465 /// delimit the construct.
468 enum IdentFieldIndex {
469 /// \brief might be used in Fortran
470 IdentField_Reserved_1,
471 /// \brief OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
473 /// \brief Not really used in Fortran any more
474 IdentField_Reserved_2,
475 /// \brief Source[4] in Fortran, do not use for C++
476 IdentField_Reserved_3,
477 /// \brief String describing the source location. The string is composed of
478 /// semi-colon separated fields which describe the source file, the function
479 /// and a pair of line numbers that delimit the construct.
483 /// \brief Schedule types for 'omp for' loops (these enumerators are taken from
484 /// the enum sched_type in kmp.h).
485 enum OpenMPSchedType {
486 /// \brief Lower bound for default (unordered) versions.
488 OMP_sch_static_chunked = 33,
490 OMP_sch_dynamic_chunked = 35,
491 OMP_sch_guided_chunked = 36,
492 OMP_sch_runtime = 37,
494 /// static with chunk adjustment (e.g., simd)
495 OMP_sch_static_balanced_chunked = 45,
496 /// \brief Lower bound for 'ordered' versions.
498 OMP_ord_static_chunked = 65,
500 OMP_ord_dynamic_chunked = 67,
501 OMP_ord_guided_chunked = 68,
502 OMP_ord_runtime = 69,
504 OMP_sch_default = OMP_sch_static,
505 /// \brief dist_schedule types
506 OMP_dist_sch_static_chunked = 91,
507 OMP_dist_sch_static = 92,
508 /// Support for OpenMP 4.5 monotonic and nonmonotonic schedule modifiers.
509 /// Set if the monotonic schedule modifier was present.
510 OMP_sch_modifier_monotonic = (1 << 29),
511 /// Set if the nonmonotonic schedule modifier was present.
512 OMP_sch_modifier_nonmonotonic = (1 << 30),
515 enum OpenMPRTLFunction {
516 /// \brief Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
517 /// kmpc_micro microtask, ...);
518 OMPRTL__kmpc_fork_call,
519 /// \brief Call to void *__kmpc_threadprivate_cached(ident_t *loc,
520 /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
521 OMPRTL__kmpc_threadprivate_cached,
522 /// \brief Call to void __kmpc_threadprivate_register( ident_t *,
523 /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
524 OMPRTL__kmpc_threadprivate_register,
525 // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
526 OMPRTL__kmpc_global_thread_num,
527 // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
528 // kmp_critical_name *crit);
529 OMPRTL__kmpc_critical,
530 // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32
531 // global_tid, kmp_critical_name *crit, uintptr_t hint);
532 OMPRTL__kmpc_critical_with_hint,
533 // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
534 // kmp_critical_name *crit);
535 OMPRTL__kmpc_end_critical,
536 // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
538 OMPRTL__kmpc_cancel_barrier,
539 // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
540 OMPRTL__kmpc_barrier,
541 // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
542 OMPRTL__kmpc_for_static_fini,
543 // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
545 OMPRTL__kmpc_serialized_parallel,
546 // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
548 OMPRTL__kmpc_end_serialized_parallel,
549 // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
550 // kmp_int32 num_threads);
551 OMPRTL__kmpc_push_num_threads,
552 // Call to void __kmpc_flush(ident_t *loc);
554 // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
556 // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
557 OMPRTL__kmpc_end_master,
558 // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
560 OMPRTL__kmpc_omp_taskyield,
561 // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
563 // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
564 OMPRTL__kmpc_end_single,
565 // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
566 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
567 // kmp_routine_entry_t *task_entry);
568 OMPRTL__kmpc_omp_task_alloc,
569 // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t *
571 OMPRTL__kmpc_omp_task,
572 // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
573 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
575 OMPRTL__kmpc_copyprivate,
576 // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
577 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
578 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
580 // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
581 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
582 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
584 OMPRTL__kmpc_reduce_nowait,
585 // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
586 // kmp_critical_name *lck);
587 OMPRTL__kmpc_end_reduce,
588 // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
589 // kmp_critical_name *lck);
590 OMPRTL__kmpc_end_reduce_nowait,
591 // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
592 // kmp_task_t * new_task);
593 OMPRTL__kmpc_omp_task_begin_if0,
594 // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
595 // kmp_task_t * new_task);
596 OMPRTL__kmpc_omp_task_complete_if0,
597 // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
598 OMPRTL__kmpc_ordered,
599 // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
600 OMPRTL__kmpc_end_ordered,
601 // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
603 OMPRTL__kmpc_omp_taskwait,
604 // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
605 OMPRTL__kmpc_taskgroup,
606 // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
607 OMPRTL__kmpc_end_taskgroup,
608 // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
610 OMPRTL__kmpc_push_proc_bind,
611 // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32
612 // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t
613 // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
614 OMPRTL__kmpc_omp_task_with_deps,
615 // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32
616 // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
617 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
618 OMPRTL__kmpc_omp_wait_deps,
619 // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
620 // global_tid, kmp_int32 cncl_kind);
621 OMPRTL__kmpc_cancellationpoint,
622 // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
623 // kmp_int32 cncl_kind);
625 // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid,
626 // kmp_int32 num_teams, kmp_int32 thread_limit);
627 OMPRTL__kmpc_push_num_teams,
628 // Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
630 OMPRTL__kmpc_fork_teams,
631 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
632 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
633 // sched, kmp_uint64 grainsize, void *task_dup);
634 OMPRTL__kmpc_taskloop,
635 // Call to void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
636 // num_dims, struct kmp_dim *dims);
637 OMPRTL__kmpc_doacross_init,
638 // Call to void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
639 OMPRTL__kmpc_doacross_fini,
640 // Call to void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
642 OMPRTL__kmpc_doacross_post,
643 // Call to void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
645 OMPRTL__kmpc_doacross_wait,
648 // Offloading related calls
650 // Call to int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
651 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
654 // Call to int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
655 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
656 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
657 OMPRTL__tgt_target_teams,
658 // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
659 OMPRTL__tgt_register_lib,
660 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
661 OMPRTL__tgt_unregister_lib,
662 // Call to void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
663 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
664 OMPRTL__tgt_target_data_begin,
665 // Call to void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
666 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
667 OMPRTL__tgt_target_data_end,
668 // Call to void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
669 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
670 OMPRTL__tgt_target_data_update,
673 /// A basic class for pre|post-action for advanced codegen sequence for OpenMP
675 class CleanupTy final : public EHScopeStack::Cleanup {
676 PrePostActionTy *Action;
679 explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
680 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
681 if (!CGF.HaveInsertPoint())
687 } // anonymous namespace
689 void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
690 CodeGenFunction::RunCleanupsScope Scope(CGF);
692 CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
693 Callback(CodeGen, CGF, *PrePostAction);
695 PrePostActionTy Action;
696 Callback(CodeGen, CGF, Action);
700 LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
701 return CGF.EmitLoadOfPointerLValue(
702 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
703 getThreadIDVariable()->getType()->castAs<PointerType>());
706 void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
707 if (!CGF.HaveInsertPoint())
709 // 1.2.2 OpenMP Language Terminology
710 // Structured block - An executable statement with a single entry at the
711 // top and a single exit at the bottom.
712 // The point of exit cannot be a branch out of the structured block.
713 // longjmp() and throw() must not violate the entry/exit criteria.
714 CGF.EHStack.pushTerminate();
716 CGF.EHStack.popTerminate();
719 LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
720 CodeGenFunction &CGF) {
721 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
722 getThreadIDVariable()->getType(),
723 LValueBaseInfo(AlignmentSource::Decl, false));
726 CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
727 : CGM(CGM), OffloadEntriesInfoManager(CGM) {
728 IdentTy = llvm::StructType::create(
729 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
730 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
731 CGM.Int8PtrTy /* psource */);
732 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
734 loadOffloadInfoMetadata();
737 void CGOpenMPRuntime::clear() {
738 InternalVars.clear();
741 static llvm::Function *
742 emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
743 const Expr *CombinerInitializer, const VarDecl *In,
744 const VarDecl *Out, bool IsCombiner) {
745 // void .omp_combiner.(Ty *in, Ty *out);
746 auto &C = CGM.getContext();
747 QualType PtrTy = C.getPointerType(Ty).withRestrict();
748 FunctionArgList Args;
749 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
750 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
751 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
752 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
753 Args.push_back(&OmpOutParm);
754 Args.push_back(&OmpInParm);
756 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
757 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
758 auto *Fn = llvm::Function::Create(
759 FnTy, llvm::GlobalValue::InternalLinkage,
760 IsCombiner ? ".omp_combiner." : ".omp_initializer.", &CGM.getModule());
761 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
762 Fn->removeFnAttr(llvm::Attribute::NoInline);
763 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
764 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
765 CodeGenFunction CGF(CGM);
766 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
767 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
768 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
769 CodeGenFunction::OMPPrivateScope Scope(CGF);
770 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
771 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() -> Address {
772 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
775 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
776 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() -> Address {
777 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
780 (void)Scope.Privatize();
781 CGF.EmitIgnoredExpr(CombinerInitializer);
782 Scope.ForceCleanup();
783 CGF.FinishFunction();
787 void CGOpenMPRuntime::emitUserDefinedReduction(
788 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
789 if (UDRMap.count(D) > 0)
791 auto &C = CGM.getContext();
793 In = &C.Idents.get("omp_in");
794 Out = &C.Idents.get("omp_out");
796 llvm::Function *Combiner = emitCombinerOrInitializer(
797 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
798 cast<VarDecl>(D->lookup(Out).front()),
799 /*IsCombiner=*/true);
800 llvm::Function *Initializer = nullptr;
801 if (auto *Init = D->getInitializer()) {
802 if (!Priv || !Orig) {
803 Priv = &C.Idents.get("omp_priv");
804 Orig = &C.Idents.get("omp_orig");
806 Initializer = emitCombinerOrInitializer(
807 CGM, D->getType(), Init, cast<VarDecl>(D->lookup(Orig).front()),
808 cast<VarDecl>(D->lookup(Priv).front()),
809 /*IsCombiner=*/false);
811 UDRMap.insert(std::make_pair(D, std::make_pair(Combiner, Initializer)));
813 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
814 Decls.second.push_back(D);
818 std::pair<llvm::Function *, llvm::Function *>
819 CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
820 auto I = UDRMap.find(D);
821 if (I != UDRMap.end())
823 emitUserDefinedReduction(/*CGF=*/nullptr, D);
824 return UDRMap.lookup(D);
827 // Layout information for ident_t.
828 static CharUnits getIdentAlign(CodeGenModule &CGM) {
829 return CGM.getPointerAlign();
831 static CharUnits getIdentSize(CodeGenModule &CGM) {
832 assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
833 return CharUnits::fromQuantity(16) + CGM.getPointerSize();
835 static CharUnits getOffsetOfIdentField(IdentFieldIndex Field) {
836 // All the fields except the last are i32, so this works beautifully.
837 return unsigned(Field) * CharUnits::fromQuantity(4);
839 static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
840 IdentFieldIndex Field,
841 const llvm::Twine &Name = "") {
842 auto Offset = getOffsetOfIdentField(Field);
843 return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
846 static llvm::Value *emitParallelOrTeamsOutlinedFunction(
847 CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
848 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
849 const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
850 assert(ThreadIDVar->getType()->isPointerType() &&
851 "thread id variable must be of type kmp_int32 *");
852 CodeGenFunction CGF(CGM, true);
853 bool HasCancel = false;
854 if (auto *OPD = dyn_cast<OMPParallelDirective>(&D))
855 HasCancel = OPD->hasCancel();
856 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
857 HasCancel = OPSD->hasCancel();
858 else if (auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
859 HasCancel = OPFD->hasCancel();
860 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
861 HasCancel, OutlinedHelperName);
862 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
863 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
866 llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
867 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
868 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
869 const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
870 return emitParallelOrTeamsOutlinedFunction(
871 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
874 llvm::Value *CGOpenMPRuntime::emitTeamsOutlinedFunction(
875 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
876 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
877 const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
878 return emitParallelOrTeamsOutlinedFunction(
879 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
882 llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
883 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
884 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
885 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
886 bool Tied, unsigned &NumberOfParts) {
887 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
889 auto *ThreadID = getThreadID(CGF, D.getLocStart());
890 auto *UpLoc = emitUpdateLocation(CGF, D.getLocStart());
891 llvm::Value *TaskArgs[] = {
893 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
894 TaskTVar->getType()->castAs<PointerType>())
896 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
898 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
900 CodeGen.setAction(Action);
901 assert(!ThreadIDVar->getType()->isPointerType() &&
902 "thread id variable must be of type kmp_int32 for tasks");
903 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
904 auto *TD = dyn_cast<OMPTaskDirective>(&D);
905 CodeGenFunction CGF(CGM, true);
906 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
908 TD ? TD->hasCancel() : false, Action);
909 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
910 auto *Res = CGF.GenerateCapturedStmtFunction(*CS);
912 NumberOfParts = Action.getNumberOfParts();
916 Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
917 CharUnits Align = getIdentAlign(CGM);
918 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
920 if (!DefaultOpenMPPSource) {
921 // Initialize default location for psource field of ident_t structure of
922 // all ident_t objects. Format is ";file;function;line;column;;".
924 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
925 DefaultOpenMPPSource =
926 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
927 DefaultOpenMPPSource =
928 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
931 ConstantInitBuilder builder(CGM);
932 auto fields = builder.beginStruct(IdentTy);
933 fields.addInt(CGM.Int32Ty, 0);
934 fields.addInt(CGM.Int32Ty, Flags);
935 fields.addInt(CGM.Int32Ty, 0);
936 fields.addInt(CGM.Int32Ty, 0);
937 fields.add(DefaultOpenMPPSource);
938 auto DefaultOpenMPLocation =
939 fields.finishAndCreateGlobal("", Align, /*isConstant*/ true,
940 llvm::GlobalValue::PrivateLinkage);
941 DefaultOpenMPLocation->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
943 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
945 return Address(Entry, Align);
948 llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
951 Flags |= OMP_IDENT_KMPC;
952 // If no debug info is generated - return global default location.
953 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
955 return getOrCreateDefaultLocation(Flags).getPointer();
957 assert(CGF.CurFn && "No function in current CodeGenFunction.");
959 Address LocValue = Address::invalid();
960 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
961 if (I != OpenMPLocThreadIDMap.end())
962 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
964 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
965 // GetOpenMPThreadID was called before this routine.
966 if (!LocValue.isValid()) {
967 // Generate "ident_t .kmpc_loc.addr;"
968 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
970 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
971 Elem.second.DebugLoc = AI.getPointer();
974 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
975 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
976 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
977 CGM.getSize(getIdentSize(CGF.CGM)));
980 // char **psource = &.kmpc_loc_<flags>.addr.psource;
981 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
983 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
984 if (OMPDebugLoc == nullptr) {
985 SmallString<128> Buffer2;
986 llvm::raw_svector_ostream OS2(Buffer2);
987 // Build debug location
988 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
989 OS2 << ";" << PLoc.getFilename() << ";";
990 if (const FunctionDecl *FD =
991 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
992 OS2 << FD->getQualifiedNameAsString();
994 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
995 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
996 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
998 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
999 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
1001 // Our callers always pass this to a runtime function, so for
1002 // convenience, go ahead and return a naked pointer.
1003 return LocValue.getPointer();
1006 llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1007 SourceLocation Loc) {
1008 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1010 llvm::Value *ThreadID = nullptr;
1011 // Check whether we've already cached a load of the thread id in this
1013 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1014 if (I != OpenMPLocThreadIDMap.end()) {
1015 ThreadID = I->second.ThreadID;
1016 if (ThreadID != nullptr)
1019 if (auto *OMPRegionInfo =
1020 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1021 if (OMPRegionInfo->getThreadIDVariable()) {
1022 // Check if this an outlined function with thread id passed as argument.
1023 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
1024 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
1025 // If value loaded in entry block, cache it and use it everywhere in
1027 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1028 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1029 Elem.second.ThreadID = ThreadID;
1035 // This is not an outlined function region - need to call __kmpc_int32
1036 // kmpc_global_thread_num(ident_t *loc).
1037 // Generate thread id value and cache this value for use across the
1039 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1040 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
1042 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1043 emitUpdateLocation(CGF, Loc));
1044 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1045 Elem.second.ThreadID = ThreadID;
1049 void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
1050 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1051 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1052 OpenMPLocThreadIDMap.erase(CGF.CurFn);
1053 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
1054 for(auto *D : FunctionUDRMap[CGF.CurFn]) {
1057 FunctionUDRMap.erase(CGF.CurFn);
1061 llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
1064 return llvm::PointerType::getUnqual(IdentTy);
1067 llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
1068 if (!Kmpc_MicroTy) {
1069 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1070 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1071 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1072 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1074 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1078 CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
1079 llvm::Constant *RTLFn = nullptr;
1080 switch (static_cast<OpenMPRTLFunction>(Function)) {
1081 case OMPRTL__kmpc_fork_call: {
1082 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1084 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1085 getKmpc_MicroPointerTy()};
1086 llvm::FunctionType *FnTy =
1087 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1088 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1091 case OMPRTL__kmpc_global_thread_num: {
1092 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
1093 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1094 llvm::FunctionType *FnTy =
1095 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1096 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1099 case OMPRTL__kmpc_threadprivate_cached: {
1100 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1101 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1102 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1103 CGM.VoidPtrTy, CGM.SizeTy,
1104 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
1105 llvm::FunctionType *FnTy =
1106 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1107 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1110 case OMPRTL__kmpc_critical: {
1111 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1112 // kmp_critical_name *crit);
1113 llvm::Type *TypeParams[] = {
1114 getIdentTyPointerTy(), CGM.Int32Ty,
1115 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1116 llvm::FunctionType *FnTy =
1117 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1118 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1121 case OMPRTL__kmpc_critical_with_hint: {
1122 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1123 // kmp_critical_name *crit, uintptr_t hint);
1124 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1125 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1127 llvm::FunctionType *FnTy =
1128 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1129 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1132 case OMPRTL__kmpc_threadprivate_register: {
1133 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1134 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1135 // typedef void *(*kmpc_ctor)(void *);
1137 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1138 /*isVarArg*/ false)->getPointerTo();
1139 // typedef void *(*kmpc_cctor)(void *, void *);
1140 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1141 auto KmpcCopyCtorTy =
1142 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
1143 /*isVarArg*/ false)->getPointerTo();
1144 // typedef void (*kmpc_dtor)(void *);
1146 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1148 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1149 KmpcCopyCtorTy, KmpcDtorTy};
1150 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
1151 /*isVarArg*/ false);
1152 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1155 case OMPRTL__kmpc_end_critical: {
1156 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1157 // kmp_critical_name *crit);
1158 llvm::Type *TypeParams[] = {
1159 getIdentTyPointerTy(), CGM.Int32Ty,
1160 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1161 llvm::FunctionType *FnTy =
1162 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1163 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1166 case OMPRTL__kmpc_cancel_barrier: {
1167 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1169 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1170 llvm::FunctionType *FnTy =
1171 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1172 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
1175 case OMPRTL__kmpc_barrier: {
1176 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
1177 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1178 llvm::FunctionType *FnTy =
1179 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1180 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1183 case OMPRTL__kmpc_for_static_fini: {
1184 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1185 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1186 llvm::FunctionType *FnTy =
1187 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1188 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1191 case OMPRTL__kmpc_push_num_threads: {
1192 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1193 // kmp_int32 num_threads)
1194 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1196 llvm::FunctionType *FnTy =
1197 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1198 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1201 case OMPRTL__kmpc_serialized_parallel: {
1202 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1204 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1205 llvm::FunctionType *FnTy =
1206 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1207 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1210 case OMPRTL__kmpc_end_serialized_parallel: {
1211 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1213 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1214 llvm::FunctionType *FnTy =
1215 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1216 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1219 case OMPRTL__kmpc_flush: {
1220 // Build void __kmpc_flush(ident_t *loc);
1221 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1222 llvm::FunctionType *FnTy =
1223 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1224 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1227 case OMPRTL__kmpc_master: {
1228 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1229 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1230 llvm::FunctionType *FnTy =
1231 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1232 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1235 case OMPRTL__kmpc_end_master: {
1236 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1237 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1238 llvm::FunctionType *FnTy =
1239 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1240 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1243 case OMPRTL__kmpc_omp_taskyield: {
1244 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1246 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1247 llvm::FunctionType *FnTy =
1248 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1249 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1252 case OMPRTL__kmpc_single: {
1253 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1254 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1255 llvm::FunctionType *FnTy =
1256 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1257 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1260 case OMPRTL__kmpc_end_single: {
1261 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1262 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1263 llvm::FunctionType *FnTy =
1264 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1265 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1268 case OMPRTL__kmpc_omp_task_alloc: {
1269 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1270 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1271 // kmp_routine_entry_t *task_entry);
1272 assert(KmpRoutineEntryPtrTy != nullptr &&
1273 "Type kmp_routine_entry_t must be created.");
1274 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1275 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1276 // Return void * and then cast to particular kmp_task_t type.
1277 llvm::FunctionType *FnTy =
1278 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1279 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1282 case OMPRTL__kmpc_omp_task: {
1283 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1285 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1287 llvm::FunctionType *FnTy =
1288 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1289 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1292 case OMPRTL__kmpc_copyprivate: {
1293 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
1294 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
1295 // kmp_int32 didit);
1296 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1298 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
1299 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
1300 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1302 llvm::FunctionType *FnTy =
1303 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1304 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1307 case OMPRTL__kmpc_reduce: {
1308 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1309 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1310 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1311 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1312 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1313 /*isVarArg=*/false);
1314 llvm::Type *TypeParams[] = {
1315 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1316 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1317 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1318 llvm::FunctionType *FnTy =
1319 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1320 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1323 case OMPRTL__kmpc_reduce_nowait: {
1324 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1325 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1326 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1328 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1329 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1330 /*isVarArg=*/false);
1331 llvm::Type *TypeParams[] = {
1332 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1333 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1334 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1335 llvm::FunctionType *FnTy =
1336 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1337 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1340 case OMPRTL__kmpc_end_reduce: {
1341 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1342 // kmp_critical_name *lck);
1343 llvm::Type *TypeParams[] = {
1344 getIdentTyPointerTy(), CGM.Int32Ty,
1345 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1346 llvm::FunctionType *FnTy =
1347 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1348 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1351 case OMPRTL__kmpc_end_reduce_nowait: {
1352 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1353 // kmp_critical_name *lck);
1354 llvm::Type *TypeParams[] = {
1355 getIdentTyPointerTy(), CGM.Int32Ty,
1356 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1357 llvm::FunctionType *FnTy =
1358 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1360 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1363 case OMPRTL__kmpc_omp_task_begin_if0: {
1364 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1366 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1368 llvm::FunctionType *FnTy =
1369 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1371 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1374 case OMPRTL__kmpc_omp_task_complete_if0: {
1375 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1377 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1379 llvm::FunctionType *FnTy =
1380 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1381 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1382 /*Name=*/"__kmpc_omp_task_complete_if0");
1385 case OMPRTL__kmpc_ordered: {
1386 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1387 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1388 llvm::FunctionType *FnTy =
1389 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1390 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1393 case OMPRTL__kmpc_end_ordered: {
1394 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
1395 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1396 llvm::FunctionType *FnTy =
1397 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1398 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1401 case OMPRTL__kmpc_omp_taskwait: {
1402 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1403 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1404 llvm::FunctionType *FnTy =
1405 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1406 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1409 case OMPRTL__kmpc_taskgroup: {
1410 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1411 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1412 llvm::FunctionType *FnTy =
1413 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1414 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1417 case OMPRTL__kmpc_end_taskgroup: {
1418 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1419 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1420 llvm::FunctionType *FnTy =
1421 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1422 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1425 case OMPRTL__kmpc_push_proc_bind: {
1426 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1428 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1429 llvm::FunctionType *FnTy =
1430 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1431 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1434 case OMPRTL__kmpc_omp_task_with_deps: {
1435 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1436 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1437 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1438 llvm::Type *TypeParams[] = {
1439 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1440 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
1441 llvm::FunctionType *FnTy =
1442 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1444 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1447 case OMPRTL__kmpc_omp_wait_deps: {
1448 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1449 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1450 // kmp_depend_info_t *noalias_dep_list);
1451 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1452 CGM.Int32Ty, CGM.VoidPtrTy,
1453 CGM.Int32Ty, CGM.VoidPtrTy};
1454 llvm::FunctionType *FnTy =
1455 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1456 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
1459 case OMPRTL__kmpc_cancellationpoint: {
1460 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
1461 // global_tid, kmp_int32 cncl_kind)
1462 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1463 llvm::FunctionType *FnTy =
1464 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1465 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
1468 case OMPRTL__kmpc_cancel: {
1469 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
1470 // kmp_int32 cncl_kind)
1471 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1472 llvm::FunctionType *FnTy =
1473 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1474 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
1477 case OMPRTL__kmpc_push_num_teams: {
1478 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
1479 // kmp_int32 num_teams, kmp_int32 num_threads)
1480 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1482 llvm::FunctionType *FnTy =
1483 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1484 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
1487 case OMPRTL__kmpc_fork_teams: {
1488 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
1490 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1491 getKmpc_MicroPointerTy()};
1492 llvm::FunctionType *FnTy =
1493 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1494 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
1497 case OMPRTL__kmpc_taskloop: {
1498 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
1499 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
1500 // sched, kmp_uint64 grainsize, void *task_dup);
1501 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1505 CGM.Int64Ty->getPointerTo(),
1506 CGM.Int64Ty->getPointerTo(),
1512 llvm::FunctionType *FnTy =
1513 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1514 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
1517 case OMPRTL__kmpc_doacross_init: {
1518 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
1519 // num_dims, struct kmp_dim *dims);
1520 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1524 llvm::FunctionType *FnTy =
1525 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1526 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
1529 case OMPRTL__kmpc_doacross_fini: {
1530 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
1531 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1532 llvm::FunctionType *FnTy =
1533 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1534 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
1537 case OMPRTL__kmpc_doacross_post: {
1538 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
1540 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1541 CGM.Int64Ty->getPointerTo()};
1542 llvm::FunctionType *FnTy =
1543 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1544 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
1547 case OMPRTL__kmpc_doacross_wait: {
1548 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
1550 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1551 CGM.Int64Ty->getPointerTo()};
1552 llvm::FunctionType *FnTy =
1553 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1554 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
1557 case OMPRTL__tgt_target: {
1558 // Build int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
1559 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
1561 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1566 CGM.SizeTy->getPointerTo(),
1567 CGM.Int32Ty->getPointerTo()};
1568 llvm::FunctionType *FnTy =
1569 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1570 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
1573 case OMPRTL__tgt_target_teams: {
1574 // Build int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
1575 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
1576 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
1577 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1582 CGM.SizeTy->getPointerTo(),
1583 CGM.Int32Ty->getPointerTo(),
1586 llvm::FunctionType *FnTy =
1587 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1588 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
1591 case OMPRTL__tgt_register_lib: {
1592 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
1594 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1595 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
1596 llvm::FunctionType *FnTy =
1597 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1598 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
1601 case OMPRTL__tgt_unregister_lib: {
1602 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
1604 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1605 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
1606 llvm::FunctionType *FnTy =
1607 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1608 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
1611 case OMPRTL__tgt_target_data_begin: {
1612 // Build void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
1613 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
1614 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1618 CGM.SizeTy->getPointerTo(),
1619 CGM.Int32Ty->getPointerTo()};
1620 llvm::FunctionType *FnTy =
1621 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1622 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
1625 case OMPRTL__tgt_target_data_end: {
1626 // Build void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
1627 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
1628 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1632 CGM.SizeTy->getPointerTo(),
1633 CGM.Int32Ty->getPointerTo()};
1634 llvm::FunctionType *FnTy =
1635 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1636 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
1639 case OMPRTL__tgt_target_data_update: {
1640 // Build void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
1641 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
1642 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1646 CGM.SizeTy->getPointerTo(),
1647 CGM.Int32Ty->getPointerTo()};
1648 llvm::FunctionType *FnTy =
1649 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1650 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
1654 assert(RTLFn && "Unable to find OpenMP runtime function");
1658 llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
1660 assert((IVSize == 32 || IVSize == 64) &&
1661 "IV size is not compatible with the omp runtime");
1662 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
1663 : "__kmpc_for_static_init_4u")
1664 : (IVSigned ? "__kmpc_for_static_init_8"
1665 : "__kmpc_for_static_init_8u");
1666 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1667 auto PtrTy = llvm::PointerType::getUnqual(ITy);
1668 llvm::Type *TypeParams[] = {
1669 getIdentTyPointerTy(), // loc
1671 CGM.Int32Ty, // schedtype
1672 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1679 llvm::FunctionType *FnTy =
1680 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1681 return CGM.CreateRuntimeFunction(FnTy, Name);
1684 llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
1686 assert((IVSize == 32 || IVSize == 64) &&
1687 "IV size is not compatible with the omp runtime");
1690 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
1691 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
1692 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1693 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
1695 CGM.Int32Ty, // schedtype
1701 llvm::FunctionType *FnTy =
1702 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1703 return CGM.CreateRuntimeFunction(FnTy, Name);
1706 llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
1708 assert((IVSize == 32 || IVSize == 64) &&
1709 "IV size is not compatible with the omp runtime");
1712 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
1713 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
1714 llvm::Type *TypeParams[] = {
1715 getIdentTyPointerTy(), // loc
1718 llvm::FunctionType *FnTy =
1719 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1720 return CGM.CreateRuntimeFunction(FnTy, Name);
1723 llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
1725 assert((IVSize == 32 || IVSize == 64) &&
1726 "IV size is not compatible with the omp runtime");
1729 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
1730 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
1731 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1732 auto PtrTy = llvm::PointerType::getUnqual(ITy);
1733 llvm::Type *TypeParams[] = {
1734 getIdentTyPointerTy(), // loc
1736 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1741 llvm::FunctionType *FnTy =
1742 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1743 return CGM.CreateRuntimeFunction(FnTy, Name);
1747 CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
1748 assert(!CGM.getLangOpts().OpenMPUseTLS ||
1749 !CGM.getContext().getTargetInfo().isTLSSupported());
1750 // Lookup the entry, lazily creating it if necessary.
1751 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
1752 Twine(CGM.getMangledName(VD)) + ".cache.");
1755 Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
1758 SourceLocation Loc) {
1759 if (CGM.getLangOpts().OpenMPUseTLS &&
1760 CGM.getContext().getTargetInfo().isTLSSupported())
1763 auto VarTy = VDAddr.getElementType();
1764 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
1765 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1767 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
1768 getOrCreateThreadPrivateCache(VD)};
1769 return Address(CGF.EmitRuntimeCall(
1770 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
1771 VDAddr.getAlignment());
1774 void CGOpenMPRuntime::emitThreadPrivateVarInit(
1775 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
1776 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
1777 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
1779 auto OMPLoc = emitUpdateLocation(CGF, Loc);
1780 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1782 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
1783 // to register constructor/destructor for variable.
1784 llvm::Value *Args[] = {OMPLoc,
1785 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1787 Ctor, CopyCtor, Dtor};
1788 CGF.EmitRuntimeCall(
1789 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
1792 llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
1793 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
1794 bool PerformInit, CodeGenFunction *CGF) {
1795 if (CGM.getLangOpts().OpenMPUseTLS &&
1796 CGM.getContext().getTargetInfo().isTLSSupported())
1799 VD = VD->getDefinition(CGM.getContext());
1800 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
1801 ThreadPrivateWithDefinition.insert(VD);
1802 QualType ASTTy = VD->getType();
1804 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
1805 auto Init = VD->getAnyInitializer();
1806 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
1807 // Generate function that re-emits the declaration's initializer into the
1808 // threadprivate copy of the variable VD
1809 CodeGenFunction CtorCGF(CGM);
1810 FunctionArgList Args;
1811 ImplicitParamDecl Dst(CGM.getContext(), CGM.getContext().VoidPtrTy,
1812 ImplicitParamDecl::Other);
1813 Args.push_back(&Dst);
1815 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
1816 CGM.getContext().VoidPtrTy, Args);
1817 auto FTy = CGM.getTypes().GetFunctionType(FI);
1818 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
1819 FTy, ".__kmpc_global_ctor_.", FI, Loc);
1820 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
1821 Args, SourceLocation());
1822 auto ArgVal = CtorCGF.EmitLoadOfScalar(
1823 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
1824 CGM.getContext().VoidPtrTy, Dst.getLocation());
1825 Address Arg = Address(ArgVal, VDAddr.getAlignment());
1826 Arg = CtorCGF.Builder.CreateElementBitCast(Arg,
1827 CtorCGF.ConvertTypeForMem(ASTTy));
1828 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
1829 /*IsInitializer=*/true);
1830 ArgVal = CtorCGF.EmitLoadOfScalar(
1831 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
1832 CGM.getContext().VoidPtrTy, Dst.getLocation());
1833 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
1834 CtorCGF.FinishFunction();
1837 if (VD->getType().isDestructedType() != QualType::DK_none) {
1838 // Generate function that emits destructor call for the threadprivate copy
1839 // of the variable VD
1840 CodeGenFunction DtorCGF(CGM);
1841 FunctionArgList Args;
1842 ImplicitParamDecl Dst(CGM.getContext(), CGM.getContext().VoidPtrTy,
1843 ImplicitParamDecl::Other);
1844 Args.push_back(&Dst);
1846 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
1847 CGM.getContext().VoidTy, Args);
1848 auto FTy = CGM.getTypes().GetFunctionType(FI);
1849 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
1850 FTy, ".__kmpc_global_dtor_.", FI, Loc);
1851 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
1852 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
1854 // Create a scope with an artificial location for the body of this function.
1855 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
1856 auto ArgVal = DtorCGF.EmitLoadOfScalar(
1857 DtorCGF.GetAddrOfLocalVar(&Dst),
1858 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
1859 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
1860 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
1861 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
1862 DtorCGF.FinishFunction();
1865 // Do not emit init function if it is not required.
1869 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1871 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
1872 /*isVarArg=*/false)->getPointerTo();
1873 // Copying constructor for the threadprivate variable.
1874 // Must be NULL - reserved by runtime, but currently it requires that this
1875 // parameter is always NULL. Otherwise it fires assertion.
1876 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
1877 if (Ctor == nullptr) {
1878 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1879 /*isVarArg=*/false)->getPointerTo();
1880 Ctor = llvm::Constant::getNullValue(CtorTy);
1882 if (Dtor == nullptr) {
1883 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
1884 /*isVarArg=*/false)->getPointerTo();
1885 Dtor = llvm::Constant::getNullValue(DtorTy);
1888 auto InitFunctionTy =
1889 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
1890 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
1891 InitFunctionTy, ".__omp_threadprivate_init_.",
1892 CGM.getTypes().arrangeNullaryFunction());
1893 CodeGenFunction InitCGF(CGM);
1894 FunctionArgList ArgList;
1895 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
1896 CGM.getTypes().arrangeNullaryFunction(), ArgList,
1898 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
1899 InitCGF.FinishFunction();
1900 return InitFunction;
1902 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
1907 /// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
1908 /// function. Here is the logic:
1914 void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
1915 const RegionCodeGenTy &ThenGen,
1916 const RegionCodeGenTy &ElseGen) {
1917 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
1919 // If the condition constant folds and can be elided, try to avoid emitting
1920 // the condition and the dead arm of the if/else.
1922 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
1930 // Otherwise, the condition did not fold, or we couldn't elide it. Just
1931 // emit the conditional branch.
1932 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
1933 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
1934 auto ContBlock = CGF.createBasicBlock("omp_if.end");
1935 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
1937 // Emit the 'then' code.
1938 CGF.EmitBlock(ThenBlock);
1940 CGF.EmitBranch(ContBlock);
1941 // Emit the 'else' code if present.
1942 // There is no need to emit line number for unconditional branch.
1943 (void)ApplyDebugLocation::CreateEmpty(CGF);
1944 CGF.EmitBlock(ElseBlock);
1946 // There is no need to emit line number for unconditional branch.
1947 (void)ApplyDebugLocation::CreateEmpty(CGF);
1948 CGF.EmitBranch(ContBlock);
1949 // Emit the continuation block for code after the if.
1950 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
1953 void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
1954 llvm::Value *OutlinedFn,
1955 ArrayRef<llvm::Value *> CapturedVars,
1956 const Expr *IfCond) {
1957 if (!CGF.HaveInsertPoint())
1959 auto *RTLoc = emitUpdateLocation(CGF, Loc);
1960 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
1961 PrePostActionTy &) {
1962 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
1963 auto &RT = CGF.CGM.getOpenMPRuntime();
1964 llvm::Value *Args[] = {
1966 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
1967 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
1968 llvm::SmallVector<llvm::Value *, 16> RealArgs;
1969 RealArgs.append(std::begin(Args), std::end(Args));
1970 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
1972 auto RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
1973 CGF.EmitRuntimeCall(RTLFn, RealArgs);
1975 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
1976 PrePostActionTy &) {
1977 auto &RT = CGF.CGM.getOpenMPRuntime();
1978 auto ThreadID = RT.getThreadID(CGF, Loc);
1980 // __kmpc_serialized_parallel(&Loc, GTid);
1981 llvm::Value *Args[] = {RTLoc, ThreadID};
1982 CGF.EmitRuntimeCall(
1983 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
1985 // OutlinedFn(>id, &zero, CapturedStruct);
1986 auto ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
1988 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
1989 /*Name*/ ".zero.addr");
1990 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
1991 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
1992 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
1993 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
1994 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
1995 CGF.EmitCallOrInvoke(OutlinedFn, OutlinedFnArgs);
1997 // __kmpc_end_serialized_parallel(&Loc, GTid);
1998 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
1999 CGF.EmitRuntimeCall(
2000 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2004 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
2006 RegionCodeGenTy ThenRCG(ThenGen);
2011 // If we're inside an (outlined) parallel region, use the region info's
2012 // thread-ID variable (it is passed in a first argument of the outlined function
2013 // as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2014 // regular serial code region, get thread ID by calling kmp_int32
2015 // kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2016 // return the address of that temp.
2017 Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2018 SourceLocation Loc) {
2019 if (auto *OMPRegionInfo =
2020 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2021 if (OMPRegionInfo->getThreadIDVariable())
2022 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
2024 auto ThreadID = getThreadID(CGF, Loc);
2026 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
2027 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
2028 CGF.EmitStoreOfScalar(ThreadID,
2029 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
2031 return ThreadIDTemp;
2035 CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
2036 const llvm::Twine &Name) {
2037 SmallString<256> Buffer;
2038 llvm::raw_svector_ostream Out(Buffer);
2040 auto RuntimeName = Out.str();
2041 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
2043 assert(Elem.second->getType()->getPointerElementType() == Ty &&
2044 "OMP internal variable has different type than requested");
2045 return &*Elem.second;
2048 return Elem.second = new llvm::GlobalVariable(
2049 CGM.getModule(), Ty, /*IsConstant*/ false,
2050 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2054 llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
2055 llvm::Twine Name(".gomp_critical_user_", CriticalName);
2056 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
2060 /// Common pre(post)-action for different OpenMP constructs.
2061 class CommonActionTy final : public PrePostActionTy {
2062 llvm::Value *EnterCallee;
2063 ArrayRef<llvm::Value *> EnterArgs;
2064 llvm::Value *ExitCallee;
2065 ArrayRef<llvm::Value *> ExitArgs;
2067 llvm::BasicBlock *ContBlock = nullptr;
2070 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2071 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2072 bool Conditional = false)
2073 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2074 ExitArgs(ExitArgs), Conditional(Conditional) {}
2075 void Enter(CodeGenFunction &CGF) override {
2076 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2078 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2079 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2080 ContBlock = CGF.createBasicBlock("omp_if.end");
2081 // Generate the branch (If-stmt)
2082 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2083 CGF.EmitBlock(ThenBlock);
2086 void Done(CodeGenFunction &CGF) {
2087 // Emit the rest of blocks/branches
2088 CGF.EmitBranch(ContBlock);
2089 CGF.EmitBlock(ContBlock, true);
2091 void Exit(CodeGenFunction &CGF) override {
2092 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
2095 } // anonymous namespace
2097 void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2098 StringRef CriticalName,
2099 const RegionCodeGenTy &CriticalOpGen,
2100 SourceLocation Loc, const Expr *Hint) {
2101 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
2103 // __kmpc_end_critical(ident_t *, gtid, Lock);
2104 // Prepare arguments and build a call to __kmpc_critical
2105 if (!CGF.HaveInsertPoint())
2107 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2108 getCriticalRegionLock(CriticalName)};
2109 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2112 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2113 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2115 CommonActionTy Action(
2116 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2117 : OMPRTL__kmpc_critical),
2118 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2119 CriticalOpGen.setAction(Action);
2120 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
2123 void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
2124 const RegionCodeGenTy &MasterOpGen,
2125 SourceLocation Loc) {
2126 if (!CGF.HaveInsertPoint())
2128 // if(__kmpc_master(ident_t *, gtid)) {
2130 // __kmpc_end_master(ident_t *, gtid);
2132 // Prepare arguments and build a call to __kmpc_master
2133 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2134 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2135 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2136 /*Conditional=*/true);
2137 MasterOpGen.setAction(Action);
2138 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2142 void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
2143 SourceLocation Loc) {
2144 if (!CGF.HaveInsertPoint())
2146 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2147 llvm::Value *Args[] = {
2148 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2149 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
2150 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
2151 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2152 Region->emitUntiedSwitch(CGF);
2155 void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
2156 const RegionCodeGenTy &TaskgroupOpGen,
2157 SourceLocation Loc) {
2158 if (!CGF.HaveInsertPoint())
2160 // __kmpc_taskgroup(ident_t *, gtid);
2161 // TaskgroupOpGen();
2162 // __kmpc_end_taskgroup(ident_t *, gtid);
2163 // Prepare arguments and build a call to __kmpc_taskgroup
2164 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2165 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
2166 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
2168 TaskgroupOpGen.setAction(Action);
2169 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
2172 /// Given an array of pointers to variables, project the address of a
2174 static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
2175 unsigned Index, const VarDecl *Var) {
2176 // Pull out the pointer to the variable.
2178 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
2179 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
2181 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
2182 Addr = CGF.Builder.CreateElementBitCast(
2183 Addr, CGF.ConvertTypeForMem(Var->getType()));
2187 static llvm::Value *emitCopyprivateCopyFunction(
2188 CodeGenModule &CGM, llvm::Type *ArgsType,
2189 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
2190 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
2191 auto &C = CGM.getContext();
2192 // void copy_func(void *LHSArg, void *RHSArg);
2193 FunctionArgList Args;
2194 ImplicitParamDecl LHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
2195 ImplicitParamDecl RHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
2196 Args.push_back(&LHSArg);
2197 Args.push_back(&RHSArg);
2198 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
2199 auto *Fn = llvm::Function::Create(
2200 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2201 ".omp.copyprivate.copy_func", &CGM.getModule());
2202 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
2203 CodeGenFunction CGF(CGM);
2204 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
2205 // Dest = (void*[n])(LHSArg);
2206 // Src = (void*[n])(RHSArg);
2207 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2208 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
2209 ArgsType), CGF.getPointerAlign());
2210 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2211 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
2212 ArgsType), CGF.getPointerAlign());
2213 // *(Type0*)Dst[0] = *(Type0*)Src[0];
2214 // *(Type1*)Dst[1] = *(Type1*)Src[1];
2216 // *(Typen*)Dst[n] = *(Typen*)Src[n];
2217 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
2218 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
2219 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
2221 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
2222 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
2224 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
2225 QualType Type = VD->getType();
2226 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
2228 CGF.FinishFunction();
2232 void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
2233 const RegionCodeGenTy &SingleOpGen,
2235 ArrayRef<const Expr *> CopyprivateVars,
2236 ArrayRef<const Expr *> SrcExprs,
2237 ArrayRef<const Expr *> DstExprs,
2238 ArrayRef<const Expr *> AssignmentOps) {
2239 if (!CGF.HaveInsertPoint())
2241 assert(CopyprivateVars.size() == SrcExprs.size() &&
2242 CopyprivateVars.size() == DstExprs.size() &&
2243 CopyprivateVars.size() == AssignmentOps.size());
2244 auto &C = CGM.getContext();
2245 // int32 did_it = 0;
2246 // if(__kmpc_single(ident_t *, gtid)) {
2248 // __kmpc_end_single(ident_t *, gtid);
2251 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2252 // <copy_func>, did_it);
2254 Address DidIt = Address::invalid();
2255 if (!CopyprivateVars.empty()) {
2256 // int32 did_it = 0;
2257 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2258 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
2259 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
2261 // Prepare arguments and build a call to __kmpc_single
2262 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2263 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
2264 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
2265 /*Conditional=*/true);
2266 SingleOpGen.setAction(Action);
2267 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
2268 if (DidIt.isValid()) {
2270 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
2273 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2274 // <copy_func>, did_it);
2275 if (DidIt.isValid()) {
2276 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
2277 auto CopyprivateArrayTy =
2278 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2279 /*IndexTypeQuals=*/0);
2280 // Create a list of all private variables for copyprivate.
2281 Address CopyprivateList =
2282 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
2283 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
2284 Address Elem = CGF.Builder.CreateConstArrayGEP(
2285 CopyprivateList, I, CGF.getPointerSize());
2286 CGF.Builder.CreateStore(
2287 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2288 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
2291 // Build function that copies private values from single region to all other
2292 // threads in the corresponding parallel region.
2293 auto *CpyFn = emitCopyprivateCopyFunction(
2294 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
2295 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
2296 auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
2298 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
2300 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
2301 llvm::Value *Args[] = {
2302 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
2303 getThreadID(CGF, Loc), // i32 <gtid>
2304 BufSize, // size_t <buf_size>
2305 CL.getPointer(), // void *<copyprivate list>
2306 CpyFn, // void (*) (void *, void *) <copy_func>
2307 DidItVal // i32 did_it
2309 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
2313 void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
2314 const RegionCodeGenTy &OrderedOpGen,
2315 SourceLocation Loc, bool IsThreads) {
2316 if (!CGF.HaveInsertPoint())
2318 // __kmpc_ordered(ident_t *, gtid);
2320 // __kmpc_end_ordered(ident_t *, gtid);
2321 // Prepare arguments and build a call to __kmpc_ordered
2323 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2324 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
2325 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
2327 OrderedOpGen.setAction(Action);
2328 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2331 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2334 void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
2335 OpenMPDirectiveKind Kind, bool EmitChecks,
2336 bool ForceSimpleCall) {
2337 if (!CGF.HaveInsertPoint())
2339 // Build call __kmpc_cancel_barrier(loc, thread_id);
2340 // Build call __kmpc_barrier(loc, thread_id);
2342 if (Kind == OMPD_for)
2343 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
2344 else if (Kind == OMPD_sections)
2345 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
2346 else if (Kind == OMPD_single)
2347 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
2348 else if (Kind == OMPD_barrier)
2349 Flags = OMP_IDENT_BARRIER_EXPL;
2351 Flags = OMP_IDENT_BARRIER_IMPL;
2352 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
2354 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2355 getThreadID(CGF, Loc)};
2356 if (auto *OMPRegionInfo =
2357 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
2358 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
2359 auto *Result = CGF.EmitRuntimeCall(
2360 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
2362 // if (__kmpc_cancel_barrier()) {
2363 // exit from construct;
2365 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2366 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2367 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2368 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2369 CGF.EmitBlock(ExitBB);
2370 // exit from construct;
2371 auto CancelDestination =
2372 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
2373 CGF.EmitBranchThroughCleanup(CancelDestination);
2374 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2379 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
2382 /// \brief Map the OpenMP loop schedule to the runtime enumeration.
2383 static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
2384 bool Chunked, bool Ordered) {
2385 switch (ScheduleKind) {
2386 case OMPC_SCHEDULE_static:
2387 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
2388 : (Ordered ? OMP_ord_static : OMP_sch_static);
2389 case OMPC_SCHEDULE_dynamic:
2390 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
2391 case OMPC_SCHEDULE_guided:
2392 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
2393 case OMPC_SCHEDULE_runtime:
2394 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
2395 case OMPC_SCHEDULE_auto:
2396 return Ordered ? OMP_ord_auto : OMP_sch_auto;
2397 case OMPC_SCHEDULE_unknown:
2398 assert(!Chunked && "chunk was specified but schedule kind not known");
2399 return Ordered ? OMP_ord_static : OMP_sch_static;
2401 llvm_unreachable("Unexpected runtime schedule");
2404 /// \brief Map the OpenMP distribute schedule to the runtime enumeration.
2405 static OpenMPSchedType
2406 getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
2407 // only static is allowed for dist_schedule
2408 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
2411 bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
2412 bool Chunked) const {
2413 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
2414 return Schedule == OMP_sch_static;
2417 bool CGOpenMPRuntime::isStaticNonchunked(
2418 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
2419 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
2420 return Schedule == OMP_dist_sch_static;
2424 bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
2426 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
2427 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
2428 return Schedule != OMP_sch_static;
2431 static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
2432 OpenMPScheduleClauseModifier M1,
2433 OpenMPScheduleClauseModifier M2) {
2436 case OMPC_SCHEDULE_MODIFIER_monotonic:
2437 Modifier = OMP_sch_modifier_monotonic;
2439 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
2440 Modifier = OMP_sch_modifier_nonmonotonic;
2442 case OMPC_SCHEDULE_MODIFIER_simd:
2443 if (Schedule == OMP_sch_static_chunked)
2444 Schedule = OMP_sch_static_balanced_chunked;
2446 case OMPC_SCHEDULE_MODIFIER_last:
2447 case OMPC_SCHEDULE_MODIFIER_unknown:
2451 case OMPC_SCHEDULE_MODIFIER_monotonic:
2452 Modifier = OMP_sch_modifier_monotonic;
2454 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
2455 Modifier = OMP_sch_modifier_nonmonotonic;
2457 case OMPC_SCHEDULE_MODIFIER_simd:
2458 if (Schedule == OMP_sch_static_chunked)
2459 Schedule = OMP_sch_static_balanced_chunked;
2461 case OMPC_SCHEDULE_MODIFIER_last:
2462 case OMPC_SCHEDULE_MODIFIER_unknown:
2465 return Schedule | Modifier;
2468 void CGOpenMPRuntime::emitForDispatchInit(
2469 CodeGenFunction &CGF, SourceLocation Loc,
2470 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
2471 bool Ordered, const DispatchRTInput &DispatchValues) {
2472 if (!CGF.HaveInsertPoint())
2474 OpenMPSchedType Schedule = getRuntimeSchedule(
2475 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
2477 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
2478 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
2479 Schedule != OMP_sch_static_balanced_chunked));
2480 // Call __kmpc_dispatch_init(
2481 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
2482 // kmp_int[32|64] lower, kmp_int[32|64] upper,
2483 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
2485 // If the Chunk was not specified in the clause - use default value 1.
2486 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
2487 : CGF.Builder.getIntN(IVSize, 1);
2488 llvm::Value *Args[] = {
2489 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2490 CGF.Builder.getInt32(addMonoNonMonoModifier(
2491 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
2492 DispatchValues.LB, // Lower
2493 DispatchValues.UB, // Upper
2494 CGF.Builder.getIntN(IVSize, 1), // Stride
2497 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
2500 static void emitForStaticInitCall(
2501 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
2502 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
2503 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
2504 unsigned IVSize, bool Ordered, Address IL, Address LB, Address UB,
2505 Address ST, llvm::Value *Chunk) {
2506 if (!CGF.HaveInsertPoint())
2510 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
2511 Schedule == OMP_sch_static_balanced_chunked ||
2512 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
2513 Schedule == OMP_dist_sch_static ||
2514 Schedule == OMP_dist_sch_static_chunked);
2516 // Call __kmpc_for_static_init(
2517 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
2518 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
2519 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
2520 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
2521 if (Chunk == nullptr) {
2522 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
2523 Schedule == OMP_dist_sch_static) &&
2524 "expected static non-chunked schedule");
2525 // If the Chunk was not specified in the clause - use default value 1.
2526 Chunk = CGF.Builder.getIntN(IVSize, 1);
2528 assert((Schedule == OMP_sch_static_chunked ||
2529 Schedule == OMP_sch_static_balanced_chunked ||
2530 Schedule == OMP_ord_static_chunked ||
2531 Schedule == OMP_dist_sch_static_chunked) &&
2532 "expected static chunked schedule");
2534 llvm::Value *Args[] = {
2535 UpdateLocation, ThreadId, CGF.Builder.getInt32(addMonoNonMonoModifier(
2536 Schedule, M1, M2)), // Schedule type
2537 IL.getPointer(), // &isLastIter
2538 LB.getPointer(), // &LB
2539 UB.getPointer(), // &UB
2540 ST.getPointer(), // &Stride
2541 CGF.Builder.getIntN(IVSize, 1), // Incr
2544 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
2547 void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
2549 const OpenMPScheduleTy &ScheduleKind,
2550 unsigned IVSize, bool IVSigned,
2551 bool Ordered, Address IL, Address LB,
2552 Address UB, Address ST,
2553 llvm::Value *Chunk) {
2554 OpenMPSchedType ScheduleNum =
2555 getRuntimeSchedule(ScheduleKind.Schedule, Chunk != nullptr, Ordered);
2556 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc);
2557 auto *ThreadId = getThreadID(CGF, Loc);
2558 auto *StaticInitFunction = createForStaticInitFunction(IVSize, IVSigned);
2559 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
2560 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, IVSize,
2561 Ordered, IL, LB, UB, ST, Chunk);
2564 void CGOpenMPRuntime::emitDistributeStaticInit(
2565 CodeGenFunction &CGF, SourceLocation Loc,
2566 OpenMPDistScheduleClauseKind SchedKind, unsigned IVSize, bool IVSigned,
2567 bool Ordered, Address IL, Address LB, Address UB, Address ST,
2568 llvm::Value *Chunk) {
2569 OpenMPSchedType ScheduleNum = getRuntimeSchedule(SchedKind, Chunk != nullptr);
2570 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc);
2571 auto *ThreadId = getThreadID(CGF, Loc);
2572 auto *StaticInitFunction = createForStaticInitFunction(IVSize, IVSigned);
2573 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
2574 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
2575 OMPC_SCHEDULE_MODIFIER_unknown, IVSize, Ordered, IL, LB,
2579 void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
2580 SourceLocation Loc) {
2581 if (!CGF.HaveInsertPoint())
2583 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
2584 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2585 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
2589 void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
2593 if (!CGF.HaveInsertPoint())
2595 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
2596 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2597 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
2600 llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
2601 SourceLocation Loc, unsigned IVSize,
2602 bool IVSigned, Address IL,
2603 Address LB, Address UB,
2605 // Call __kmpc_dispatch_next(
2606 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
2607 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
2608 // kmp_int[32|64] *p_stride);
2609 llvm::Value *Args[] = {
2610 emitUpdateLocation(CGF, Loc),
2611 getThreadID(CGF, Loc),
2612 IL.getPointer(), // &isLastIter
2613 LB.getPointer(), // &Lower
2614 UB.getPointer(), // &Upper
2615 ST.getPointer() // &Stride
2618 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
2619 return CGF.EmitScalarConversion(
2620 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
2621 CGF.getContext().BoolTy, Loc);
2624 void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
2625 llvm::Value *NumThreads,
2626 SourceLocation Loc) {
2627 if (!CGF.HaveInsertPoint())
2629 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
2630 llvm::Value *Args[] = {
2631 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2632 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
2633 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
2637 void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
2638 OpenMPProcBindClauseKind ProcBind,
2639 SourceLocation Loc) {
2640 if (!CGF.HaveInsertPoint())
2642 // Constants for proc bind value accepted by the runtime.
2653 case OMPC_PROC_BIND_master:
2654 RuntimeProcBind = ProcBindMaster;
2656 case OMPC_PROC_BIND_close:
2657 RuntimeProcBind = ProcBindClose;
2659 case OMPC_PROC_BIND_spread:
2660 RuntimeProcBind = ProcBindSpread;
2662 case OMPC_PROC_BIND_unknown:
2663 llvm_unreachable("Unsupported proc_bind value.");
2665 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
2666 llvm::Value *Args[] = {
2667 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2668 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
2669 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
2672 void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
2673 SourceLocation Loc) {
2674 if (!CGF.HaveInsertPoint())
2676 // Build call void __kmpc_flush(ident_t *loc)
2677 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
2678 emitUpdateLocation(CGF, Loc));
2682 /// \brief Indexes of fields for type kmp_task_t.
2683 enum KmpTaskTFields {
2684 /// \brief List of shared variables.
2686 /// \brief Task routine.
2688 /// \brief Partition id for the untied tasks.
2690 /// Function with call of destructors for private variables.
2694 /// (Taskloops only) Lower bound.
2696 /// (Taskloops only) Upper bound.
2698 /// (Taskloops only) Stride.
2700 /// (Taskloops only) Is last iteration flag.
2703 } // anonymous namespace
2705 bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
2706 // FIXME: Add other entries type when they become supported.
2707 return OffloadEntriesTargetRegion.empty();
2710 /// \brief Initialize target region entry.
2711 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2712 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2713 StringRef ParentName, unsigned LineNum,
2715 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
2716 "only required for the device "
2717 "code generation.");
2718 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
2719 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
2721 ++OffloadingEntriesNum;
2724 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2725 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2726 StringRef ParentName, unsigned LineNum,
2727 llvm::Constant *Addr, llvm::Constant *ID,
2729 // If we are emitting code for a target, the entry is already initialized,
2730 // only has to be registered.
2731 if (CGM.getLangOpts().OpenMPIsDevice) {
2732 assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
2733 "Entry must exist.");
2735 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
2736 assert(Entry.isValid() && "Entry not initialized!");
2737 Entry.setAddress(Addr);
2739 Entry.setFlags(Flags);
2742 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum++, Addr, ID, Flags);
2743 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
2747 bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
2748 unsigned DeviceID, unsigned FileID, StringRef ParentName,
2749 unsigned LineNum) const {
2750 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
2751 if (PerDevice == OffloadEntriesTargetRegion.end())
2753 auto PerFile = PerDevice->second.find(FileID);
2754 if (PerFile == PerDevice->second.end())
2756 auto PerParentName = PerFile->second.find(ParentName);
2757 if (PerParentName == PerFile->second.end())
2759 auto PerLine = PerParentName->second.find(LineNum);
2760 if (PerLine == PerParentName->second.end())
2762 // Fail if this entry is already registered.
2763 if (PerLine->second.getAddress() || PerLine->second.getID())
2768 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
2769 const OffloadTargetRegionEntryInfoActTy &Action) {
2770 // Scan all target region entries and perform the provided action.
2771 for (auto &D : OffloadEntriesTargetRegion)
2772 for (auto &F : D.second)
2773 for (auto &P : F.second)
2774 for (auto &L : P.second)
2775 Action(D.first, F.first, P.first(), L.first, L.second);
2778 /// \brief Create a Ctor/Dtor-like function whose body is emitted through
2779 /// \a Codegen. This is used to emit the two functions that register and
2780 /// unregister the descriptor of the current compilation unit.
2781 static llvm::Function *
2782 createOffloadingBinaryDescriptorFunction(CodeGenModule &CGM, StringRef Name,
2783 const RegionCodeGenTy &Codegen) {
2784 auto &C = CGM.getContext();
2785 FunctionArgList Args;
2786 ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
2787 Args.push_back(&DummyPtr);
2789 CodeGenFunction CGF(CGM);
2790 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
2791 auto FTy = CGM.getTypes().GetFunctionType(FI);
2793 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, SourceLocation());
2794 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FI, Args, SourceLocation());
2796 CGF.FinishFunction();
2801 CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
2803 // If we don't have entries or if we are emitting code for the device, we
2804 // don't need to do anything.
2805 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
2808 auto &M = CGM.getModule();
2809 auto &C = CGM.getContext();
2811 // Get list of devices we care about
2812 auto &Devices = CGM.getLangOpts().OMPTargetTriples;
2814 // We should be creating an offloading descriptor only if there are devices
2816 assert(!Devices.empty() && "No OpenMP offloading devices??");
2818 // Create the external variables that will point to the begin and end of the
2819 // host entries section. These will be defined by the linker.
2820 auto *OffloadEntryTy =
2821 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
2822 llvm::GlobalVariable *HostEntriesBegin = new llvm::GlobalVariable(
2823 M, OffloadEntryTy, /*isConstant=*/true,
2824 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
2825 ".omp_offloading.entries_begin");
2826 llvm::GlobalVariable *HostEntriesEnd = new llvm::GlobalVariable(
2827 M, OffloadEntryTy, /*isConstant=*/true,
2828 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
2829 ".omp_offloading.entries_end");
2831 // Create all device images
2832 auto *DeviceImageTy = cast<llvm::StructType>(
2833 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
2834 ConstantInitBuilder DeviceImagesBuilder(CGM);
2835 auto DeviceImagesEntries = DeviceImagesBuilder.beginArray(DeviceImageTy);
2837 for (unsigned i = 0; i < Devices.size(); ++i) {
2838 StringRef T = Devices[i].getTriple();
2839 auto *ImgBegin = new llvm::GlobalVariable(
2840 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
2841 /*Initializer=*/nullptr,
2842 Twine(".omp_offloading.img_start.") + Twine(T));
2843 auto *ImgEnd = new llvm::GlobalVariable(
2844 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
2845 /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
2847 auto Dev = DeviceImagesEntries.beginStruct(DeviceImageTy);
2850 Dev.add(HostEntriesBegin);
2851 Dev.add(HostEntriesEnd);
2852 Dev.finishAndAddTo(DeviceImagesEntries);
2855 // Create device images global array.
2856 llvm::GlobalVariable *DeviceImages =
2857 DeviceImagesEntries.finishAndCreateGlobal(".omp_offloading.device_images",
2858 CGM.getPointerAlign(),
2859 /*isConstant=*/true);
2860 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2862 // This is a Zero array to be used in the creation of the constant expressions
2863 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
2864 llvm::Constant::getNullValue(CGM.Int32Ty)};
2866 // Create the target region descriptor.
2867 auto *BinaryDescriptorTy = cast<llvm::StructType>(
2868 CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
2869 ConstantInitBuilder DescBuilder(CGM);
2870 auto DescInit = DescBuilder.beginStruct(BinaryDescriptorTy);
2871 DescInit.addInt(CGM.Int32Ty, Devices.size());
2872 DescInit.add(llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
2875 DescInit.add(HostEntriesBegin);
2876 DescInit.add(HostEntriesEnd);
2878 auto *Desc = DescInit.finishAndCreateGlobal(".omp_offloading.descriptor",
2879 CGM.getPointerAlign(),
2880 /*isConstant=*/true);
2882 // Emit code to register or unregister the descriptor at execution
2883 // startup or closing, respectively.
2885 // Create a variable to drive the registration and unregistration of the
2886 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
2887 auto *IdentInfo = &C.Idents.get(".omp_offloading.reg_unreg_var");
2888 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), SourceLocation(),
2889 IdentInfo, C.CharTy, ImplicitParamDecl::Other);
2891 auto *UnRegFn = createOffloadingBinaryDescriptorFunction(
2892 CGM, ".omp_offloading.descriptor_unreg",
2893 [&](CodeGenFunction &CGF, PrePostActionTy &) {
2894 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
2897 auto *RegFn = createOffloadingBinaryDescriptorFunction(
2898 CGM, ".omp_offloading.descriptor_reg",
2899 [&](CodeGenFunction &CGF, PrePostActionTy &) {
2900 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_register_lib),
2902 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
2904 if (CGM.supportsCOMDAT()) {
2905 // It is sufficient to call registration function only once, so create a
2906 // COMDAT group for registration/unregistration functions and associated
2907 // data. That would reduce startup time and code size. Registration
2908 // function serves as a COMDAT group key.
2909 auto ComdatKey = M.getOrInsertComdat(RegFn->getName());
2910 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
2911 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
2912 RegFn->setComdat(ComdatKey);
2913 UnRegFn->setComdat(ComdatKey);
2914 DeviceImages->setComdat(ComdatKey);
2915 Desc->setComdat(ComdatKey);
2920 void CGOpenMPRuntime::createOffloadEntry(llvm::Constant *ID,
2921 llvm::Constant *Addr, uint64_t Size,
2923 StringRef Name = Addr->getName();
2924 auto *TgtOffloadEntryType = cast<llvm::StructType>(
2925 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
2926 llvm::LLVMContext &C = CGM.getModule().getContext();
2927 llvm::Module &M = CGM.getModule();
2929 // Make sure the address has the right type.
2930 llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy);
2932 // Create constant string with the name.
2933 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
2935 llvm::GlobalVariable *Str =
2936 new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
2937 llvm::GlobalValue::InternalLinkage, StrPtrInit,
2938 ".omp_offloading.entry_name");
2939 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2940 llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
2942 // We can't have any padding between symbols, so we need to have 1-byte
2944 auto Align = CharUnits::fromQuantity(1);
2946 // Create the entry struct.
2947 ConstantInitBuilder EntryBuilder(CGM);
2948 auto EntryInit = EntryBuilder.beginStruct(TgtOffloadEntryType);
2949 EntryInit.add(AddrPtr);
2950 EntryInit.add(StrPtr);
2951 EntryInit.addInt(CGM.SizeTy, Size);
2952 EntryInit.addInt(CGM.Int32Ty, Flags);
2953 EntryInit.addInt(CGM.Int32Ty, 0);
2954 llvm::GlobalVariable *Entry =
2955 EntryInit.finishAndCreateGlobal(".omp_offloading.entry",
2958 llvm::GlobalValue::ExternalLinkage);
2960 // The entry has to be created in the section the linker expects it to be.
2961 Entry->setSection(".omp_offloading.entries");
2964 void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
2965 // Emit the offloading entries and metadata so that the device codegen side
2966 // can easily figure out what to emit. The produced metadata looks like
2969 // !omp_offload.info = !{!1, ...}
2971 // Right now we only generate metadata for function that contain target
2974 // If we do not have entries, we dont need to do anything.
2975 if (OffloadEntriesInfoManager.empty())
2978 llvm::Module &M = CGM.getModule();
2979 llvm::LLVMContext &C = M.getContext();
2980 SmallVector<OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
2981 OrderedEntries(OffloadEntriesInfoManager.size());
2983 // Create the offloading info metadata node.
2984 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
2986 // Auxiliary methods to create metadata values and strings.
2987 auto getMDInt = [&](unsigned v) {
2988 return llvm::ConstantAsMetadata::get(
2989 llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), v));
2992 auto getMDString = [&](StringRef v) { return llvm::MDString::get(C, v); };
2994 // Create function that emits metadata for each target region entry;
2995 auto &&TargetRegionMetadataEmitter = [&](
2996 unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned Line,
2997 OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
2998 llvm::SmallVector<llvm::Metadata *, 32> Ops;
2999 // Generate metadata for target regions. Each entry of this metadata
3001 // - Entry 0 -> Kind of this type of metadata (0).
3002 // - Entry 1 -> Device ID of the file where the entry was identified.
3003 // - Entry 2 -> File ID of the file where the entry was identified.
3004 // - Entry 3 -> Mangled name of the function where the entry was identified.
3005 // - Entry 4 -> Line in the file where the entry was identified.
3006 // - Entry 5 -> Order the entry was created.
3007 // The first element of the metadata node is the kind.
3008 Ops.push_back(getMDInt(E.getKind()));
3009 Ops.push_back(getMDInt(DeviceID));
3010 Ops.push_back(getMDInt(FileID));
3011 Ops.push_back(getMDString(ParentName));
3012 Ops.push_back(getMDInt(Line));
3013 Ops.push_back(getMDInt(E.getOrder()));
3015 // Save this entry in the right position of the ordered entries array.
3016 OrderedEntries[E.getOrder()] = &E;
3018 // Add metadata to the named metadata node.
3019 MD->addOperand(llvm::MDNode::get(C, Ops));
3022 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
3023 TargetRegionMetadataEmitter);
3025 for (auto *E : OrderedEntries) {
3026 assert(E && "All ordered entries must exist!");
3028 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
3030 assert(CE->getID() && CE->getAddress() &&
3031 "Entry ID and Addr are invalid!");
3032 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0);
3034 llvm_unreachable("Unsupported entry kind.");
3038 /// \brief Loads all the offload entries information from the host IR
3040 void CGOpenMPRuntime::loadOffloadInfoMetadata() {
3041 // If we are in target mode, load the metadata from the host IR. This code has
3042 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
3044 if (!CGM.getLangOpts().OpenMPIsDevice)
3047 if (CGM.getLangOpts().OMPHostIRFile.empty())
3050 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
3054 llvm::LLVMContext C;
3055 auto ME = expectedToErrorOrAndEmitErrors(
3056 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
3061 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
3065 for (auto I : MD->operands()) {
3066 llvm::MDNode *MN = cast<llvm::MDNode>(I);
3068 auto getMDInt = [&](unsigned Idx) {
3069 llvm::ConstantAsMetadata *V =
3070 cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
3071 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
3074 auto getMDString = [&](unsigned Idx) {
3075 llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
3076 return V->getString();
3079 switch (getMDInt(0)) {
3081 llvm_unreachable("Unexpected metadata!");
3083 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
3084 OFFLOAD_ENTRY_INFO_TARGET_REGION:
3085 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
3086 /*DeviceID=*/getMDInt(1), /*FileID=*/getMDInt(2),
3087 /*ParentName=*/getMDString(3), /*Line=*/getMDInt(4),
3088 /*Order=*/getMDInt(5));
3094 void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
3095 if (!KmpRoutineEntryPtrTy) {
3096 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
3097 auto &C = CGM.getContext();
3098 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
3099 FunctionProtoType::ExtProtoInfo EPI;
3100 KmpRoutineEntryPtrQTy = C.getPointerType(
3101 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
3102 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
3106 static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
3108 auto *Field = FieldDecl::Create(
3109 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
3110 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
3111 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
3112 Field->setAccess(AS_public);
3117 QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
3119 // Make sure the type of the entry is already created. This is the type we
3121 // struct __tgt_offload_entry{
3122 // void *addr; // Pointer to the offload entry info.
3123 // // (function or global)
3124 // char *name; // Name of the function or global.
3125 // size_t size; // Size of the entry info (0 if it a function).
3126 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
3127 // int32_t reserved; // Reserved, to use by the runtime library.
3129 if (TgtOffloadEntryQTy.isNull()) {
3130 ASTContext &C = CGM.getContext();
3131 auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
3132 RD->startDefinition();
3133 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3134 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
3135 addFieldToRecordDecl(C, RD, C.getSizeType());
3136 addFieldToRecordDecl(
3137 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3138 addFieldToRecordDecl(
3139 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3140 RD->completeDefinition();
3141 TgtOffloadEntryQTy = C.getRecordType(RD);
3143 return TgtOffloadEntryQTy;
3146 QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
3147 // These are the types we need to build:
3148 // struct __tgt_device_image{
3149 // void *ImageStart; // Pointer to the target code start.
3150 // void *ImageEnd; // Pointer to the target code end.
3151 // // We also add the host entries to the device image, as it may be useful
3152 // // for the target runtime to have access to that information.
3153 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
3155 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3156 // // entries (non inclusive).
3158 if (TgtDeviceImageQTy.isNull()) {
3159 ASTContext &C = CGM.getContext();
3160 auto *RD = C.buildImplicitRecord("__tgt_device_image");
3161 RD->startDefinition();
3162 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3163 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3164 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3165 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3166 RD->completeDefinition();
3167 TgtDeviceImageQTy = C.getRecordType(RD);
3169 return TgtDeviceImageQTy;
3172 QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
3173 // struct __tgt_bin_desc{
3174 // int32_t NumDevices; // Number of devices supported.
3175 // __tgt_device_image *DeviceImages; // Arrays of device images
3176 // // (one per device).
3177 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
3179 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3180 // // entries (non inclusive).
3182 if (TgtBinaryDescriptorQTy.isNull()) {
3183 ASTContext &C = CGM.getContext();
3184 auto *RD = C.buildImplicitRecord("__tgt_bin_desc");
3185 RD->startDefinition();
3186 addFieldToRecordDecl(
3187 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3188 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
3189 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3190 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3191 RD->completeDefinition();
3192 TgtBinaryDescriptorQTy = C.getRecordType(RD);
3194 return TgtBinaryDescriptorQTy;
3198 struct PrivateHelpersTy {
3199 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
3200 const VarDecl *PrivateElemInit)
3201 : Original(Original), PrivateCopy(PrivateCopy),
3202 PrivateElemInit(PrivateElemInit) {}
3203 const VarDecl *Original;
3204 const VarDecl *PrivateCopy;
3205 const VarDecl *PrivateElemInit;
3207 typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
3208 } // anonymous namespace
3211 createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
3212 if (!Privates.empty()) {
3213 auto &C = CGM.getContext();
3214 // Build struct .kmp_privates_t. {
3215 // /* private vars */
3217 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
3218 RD->startDefinition();
3219 for (auto &&Pair : Privates) {
3220 auto *VD = Pair.second.Original;
3221 auto Type = VD->getType();
3222 Type = Type.getNonReferenceType();
3223 auto *FD = addFieldToRecordDecl(C, RD, Type);
3224 if (VD->hasAttrs()) {
3225 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
3226 E(VD->getAttrs().end());
3231 RD->completeDefinition();
3238 createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
3239 QualType KmpInt32Ty,
3240 QualType KmpRoutineEntryPointerQTy) {
3241 auto &C = CGM.getContext();
3242 // Build struct kmp_task_t {
3244 // kmp_routine_entry_t routine;
3245 // kmp_int32 part_id;
3246 // kmp_cmplrdata_t data1;
3247 // kmp_cmplrdata_t data2;
3248 // For taskloops additional fields:
3254 auto *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
3255 UD->startDefinition();
3256 addFieldToRecordDecl(C, UD, KmpInt32Ty);
3257 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
3258 UD->completeDefinition();
3259 QualType KmpCmplrdataTy = C.getRecordType(UD);
3260 auto *RD = C.buildImplicitRecord("kmp_task_t");
3261 RD->startDefinition();
3262 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3263 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
3264 addFieldToRecordDecl(C, RD, KmpInt32Ty);
3265 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
3266 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
3267 if (isOpenMPTaskLoopDirective(Kind)) {
3268 QualType KmpUInt64Ty =
3269 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3270 QualType KmpInt64Ty =
3271 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3272 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3273 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3274 addFieldToRecordDecl(C, RD, KmpInt64Ty);
3275 addFieldToRecordDecl(C, RD, KmpInt32Ty);
3277 RD->completeDefinition();
3282 createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
3283 ArrayRef<PrivateDataTy> Privates) {
3284 auto &C = CGM.getContext();
3285 // Build struct kmp_task_t_with_privates {
3286 // kmp_task_t task_data;
3287 // .kmp_privates_t. privates;
3289 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
3290 RD->startDefinition();
3291 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
3292 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
3293 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
3295 RD->completeDefinition();
3299 /// \brief Emit a proxy function which accepts kmp_task_t as the second
3302 /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
3303 /// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
3305 /// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
3310 static llvm::Value *
3311 emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
3312 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
3313 QualType KmpTaskTWithPrivatesPtrQTy,
3314 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
3315 QualType SharedsPtrTy, llvm::Value *TaskFunction,
3316 llvm::Value *TaskPrivatesMap) {
3317 auto &C = CGM.getContext();
3318 FunctionArgList Args;
3319 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3320 ImplicitParamDecl::Other);
3321 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3322 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3323 ImplicitParamDecl::Other);
3324 Args.push_back(&GtidArg);
3325 Args.push_back(&TaskTypeArg);
3326 auto &TaskEntryFnInfo =
3327 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
3328 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
3330 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
3331 ".omp_task_entry.", &CGM.getModule());
3332 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskEntry, TaskEntryFnInfo);
3333 CodeGenFunction CGF(CGM);
3334 CGF.disableDebugInfo();
3335 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
3337 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
3340 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
3341 // tt->task_data.shareds);
3342 auto *GtidParam = CGF.EmitLoadOfScalar(
3343 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
3344 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3345 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3346 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
3347 auto *KmpTaskTWithPrivatesQTyRD =
3348 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
3350 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
3351 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
3352 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
3353 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
3354 auto *PartidParam = PartIdLVal.getPointer();
3356 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
3357 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
3358 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3359 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
3360 CGF.ConvertTypeForMem(SharedsPtrTy));
3362 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
3363 llvm::Value *PrivatesParam;
3364 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
3365 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
3366 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3367 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
3369 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
3371 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
3374 .CreatePointerBitCastOrAddrSpaceCast(
3375 TDBase.getAddress(), CGF.VoidPtrTy)
3377 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
3378 std::end(CommonArgs));
3379 if (isOpenMPTaskLoopDirective(Kind)) {
3380 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
3381 auto LBLVal = CGF.EmitLValueForField(Base, *LBFI);
3382 auto *LBParam = CGF.EmitLoadOfLValue(LBLVal, Loc).getScalarVal();
3383 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
3384 auto UBLVal = CGF.EmitLValueForField(Base, *UBFI);
3385 auto *UBParam = CGF.EmitLoadOfLValue(UBLVal, Loc).getScalarVal();
3386 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
3387 auto StLVal = CGF.EmitLValueForField(Base, *StFI);
3388 auto *StParam = CGF.EmitLoadOfLValue(StLVal, Loc).getScalarVal();
3389 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3390 auto LILVal = CGF.EmitLValueForField(Base, *LIFI);
3391 auto *LIParam = CGF.EmitLoadOfLValue(LILVal, Loc).getScalarVal();
3392 CallArgs.push_back(LBParam);
3393 CallArgs.push_back(UBParam);
3394 CallArgs.push_back(StParam);
3395 CallArgs.push_back(LIParam);
3397 CallArgs.push_back(SharedsParam);
3399 CGF.EmitCallOrInvoke(TaskFunction, CallArgs);
3400 CGF.EmitStoreThroughLValue(
3401 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
3402 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
3403 CGF.FinishFunction();
3407 static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
3409 QualType KmpInt32Ty,
3410 QualType KmpTaskTWithPrivatesPtrQTy,
3411 QualType KmpTaskTWithPrivatesQTy) {
3412 auto &C = CGM.getContext();
3413 FunctionArgList Args;
3414 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3415 ImplicitParamDecl::Other);
3416 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3417 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3418 ImplicitParamDecl::Other);
3419 Args.push_back(&GtidArg);
3420 Args.push_back(&TaskTypeArg);
3421 FunctionType::ExtInfo Info;
3422 auto &DestructorFnInfo =
3423 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
3424 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
3425 auto *DestructorFn =
3426 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
3427 ".omp_task_destructor.", &CGM.getModule());
3428 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, DestructorFn,
3430 CodeGenFunction CGF(CGM);
3431 CGF.disableDebugInfo();
3432 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
3435 LValue Base = CGF.EmitLoadOfPointerLValue(
3436 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3437 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
3438 auto *KmpTaskTWithPrivatesQTyRD =
3439 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
3440 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3441 Base = CGF.EmitLValueForField(Base, *FI);
3443 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
3444 if (auto DtorKind = Field->getType().isDestructedType()) {
3445 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
3446 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
3449 CGF.FinishFunction();
3450 return DestructorFn;
3453 /// \brief Emit a privates mapping function for correct handling of private and
3454 /// firstprivate variables.
3456 /// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
3457 /// **noalias priv1,..., <tyn> **noalias privn) {
3458 /// *priv1 = &.privates.priv1;
3460 /// *privn = &.privates.privn;
3463 static llvm::Value *
3464 emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
3465 ArrayRef<const Expr *> PrivateVars,
3466 ArrayRef<const Expr *> FirstprivateVars,
3467 ArrayRef<const Expr *> LastprivateVars,
3468 QualType PrivatesQTy,
3469 ArrayRef<PrivateDataTy> Privates) {
3470 auto &C = CGM.getContext();
3471 FunctionArgList Args;
3472 ImplicitParamDecl TaskPrivatesArg(
3473 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3474 C.getPointerType(PrivatesQTy).withConst().withRestrict(),
3475 ImplicitParamDecl::Other);
3476 Args.push_back(&TaskPrivatesArg);
3477 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
3478 unsigned Counter = 1;
3479 for (auto *E: PrivateVars) {
3480 Args.push_back(ImplicitParamDecl::Create(
3481 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3482 C.getPointerType(C.getPointerType(E->getType()))
3485 ImplicitParamDecl::Other));
3486 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3487 PrivateVarsPos[VD] = Counter;
3490 for (auto *E : FirstprivateVars) {
3491 Args.push_back(ImplicitParamDecl::Create(
3492 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3493 C.getPointerType(C.getPointerType(E->getType()))
3496 ImplicitParamDecl::Other));
3497 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3498 PrivateVarsPos[VD] = Counter;
3501 for (auto *E: LastprivateVars) {
3502 Args.push_back(ImplicitParamDecl::Create(
3503 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3504 C.getPointerType(C.getPointerType(E->getType()))
3507 ImplicitParamDecl::Other));
3508 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3509 PrivateVarsPos[VD] = Counter;
3512 auto &TaskPrivatesMapFnInfo =
3513 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3514 auto *TaskPrivatesMapTy =
3515 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
3516 auto *TaskPrivatesMap = llvm::Function::Create(
3517 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
3518 ".omp_task_privates_map.", &CGM.getModule());
3519 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskPrivatesMap,
3520 TaskPrivatesMapFnInfo);
3521 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
3522 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
3523 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
3524 CodeGenFunction CGF(CGM);
3525 CGF.disableDebugInfo();
3526 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
3527 TaskPrivatesMapFnInfo, Args);
3529 // *privi = &.privates.privi;
3530 LValue Base = CGF.EmitLoadOfPointerLValue(
3531 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
3532 TaskPrivatesArg.getType()->castAs<PointerType>());
3533 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
3535 for (auto *Field : PrivatesQTyRD->fields()) {
3536 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
3537 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
3538 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
3539 auto RefLoadLVal = CGF.EmitLoadOfPointerLValue(
3540 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
3541 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
3544 CGF.FinishFunction();
3545 return TaskPrivatesMap;
3548 static int array_pod_sort_comparator(const PrivateDataTy *P1,
3549 const PrivateDataTy *P2) {
3550 return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
3553 /// Emit initialization for private variables in task-based directives.
3554 static void emitPrivatesInit(CodeGenFunction &CGF,
3555 const OMPExecutableDirective &D,
3556 Address KmpTaskSharedsPtr, LValue TDBase,
3557 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
3558 QualType SharedsTy, QualType SharedsPtrTy,
3559 const OMPTaskDataTy &Data,
3560 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
3561 auto &C = CGF.getContext();
3562 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3563 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
3565 if (!Data.FirstprivateVars.empty()) {
3566 SrcBase = CGF.MakeAddrLValue(
3567 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3568 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
3571 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
3572 cast<CapturedStmt>(*D.getAssociatedStmt()));
3573 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
3574 for (auto &&Pair : Privates) {
3575 auto *VD = Pair.second.PrivateCopy;
3576 auto *Init = VD->getAnyInitializer();
3577 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
3578 !CGF.isTrivialInitializer(Init)))) {
3579 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
3580 if (auto *Elem = Pair.second.PrivateElemInit) {
3581 auto *OriginalVD = Pair.second.Original;
3582 auto *SharedField = CapturesInfo.lookup(OriginalVD);
3583 auto SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
3584 SharedRefLValue = CGF.MakeAddrLValue(
3585 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
3586 SharedRefLValue.getType(),
3587 LValueBaseInfo(AlignmentSource::Decl,
3588 SharedRefLValue.getBaseInfo().getMayAlias()));
3589 QualType Type = OriginalVD->getType();
3590 if (Type->isArrayType()) {
3591 // Initialize firstprivate array.
3592 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
3593 // Perform simple memcpy.
3594 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
3595 SharedRefLValue.getAddress(), Type);
3597 // Initialize firstprivate array using element-by-element
3599 CGF.EmitOMPAggregateAssign(
3600 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
3601 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
3602 Address SrcElement) {
3603 // Clean up any temporaries needed by the initialization.
3604 CodeGenFunction::OMPPrivateScope InitScope(CGF);
3605 InitScope.addPrivate(
3606 Elem, [SrcElement]() -> Address { return SrcElement; });
3607 (void)InitScope.Privatize();
3608 // Emit initialization for single element.
3609 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
3610 CGF, &CapturesInfo);
3611 CGF.EmitAnyExprToMem(Init, DestElement,
3612 Init->getType().getQualifiers(),
3613 /*IsInitializer=*/false);
3617 CodeGenFunction::OMPPrivateScope InitScope(CGF);
3618 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
3619 return SharedRefLValue.getAddress();
3621 (void)InitScope.Privatize();
3622 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
3623 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
3624 /*capturedByInit=*/false);
3627 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
3633 /// Check if duplication function is required for taskloops.
3634 static bool checkInitIsRequired(CodeGenFunction &CGF,
3635 ArrayRef<PrivateDataTy> Privates) {
3636 bool InitRequired = false;
3637 for (auto &&Pair : Privates) {
3638 auto *VD = Pair.second.PrivateCopy;
3639 auto *Init = VD->getAnyInitializer();
3640 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
3641 !CGF.isTrivialInitializer(Init));
3643 return InitRequired;
3647 /// Emit task_dup function (for initialization of
3648 /// private/firstprivate/lastprivate vars and last_iter flag)
3650 /// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
3652 /// // setup lastprivate flag
3653 /// task_dst->last = lastpriv;
3654 /// // could be constructor calls here...
3657 static llvm::Value *
3658 emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
3659 const OMPExecutableDirective &D,
3660 QualType KmpTaskTWithPrivatesPtrQTy,
3661 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
3662 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
3663 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
3664 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
3665 auto &C = CGM.getContext();
3666 FunctionArgList Args;
3667 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3668 KmpTaskTWithPrivatesPtrQTy,
3669 ImplicitParamDecl::Other);
3670 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3671 KmpTaskTWithPrivatesPtrQTy,
3672 ImplicitParamDecl::Other);
3673 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3674 ImplicitParamDecl::Other);
3675 Args.push_back(&DstArg);
3676 Args.push_back(&SrcArg);
3677 Args.push_back(&LastprivArg);
3678 auto &TaskDupFnInfo =
3679 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3680 auto *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
3682 llvm::Function::Create(TaskDupTy, llvm::GlobalValue::InternalLinkage,
3683 ".omp_task_dup.", &CGM.getModule());
3684 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskDup, TaskDupFnInfo);
3685 CodeGenFunction CGF(CGM);
3686 CGF.disableDebugInfo();
3687 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args);
3689 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3690 CGF.GetAddrOfLocalVar(&DstArg),
3691 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
3692 // task_dst->liter = lastpriv;
3694 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3695 LValue Base = CGF.EmitLValueForField(
3696 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
3697 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
3698 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
3699 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
3700 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
3703 // Emit initial values for private copies (if any).
3704 assert(!Privates.empty());
3705 Address KmpTaskSharedsPtr = Address::invalid();
3706 if (!Data.FirstprivateVars.empty()) {
3707 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3708 CGF.GetAddrOfLocalVar(&SrcArg),
3709 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
3710 LValue Base = CGF.EmitLValueForField(
3711 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
3712 KmpTaskSharedsPtr = Address(
3713 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
3714 Base, *std::next(KmpTaskTQTyRD->field_begin(),
3717 CGF.getNaturalTypeAlignment(SharedsTy));
3719 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
3720 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
3721 CGF.FinishFunction();
3725 /// Checks if destructor function is required to be generated.
3726 /// \return true if cleanups are required, false otherwise.
3728 checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
3729 bool NeedsCleanup = false;
3730 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3731 auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
3732 for (auto *FD : PrivateRD->fields()) {
3733 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
3737 return NeedsCleanup;
3740 CGOpenMPRuntime::TaskResultTy
3741 CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
3742 const OMPExecutableDirective &D,
3743 llvm::Value *TaskFunction, QualType SharedsTy,
3744 Address Shareds, const OMPTaskDataTy &Data) {
3745 auto &C = CGM.getContext();
3746 llvm::SmallVector<PrivateDataTy, 4> Privates;
3747 // Aggregate privates and sort them by the alignment.
3748 auto I = Data.PrivateCopies.begin();
3749 for (auto *E : Data.PrivateVars) {
3750 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3751 Privates.push_back(std::make_pair(
3753 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3754 /*PrivateElemInit=*/nullptr)));
3757 I = Data.FirstprivateCopies.begin();
3758 auto IElemInitRef = Data.FirstprivateInits.begin();
3759 for (auto *E : Data.FirstprivateVars) {
3760 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3761 Privates.push_back(std::make_pair(
3764 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3765 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
3769 I = Data.LastprivateCopies.begin();
3770 for (auto *E : Data.LastprivateVars) {
3771 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3772 Privates.push_back(std::make_pair(
3774 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3775 /*PrivateElemInit=*/nullptr)));
3778 llvm::array_pod_sort(Privates.begin(), Privates.end(),
3779 array_pod_sort_comparator);
3780 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
3781 // Build type kmp_routine_entry_t (if not built yet).
3782 emitKmpRoutineEntryT(KmpInt32Ty);
3783 // Build type kmp_task_t (if not built yet).
3784 if (KmpTaskTQTy.isNull()) {
3785 KmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
3786 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
3788 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
3789 // Build particular struct kmp_task_t for the given task.
3790 auto *KmpTaskTWithPrivatesQTyRD =
3791 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
3792 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
3793 QualType KmpTaskTWithPrivatesPtrQTy =
3794 C.getPointerType(KmpTaskTWithPrivatesQTy);
3795 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
3796 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
3797 auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
3798 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
3800 // Emit initial values for private copies (if any).
3801 llvm::Value *TaskPrivatesMap = nullptr;
3802 auto *TaskPrivatesMapTy =
3803 std::next(cast<llvm::Function>(TaskFunction)->arg_begin(), 3)->getType();
3804 if (!Privates.empty()) {
3805 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3806 TaskPrivatesMap = emitTaskPrivateMappingFunction(
3807 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
3808 FI->getType(), Privates);
3809 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3810 TaskPrivatesMap, TaskPrivatesMapTy);
3812 TaskPrivatesMap = llvm::ConstantPointerNull::get(
3813 cast<llvm::PointerType>(TaskPrivatesMapTy));
3815 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
3817 auto *TaskEntry = emitProxyTaskFunction(
3818 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
3819 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
3822 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
3823 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
3824 // kmp_routine_entry_t *task_entry);
3825 // Task flags. Format is taken from
3826 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
3827 // description of kmp_tasking_flags struct.
3831 DestructorsFlag = 0x8,
3834 unsigned Flags = Data.Tied ? TiedFlag : 0;
3835 bool NeedsCleanup = false;
3836 if (!Privates.empty()) {
3837 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
3839 Flags = Flags | DestructorsFlag;
3841 if (Data.Priority.getInt())
3842 Flags = Flags | PriorityFlag;
3844 Data.Final.getPointer()
3845 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
3846 CGF.Builder.getInt32(FinalFlag),
3847 CGF.Builder.getInt32(/*C=*/0))
3848 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
3849 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
3850 auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
3851 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
3852 getThreadID(CGF, Loc), TaskFlags,
3853 KmpTaskTWithPrivatesTySize, SharedsSize,
3854 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3855 TaskEntry, KmpRoutineEntryPtrTy)};
3856 auto *NewTask = CGF.EmitRuntimeCall(
3857 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
3858 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3859 NewTask, KmpTaskTWithPrivatesPtrTy);
3860 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
3861 KmpTaskTWithPrivatesQTy);
3863 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
3864 // Fill the data in the resulting kmp_task_t record.
3865 // Copy shareds if there are any.
3866 Address KmpTaskSharedsPtr = Address::invalid();
3867 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
3869 Address(CGF.EmitLoadOfScalar(
3870 CGF.EmitLValueForField(
3871 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
3874 CGF.getNaturalTypeAlignment(SharedsTy));
3875 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
3877 // Emit initial values for private copies (if any).
3878 TaskResultTy Result;
3879 if (!Privates.empty()) {
3880 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
3881 SharedsTy, SharedsPtrTy, Data, Privates,
3883 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
3884 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
3885 Result.TaskDupFn = emitTaskDupFunction(
3886 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
3887 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
3888 /*WithLastIter=*/!Data.LastprivateVars.empty());
3891 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
3892 enum { Priority = 0, Destructors = 1 };
3893 // Provide pointer to function with destructors for privates.
3894 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
3895 auto *KmpCmplrdataUD = (*FI)->getType()->getAsUnionType()->getDecl();
3897 llvm::Value *DestructorFn = emitDestructorsFunction(
3898 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
3899 KmpTaskTWithPrivatesQTy);
3900 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
3901 LValue DestructorsLV = CGF.EmitLValueForField(
3902 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
3903 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3904 DestructorFn, KmpRoutineEntryPtrTy),
3908 if (Data.Priority.getInt()) {
3909 LValue Data2LV = CGF.EmitLValueForField(
3910 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
3911 LValue PriorityLV = CGF.EmitLValueForField(
3912 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
3913 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
3915 Result.NewTask = NewTask;
3916 Result.TaskEntry = TaskEntry;
3917 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
3918 Result.TDBase = TDBase;
3919 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
3923 void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
3924 const OMPExecutableDirective &D,
3925 llvm::Value *TaskFunction,
3926 QualType SharedsTy, Address Shareds,
3928 const OMPTaskDataTy &Data) {
3929 if (!CGF.HaveInsertPoint())
3932 TaskResultTy Result =
3933 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
3934 llvm::Value *NewTask = Result.NewTask;
3935 llvm::Value *TaskEntry = Result.TaskEntry;
3936 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
3937 LValue TDBase = Result.TDBase;
3938 RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
3939 auto &C = CGM.getContext();
3940 // Process list of dependences.
3941 Address DependenciesArray = Address::invalid();
3942 unsigned NumDependencies = Data.Dependences.size();
3943 if (NumDependencies) {
3944 // Dependence kind for RTL.
3945 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
3946 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
3947 RecordDecl *KmpDependInfoRD;
3949 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
3950 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
3951 if (KmpDependInfoTy.isNull()) {
3952 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
3953 KmpDependInfoRD->startDefinition();
3954 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
3955 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
3956 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
3957 KmpDependInfoRD->completeDefinition();
3958 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
3960 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
3961 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
3962 // Define type kmp_depend_info[<Dependences.size()>];
3963 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
3964 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
3965 ArrayType::Normal, /*IndexTypeQuals=*/0);
3966 // kmp_depend_info[<Dependences.size()>] deps;
3968 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
3969 for (unsigned i = 0; i < NumDependencies; ++i) {
3970 const Expr *E = Data.Dependences[i].second;
3971 auto Addr = CGF.EmitLValue(E);
3973 QualType Ty = E->getType();
3974 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
3976 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
3977 llvm::Value *UpAddr =
3978 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
3979 llvm::Value *LowIntPtr =
3980 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
3981 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
3982 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
3984 Size = CGF.getTypeSize(Ty);
3985 auto Base = CGF.MakeAddrLValue(
3986 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
3988 // deps[i].base_addr = &<Dependences[i].second>;
3989 auto BaseAddrLVal = CGF.EmitLValueForField(
3990 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
3991 CGF.EmitStoreOfScalar(
3992 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
3994 // deps[i].len = sizeof(<Dependences[i].second>);
3995 auto LenLVal = CGF.EmitLValueForField(
3996 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
3997 CGF.EmitStoreOfScalar(Size, LenLVal);
3998 // deps[i].flags = <Dependences[i].first>;
3999 RTLDependenceKindTy DepKind;
4000 switch (Data.Dependences[i].first) {
4001 case OMPC_DEPEND_in:
4004 // Out and InOut dependencies must use the same code.
4005 case OMPC_DEPEND_out:
4006 case OMPC_DEPEND_inout:
4009 case OMPC_DEPEND_source:
4010 case OMPC_DEPEND_sink:
4011 case OMPC_DEPEND_unknown:
4012 llvm_unreachable("Unknown task dependence type");
4014 auto FlagsLVal = CGF.EmitLValueForField(
4015 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
4016 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
4019 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4020 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
4024 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4026 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
4027 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
4028 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
4029 // list is not empty
4030 auto *ThreadID = getThreadID(CGF, Loc);
4031 auto *UpLoc = emitUpdateLocation(CGF, Loc);
4032 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
4033 llvm::Value *DepTaskArgs[7];
4034 if (NumDependencies) {
4035 DepTaskArgs[0] = UpLoc;
4036 DepTaskArgs[1] = ThreadID;
4037 DepTaskArgs[2] = NewTask;
4038 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
4039 DepTaskArgs[4] = DependenciesArray.getPointer();
4040 DepTaskArgs[5] = CGF.Builder.getInt32(0);
4041 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4043 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
4045 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
4047 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
4048 auto PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
4049 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
4051 if (NumDependencies) {
4052 CGF.EmitRuntimeCall(
4053 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
4055 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
4058 // Check if parent region is untied and build return for untied task;
4060 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4061 Region->emitUntiedSwitch(CGF);
4064 llvm::Value *DepWaitTaskArgs[6];
4065 if (NumDependencies) {
4066 DepWaitTaskArgs[0] = UpLoc;
4067 DepWaitTaskArgs[1] = ThreadID;
4068 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
4069 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
4070 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
4071 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4073 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
4074 NumDependencies, &DepWaitTaskArgs](CodeGenFunction &CGF,
4075 PrePostActionTy &) {
4076 auto &RT = CGF.CGM.getOpenMPRuntime();
4077 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
4078 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
4079 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
4080 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
4082 if (NumDependencies)
4083 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
4085 // Call proxy_task_entry(gtid, new_task);
4086 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy](
4087 CodeGenFunction &CGF, PrePostActionTy &Action) {
4089 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
4090 CGF.EmitCallOrInvoke(TaskEntry, OutlinedFnArgs);
4093 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
4094 // kmp_task_t *new_task);
4095 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
4096 // kmp_task_t *new_task);
4097 RegionCodeGenTy RCG(CodeGen);
4098 CommonActionTy Action(
4099 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
4100 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
4101 RCG.setAction(Action);
4106 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
4108 RegionCodeGenTy ThenRCG(ThenCodeGen);
4113 void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
4114 const OMPLoopDirective &D,
4115 llvm::Value *TaskFunction,
4116 QualType SharedsTy, Address Shareds,
4118 const OMPTaskDataTy &Data) {
4119 if (!CGF.HaveInsertPoint())
4121 TaskResultTy Result =
4122 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
4123 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4125 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
4126 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
4127 // sched, kmp_uint64 grainsize, void *task_dup);
4128 llvm::Value *ThreadID = getThreadID(CGF, Loc);
4129 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
4132 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
4135 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
4137 LValue LBLVal = CGF.EmitLValueForField(
4139 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
4141 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
4142 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
4143 /*IsInitializer=*/true);
4144 LValue UBLVal = CGF.EmitLValueForField(
4146 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
4148 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
4149 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
4150 /*IsInitializer=*/true);
4151 LValue StLVal = CGF.EmitLValueForField(
4153 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
4155 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
4156 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
4157 /*IsInitializer=*/true);
4158 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
4159 llvm::Value *TaskArgs[] = {
4160 UpLoc, ThreadID, Result.NewTask, IfVal, LBLVal.getPointer(),
4161 UBLVal.getPointer(), CGF.EmitLoadOfScalar(StLVal, SourceLocation()),
4162 llvm::ConstantInt::getSigned(CGF.IntTy, Data.Nogroup ? 1 : 0),
4163 llvm::ConstantInt::getSigned(
4164 CGF.IntTy, Data.Schedule.getPointer()
4165 ? Data.Schedule.getInt() ? NumTasks : Grainsize
4167 Data.Schedule.getPointer()
4168 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
4170 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
4172 ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Result.TaskDupFn,
4174 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
4175 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
4178 /// \brief Emit reduction operation for each element of array (required for
4179 /// array sections) LHS op = RHS.
4180 /// \param Type Type of array.
4181 /// \param LHSVar Variable on the left side of the reduction operation
4182 /// (references element of array in original variable).
4183 /// \param RHSVar Variable on the right side of the reduction operation
4184 /// (references element of array in original variable).
4185 /// \param RedOpGen Generator of reduction operation with use of LHSVar and
4187 static void EmitOMPAggregateReduction(
4188 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
4189 const VarDecl *RHSVar,
4190 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
4191 const Expr *, const Expr *)> &RedOpGen,
4192 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
4193 const Expr *UpExpr = nullptr) {
4194 // Perform element-by-element initialization.
4196 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
4197 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
4199 // Drill down to the base element type on both arrays.
4200 auto ArrayTy = Type->getAsArrayTypeUnsafe();
4201 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
4203 auto RHSBegin = RHSAddr.getPointer();
4204 auto LHSBegin = LHSAddr.getPointer();
4205 // Cast from pointer to array type to pointer to single element.
4206 auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
4207 // The basic structure here is a while-do loop.
4208 auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
4209 auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
4211 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
4212 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
4214 // Enter the loop body, making that address the current address.
4215 auto EntryBB = CGF.Builder.GetInsertBlock();
4216 CGF.EmitBlock(BodyBB);
4218 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
4220 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
4221 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
4222 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
4223 Address RHSElementCurrent =
4224 Address(RHSElementPHI,
4225 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4227 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
4228 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
4229 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
4230 Address LHSElementCurrent =
4231 Address(LHSElementPHI,
4232 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4235 CodeGenFunction::OMPPrivateScope Scope(CGF);
4236 Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
4237 Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
4239 RedOpGen(CGF, XExpr, EExpr, UpExpr);
4240 Scope.ForceCleanup();
4242 // Shift the address forward by one element.
4243 auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
4244 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
4245 auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
4246 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
4247 // Check whether we've reached the end.
4249 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
4250 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
4251 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
4252 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
4255 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
4258 /// Emit reduction combiner. If the combiner is a simple expression emit it as
4259 /// is, otherwise consider it as combiner of UDR decl and emit it as a call of
4260 /// UDR combiner function.
4261 static void emitReductionCombiner(CodeGenFunction &CGF,
4262 const Expr *ReductionOp) {
4263 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
4264 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
4266 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
4267 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
4268 std::pair<llvm::Function *, llvm::Function *> Reduction =
4269 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
4270 RValue Func = RValue::get(Reduction.first);
4271 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
4272 CGF.EmitIgnoredExpr(ReductionOp);
4275 CGF.EmitIgnoredExpr(ReductionOp);
4278 llvm::Value *CGOpenMPRuntime::emitReductionFunction(
4279 CodeGenModule &CGM, llvm::Type *ArgsType, ArrayRef<const Expr *> Privates,
4280 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
4281 ArrayRef<const Expr *> ReductionOps) {
4282 auto &C = CGM.getContext();
4284 // void reduction_func(void *LHSArg, void *RHSArg);
4285 FunctionArgList Args;
4286 ImplicitParamDecl LHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
4287 ImplicitParamDecl RHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
4288 Args.push_back(&LHSArg);
4289 Args.push_back(&RHSArg);
4290 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
4291 auto *Fn = llvm::Function::Create(
4292 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
4293 ".omp.reduction.reduction_func", &CGM.getModule());
4294 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
4295 CodeGenFunction CGF(CGM);
4296 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
4298 // Dst = (void*[n])(LHSArg);
4299 // Src = (void*[n])(RHSArg);
4300 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4301 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
4302 ArgsType), CGF.getPointerAlign());
4303 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4304 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
4305 ArgsType), CGF.getPointerAlign());
4308 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
4310 CodeGenFunction::OMPPrivateScope Scope(CGF);
4311 auto IPriv = Privates.begin();
4313 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
4314 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
4315 Scope.addPrivate(RHSVar, [&]() -> Address {
4316 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
4318 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
4319 Scope.addPrivate(LHSVar, [&]() -> Address {
4320 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
4322 QualType PrivTy = (*IPriv)->getType();
4323 if (PrivTy->isVariablyModifiedType()) {
4324 // Get array size and emit VLA type.
4327 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
4328 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
4329 auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
4330 auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
4331 CodeGenFunction::OpaqueValueMapping OpaqueMap(
4332 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
4333 CGF.EmitVariablyModifiedType(PrivTy);
4337 IPriv = Privates.begin();
4338 auto ILHS = LHSExprs.begin();
4339 auto IRHS = RHSExprs.begin();
4340 for (auto *E : ReductionOps) {
4341 if ((*IPriv)->getType()->isArrayType()) {
4342 // Emit reduction for array section.
4343 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4344 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
4345 EmitOMPAggregateReduction(
4346 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
4347 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4348 emitReductionCombiner(CGF, E);
4351 // Emit reduction for array subscript or single variable.
4352 emitReductionCombiner(CGF, E);
4357 Scope.ForceCleanup();
4358 CGF.FinishFunction();
4362 void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
4363 const Expr *ReductionOp,
4364 const Expr *PrivateRef,
4365 const DeclRefExpr *LHS,
4366 const DeclRefExpr *RHS) {
4367 if (PrivateRef->getType()->isArrayType()) {
4368 // Emit reduction for array section.
4369 auto *LHSVar = cast<VarDecl>(LHS->getDecl());
4370 auto *RHSVar = cast<VarDecl>(RHS->getDecl());
4371 EmitOMPAggregateReduction(
4372 CGF, PrivateRef->getType(), LHSVar, RHSVar,
4373 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4374 emitReductionCombiner(CGF, ReductionOp);
4377 // Emit reduction for array subscript or single variable.
4378 emitReductionCombiner(CGF, ReductionOp);
4381 void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
4382 ArrayRef<const Expr *> Privates,
4383 ArrayRef<const Expr *> LHSExprs,
4384 ArrayRef<const Expr *> RHSExprs,
4385 ArrayRef<const Expr *> ReductionOps,
4386 ReductionOptionsTy Options) {
4387 if (!CGF.HaveInsertPoint())
4390 bool WithNowait = Options.WithNowait;
4391 bool SimpleReduction = Options.SimpleReduction;
4393 // Next code should be emitted for reduction:
4395 // static kmp_critical_name lock = { 0 };
4397 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
4398 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
4400 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
4401 // *(Type<n>-1*)rhs[<n>-1]);
4405 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
4406 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4407 // RedList, reduce_func, &<lock>)) {
4410 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4412 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4416 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
4418 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
4423 // if SimpleReduction is true, only the next code is generated:
4425 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4428 auto &C = CGM.getContext();
4430 if (SimpleReduction) {
4431 CodeGenFunction::RunCleanupsScope Scope(CGF);
4432 auto IPriv = Privates.begin();
4433 auto ILHS = LHSExprs.begin();
4434 auto IRHS = RHSExprs.begin();
4435 for (auto *E : ReductionOps) {
4436 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4437 cast<DeclRefExpr>(*IRHS));
4445 // 1. Build a list of reduction variables.
4446 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
4447 auto Size = RHSExprs.size();
4448 for (auto *E : Privates) {
4449 if (E->getType()->isVariablyModifiedType())
4450 // Reserve place for array size.
4453 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
4454 QualType ReductionArrayTy =
4455 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
4456 /*IndexTypeQuals=*/0);
4457 Address ReductionList =
4458 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
4459 auto IPriv = Privates.begin();
4461 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
4463 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
4464 CGF.Builder.CreateStore(
4465 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4466 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
4468 if ((*IPriv)->getType()->isVariablyModifiedType()) {
4469 // Store array size.
4471 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
4472 CGF.getPointerSize());
4473 llvm::Value *Size = CGF.Builder.CreateIntCast(
4475 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
4477 CGF.SizeTy, /*isSigned=*/false);
4478 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
4483 // 2. Emit reduce_func().
4484 auto *ReductionFn = emitReductionFunction(
4485 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
4486 LHSExprs, RHSExprs, ReductionOps);
4488 // 3. Create static kmp_critical_name lock = { 0 };
4489 auto *Lock = getCriticalRegionLock(".reduction");
4491 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4492 // RedList, reduce_func, &<lock>);
4493 auto *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
4494 auto *ThreadId = getThreadID(CGF, Loc);
4495 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
4496 auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4497 ReductionList.getPointer(), CGF.VoidPtrTy);
4498 llvm::Value *Args[] = {
4499 IdentTLoc, // ident_t *<loc>
4500 ThreadId, // i32 <gtid>
4501 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
4502 ReductionArrayTySize, // size_type sizeof(RedList)
4503 RL, // void *RedList
4504 ReductionFn, // void (*) (void *, void *) <reduce_func>
4505 Lock // kmp_critical_name *&<lock>
4507 auto Res = CGF.EmitRuntimeCall(
4508 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
4509 : OMPRTL__kmpc_reduce),
4512 // 5. Build switch(res)
4513 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
4514 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
4518 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4520 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4522 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
4523 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
4524 CGF.EmitBlock(Case1BB);
4526 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4527 llvm::Value *EndArgs[] = {
4528 IdentTLoc, // ident_t *<loc>
4529 ThreadId, // i32 <gtid>
4530 Lock // kmp_critical_name *&<lock>
4532 auto &&CodeGen = [&Privates, &LHSExprs, &RHSExprs, &ReductionOps](
4533 CodeGenFunction &CGF, PrePostActionTy &Action) {
4534 auto &RT = CGF.CGM.getOpenMPRuntime();
4535 auto IPriv = Privates.begin();
4536 auto ILHS = LHSExprs.begin();
4537 auto IRHS = RHSExprs.begin();
4538 for (auto *E : ReductionOps) {
4539 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4540 cast<DeclRefExpr>(*IRHS));
4546 RegionCodeGenTy RCG(CodeGen);
4547 CommonActionTy Action(
4548 nullptr, llvm::None,
4549 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
4550 : OMPRTL__kmpc_end_reduce),
4552 RCG.setAction(Action);
4555 CGF.EmitBranch(DefaultBB);
4559 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
4562 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
4563 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
4564 CGF.EmitBlock(Case2BB);
4566 auto &&AtomicCodeGen = [Loc, &Privates, &LHSExprs, &RHSExprs, &ReductionOps](
4567 CodeGenFunction &CGF, PrePostActionTy &Action) {
4568 auto ILHS = LHSExprs.begin();
4569 auto IRHS = RHSExprs.begin();
4570 auto IPriv = Privates.begin();
4571 for (auto *E : ReductionOps) {
4572 const Expr *XExpr = nullptr;
4573 const Expr *EExpr = nullptr;
4574 const Expr *UpExpr = nullptr;
4575 BinaryOperatorKind BO = BO_Comma;
4576 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
4577 if (BO->getOpcode() == BO_Assign) {
4578 XExpr = BO->getLHS();
4579 UpExpr = BO->getRHS();
4582 // Try to emit update expression as a simple atomic.
4583 auto *RHSExpr = UpExpr;
4585 // Analyze RHS part of the whole expression.
4586 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
4587 RHSExpr->IgnoreParenImpCasts())) {
4588 // If this is a conditional operator, analyze its condition for
4589 // min/max reduction operator.
4590 RHSExpr = ACO->getCond();
4593 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
4594 EExpr = BORHS->getRHS();
4595 BO = BORHS->getOpcode();
4599 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4600 auto &&AtomicRedGen = [BO, VD,
4601 Loc](CodeGenFunction &CGF, const Expr *XExpr,
4602 const Expr *EExpr, const Expr *UpExpr) {
4603 LValue X = CGF.EmitLValue(XExpr);
4606 E = CGF.EmitAnyExpr(EExpr);
4607 CGF.EmitOMPAtomicSimpleUpdateExpr(
4608 X, E, BO, /*IsXLHSInRHSPart=*/true,
4609 llvm::AtomicOrdering::Monotonic, Loc,
4610 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
4611 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4612 PrivateScope.addPrivate(
4613 VD, [&CGF, VD, XRValue, Loc]() -> Address {
4614 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
4615 CGF.emitOMPSimpleStore(
4616 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
4617 VD->getType().getNonReferenceType(), Loc);
4620 (void)PrivateScope.Privatize();
4621 return CGF.EmitAnyExpr(UpExpr);
4624 if ((*IPriv)->getType()->isArrayType()) {
4625 // Emit atomic reduction for array section.
4626 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
4627 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
4628 AtomicRedGen, XExpr, EExpr, UpExpr);
4630 // Emit atomic reduction for array subscript or single variable.
4631 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
4633 // Emit as a critical region.
4634 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
4635 const Expr *, const Expr *) {
4636 auto &RT = CGF.CGM.getOpenMPRuntime();
4637 RT.emitCriticalRegion(
4638 CGF, ".atomic_reduction",
4639 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
4641 emitReductionCombiner(CGF, E);
4645 if ((*IPriv)->getType()->isArrayType()) {
4646 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4647 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
4648 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
4651 CritRedGen(CGF, nullptr, nullptr, nullptr);
4658 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
4660 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
4661 llvm::Value *EndArgs[] = {
4662 IdentTLoc, // ident_t *<loc>
4663 ThreadId, // i32 <gtid>
4664 Lock // kmp_critical_name *&<lock>
4666 CommonActionTy Action(nullptr, llvm::None,
4667 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
4669 AtomicRCG.setAction(Action);
4674 CGF.EmitBranch(DefaultBB);
4675 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
4678 void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
4679 SourceLocation Loc) {
4680 if (!CGF.HaveInsertPoint())
4682 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
4684 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
4685 // Ignore return result until untied tasks are supported.
4686 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
4687 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4688 Region->emitUntiedSwitch(CGF);
4691 void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
4692 OpenMPDirectiveKind InnerKind,
4693 const RegionCodeGenTy &CodeGen,
4695 if (!CGF.HaveInsertPoint())
4697 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
4698 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
4709 } // anonymous namespace
4711 static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
4712 RTCancelKind CancelKind = CancelNoreq;
4713 if (CancelRegion == OMPD_parallel)
4714 CancelKind = CancelParallel;
4715 else if (CancelRegion == OMPD_for)
4716 CancelKind = CancelLoop;
4717 else if (CancelRegion == OMPD_sections)
4718 CancelKind = CancelSections;
4720 assert(CancelRegion == OMPD_taskgroup);
4721 CancelKind = CancelTaskgroup;
4726 void CGOpenMPRuntime::emitCancellationPointCall(
4727 CodeGenFunction &CGF, SourceLocation Loc,
4728 OpenMPDirectiveKind CancelRegion) {
4729 if (!CGF.HaveInsertPoint())
4731 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
4732 // global_tid, kmp_int32 cncl_kind);
4733 if (auto *OMPRegionInfo =
4734 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
4735 // For 'cancellation point taskgroup', the task region info may not have a
4736 // cancel. This may instead happen in another adjacent task.
4737 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
4738 llvm::Value *Args[] = {
4739 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
4740 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
4741 // Ignore return result until untied tasks are supported.
4742 auto *Result = CGF.EmitRuntimeCall(
4743 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
4744 // if (__kmpc_cancellationpoint()) {
4745 // exit from construct;
4747 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
4748 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
4749 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
4750 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
4751 CGF.EmitBlock(ExitBB);
4752 // exit from construct;
4754 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
4755 CGF.EmitBranchThroughCleanup(CancelDest);
4756 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
4761 void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
4763 OpenMPDirectiveKind CancelRegion) {
4764 if (!CGF.HaveInsertPoint())
4766 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
4767 // kmp_int32 cncl_kind);
4768 if (auto *OMPRegionInfo =
4769 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
4770 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
4771 PrePostActionTy &) {
4772 auto &RT = CGF.CGM.getOpenMPRuntime();
4773 llvm::Value *Args[] = {
4774 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
4775 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
4776 // Ignore return result until untied tasks are supported.
4777 auto *Result = CGF.EmitRuntimeCall(
4778 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
4779 // if (__kmpc_cancel()) {
4780 // exit from construct;
4782 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
4783 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
4784 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
4785 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
4786 CGF.EmitBlock(ExitBB);
4787 // exit from construct;
4789 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
4790 CGF.EmitBranchThroughCleanup(CancelDest);
4791 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
4794 emitOMPIfClause(CGF, IfCond, ThenGen,
4795 [](CodeGenFunction &, PrePostActionTy &) {});
4797 RegionCodeGenTy ThenRCG(ThenGen);
4803 /// \brief Obtain information that uniquely identifies a target entry. This
4804 /// consists of the file and device IDs as well as line number associated with
4805 /// the relevant entry source location.
4806 static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
4807 unsigned &DeviceID, unsigned &FileID,
4808 unsigned &LineNum) {
4810 auto &SM = C.getSourceManager();
4812 // The loc should be always valid and have a file ID (the user cannot use
4813 // #pragma directives in macros)
4815 assert(Loc.isValid() && "Source location is expected to be always valid.");
4816 assert(Loc.isFileID() && "Source location is expected to refer to a file.");
4818 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
4819 assert(PLoc.isValid() && "Source location is expected to be always valid.");
4821 llvm::sys::fs::UniqueID ID;
4822 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
4823 llvm_unreachable("Source file with target region no longer exists!");
4825 DeviceID = ID.getDevice();
4826 FileID = ID.getFile();
4827 LineNum = PLoc.getLine();
4830 void CGOpenMPRuntime::emitTargetOutlinedFunction(
4831 const OMPExecutableDirective &D, StringRef ParentName,
4832 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
4833 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
4834 assert(!ParentName.empty() && "Invalid target region parent name!");
4836 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
4837 IsOffloadEntry, CodeGen);
4840 void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
4841 const OMPExecutableDirective &D, StringRef ParentName,
4842 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
4843 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
4844 // Create a unique name for the entry function using the source location
4845 // information of the current target region. The name will be something like:
4847 // __omp_offloading_DD_FFFF_PP_lBB
4849 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
4850 // mangled name of the function that encloses the target region and BB is the
4851 // line number of the target region.
4856 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
4858 SmallString<64> EntryFnName;
4860 llvm::raw_svector_ostream OS(EntryFnName);
4861 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
4862 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
4865 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4867 CodeGenFunction CGF(CGM, true);
4868 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
4869 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
4871 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
4873 // If this target outline function is not an offload entry, we don't need to
4875 if (!IsOffloadEntry)
4878 // The target region ID is used by the runtime library to identify the current
4879 // target region, so it only has to be unique and not necessarily point to
4880 // anything. It could be the pointer to the outlined function that implements
4881 // the target region, but we aren't using that so that the compiler doesn't
4882 // need to keep that, and could therefore inline the host function if proven
4883 // worthwhile during optimization. In the other hand, if emitting code for the
4884 // device, the ID has to be the function address so that it can retrieved from
4885 // the offloading entry and launched by the runtime library. We also mark the
4886 // outlined function to have external linkage in case we are emitting code for
4887 // the device, because these functions will be entry points to the device.
4889 if (CGM.getLangOpts().OpenMPIsDevice) {
4890 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
4891 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
4893 OutlinedFnID = new llvm::GlobalVariable(
4894 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
4895 llvm::GlobalValue::PrivateLinkage,
4896 llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
4898 // Register the information for the entry associated with this target region.
4899 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
4900 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
4904 /// discard all CompoundStmts intervening between two constructs
4905 static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
4906 while (auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
4907 Body = CS->body_front();
4912 /// Emit the number of teams for a target directive. Inspect the num_teams
4913 /// clause associated with a teams construct combined or closely nested
4914 /// with the target directive.
4916 /// Emit a team of size one for directives such as 'target parallel' that
4917 /// have no associated teams construct.
4919 /// Otherwise, return nullptr.
4920 static llvm::Value *
4921 emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
4922 CodeGenFunction &CGF,
4923 const OMPExecutableDirective &D) {
4925 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
4926 "teams directive expected to be "
4927 "emitted only for the host!");
4929 auto &Bld = CGF.Builder;
4931 // If the target directive is combined with a teams directive:
4932 // Return the value in the num_teams clause, if any.
4933 // Otherwise, return 0 to denote the runtime default.
4934 if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
4935 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
4936 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
4937 auto NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
4938 /*IgnoreResultAssign*/ true);
4939 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
4943 // The default value is 0.
4944 return Bld.getInt32(0);
4947 // If the target directive is combined with a parallel directive but not a
4948 // teams directive, start one team.
4949 if (isOpenMPParallelDirective(D.getDirectiveKind()))
4950 return Bld.getInt32(1);
4952 // If the current target region has a teams region enclosed, we need to get
4953 // the number of teams to pass to the runtime function call. This is done
4954 // by generating the expression in a inlined region. This is required because
4955 // the expression is captured in the enclosing target environment when the
4956 // teams directive is not combined with target.
4958 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4960 // FIXME: Accommodate other combined directives with teams when they become
4962 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
4963 ignoreCompoundStmts(CS.getCapturedStmt()))) {
4964 if (auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
4965 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
4966 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
4967 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
4968 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
4972 // If we have an enclosed teams directive but no num_teams clause we use
4973 // the default value 0.
4974 return Bld.getInt32(0);
4977 // No teams associated with the directive.
4981 /// Emit the number of threads for a target directive. Inspect the
4982 /// thread_limit clause associated with a teams construct combined or closely
4983 /// nested with the target directive.
4985 /// Emit the num_threads clause for directives such as 'target parallel' that
4986 /// have no associated teams construct.
4988 /// Otherwise, return nullptr.
4989 static llvm::Value *
4990 emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
4991 CodeGenFunction &CGF,
4992 const OMPExecutableDirective &D) {
4994 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
4995 "teams directive expected to be "
4996 "emitted only for the host!");
4998 auto &Bld = CGF.Builder;
5001 // If the target directive is combined with a teams directive:
5002 // Return the value in the thread_limit clause, if any.
5004 // If the target directive is combined with a parallel directive:
5005 // Return the value in the num_threads clause, if any.
5007 // If both clauses are set, select the minimum of the two.
5009 // If neither teams or parallel combined directives set the number of threads
5010 // in a team, return 0 to denote the runtime default.
5012 // If this is not a teams directive return nullptr.
5014 if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
5015 isOpenMPParallelDirective(D.getDirectiveKind())) {
5016 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
5017 llvm::Value *NumThreadsVal = nullptr;
5018 llvm::Value *ThreadLimitVal = nullptr;
5020 if (const auto *ThreadLimitClause =
5021 D.getSingleClause<OMPThreadLimitClause>()) {
5022 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
5023 auto ThreadLimit = CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
5024 /*IgnoreResultAssign*/ true);
5025 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
5029 if (const auto *NumThreadsClause =
5030 D.getSingleClause<OMPNumThreadsClause>()) {
5031 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
5032 llvm::Value *NumThreads =
5033 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
5034 /*IgnoreResultAssign*/ true);
5036 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
5039 // Select the lesser of thread_limit and num_threads.
5041 ThreadLimitVal = ThreadLimitVal
5042 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
5044 NumThreadsVal, ThreadLimitVal)
5047 // Set default value passed to the runtime if either teams or a target
5048 // parallel type directive is found but no clause is specified.
5049 if (!ThreadLimitVal)
5050 ThreadLimitVal = DefaultThreadLimitVal;
5052 return ThreadLimitVal;
5055 // If the current target region has a teams region enclosed, we need to get
5056 // the thread limit to pass to the runtime function call. This is done
5057 // by generating the expression in a inlined region. This is required because
5058 // the expression is captured in the enclosing target environment when the
5059 // teams directive is not combined with target.
5061 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5063 // FIXME: Accommodate other combined directives with teams when they become
5065 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
5066 ignoreCompoundStmts(CS.getCapturedStmt()))) {
5067 if (auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
5068 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
5069 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
5070 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
5071 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
5075 // If we have an enclosed teams directive but no thread_limit clause we use
5076 // the default value 0.
5077 return CGF.Builder.getInt32(0);
5080 // No teams associated with the directive.
5085 // \brief Utility to handle information from clauses associated with a given
5086 // construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
5087 // It provides a convenient interface to obtain the information and generate
5088 // code for that information.
5089 class MappableExprsHandler {
5091 /// \brief Values for bit flags used to specify the mapping type for
5093 enum OpenMPOffloadMappingFlags {
5094 /// \brief Allocate memory on the device and move data from host to device.
5096 /// \brief Allocate memory on the device and move data from device to host.
5097 OMP_MAP_FROM = 0x02,
5098 /// \brief Always perform the requested mapping action on the element, even
5099 /// if it was already mapped before.
5100 OMP_MAP_ALWAYS = 0x04,
5101 /// \brief Delete the element from the device environment, ignoring the
5102 /// current reference count associated with the element.
5103 OMP_MAP_DELETE = 0x08,
5104 /// \brief The element being mapped is a pointer, therefore the pointee
5105 /// should be mapped as well.
5106 OMP_MAP_IS_PTR = 0x10,
5107 /// \brief This flags signals that an argument is the first one relating to
5108 /// a map/private clause expression. For some cases a single
5109 /// map/privatization results in multiple arguments passed to the runtime
5111 OMP_MAP_FIRST_REF = 0x20,
5112 /// \brief Signal that the runtime library has to return the device pointer
5113 /// in the current position for the data being mapped.
5114 OMP_MAP_RETURN_PTR = 0x40,
5115 /// \brief This flag signals that the reference being passed is a pointer to
5117 OMP_MAP_PRIVATE_PTR = 0x80,
5118 /// \brief Pass the element to the device by value.
5119 OMP_MAP_PRIVATE_VAL = 0x100,
5122 /// Class that associates information with a base pointer to be passed to the
5123 /// runtime library.
5124 class BasePointerInfo {
5125 /// The base pointer.
5126 llvm::Value *Ptr = nullptr;
5127 /// The base declaration that refers to this device pointer, or null if
5129 const ValueDecl *DevPtrDecl = nullptr;
5132 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
5133 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
5134 llvm::Value *operator*() const { return Ptr; }
5135 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
5136 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
5139 typedef SmallVector<BasePointerInfo, 16> MapBaseValuesArrayTy;
5140 typedef SmallVector<llvm::Value *, 16> MapValuesArrayTy;
5141 typedef SmallVector<unsigned, 16> MapFlagsArrayTy;
5144 /// \brief Directive from where the map clauses were extracted.
5145 const OMPExecutableDirective &CurDir;
5147 /// \brief Function the directive is being generated for.
5148 CodeGenFunction &CGF;
5150 /// \brief Set of all first private variables in the current directive.
5151 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
5153 /// Map between device pointer declarations and their expression components.
5154 /// The key value for declarations in 'this' is null.
5157 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
5160 llvm::Value *getExprTypeSize(const Expr *E) const {
5161 auto ExprTy = E->getType().getCanonicalType();
5163 // Reference types are ignored for mapping purposes.
5164 if (auto *RefTy = ExprTy->getAs<ReferenceType>())
5165 ExprTy = RefTy->getPointeeType().getCanonicalType();
5167 // Given that an array section is considered a built-in type, we need to
5168 // do the calculation based on the length of the section instead of relying
5169 // on CGF.getTypeSize(E->getType()).
5170 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
5171 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
5172 OAE->getBase()->IgnoreParenImpCasts())
5173 .getCanonicalType();
5175 // If there is no length associated with the expression, that means we
5176 // are using the whole length of the base.
5177 if (!OAE->getLength() && OAE->getColonLoc().isValid())
5178 return CGF.getTypeSize(BaseTy);
5180 llvm::Value *ElemSize;
5181 if (auto *PTy = BaseTy->getAs<PointerType>())
5182 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
5184 auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
5185 assert(ATy && "Expecting array type if not a pointer type.");
5186 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
5189 // If we don't have a length at this point, that is because we have an
5190 // array section with a single element.
5191 if (!OAE->getLength())
5194 auto *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
5196 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
5197 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
5199 return CGF.getTypeSize(ExprTy);
5202 /// \brief Return the corresponding bits for a given map clause modifier. Add
5203 /// a flag marking the map as a pointer if requested. Add a flag marking the
5204 /// map as the first one of a series of maps that relate to the same map
5206 unsigned getMapTypeBits(OpenMPMapClauseKind MapType,
5207 OpenMPMapClauseKind MapTypeModifier, bool AddPtrFlag,
5208 bool AddIsFirstFlag) const {
5211 case OMPC_MAP_alloc:
5212 case OMPC_MAP_release:
5213 // alloc and release is the default behavior in the runtime library, i.e.
5214 // if we don't pass any bits alloc/release that is what the runtime is
5215 // going to do. Therefore, we don't need to signal anything for these two
5222 Bits = OMP_MAP_FROM;
5224 case OMPC_MAP_tofrom:
5225 Bits = OMP_MAP_TO | OMP_MAP_FROM;
5227 case OMPC_MAP_delete:
5228 Bits = OMP_MAP_DELETE;
5231 llvm_unreachable("Unexpected map type!");
5235 Bits |= OMP_MAP_IS_PTR;
5237 Bits |= OMP_MAP_FIRST_REF;
5238 if (MapTypeModifier == OMPC_MAP_always)
5239 Bits |= OMP_MAP_ALWAYS;
5243 /// \brief Return true if the provided expression is a final array section. A
5244 /// final array section, is one whose length can't be proved to be one.
5245 bool isFinalArraySectionExpression(const Expr *E) const {
5246 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
5248 // It is not an array section and therefore not a unity-size one.
5252 // An array section with no colon always refer to a single element.
5253 if (OASE->getColonLoc().isInvalid())
5256 auto *Length = OASE->getLength();
5258 // If we don't have a length we have to check if the array has size 1
5259 // for this dimension. Also, we should always expect a length if the
5260 // base type is pointer.
5262 auto BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
5263 OASE->getBase()->IgnoreParenImpCasts())
5264 .getCanonicalType();
5265 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
5266 return ATy->getSize().getSExtValue() != 1;
5267 // If we don't have a constant dimension length, we have to consider
5268 // the current section as having any size, so it is not necessarily
5269 // unitary. If it happen to be unity size, that's user fault.
5273 // Check if the length evaluates to 1.
5274 llvm::APSInt ConstLength;
5275 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
5276 return true; // Can have more that size 1.
5278 return ConstLength.getSExtValue() != 1;
5281 /// \brief Generate the base pointers, section pointers, sizes and map type
5282 /// bits for the provided map type, map modifier, and expression components.
5283 /// \a IsFirstComponent should be set to true if the provided set of
5284 /// components is the first associated with a capture.
5285 void generateInfoForComponentList(
5286 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
5287 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
5288 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
5289 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
5290 bool IsFirstComponentList) const {
5292 // The following summarizes what has to be generated for each map and the
5293 // types bellow. The generated information is expressed in this order:
5294 // base pointer, section pointer, size, flags
5295 // (to add to the ones that come from the map type and modifier).
5316 // &d, &d, sizeof(double), noflags
5319 // &i, &i, 100*sizeof(int), noflags
5322 // &i(=&i[0]), &i[1], 23*sizeof(int), noflags
5325 // &p, &p, sizeof(float*), noflags
5328 // p, &p[1], 24*sizeof(float), noflags
5331 // &s, &s, sizeof(S2), noflags
5334 // &s, &(s.i), sizeof(int), noflags
5337 // &s, &(s.i.f), 50*sizeof(int), noflags
5340 // &s, &(s.p), sizeof(double*), noflags
5342 // map(s.p[:22], s.a s.b)
5343 // &s, &(s.p), sizeof(double*), noflags
5344 // &(s.p), &(s.p[0]), 22*sizeof(double), ptr_flag + extra_flag
5347 // &s, &(s.ps), sizeof(S2*), noflags
5350 // &s, &(s.ps), sizeof(S2*), noflags
5351 // &(s.ps), &(s.ps->s.i), sizeof(int), ptr_flag + extra_flag
5354 // &s, &(s.ps), sizeof(S2*), noflags
5355 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
5357 // map(s.ps->ps->ps)
5358 // &s, &(s.ps), sizeof(S2*), noflags
5359 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
5360 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5362 // map(s.ps->ps->s.f[:22])
5363 // &s, &(s.ps), sizeof(S2*), noflags
5364 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
5365 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), ptr_flag + extra_flag
5368 // &ps, &ps, sizeof(S2*), noflags
5371 // ps, &(ps->i), sizeof(int), noflags
5374 // ps, &(ps->s.f[0]), 50*sizeof(float), noflags
5377 // ps, &(ps->p), sizeof(double*), noflags
5380 // ps, &(ps->p), sizeof(double*), noflags
5381 // &(ps->p), &(ps->p[0]), 22*sizeof(double), ptr_flag + extra_flag
5384 // ps, &(ps->ps), sizeof(S2*), noflags
5387 // ps, &(ps->ps), sizeof(S2*), noflags
5388 // &(ps->ps), &(ps->ps->s.i), sizeof(int), ptr_flag + extra_flag
5391 // ps, &(ps->ps), sizeof(S2*), noflags
5392 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5394 // map(ps->ps->ps->ps)
5395 // ps, &(ps->ps), sizeof(S2*), noflags
5396 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5397 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5399 // map(ps->ps->ps->s.f[:22])
5400 // ps, &(ps->ps), sizeof(S2*), noflags
5401 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5402 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), ptr_flag +
5405 // Track if the map information being generated is the first for a capture.
5406 bool IsCaptureFirstInfo = IsFirstComponentList;
5408 // Scan the components from the base to the complete expression.
5409 auto CI = Components.rbegin();
5410 auto CE = Components.rend();
5413 // Track if the map information being generated is the first for a list of
5415 bool IsExpressionFirstInfo = true;
5416 llvm::Value *BP = nullptr;
5418 if (auto *ME = dyn_cast<MemberExpr>(I->getAssociatedExpression())) {
5419 // The base is the 'this' pointer. The content of the pointer is going
5420 // to be the base of the field being mapped.
5421 BP = CGF.EmitScalarExpr(ME->getBase());
5423 // The base is the reference to the variable.
5425 BP = CGF.EmitLValue(cast<DeclRefExpr>(I->getAssociatedExpression()))
5428 // If the variable is a pointer and is being dereferenced (i.e. is not
5429 // the last component), the base has to be the pointer itself, not its
5430 // reference. References are ignored for mapping purposes.
5432 I->getAssociatedDeclaration()->getType().getNonReferenceType();
5433 if (Ty->isAnyPointerType() && std::next(I) != CE) {
5434 auto PtrAddr = CGF.MakeNaturalAlignAddrLValue(BP, Ty);
5435 BP = CGF.EmitLoadOfPointerLValue(PtrAddr.getAddress(),
5436 Ty->castAs<PointerType>())
5439 // We do not need to generate individual map information for the
5440 // pointer, it can be associated with the combined storage.
5445 for (; I != CE; ++I) {
5446 auto Next = std::next(I);
5448 // We need to generate the addresses and sizes if this is the last
5449 // component, if the component is a pointer or if it is an array section
5450 // whose length can't be proved to be one. If this is a pointer, it
5451 // becomes the base address for the following components.
5453 // A final array section, is one whose length can't be proved to be one.
5454 bool IsFinalArraySection =
5455 isFinalArraySectionExpression(I->getAssociatedExpression());
5457 // Get information on whether the element is a pointer. Have to do a
5458 // special treatment for array sections given that they are built-in
5461 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
5464 OMPArraySectionExpr::getBaseOriginalType(OASE)
5466 ->isAnyPointerType()) ||
5467 I->getAssociatedExpression()->getType()->isAnyPointerType();
5469 if (Next == CE || IsPointer || IsFinalArraySection) {
5471 // If this is not the last component, we expect the pointer to be
5472 // associated with an array expression or member expression.
5473 assert((Next == CE ||
5474 isa<MemberExpr>(Next->getAssociatedExpression()) ||
5475 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
5476 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
5477 "Unexpected expression");
5479 auto *LB = CGF.EmitLValue(I->getAssociatedExpression()).getPointer();
5480 auto *Size = getExprTypeSize(I->getAssociatedExpression());
5482 // If we have a member expression and the current component is a
5483 // reference, we have to map the reference too. Whenever we have a
5484 // reference, the section that reference refers to is going to be a
5485 // load instruction from the storage assigned to the reference.
5486 if (isa<MemberExpr>(I->getAssociatedExpression()) &&
5487 I->getAssociatedDeclaration()->getType()->isReferenceType()) {
5488 auto *LI = cast<llvm::LoadInst>(LB);
5489 auto *RefAddr = LI->getPointerOperand();
5491 BasePointers.push_back(BP);
5492 Pointers.push_back(RefAddr);
5493 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
5494 Types.push_back(getMapTypeBits(
5495 /*MapType*/ OMPC_MAP_alloc, /*MapTypeModifier=*/OMPC_MAP_unknown,
5496 !IsExpressionFirstInfo, IsCaptureFirstInfo));
5497 IsExpressionFirstInfo = false;
5498 IsCaptureFirstInfo = false;
5499 // The reference will be the next base address.
5503 BasePointers.push_back(BP);
5504 Pointers.push_back(LB);
5505 Sizes.push_back(Size);
5507 // We need to add a pointer flag for each map that comes from the
5508 // same expression except for the first one. We also need to signal
5509 // this map is the first one that relates with the current capture
5510 // (there is a set of entries for each capture).
5511 Types.push_back(getMapTypeBits(MapType, MapTypeModifier,
5512 !IsExpressionFirstInfo,
5513 IsCaptureFirstInfo));
5515 // If we have a final array section, we are done with this expression.
5516 if (IsFinalArraySection)
5519 // The pointer becomes the base for the next element.
5523 IsExpressionFirstInfo = false;
5524 IsCaptureFirstInfo = false;
5530 /// \brief Return the adjusted map modifiers if the declaration a capture
5531 /// refers to appears in a first-private clause. This is expected to be used
5532 /// only with directives that start with 'target'.
5533 unsigned adjustMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap,
5534 unsigned CurrentModifiers) {
5535 assert(Cap.capturesVariable() && "Expected capture by reference only!");
5537 // A first private variable captured by reference will use only the
5538 // 'private ptr' and 'map to' flag. Return the right flags if the captured
5539 // declaration is known as first-private in this handler.
5540 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
5541 return MappableExprsHandler::OMP_MAP_PRIVATE_PTR |
5542 MappableExprsHandler::OMP_MAP_TO;
5544 // We didn't modify anything.
5545 return CurrentModifiers;
5549 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
5550 : CurDir(Dir), CGF(CGF) {
5551 // Extract firstprivate clause information.
5552 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
5553 for (const auto *D : C->varlists())
5554 FirstPrivateDecls.insert(
5555 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
5556 // Extract device pointer clause information.
5557 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
5558 for (auto L : C->component_lists())
5559 DevPointersMap[L.first].push_back(L.second);
5562 /// \brief Generate all the base pointers, section pointers, sizes and map
5563 /// types for the extracted mappable expressions. Also, for each item that
5564 /// relates with a device pointer, a pair of the relevant declaration and
5565 /// index where it occurs is appended to the device pointers info array.
5566 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
5567 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
5568 MapFlagsArrayTy &Types) const {
5569 BasePointers.clear();
5575 /// Kind that defines how a device pointer has to be returned.
5576 enum ReturnPointerKind {
5577 // Don't have to return any pointer.
5579 // Pointer is the base of the declaration.
5581 // Pointer is a member of the base declaration - 'this'
5583 // Pointer is a reference and a member of the base declaration - 'this'
5584 RPK_MemberReference,
5586 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
5587 OpenMPMapClauseKind MapType;
5588 OpenMPMapClauseKind MapTypeModifier;
5589 ReturnPointerKind ReturnDevicePointer;
5592 : MapType(OMPC_MAP_unknown), MapTypeModifier(OMPC_MAP_unknown),
5593 ReturnDevicePointer(RPK_None) {}
5595 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
5596 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
5597 ReturnPointerKind ReturnDevicePointer)
5598 : Components(Components), MapType(MapType),
5599 MapTypeModifier(MapTypeModifier),
5600 ReturnDevicePointer(ReturnDevicePointer) {}
5603 // We have to process the component lists that relate with the same
5604 // declaration in a single chunk so that we can generate the map flags
5605 // correctly. Therefore, we organize all lists in a map.
5606 llvm::DenseMap<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
5608 // Helper function to fill the information map for the different supported
5610 auto &&InfoGen = [&Info](
5612 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
5613 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
5614 MapInfo::ReturnPointerKind ReturnDevicePointer) {
5615 const ValueDecl *VD =
5616 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
5617 Info[VD].push_back({L, MapType, MapModifier, ReturnDevicePointer});
5620 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
5621 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
5622 for (auto L : C->component_lists())
5623 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
5625 for (auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
5626 for (auto L : C->component_lists())
5627 InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
5629 for (auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
5630 for (auto L : C->component_lists())
5631 InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
5634 // Look at the use_device_ptr clause information and mark the existing map
5635 // entries as such. If there is no map information for an entry in the
5636 // use_device_ptr list, we create one with map type 'alloc' and zero size
5637 // section. It is the user fault if that was not mapped before.
5638 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
5639 for (auto *C : this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>())
5640 for (auto L : C->component_lists()) {
5641 assert(!L.second.empty() && "Not expecting empty list of components!");
5642 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
5643 VD = cast<ValueDecl>(VD->getCanonicalDecl());
5644 auto *IE = L.second.back().getAssociatedExpression();
5645 // If the first component is a member expression, we have to look into
5646 // 'this', which maps to null in the map of map information. Otherwise
5647 // look directly for the information.
5648 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
5650 // We potentially have map information for this declaration already.
5651 // Look for the first set of components that refer to it.
5652 if (It != Info.end()) {
5653 auto CI = std::find_if(
5654 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
5655 return MI.Components.back().getAssociatedDeclaration() == VD;
5657 // If we found a map entry, signal that the pointer has to be returned
5658 // and move on to the next declaration.
5659 if (CI != It->second.end()) {
5660 CI->ReturnDevicePointer = isa<MemberExpr>(IE)
5661 ? (VD->getType()->isReferenceType()
5662 ? MapInfo::RPK_MemberReference
5663 : MapInfo::RPK_Member)
5664 : MapInfo::RPK_Base;
5669 // We didn't find any match in our map information - generate a zero
5670 // size array section.
5671 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
5674 .EmitLoadOfLValue(this->CGF.EmitLValue(IE), SourceLocation())
5676 BasePointers.push_back({Ptr, VD});
5677 Pointers.push_back(Ptr);
5678 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
5679 Types.push_back(OMP_MAP_RETURN_PTR | OMP_MAP_FIRST_REF);
5682 for (auto &M : Info) {
5683 // We need to know when we generate information for the first component
5684 // associated with a capture, because the mapping flags depend on it.
5685 bool IsFirstComponentList = true;
5686 for (MapInfo &L : M.second) {
5687 assert(!L.Components.empty() &&
5688 "Not expecting declaration with no component lists.");
5690 // Remember the current base pointer index.
5691 unsigned CurrentBasePointersIdx = BasePointers.size();
5692 // FIXME: MSVC 2013 seems to require this-> to find the member method.
5693 this->generateInfoForComponentList(L.MapType, L.MapTypeModifier,
5694 L.Components, BasePointers, Pointers,
5695 Sizes, Types, IsFirstComponentList);
5697 // If this entry relates with a device pointer, set the relevant
5698 // declaration and add the 'return pointer' flag.
5699 if (IsFirstComponentList &&
5700 L.ReturnDevicePointer != MapInfo::RPK_None) {
5701 // If the pointer is not the base of the map, we need to skip the
5702 // base. If it is a reference in a member field, we also need to skip
5703 // the map of the reference.
5704 if (L.ReturnDevicePointer != MapInfo::RPK_Base) {
5705 ++CurrentBasePointersIdx;
5706 if (L.ReturnDevicePointer == MapInfo::RPK_MemberReference)
5707 ++CurrentBasePointersIdx;
5709 assert(BasePointers.size() > CurrentBasePointersIdx &&
5710 "Unexpected number of mapped base pointers.");
5712 auto *RelevantVD = L.Components.back().getAssociatedDeclaration();
5713 assert(RelevantVD &&
5714 "No relevant declaration related with device pointer??");
5716 BasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
5717 Types[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PTR;
5719 IsFirstComponentList = false;
5724 /// \brief Generate the base pointers, section pointers, sizes and map types
5725 /// associated to a given capture.
5726 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
5728 MapBaseValuesArrayTy &BasePointers,
5729 MapValuesArrayTy &Pointers,
5730 MapValuesArrayTy &Sizes,
5731 MapFlagsArrayTy &Types) const {
5732 assert(!Cap->capturesVariableArrayType() &&
5733 "Not expecting to generate map info for a variable array type!");
5735 BasePointers.clear();
5740 // We need to know when we generating information for the first component
5741 // associated with a capture, because the mapping flags depend on it.
5742 bool IsFirstComponentList = true;
5744 const ValueDecl *VD =
5747 : cast<ValueDecl>(Cap->getCapturedVar()->getCanonicalDecl());
5749 // If this declaration appears in a is_device_ptr clause we just have to
5750 // pass the pointer by value. If it is a reference to a declaration, we just
5751 // pass its value, otherwise, if it is a member expression, we need to map
5754 auto It = DevPointersMap.find(VD);
5755 if (It != DevPointersMap.end()) {
5756 for (auto L : It->second) {
5757 generateInfoForComponentList(
5758 /*MapType=*/OMPC_MAP_to, /*MapTypeModifier=*/OMPC_MAP_unknown, L,
5759 BasePointers, Pointers, Sizes, Types, IsFirstComponentList);
5760 IsFirstComponentList = false;
5764 } else if (DevPointersMap.count(VD)) {
5765 BasePointers.push_back({Arg, VD});
5766 Pointers.push_back(Arg);
5767 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
5768 Types.push_back(OMP_MAP_PRIVATE_VAL | OMP_MAP_FIRST_REF);
5772 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
5773 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
5774 for (auto L : C->decl_component_lists(VD)) {
5775 assert(L.first == VD &&
5776 "We got information for the wrong declaration??");
5777 assert(!L.second.empty() &&
5778 "Not expecting declaration with no component lists.");
5779 generateInfoForComponentList(C->getMapType(), C->getMapTypeModifier(),
5780 L.second, BasePointers, Pointers, Sizes,
5781 Types, IsFirstComponentList);
5782 IsFirstComponentList = false;
5788 /// \brief Generate the default map information for a given capture \a CI,
5789 /// record field declaration \a RI and captured value \a CV.
5790 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
5791 const FieldDecl &RI, llvm::Value *CV,
5792 MapBaseValuesArrayTy &CurBasePointers,
5793 MapValuesArrayTy &CurPointers,
5794 MapValuesArrayTy &CurSizes,
5795 MapFlagsArrayTy &CurMapTypes) {
5797 // Do the default mapping.
5798 if (CI.capturesThis()) {
5799 CurBasePointers.push_back(CV);
5800 CurPointers.push_back(CV);
5801 const PointerType *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
5802 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
5803 // Default map type.
5804 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
5805 } else if (CI.capturesVariableByCopy()) {
5806 CurBasePointers.push_back(CV);
5807 CurPointers.push_back(CV);
5808 if (!RI.getType()->isAnyPointerType()) {
5809 // We have to signal to the runtime captures passed by value that are
5811 CurMapTypes.push_back(OMP_MAP_PRIVATE_VAL);
5812 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
5814 // Pointers are implicitly mapped with a zero size and no flags
5815 // (other than first map that is added for all implicit maps).
5816 CurMapTypes.push_back(0u);
5817 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
5820 assert(CI.capturesVariable() && "Expected captured reference.");
5821 CurBasePointers.push_back(CV);
5822 CurPointers.push_back(CV);
5824 const ReferenceType *PtrTy =
5825 cast<ReferenceType>(RI.getType().getTypePtr());
5826 QualType ElementType = PtrTy->getPointeeType();
5827 CurSizes.push_back(CGF.getTypeSize(ElementType));
5828 // The default map type for a scalar/complex type is 'to' because by
5829 // default the value doesn't have to be retrieved. For an aggregate
5830 // type, the default is 'tofrom'.
5831 CurMapTypes.push_back(ElementType->isAggregateType()
5832 ? (OMP_MAP_TO | OMP_MAP_FROM)
5835 // If we have a capture by reference we may need to add the private
5836 // pointer flag if the base declaration shows in some first-private
5838 CurMapTypes.back() =
5839 adjustMapModifiersForPrivateClauses(CI, CurMapTypes.back());
5841 // Every default map produces a single argument, so, it is always the
5843 CurMapTypes.back() |= OMP_MAP_FIRST_REF;
5847 enum OpenMPOffloadingReservedDeviceIDs {
5848 /// \brief Device ID if the device was not defined, runtime should get it
5849 /// from environment variables in the spec.
5850 OMP_DEVICEID_UNDEF = -1,
5852 } // anonymous namespace
5854 /// \brief Emit the arrays used to pass the captures and map information to the
5855 /// offloading runtime library. If there is no map or capture information,
5856 /// return nullptr by reference.
5858 emitOffloadingArrays(CodeGenFunction &CGF,
5859 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
5860 MappableExprsHandler::MapValuesArrayTy &Pointers,
5861 MappableExprsHandler::MapValuesArrayTy &Sizes,
5862 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
5863 CGOpenMPRuntime::TargetDataInfo &Info) {
5864 auto &CGM = CGF.CGM;
5865 auto &Ctx = CGF.getContext();
5867 // Reset the array information.
5868 Info.clearArrayInfo();
5869 Info.NumberOfPtrs = BasePointers.size();
5871 if (Info.NumberOfPtrs) {
5872 // Detect if we have any capture size requiring runtime evaluation of the
5873 // size so that a constant array could be eventually used.
5874 bool hasRuntimeEvaluationCaptureSize = false;
5875 for (auto *S : Sizes)
5876 if (!isa<llvm::Constant>(S)) {
5877 hasRuntimeEvaluationCaptureSize = true;
5881 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
5882 QualType PointerArrayType =
5883 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
5884 /*IndexTypeQuals=*/0);
5886 Info.BasePointersArray =
5887 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
5888 Info.PointersArray =
5889 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
5891 // If we don't have any VLA types or other types that require runtime
5892 // evaluation, we can use a constant array for the map sizes, otherwise we
5893 // need to fill up the arrays as we do for the pointers.
5894 if (hasRuntimeEvaluationCaptureSize) {
5895 QualType SizeArrayType = Ctx.getConstantArrayType(
5896 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
5897 /*IndexTypeQuals=*/0);
5899 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
5901 // We expect all the sizes to be constant, so we collect them to create
5902 // a constant array.
5903 SmallVector<llvm::Constant *, 16> ConstSizes;
5904 for (auto S : Sizes)
5905 ConstSizes.push_back(cast<llvm::Constant>(S));
5907 auto *SizesArrayInit = llvm::ConstantArray::get(
5908 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
5909 auto *SizesArrayGbl = new llvm::GlobalVariable(
5910 CGM.getModule(), SizesArrayInit->getType(),
5911 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
5912 SizesArrayInit, ".offload_sizes");
5913 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
5914 Info.SizesArray = SizesArrayGbl;
5917 // The map types are always constant so we don't need to generate code to
5918 // fill arrays. Instead, we create an array constant.
5919 llvm::Constant *MapTypesArrayInit =
5920 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
5921 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
5922 CGM.getModule(), MapTypesArrayInit->getType(),
5923 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
5924 MapTypesArrayInit, ".offload_maptypes");
5925 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
5926 Info.MapTypesArray = MapTypesArrayGbl;
5928 for (unsigned i = 0; i < Info.NumberOfPtrs; ++i) {
5929 llvm::Value *BPVal = *BasePointers[i];
5930 if (BPVal->getType()->isPointerTy())
5931 BPVal = CGF.Builder.CreateBitCast(BPVal, CGM.VoidPtrTy);
5933 assert(BPVal->getType()->isIntegerTy() &&
5934 "If not a pointer, the value type must be an integer.");
5935 BPVal = CGF.Builder.CreateIntToPtr(BPVal, CGM.VoidPtrTy);
5937 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
5938 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
5939 Info.BasePointersArray, 0, i);
5940 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
5941 CGF.Builder.CreateStore(BPVal, BPAddr);
5943 if (Info.requiresDevicePointerInfo())
5944 if (auto *DevVD = BasePointers[i].getDevicePtrDecl())
5945 Info.CaptureDeviceAddrMap.insert(std::make_pair(DevVD, BPAddr));
5947 llvm::Value *PVal = Pointers[i];
5948 if (PVal->getType()->isPointerTy())
5949 PVal = CGF.Builder.CreateBitCast(PVal, CGM.VoidPtrTy);
5951 assert(PVal->getType()->isIntegerTy() &&
5952 "If not a pointer, the value type must be an integer.");
5953 PVal = CGF.Builder.CreateIntToPtr(PVal, CGM.VoidPtrTy);
5955 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
5956 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
5957 Info.PointersArray, 0, i);
5958 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
5959 CGF.Builder.CreateStore(PVal, PAddr);
5961 if (hasRuntimeEvaluationCaptureSize) {
5962 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
5963 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
5967 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
5968 CGF.Builder.CreateStore(
5969 CGF.Builder.CreateIntCast(Sizes[i], CGM.SizeTy, /*isSigned=*/true),
5975 /// \brief Emit the arguments to be passed to the runtime library based on the
5976 /// arrays of pointers, sizes and map types.
5977 static void emitOffloadingArraysArgument(
5978 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
5979 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
5980 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
5981 auto &CGM = CGF.CGM;
5982 if (Info.NumberOfPtrs) {
5983 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
5984 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
5985 Info.BasePointersArray,
5986 /*Idx0=*/0, /*Idx1=*/0);
5987 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
5988 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
5992 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
5993 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
5994 /*Idx0=*/0, /*Idx1=*/0);
5995 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
5996 llvm::ArrayType::get(CGM.Int32Ty, Info.NumberOfPtrs),
6001 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
6002 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
6003 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
6005 llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo());
6009 void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
6010 const OMPExecutableDirective &D,
6011 llvm::Value *OutlinedFn,
6012 llvm::Value *OutlinedFnID,
6013 const Expr *IfCond, const Expr *Device,
6014 ArrayRef<llvm::Value *> CapturedVars) {
6015 if (!CGF.HaveInsertPoint())
6018 assert(OutlinedFn && "Invalid outlined function!");
6020 auto &Ctx = CGF.getContext();
6022 // Fill up the arrays with all the captured variables.
6023 MappableExprsHandler::MapValuesArrayTy KernelArgs;
6024 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
6025 MappableExprsHandler::MapValuesArrayTy Pointers;
6026 MappableExprsHandler::MapValuesArrayTy Sizes;
6027 MappableExprsHandler::MapFlagsArrayTy MapTypes;
6029 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
6030 MappableExprsHandler::MapValuesArrayTy CurPointers;
6031 MappableExprsHandler::MapValuesArrayTy CurSizes;
6032 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
6034 // Get mappable expression information.
6035 MappableExprsHandler MEHandler(D, CGF);
6037 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
6038 auto RI = CS.getCapturedRecordDecl()->field_begin();
6039 auto CV = CapturedVars.begin();
6040 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
6041 CE = CS.capture_end();
6042 CI != CE; ++CI, ++RI, ++CV) {
6046 CurBasePointers.clear();
6047 CurPointers.clear();
6049 CurMapTypes.clear();
6051 // VLA sizes are passed to the outlined region by copy and do not have map
6052 // information associated.
6053 if (CI->capturesVariableArrayType()) {
6054 CurBasePointers.push_back(*CV);
6055 CurPointers.push_back(*CV);
6056 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
6057 // Copy to the device as an argument. No need to retrieve it.
6058 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_PRIVATE_VAL |
6059 MappableExprsHandler::OMP_MAP_FIRST_REF);
6061 // If we have any information in the map clause, we use it, otherwise we
6062 // just do a default mapping.
6063 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
6064 CurSizes, CurMapTypes);
6065 if (CurBasePointers.empty())
6066 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
6067 CurPointers, CurSizes, CurMapTypes);
6069 // We expect to have at least an element of information for this capture.
6070 assert(!CurBasePointers.empty() && "Non-existing map pointer for capture!");
6071 assert(CurBasePointers.size() == CurPointers.size() &&
6072 CurBasePointers.size() == CurSizes.size() &&
6073 CurBasePointers.size() == CurMapTypes.size() &&
6074 "Inconsistent map information sizes!");
6076 // The kernel args are always the first elements of the base pointers
6077 // associated with a capture.
6078 KernelArgs.push_back(*CurBasePointers.front());
6079 // We need to append the results of this capture to what we already have.
6080 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
6081 Pointers.append(CurPointers.begin(), CurPointers.end());
6082 Sizes.append(CurSizes.begin(), CurSizes.end());
6083 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
6086 // Keep track on whether the host function has to be executed.
6087 auto OffloadErrorQType =
6088 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true);
6089 auto OffloadError = CGF.MakeAddrLValue(
6090 CGF.CreateMemTemp(OffloadErrorQType, ".run_host_version"),
6092 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty),
6095 // Fill up the pointer arrays and transfer execution to the device.
6096 auto &&ThenGen = [&BasePointers, &Pointers, &Sizes, &MapTypes, Device,
6097 OutlinedFnID, OffloadError,
6098 &D](CodeGenFunction &CGF, PrePostActionTy &) {
6099 auto &RT = CGF.CGM.getOpenMPRuntime();
6100 // Emit the offloading arrays.
6101 TargetDataInfo Info;
6102 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
6103 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
6104 Info.PointersArray, Info.SizesArray,
6105 Info.MapTypesArray, Info);
6107 // On top of the arrays that were filled up, the target offloading call
6108 // takes as arguments the device id as well as the host pointer. The host
6109 // pointer is used by the runtime library to identify the current target
6110 // region, so it only has to be unique and not necessarily point to
6111 // anything. It could be the pointer to the outlined function that
6112 // implements the target region, but we aren't using that so that the
6113 // compiler doesn't need to keep that, and could therefore inline the host
6114 // function if proven worthwhile during optimization.
6116 // From this point on, we need to have an ID of the target region defined.
6117 assert(OutlinedFnID && "Invalid outlined function ID!");
6119 // Emit device ID if any.
6120 llvm::Value *DeviceID;
6122 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
6123 CGF.Int32Ty, /*isSigned=*/true);
6125 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6127 // Emit the number of elements in the offloading arrays.
6128 llvm::Value *PointerNum = CGF.Builder.getInt32(BasePointers.size());
6130 // Return value of the runtime offloading call.
6131 llvm::Value *Return;
6133 auto *NumTeams = emitNumTeamsForTargetDirective(RT, CGF, D);
6134 auto *NumThreads = emitNumThreadsForTargetDirective(RT, CGF, D);
6136 // The target region is an outlined function launched by the runtime
6137 // via calls __tgt_target() or __tgt_target_teams().
6139 // __tgt_target() launches a target region with one team and one thread,
6140 // executing a serial region. This master thread may in turn launch
6141 // more threads within its team upon encountering a parallel region,
6142 // however, no additional teams can be launched on the device.
6144 // __tgt_target_teams() launches a target region with one or more teams,
6145 // each with one or more threads. This call is required for target
6146 // constructs such as:
6148 // 'target' / 'teams'
6149 // 'target teams distribute parallel for'
6150 // 'target parallel'
6153 // Note that on the host and CPU targets, the runtime implementation of
6154 // these calls simply call the outlined function without forking threads.
6155 // The outlined functions themselves have runtime calls to
6156 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
6157 // the compiler in emitTeamsCall() and emitParallelCall().
6159 // In contrast, on the NVPTX target, the implementation of
6160 // __tgt_target_teams() launches a GPU kernel with the requested number
6161 // of teams and threads so no additional calls to the runtime are required.
6163 // If we have NumTeams defined this means that we have an enclosed teams
6164 // region. Therefore we also expect to have NumThreads defined. These two
6165 // values should be defined in the presence of a teams directive,
6166 // regardless of having any clauses associated. If the user is using teams
6167 // but no clauses, these two values will be the default that should be
6168 // passed to the runtime library - a 32-bit integer with the value zero.
6169 assert(NumThreads && "Thread limit expression should be available along "
6170 "with number of teams.");
6171 llvm::Value *OffloadingArgs[] = {
6172 DeviceID, OutlinedFnID,
6173 PointerNum, Info.BasePointersArray,
6174 Info.PointersArray, Info.SizesArray,
6175 Info.MapTypesArray, NumTeams,
6177 Return = CGF.EmitRuntimeCall(
6178 RT.createRuntimeFunction(OMPRTL__tgt_target_teams), OffloadingArgs);
6180 llvm::Value *OffloadingArgs[] = {
6181 DeviceID, OutlinedFnID,
6182 PointerNum, Info.BasePointersArray,
6183 Info.PointersArray, Info.SizesArray,
6184 Info.MapTypesArray};
6185 Return = CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target),
6189 CGF.EmitStoreOfScalar(Return, OffloadError);
6192 // Notify that the host version must be executed.
6193 auto &&ElseGen = [OffloadError](CodeGenFunction &CGF, PrePostActionTy &) {
6194 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/-1u),
6198 // If we have a target function ID it means that we need to support
6199 // offloading, otherwise, just execute on the host. We need to execute on host
6200 // regardless of the conditional in the if clause if, e.g., the user do not
6201 // specify target triples.
6204 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
6206 RegionCodeGenTy ThenRCG(ThenGen);
6210 RegionCodeGenTy ElseRCG(ElseGen);
6214 // Check the error code and execute the host version if required.
6215 auto OffloadFailedBlock = CGF.createBasicBlock("omp_offload.failed");
6216 auto OffloadContBlock = CGF.createBasicBlock("omp_offload.cont");
6217 auto OffloadErrorVal = CGF.EmitLoadOfScalar(OffloadError, SourceLocation());
6218 auto Failed = CGF.Builder.CreateIsNotNull(OffloadErrorVal);
6219 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
6221 CGF.EmitBlock(OffloadFailedBlock);
6222 CGF.Builder.CreateCall(OutlinedFn, KernelArgs);
6223 CGF.EmitBranch(OffloadContBlock);
6225 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
6228 void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
6229 StringRef ParentName) {
6233 // Codegen OMP target directives that offload compute to the device.
6234 bool requiresDeviceCodegen =
6235 isa<OMPExecutableDirective>(S) &&
6236 isOpenMPTargetExecutionDirective(
6237 cast<OMPExecutableDirective>(S)->getDirectiveKind());
6239 if (requiresDeviceCodegen) {
6240 auto &E = *cast<OMPExecutableDirective>(S);
6244 getTargetEntryUniqueInfo(CGM.getContext(), E.getLocStart(), DeviceID,
6247 // Is this a target region that should not be emitted as an entry point? If
6248 // so just signal we are done with this target region.
6249 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
6253 switch (S->getStmtClass()) {
6254 case Stmt::OMPTargetDirectiveClass:
6255 CodeGenFunction::EmitOMPTargetDeviceFunction(
6256 CGM, ParentName, cast<OMPTargetDirective>(*S));
6258 case Stmt::OMPTargetParallelDirectiveClass:
6259 CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
6260 CGM, ParentName, cast<OMPTargetParallelDirective>(*S));
6262 case Stmt::OMPTargetTeamsDirectiveClass:
6263 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
6264 CGM, ParentName, cast<OMPTargetTeamsDirective>(*S));
6267 llvm_unreachable("Unknown target directive for OpenMP device codegen.");
6272 if (const OMPExecutableDirective *E = dyn_cast<OMPExecutableDirective>(S)) {
6273 if (!E->hasAssociatedStmt())
6276 scanForTargetRegionsFunctions(
6277 cast<CapturedStmt>(E->getAssociatedStmt())->getCapturedStmt(),
6282 // If this is a lambda function, look into its body.
6283 if (auto *L = dyn_cast<LambdaExpr>(S))
6286 // Keep looking for target regions recursively.
6287 for (auto *II : S->children())
6288 scanForTargetRegionsFunctions(II, ParentName);
6291 bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
6292 auto &FD = *cast<FunctionDecl>(GD.getDecl());
6294 // If emitting code for the host, we do not process FD here. Instead we do
6295 // the normal code generation.
6296 if (!CGM.getLangOpts().OpenMPIsDevice)
6299 // Try to detect target regions in the function.
6300 scanForTargetRegionsFunctions(FD.getBody(), CGM.getMangledName(GD));
6302 // We should not emit any function other that the ones created during the
6303 // scanning. Therefore, we signal that this function is completely dealt
6308 bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
6309 if (!CGM.getLangOpts().OpenMPIsDevice)
6312 // Check if there are Ctors/Dtors in this declaration and look for target
6313 // regions in it. We use the complete variant to produce the kernel name
6315 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
6316 if (auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
6317 for (auto *Ctor : RD->ctors()) {
6318 StringRef ParentName =
6319 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
6320 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
6322 auto *Dtor = RD->getDestructor();
6324 StringRef ParentName =
6325 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
6326 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
6330 // If we are in target mode we do not emit any global (declare target is not
6331 // implemented yet). Therefore we signal that GD was processed in this case.
6335 bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
6336 auto *VD = GD.getDecl();
6337 if (isa<FunctionDecl>(VD))
6338 return emitTargetFunctions(GD);
6340 return emitTargetGlobalVariable(GD);
6343 llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
6344 // If we have offloading in the current module, we need to emit the entries
6345 // now and register the offloading descriptor.
6346 createOffloadEntriesAndInfoMetadata();
6348 // Create and register the offloading binary descriptors. This is the main
6349 // entity that captures all the information about offloading in the current
6350 // compilation unit.
6351 return createOffloadingBinaryDescriptorRegistration();
6354 void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
6355 const OMPExecutableDirective &D,
6357 llvm::Value *OutlinedFn,
6358 ArrayRef<llvm::Value *> CapturedVars) {
6359 if (!CGF.HaveInsertPoint())
6362 auto *RTLoc = emitUpdateLocation(CGF, Loc);
6363 CodeGenFunction::RunCleanupsScope Scope(CGF);
6365 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
6366 llvm::Value *Args[] = {
6368 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
6369 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
6370 llvm::SmallVector<llvm::Value *, 16> RealArgs;
6371 RealArgs.append(std::begin(Args), std::end(Args));
6372 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
6374 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
6375 CGF.EmitRuntimeCall(RTLFn, RealArgs);
6378 void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
6379 const Expr *NumTeams,
6380 const Expr *ThreadLimit,
6381 SourceLocation Loc) {
6382 if (!CGF.HaveInsertPoint())
6385 auto *RTLoc = emitUpdateLocation(CGF, Loc);
6387 llvm::Value *NumTeamsVal =
6389 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
6390 CGF.CGM.Int32Ty, /* isSigned = */ true)
6391 : CGF.Builder.getInt32(0);
6393 llvm::Value *ThreadLimitVal =
6395 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
6396 CGF.CGM.Int32Ty, /* isSigned = */ true)
6397 : CGF.Builder.getInt32(0);
6399 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
6400 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
6402 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
6406 void CGOpenMPRuntime::emitTargetDataCalls(
6407 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
6408 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
6409 if (!CGF.HaveInsertPoint())
6412 // Action used to replace the default codegen action and turn privatization
6414 PrePostActionTy NoPrivAction;
6416 // Generate the code for the opening of the data environment. Capture all the
6417 // arguments of the runtime call by reference because they are used in the
6418 // closing of the region.
6419 auto &&BeginThenGen = [&D, Device, &Info, &CodeGen](CodeGenFunction &CGF,
6420 PrePostActionTy &) {
6421 // Fill up the arrays with all the mapped variables.
6422 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
6423 MappableExprsHandler::MapValuesArrayTy Pointers;
6424 MappableExprsHandler::MapValuesArrayTy Sizes;
6425 MappableExprsHandler::MapFlagsArrayTy MapTypes;
6427 // Get map clause information.
6428 MappableExprsHandler MCHandler(D, CGF);
6429 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
6431 // Fill up the arrays and create the arguments.
6432 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
6434 llvm::Value *BasePointersArrayArg = nullptr;
6435 llvm::Value *PointersArrayArg = nullptr;
6436 llvm::Value *SizesArrayArg = nullptr;
6437 llvm::Value *MapTypesArrayArg = nullptr;
6438 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
6439 SizesArrayArg, MapTypesArrayArg, Info);
6441 // Emit device ID if any.
6442 llvm::Value *DeviceID = nullptr;
6444 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
6445 CGF.Int32Ty, /*isSigned=*/true);
6447 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6449 // Emit the number of elements in the offloading arrays.
6450 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
6452 llvm::Value *OffloadingArgs[] = {
6453 DeviceID, PointerNum, BasePointersArrayArg,
6454 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
6455 auto &RT = CGF.CGM.getOpenMPRuntime();
6456 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_begin),
6459 // If device pointer privatization is required, emit the body of the region
6460 // here. It will have to be duplicated: with and without privatization.
6461 if (!Info.CaptureDeviceAddrMap.empty())
6465 // Generate code for the closing of the data region.
6466 auto &&EndThenGen = [Device, &Info](CodeGenFunction &CGF, PrePostActionTy &) {
6467 assert(Info.isValid() && "Invalid data environment closing arguments.");
6469 llvm::Value *BasePointersArrayArg = nullptr;
6470 llvm::Value *PointersArrayArg = nullptr;
6471 llvm::Value *SizesArrayArg = nullptr;
6472 llvm::Value *MapTypesArrayArg = nullptr;
6473 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
6474 SizesArrayArg, MapTypesArrayArg, Info);
6476 // Emit device ID if any.
6477 llvm::Value *DeviceID = nullptr;
6479 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
6480 CGF.Int32Ty, /*isSigned=*/true);
6482 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6484 // Emit the number of elements in the offloading arrays.
6485 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
6487 llvm::Value *OffloadingArgs[] = {
6488 DeviceID, PointerNum, BasePointersArrayArg,
6489 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
6490 auto &RT = CGF.CGM.getOpenMPRuntime();
6491 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_end),
6495 // If we need device pointer privatization, we need to emit the body of the
6496 // region with no privatization in the 'else' branch of the conditional.
6497 // Otherwise, we don't have to do anything.
6498 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
6499 PrePostActionTy &) {
6500 if (!Info.CaptureDeviceAddrMap.empty()) {
6501 CodeGen.setAction(NoPrivAction);
6506 // We don't have to do anything to close the region if the if clause evaluates
6508 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
6511 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
6513 RegionCodeGenTy RCG(BeginThenGen);
6517 // If we don't require privatization of device pointers, we emit the body in
6518 // between the runtime calls. This avoids duplicating the body code.
6519 if (Info.CaptureDeviceAddrMap.empty()) {
6520 CodeGen.setAction(NoPrivAction);
6525 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
6527 RegionCodeGenTy RCG(EndThenGen);
6532 void CGOpenMPRuntime::emitTargetDataStandAloneCall(
6533 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
6534 const Expr *Device) {
6535 if (!CGF.HaveInsertPoint())
6538 assert((isa<OMPTargetEnterDataDirective>(D) ||
6539 isa<OMPTargetExitDataDirective>(D) ||
6540 isa<OMPTargetUpdateDirective>(D)) &&
6541 "Expecting either target enter, exit data, or update directives.");
6543 // Generate the code for the opening of the data environment.
6544 auto &&ThenGen = [&D, Device](CodeGenFunction &CGF, PrePostActionTy &) {
6545 // Fill up the arrays with all the mapped variables.
6546 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
6547 MappableExprsHandler::MapValuesArrayTy Pointers;
6548 MappableExprsHandler::MapValuesArrayTy Sizes;
6549 MappableExprsHandler::MapFlagsArrayTy MapTypes;
6551 // Get map clause information.
6552 MappableExprsHandler MEHandler(D, CGF);
6553 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
6555 // Fill up the arrays and create the arguments.
6556 TargetDataInfo Info;
6557 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
6558 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
6559 Info.PointersArray, Info.SizesArray,
6560 Info.MapTypesArray, Info);
6562 // Emit device ID if any.
6563 llvm::Value *DeviceID = nullptr;
6565 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
6566 CGF.Int32Ty, /*isSigned=*/true);
6568 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6570 // Emit the number of elements in the offloading arrays.
6571 auto *PointerNum = CGF.Builder.getInt32(BasePointers.size());
6573 llvm::Value *OffloadingArgs[] = {
6574 DeviceID, PointerNum, Info.BasePointersArray,
6575 Info.PointersArray, Info.SizesArray, Info.MapTypesArray};
6577 auto &RT = CGF.CGM.getOpenMPRuntime();
6578 // Select the right runtime function call for each expected standalone
6580 OpenMPRTLFunction RTLFn;
6581 switch (D.getDirectiveKind()) {
6583 llvm_unreachable("Unexpected standalone target data directive.");
6585 case OMPD_target_enter_data:
6586 RTLFn = OMPRTL__tgt_target_data_begin;
6588 case OMPD_target_exit_data:
6589 RTLFn = OMPRTL__tgt_target_data_end;
6591 case OMPD_target_update:
6592 RTLFn = OMPRTL__tgt_target_data_update;
6595 CGF.EmitRuntimeCall(RT.createRuntimeFunction(RTLFn), OffloadingArgs);
6598 // In the event we get an if clause, we don't have to take any action on the
6600 auto &&ElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
6603 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
6605 RegionCodeGenTy ThenGenRCG(ThenGen);
6611 /// Kind of parameter in a function with 'declare simd' directive.
6612 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
6613 /// Attribute set of the parameter.
6614 struct ParamAttrTy {
6615 ParamKindTy Kind = Vector;
6616 llvm::APSInt StrideOrArg;
6617 llvm::APSInt Alignment;
6621 static unsigned evaluateCDTSize(const FunctionDecl *FD,
6622 ArrayRef<ParamAttrTy> ParamAttrs) {
6623 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
6624 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
6625 // of that clause. The VLEN value must be power of 2.
6626 // In other case the notion of the function`s "characteristic data type" (CDT)
6627 // is used to compute the vector length.
6628 // CDT is defined in the following order:
6629 // a) For non-void function, the CDT is the return type.
6630 // b) If the function has any non-uniform, non-linear parameters, then the
6631 // CDT is the type of the first such parameter.
6632 // c) If the CDT determined by a) or b) above is struct, union, or class
6633 // type which is pass-by-value (except for the type that maps to the
6634 // built-in complex data type), the characteristic data type is int.
6635 // d) If none of the above three cases is applicable, the CDT is int.
6636 // The VLEN is then determined based on the CDT and the size of vector
6637 // register of that ISA for which current vector version is generated. The
6638 // VLEN is computed using the formula below:
6639 // VLEN = sizeof(vector_register) / sizeof(CDT),
6640 // where vector register size specified in section 3.2.1 Registers and the
6641 // Stack Frame of original AMD64 ABI document.
6642 QualType RetType = FD->getReturnType();
6643 if (RetType.isNull())
6645 ASTContext &C = FD->getASTContext();
6647 if (!RetType.isNull() && !RetType->isVoidType())
6650 unsigned Offset = 0;
6651 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6652 if (ParamAttrs[Offset].Kind == Vector)
6653 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
6657 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
6658 if (ParamAttrs[I + Offset].Kind == Vector) {
6659 CDT = FD->getParamDecl(I)->getType();
6667 CDT = CDT->getCanonicalTypeUnqualified();
6668 if (CDT->isRecordType() || CDT->isUnionType())
6670 return C.getTypeSize(CDT);
6674 emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
6675 const llvm::APSInt &VLENVal,
6676 ArrayRef<ParamAttrTy> ParamAttrs,
6677 OMPDeclareSimdDeclAttr::BranchStateTy State) {
6680 unsigned VecRegSize;
6682 ISADataTy ISAData[] = {
6696 llvm::SmallVector<char, 2> Masked;
6698 case OMPDeclareSimdDeclAttr::BS_Undefined:
6699 Masked.push_back('N');
6700 Masked.push_back('M');
6702 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
6703 Masked.push_back('N');
6705 case OMPDeclareSimdDeclAttr::BS_Inbranch:
6706 Masked.push_back('M');
6709 for (auto Mask : Masked) {
6710 for (auto &Data : ISAData) {
6711 SmallString<256> Buffer;
6712 llvm::raw_svector_ostream Out(Buffer);
6713 Out << "_ZGV" << Data.ISA << Mask;
6715 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
6716 evaluateCDTSize(FD, ParamAttrs));
6719 for (auto &ParamAttr : ParamAttrs) {
6720 switch (ParamAttr.Kind){
6721 case LinearWithVarStride:
6722 Out << 's' << ParamAttr.StrideOrArg;
6726 if (!!ParamAttr.StrideOrArg)
6727 Out << ParamAttr.StrideOrArg;
6736 if (!!ParamAttr.Alignment)
6737 Out << 'a' << ParamAttr.Alignment;
6739 Out << '_' << Fn->getName();
6740 Fn->addFnAttr(Out.str());
6745 void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
6746 llvm::Function *Fn) {
6747 ASTContext &C = CGM.getContext();
6748 FD = FD->getCanonicalDecl();
6749 // Map params to their positions in function decl.
6750 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
6751 if (isa<CXXMethodDecl>(FD))
6752 ParamPositions.insert({FD, 0});
6753 unsigned ParamPos = ParamPositions.size();
6754 for (auto *P : FD->parameters()) {
6755 ParamPositions.insert({P->getCanonicalDecl(), ParamPos});
6758 for (auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
6759 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
6760 // Mark uniform parameters.
6761 for (auto *E : Attr->uniforms()) {
6762 E = E->IgnoreParenImpCasts();
6764 if (isa<CXXThisExpr>(E))
6765 Pos = ParamPositions[FD];
6767 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
6768 ->getCanonicalDecl();
6769 Pos = ParamPositions[PVD];
6771 ParamAttrs[Pos].Kind = Uniform;
6773 // Get alignment info.
6774 auto NI = Attr->alignments_begin();
6775 for (auto *E : Attr->aligneds()) {
6776 E = E->IgnoreParenImpCasts();
6779 if (isa<CXXThisExpr>(E)) {
6780 Pos = ParamPositions[FD];
6781 ParmTy = E->getType();
6783 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
6784 ->getCanonicalDecl();
6785 Pos = ParamPositions[PVD];
6786 ParmTy = PVD->getType();
6788 ParamAttrs[Pos].Alignment =
6789 (*NI) ? (*NI)->EvaluateKnownConstInt(C)
6790 : llvm::APSInt::getUnsigned(
6791 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
6795 // Mark linear parameters.
6796 auto SI = Attr->steps_begin();
6797 auto MI = Attr->modifiers_begin();
6798 for (auto *E : Attr->linears()) {
6799 E = E->IgnoreParenImpCasts();
6801 if (isa<CXXThisExpr>(E))
6802 Pos = ParamPositions[FD];
6804 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
6805 ->getCanonicalDecl();
6806 Pos = ParamPositions[PVD];
6808 auto &ParamAttr = ParamAttrs[Pos];
6809 ParamAttr.Kind = Linear;
6811 if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
6812 Expr::SE_AllowSideEffects)) {
6813 if (auto *DRE = cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
6814 if (auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
6815 ParamAttr.Kind = LinearWithVarStride;
6816 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
6817 ParamPositions[StridePVD->getCanonicalDecl()]);
6825 llvm::APSInt VLENVal;
6826 if (const Expr *VLEN = Attr->getSimdlen())
6827 VLENVal = VLEN->EvaluateKnownConstInt(C);
6828 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
6829 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
6830 CGM.getTriple().getArch() == llvm::Triple::x86_64)
6831 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
6836 /// Cleanup action for doacross support.
6837 class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
6839 static const int DoacrossFinArgs = 2;
6843 llvm::Value *Args[DoacrossFinArgs];
6846 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
6848 assert(CallArgs.size() == DoacrossFinArgs);
6849 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
6851 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
6852 if (!CGF.HaveInsertPoint())
6854 CGF.EmitRuntimeCall(RTLFn, Args);
6859 void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
6860 const OMPLoopDirective &D) {
6861 if (!CGF.HaveInsertPoint())
6864 ASTContext &C = CGM.getContext();
6865 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
6867 if (KmpDimTy.isNull()) {
6868 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
6869 // kmp_int64 lo; // lower
6870 // kmp_int64 up; // upper
6871 // kmp_int64 st; // stride
6873 RD = C.buildImplicitRecord("kmp_dim");
6874 RD->startDefinition();
6875 addFieldToRecordDecl(C, RD, Int64Ty);
6876 addFieldToRecordDecl(C, RD, Int64Ty);
6877 addFieldToRecordDecl(C, RD, Int64Ty);
6878 RD->completeDefinition();
6879 KmpDimTy = C.getRecordType(RD);
6881 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
6883 Address DimsAddr = CGF.CreateMemTemp(KmpDimTy, "dims");
6884 CGF.EmitNullInitialization(DimsAddr, KmpDimTy);
6885 enum { LowerFD = 0, UpperFD, StrideFD };
6886 // Fill dims with data.
6887 LValue DimsLVal = CGF.MakeAddrLValue(DimsAddr, KmpDimTy);
6888 // dims.upper = num_iterations;
6890 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), UpperFD));
6891 llvm::Value *NumIterVal = CGF.EmitScalarConversion(
6892 CGF.EmitScalarExpr(D.getNumIterations()), D.getNumIterations()->getType(),
6893 Int64Ty, D.getNumIterations()->getExprLoc());
6894 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
6897 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), StrideFD));
6898 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
6901 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
6902 // kmp_int32 num_dims, struct kmp_dim * dims);
6903 llvm::Value *Args[] = {emitUpdateLocation(CGF, D.getLocStart()),
6904 getThreadID(CGF, D.getLocStart()),
6905 llvm::ConstantInt::getSigned(CGM.Int32Ty, 1),
6906 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6907 DimsAddr.getPointer(), CGM.VoidPtrTy)};
6909 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
6910 CGF.EmitRuntimeCall(RTLFn, Args);
6911 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
6912 emitUpdateLocation(CGF, D.getLocEnd()), getThreadID(CGF, D.getLocEnd())};
6913 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
6914 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
6915 llvm::makeArrayRef(FiniArgs));
6918 void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
6919 const OMPDependClause *C) {
6921 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
6922 const Expr *CounterVal = C->getCounterValue();
6924 llvm::Value *CntVal = CGF.EmitScalarConversion(CGF.EmitScalarExpr(CounterVal),
6925 CounterVal->getType(), Int64Ty,
6926 CounterVal->getExprLoc());
6927 Address CntAddr = CGF.CreateMemTemp(Int64Ty, ".cnt.addr");
6928 CGF.EmitStoreOfScalar(CntVal, CntAddr, /*Volatile=*/false, Int64Ty);
6929 llvm::Value *Args[] = {emitUpdateLocation(CGF, C->getLocStart()),
6930 getThreadID(CGF, C->getLocStart()),
6931 CntAddr.getPointer()};
6933 if (C->getDependencyKind() == OMPC_DEPEND_source)
6934 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
6936 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
6937 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
6939 CGF.EmitRuntimeCall(RTLFn, Args);