1 //===----- CGOpenMPRuntime.h - Interface to OpenMP Runtimes -----*- C++ -*-===//
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 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_LIB_CODEGEN_CGOPENMPRUNTIME_H
15 #define LLVM_CLANG_LIB_CODEGEN_CGOPENMPRUNTIME_H
18 #include "clang/AST/Type.h"
19 #include "clang/Basic/OpenMPKinds.h"
20 #include "clang/Basic/SourceLocation.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/StringMap.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/ValueHandle.h"
40 class OMPExecutableDirective;
41 class OMPLoopDirective;
43 class OMPDeclareReductionDecl;
48 class CodeGenFunction;
51 /// A basic class for pre|post-action for advanced codegen sequence for OpenMP
53 class PrePostActionTy {
55 explicit PrePostActionTy() {}
56 virtual void Enter(CodeGenFunction &CGF) {}
57 virtual void Exit(CodeGenFunction &CGF) {}
58 virtual ~PrePostActionTy() {}
61 /// Class provides a way to call simple version of codegen for OpenMP region, or
62 /// an advanced with possible pre|post-actions in codegen.
63 class RegionCodeGenTy final {
65 typedef void (*CodeGenTy)(intptr_t, CodeGenFunction &, PrePostActionTy &);
67 mutable PrePostActionTy *PrePostAction;
68 RegionCodeGenTy() = delete;
69 RegionCodeGenTy &operator=(const RegionCodeGenTy &) = delete;
70 template <typename Callable>
71 static void CallbackFn(intptr_t CodeGen, CodeGenFunction &CGF,
72 PrePostActionTy &Action) {
73 return (*reinterpret_cast<Callable *>(CodeGen))(CGF, Action);
77 template <typename Callable>
80 typename std::enable_if<
81 !std::is_same<typename std::remove_reference<Callable>::type,
82 RegionCodeGenTy>::value>::type * = nullptr)
83 : CodeGen(reinterpret_cast<intptr_t>(&CodeGen)),
84 Callback(CallbackFn<typename std::remove_reference<Callable>::type>),
85 PrePostAction(nullptr) {}
86 void setAction(PrePostActionTy &Action) const { PrePostAction = &Action; }
87 void operator()(CodeGenFunction &CGF) const;
90 class CGOpenMPRuntime {
94 /// \brief Creates offloading entry for the provided entry ID \a ID,
95 /// address \a Addr and size \a Size.
96 virtual void createOffloadEntry(llvm::Constant *ID, llvm::Constant *Addr,
99 /// \brief Helper to emit outlined function for 'target' directive.
100 /// \param D Directive to emit.
101 /// \param ParentName Name of the function that encloses the target region.
102 /// \param OutlinedFn Outlined function value to be defined by this call.
103 /// \param OutlinedFnID Outlined function ID value to be defined by this call.
104 /// \param IsOffloadEntry True if the outlined function is an offload entry.
105 /// \param CodeGen Lambda codegen specific to an accelerator device.
106 /// An oulined function may not be an entry if, e.g. the if clause always
107 /// evaluates to false.
108 virtual void emitTargetOutlinedFunctionHelper(const OMPExecutableDirective &D,
109 StringRef ParentName,
110 llvm::Function *&OutlinedFn,
111 llvm::Constant *&OutlinedFnID,
113 const RegionCodeGenTy &CodeGen);
116 /// \brief Default const ident_t object used for initialization of all other
118 llvm::Constant *DefaultOpenMPPSource = nullptr;
119 /// \brief Map of flags and corresponding default locations.
120 typedef llvm::DenseMap<unsigned, llvm::Value *> OpenMPDefaultLocMapTy;
121 OpenMPDefaultLocMapTy OpenMPDefaultLocMap;
122 Address getOrCreateDefaultLocation(unsigned Flags);
124 llvm::StructType *IdentTy = nullptr;
125 /// \brief Map for SourceLocation and OpenMP runtime library debug locations.
126 typedef llvm::DenseMap<unsigned, llvm::Value *> OpenMPDebugLocMapTy;
127 OpenMPDebugLocMapTy OpenMPDebugLocMap;
128 /// \brief The type for a microtask which gets passed to __kmpc_fork_call().
129 /// Original representation is:
130 /// typedef void (kmpc_micro)(kmp_int32 global_tid, kmp_int32 bound_tid,...);
131 llvm::FunctionType *Kmpc_MicroTy = nullptr;
132 /// \brief Stores debug location and ThreadID for the function.
133 struct DebugLocThreadIdTy {
134 llvm::Value *DebugLoc;
135 llvm::Value *ThreadID;
137 /// \brief Map of local debug location, ThreadId and functions.
138 typedef llvm::DenseMap<llvm::Function *, DebugLocThreadIdTy>
139 OpenMPLocThreadIDMapTy;
140 OpenMPLocThreadIDMapTy OpenMPLocThreadIDMap;
141 /// Map of UDRs and corresponding combiner/initializer.
142 typedef llvm::DenseMap<const OMPDeclareReductionDecl *,
143 std::pair<llvm::Function *, llvm::Function *>>
146 /// Map of functions and locally defined UDRs.
147 typedef llvm::DenseMap<llvm::Function *,
148 SmallVector<const OMPDeclareReductionDecl *, 4>>
150 FunctionUDRMapTy FunctionUDRMap;
151 IdentifierInfo *In = nullptr;
152 IdentifierInfo *Out = nullptr;
153 IdentifierInfo *Priv = nullptr;
154 IdentifierInfo *Orig = nullptr;
155 /// \brief Type kmp_critical_name, originally defined as typedef kmp_int32
156 /// kmp_critical_name[8];
157 llvm::ArrayType *KmpCriticalNameTy;
158 /// \brief An ordered map of auto-generated variables to their unique names.
159 /// It stores variables with the following names: 1) ".gomp_critical_user_" +
160 /// <critical_section_name> + ".var" for "omp critical" directives; 2)
161 /// <mangled_name_for_global_var> + ".cache." for cache for threadprivate
163 llvm::StringMap<llvm::AssertingVH<llvm::Constant>, llvm::BumpPtrAllocator>
165 /// \brief Type typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *);
166 llvm::Type *KmpRoutineEntryPtrTy = nullptr;
167 QualType KmpRoutineEntryPtrQTy;
168 /// \brief Type typedef struct kmp_task {
169 /// void * shareds; /**< pointer to block of pointers to
171 /// kmp_routine_entry_t routine; /**< pointer to routine to call for
172 /// executing task */
173 /// kmp_int32 part_id; /**< part id for the task */
174 /// kmp_routine_entry_t destructors; /* pointer to function to invoke
175 /// deconstructors of firstprivate C++ objects */
177 QualType KmpTaskTQTy;
178 /// \brief Type typedef struct kmp_depend_info {
179 /// kmp_intptr_t base_addr;
185 /// } kmp_depend_info_t;
186 QualType KmpDependInfoTy;
187 /// \brief Type struct __tgt_offload_entry{
188 /// void *addr; // Pointer to the offload entry info.
189 /// // (function or global)
190 /// char *name; // Name of the function or global.
191 /// size_t size; // Size of the entry info (0 if it a function).
193 QualType TgtOffloadEntryQTy;
194 /// struct __tgt_device_image{
195 /// void *ImageStart; // Pointer to the target code start.
196 /// void *ImageEnd; // Pointer to the target code end.
197 /// // We also add the host entries to the device image, as it may be useful
198 /// // for the target runtime to have access to that information.
199 /// __tgt_offload_entry *EntriesBegin; // Begin of the table with all
201 /// __tgt_offload_entry *EntriesEnd; // End of the table with all the
202 /// // entries (non inclusive).
204 QualType TgtDeviceImageQTy;
205 /// struct __tgt_bin_desc{
206 /// int32_t NumDevices; // Number of devices supported.
207 /// __tgt_device_image *DeviceImages; // Arrays of device images
208 /// // (one per device).
209 /// __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
211 /// __tgt_offload_entry *EntriesEnd; // End of the table with all the
212 /// // entries (non inclusive).
214 QualType TgtBinaryDescriptorQTy;
215 /// \brief Entity that registers the offloading constants that were emitted so
217 class OffloadEntriesInfoManagerTy {
220 /// \brief Number of entries registered so far.
221 unsigned OffloadingEntriesNum;
224 /// \brief Base class of the entries info.
225 class OffloadEntryInfo {
227 /// \brief Kind of a given entry. Currently, only target regions are
229 enum OffloadingEntryInfoKinds : unsigned {
230 // Entry is a target region.
231 OFFLOAD_ENTRY_INFO_TARGET_REGION = 0,
232 // Invalid entry info.
233 OFFLOAD_ENTRY_INFO_INVALID = ~0u
236 OffloadEntryInfo() : Order(~0u), Kind(OFFLOAD_ENTRY_INFO_INVALID) {}
237 explicit OffloadEntryInfo(OffloadingEntryInfoKinds Kind, unsigned Order)
238 : Order(Order), Kind(Kind) {}
240 bool isValid() const { return Order != ~0u; }
241 unsigned getOrder() const { return Order; }
242 OffloadingEntryInfoKinds getKind() const { return Kind; }
243 static bool classof(const OffloadEntryInfo *Info) { return true; }
246 // \brief Order this entry was emitted.
249 OffloadingEntryInfoKinds Kind;
252 /// \brief Return true if a there are no entries defined.
254 /// \brief Return number of entries defined so far.
255 unsigned size() const { return OffloadingEntriesNum; }
256 OffloadEntriesInfoManagerTy(CodeGenModule &CGM)
257 : CGM(CGM), OffloadingEntriesNum(0) {}
260 /// Target region entries related.
262 /// \brief Target region entries info.
263 class OffloadEntryInfoTargetRegion : public OffloadEntryInfo {
264 // \brief Address of the entity that has to be mapped for offloading.
265 llvm::Constant *Addr;
266 // \brief Address that can be used as the ID of the entry.
270 OffloadEntryInfoTargetRegion()
271 : OffloadEntryInfo(OFFLOAD_ENTRY_INFO_TARGET_REGION, ~0u),
272 Addr(nullptr), ID(nullptr) {}
273 explicit OffloadEntryInfoTargetRegion(unsigned Order,
274 llvm::Constant *Addr,
276 : OffloadEntryInfo(OFFLOAD_ENTRY_INFO_TARGET_REGION, Order),
277 Addr(Addr), ID(ID) {}
279 llvm::Constant *getAddress() const { return Addr; }
280 llvm::Constant *getID() const { return ID; }
281 void setAddress(llvm::Constant *V) {
282 assert(!Addr && "Address as been set before!");
285 void setID(llvm::Constant *V) {
286 assert(!ID && "ID as been set before!");
289 static bool classof(const OffloadEntryInfo *Info) {
290 return Info->getKind() == OFFLOAD_ENTRY_INFO_TARGET_REGION;
293 /// \brief Initialize target region entry.
294 void initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
295 StringRef ParentName, unsigned LineNum,
297 /// \brief Register target region entry.
298 void registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
299 StringRef ParentName, unsigned LineNum,
300 llvm::Constant *Addr,
302 /// \brief Return true if a target region entry with the provided
303 /// information exists.
304 bool hasTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
305 StringRef ParentName, unsigned LineNum) const;
306 /// brief Applies action \a Action on all registered entries.
307 typedef llvm::function_ref<void(unsigned, unsigned, StringRef, unsigned,
308 OffloadEntryInfoTargetRegion &)>
309 OffloadTargetRegionEntryInfoActTy;
310 void actOnTargetRegionEntriesInfo(
311 const OffloadTargetRegionEntryInfoActTy &Action);
314 // Storage for target region entries kind. The storage is to be indexed by
315 // file ID, device ID, parent function name and line number.
316 typedef llvm::DenseMap<unsigned, OffloadEntryInfoTargetRegion>
317 OffloadEntriesTargetRegionPerLine;
318 typedef llvm::StringMap<OffloadEntriesTargetRegionPerLine>
319 OffloadEntriesTargetRegionPerParentName;
320 typedef llvm::DenseMap<unsigned, OffloadEntriesTargetRegionPerParentName>
321 OffloadEntriesTargetRegionPerFile;
322 typedef llvm::DenseMap<unsigned, OffloadEntriesTargetRegionPerFile>
323 OffloadEntriesTargetRegionPerDevice;
324 typedef OffloadEntriesTargetRegionPerDevice OffloadEntriesTargetRegionTy;
325 OffloadEntriesTargetRegionTy OffloadEntriesTargetRegion;
327 OffloadEntriesInfoManagerTy OffloadEntriesInfoManager;
329 /// \brief Creates and registers offloading binary descriptor for the current
330 /// compilation unit. The function that does the registration is returned.
331 llvm::Function *createOffloadingBinaryDescriptorRegistration();
333 /// \brief Creates all the offload entries in the current compilation unit
334 /// along with the associated metadata.
335 void createOffloadEntriesAndInfoMetadata();
337 /// \brief Loads all the offload entries information from the host IR
339 void loadOffloadInfoMetadata();
341 /// \brief Returns __tgt_offload_entry type.
342 QualType getTgtOffloadEntryQTy();
344 /// \brief Returns __tgt_device_image type.
345 QualType getTgtDeviceImageQTy();
347 /// \brief Returns __tgt_bin_desc type.
348 QualType getTgtBinaryDescriptorQTy();
350 /// \brief Start scanning from statement \a S and and emit all target regions
351 /// found along the way.
352 /// \param S Starting statement.
353 /// \param ParentName Name of the function declaration that is being scanned.
354 void scanForTargetRegionsFunctions(const Stmt *S, StringRef ParentName);
356 /// \brief Build type kmp_routine_entry_t (if not built yet).
357 void emitKmpRoutineEntryT(QualType KmpInt32Ty);
359 /// \brief Emits object of ident_t type with info for source location.
360 /// \param Flags Flags for OpenMP location.
362 llvm::Value *emitUpdateLocation(CodeGenFunction &CGF, SourceLocation Loc,
365 /// \brief Returns pointer to ident_t type.
366 llvm::Type *getIdentTyPointerTy();
368 /// \brief Returns pointer to kmpc_micro type.
369 llvm::Type *getKmpc_MicroPointerTy();
371 /// \brief Returns specified OpenMP runtime function.
372 /// \param Function OpenMP runtime function.
373 /// \return Specified function.
374 llvm::Constant *createRuntimeFunction(unsigned Function);
376 /// \brief Returns __kmpc_for_static_init_* runtime function for the specified
377 /// size \a IVSize and sign \a IVSigned.
378 llvm::Constant *createForStaticInitFunction(unsigned IVSize, bool IVSigned);
380 /// \brief Returns __kmpc_dispatch_init_* runtime function for the specified
381 /// size \a IVSize and sign \a IVSigned.
382 llvm::Constant *createDispatchInitFunction(unsigned IVSize, bool IVSigned);
384 /// \brief Returns __kmpc_dispatch_next_* runtime function for the specified
385 /// size \a IVSize and sign \a IVSigned.
386 llvm::Constant *createDispatchNextFunction(unsigned IVSize, bool IVSigned);
388 /// \brief Returns __kmpc_dispatch_fini_* runtime function for the specified
389 /// size \a IVSize and sign \a IVSigned.
390 llvm::Constant *createDispatchFiniFunction(unsigned IVSize, bool IVSigned);
392 /// \brief If the specified mangled name is not in the module, create and
393 /// return threadprivate cache object. This object is a pointer's worth of
394 /// storage that's reserved for use by the OpenMP runtime.
395 /// \param VD Threadprivate variable.
396 /// \return Cache variable for the specified threadprivate.
397 llvm::Constant *getOrCreateThreadPrivateCache(const VarDecl *VD);
399 /// \brief Emits address of the word in a memory where current thread id is
401 virtual Address emitThreadIDAddress(CodeGenFunction &CGF, SourceLocation Loc);
403 /// \brief Gets thread id value for the current thread.
405 llvm::Value *getThreadID(CodeGenFunction &CGF, SourceLocation Loc);
407 /// \brief Gets (if variable with the given name already exist) or creates
408 /// internal global variable with the specified Name. The created variable has
409 /// linkage CommonLinkage by default and is initialized by null value.
410 /// \param Ty Type of the global variable. If it is exist already the type
411 /// must be the same.
412 /// \param Name Name of the variable.
413 llvm::Constant *getOrCreateInternalVariable(llvm::Type *Ty,
414 const llvm::Twine &Name);
416 /// \brief Set of threadprivate variables with the generated initializer.
417 llvm::SmallPtrSet<const VarDecl *, 4> ThreadPrivateWithDefinition;
419 /// \brief Emits initialization code for the threadprivate variables.
420 /// \param VDAddr Address of the global variable \a VD.
421 /// \param Ctor Pointer to a global init function for \a VD.
422 /// \param CopyCtor Pointer to a global copy function for \a VD.
423 /// \param Dtor Pointer to a global destructor function for \a VD.
424 /// \param Loc Location of threadprivate declaration.
425 void emitThreadPrivateVarInit(CodeGenFunction &CGF, Address VDAddr,
426 llvm::Value *Ctor, llvm::Value *CopyCtor,
427 llvm::Value *Dtor, SourceLocation Loc);
429 /// \brief Returns corresponding lock object for the specified critical region
430 /// name. If the lock object does not exist it is created, otherwise the
431 /// reference to the existing copy is returned.
432 /// \param CriticalName Name of the critical region.
434 llvm::Value *getCriticalRegionLock(StringRef CriticalName);
437 llvm::Value *NewTask;
438 llvm::Value *TaskEntry;
439 llvm::Value *NewTaskNewTaskTTy;
441 RecordDecl *KmpTaskTQTyRD;
443 /// Emit task region for the task directive. The task region is emitted in
445 /// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32
446 /// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
447 /// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the
449 /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
450 /// TaskFunction(gtid, tt->part_id, tt->shareds);
453 /// 2. Copy a list of shared variables to field shareds of the resulting
454 /// structure kmp_task_t returned by the previous call (if any).
455 /// 3. Copy a pointer to destructions function to field destructions of the
456 /// resulting structure kmp_task_t.
457 /// \param D Current task directive.
458 /// \param Tied true if the task is tied (the task is tied to the thread that
459 /// can suspend its task region), false - untied (the task is not tied to any
461 /// \param Final Contains either constant bool value, or llvm::Value * of i1
462 /// type for final clause. If the value is true, the task forces all of its
463 /// child tasks to become final and included tasks.
464 /// \param NumberOfParts Number of parts in untied tasks.
465 /// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32
466 /// /*part_id*/, captured_struct */*__context*/);
467 /// \param SharedsTy A type which contains references the shared variables.
468 /// \param Shareds Context with the list of shared variables from the \p
470 /// \param PrivateVars List of references to private variables for the task
472 /// \param PrivateCopies List of private copies for each private variable in
474 /// \param FirstprivateVars List of references to private variables for the
476 /// \param FirstprivateCopies List of private copies for each private variable
477 /// in \p FirstprivateVars.
478 /// \param FirstprivateInits List of references to auto generated variables
479 /// used for initialization of a single array element. Used if firstprivate
480 /// variable is of array type.
481 TaskDataTy emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
482 const OMPExecutableDirective &D, bool Tied,
483 llvm::PointerIntPair<llvm::Value *, 1, bool> Final,
484 unsigned NumberOfParts, llvm::Value *TaskFunction,
485 QualType SharedsTy, Address Shareds,
486 ArrayRef<const Expr *> PrivateVars,
487 ArrayRef<const Expr *> PrivateCopies,
488 ArrayRef<const Expr *> FirstprivateVars,
489 ArrayRef<const Expr *> FirstprivateCopies,
490 ArrayRef<const Expr *> FirstprivateInits);
493 explicit CGOpenMPRuntime(CodeGenModule &CGM);
494 virtual ~CGOpenMPRuntime() {}
495 virtual void clear();
497 /// Emit code for the specified user defined reduction construct.
498 virtual void emitUserDefinedReduction(CodeGenFunction *CGF,
499 const OMPDeclareReductionDecl *D);
500 /// Get combiner/initializer for the specified user-defined reduction, if any.
501 virtual std::pair<llvm::Function *, llvm::Function *>
502 getUserDefinedReduction(const OMPDeclareReductionDecl *D);
503 /// \brief Emits outlined function for the specified OpenMP parallel directive
504 /// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID,
505 /// kmp_int32 BoundID, struct context_vars*).
506 /// \param D OpenMP directive.
507 /// \param ThreadIDVar Variable for thread id in the current OpenMP region.
508 /// \param InnermostKind Kind of innermost directive (for simple directives it
509 /// is a directive itself, for combined - its innermost directive).
510 /// \param CodeGen Code generation sequence for the \a D directive.
511 virtual llvm::Value *emitParallelOrTeamsOutlinedFunction(
512 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
513 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen);
515 /// \brief Emits outlined function for the OpenMP task directive \a D. This
516 /// outlined function has type void(*)(kmp_int32 ThreadID, struct task_t*
518 /// \param D OpenMP directive.
519 /// \param ThreadIDVar Variable for thread id in the current OpenMP region.
520 /// \param PartIDVar Variable for partition id in the current OpenMP untied
522 /// \param TaskTVar Variable for task_t argument.
523 /// \param InnermostKind Kind of innermost directive (for simple directives it
524 /// is a directive itself, for combined - its innermost directive).
525 /// \param CodeGen Code generation sequence for the \a D directive.
526 /// \param Tied true if task is generated for tied task, false otherwise.
527 /// \param NumberOfParts Number of parts in untied task. Ignored for tied
530 virtual llvm::Value *emitTaskOutlinedFunction(
531 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
532 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
533 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
534 bool Tied, unsigned &NumberOfParts);
536 /// \brief Cleans up references to the objects in finished function.
538 void functionFinished(CodeGenFunction &CGF);
540 /// \brief Emits code for parallel or serial call of the \a OutlinedFn with
541 /// variables captured in a record which address is stored in \a
543 /// \param OutlinedFn Outlined function to be run in parallel threads. Type of
544 /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*).
545 /// \param CapturedVars A pointer to the record with the references to
546 /// variables used in \a OutlinedFn function.
547 /// \param IfCond Condition in the associated 'if' clause, if it was
548 /// specified, nullptr otherwise.
550 virtual void emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
551 llvm::Value *OutlinedFn,
552 ArrayRef<llvm::Value *> CapturedVars,
555 /// \brief Emits a critical region.
556 /// \param CriticalName Name of the critical region.
557 /// \param CriticalOpGen Generator for the statement associated with the given
559 /// \param Hint Value of the 'hint' clause (optional).
560 virtual void emitCriticalRegion(CodeGenFunction &CGF, StringRef CriticalName,
561 const RegionCodeGenTy &CriticalOpGen,
563 const Expr *Hint = nullptr);
565 /// \brief Emits a master region.
566 /// \param MasterOpGen Generator for the statement associated with the given
568 virtual void emitMasterRegion(CodeGenFunction &CGF,
569 const RegionCodeGenTy &MasterOpGen,
572 /// \brief Emits code for a taskyield directive.
573 virtual void emitTaskyieldCall(CodeGenFunction &CGF, SourceLocation Loc);
575 /// \brief Emit a taskgroup region.
576 /// \param TaskgroupOpGen Generator for the statement associated with the
577 /// given taskgroup region.
578 virtual void emitTaskgroupRegion(CodeGenFunction &CGF,
579 const RegionCodeGenTy &TaskgroupOpGen,
582 /// \brief Emits a single region.
583 /// \param SingleOpGen Generator for the statement associated with the given
585 virtual void emitSingleRegion(CodeGenFunction &CGF,
586 const RegionCodeGenTy &SingleOpGen,
588 ArrayRef<const Expr *> CopyprivateVars,
589 ArrayRef<const Expr *> DestExprs,
590 ArrayRef<const Expr *> SrcExprs,
591 ArrayRef<const Expr *> AssignmentOps);
593 /// \brief Emit an ordered region.
594 /// \param OrderedOpGen Generator for the statement associated with the given
596 virtual void emitOrderedRegion(CodeGenFunction &CGF,
597 const RegionCodeGenTy &OrderedOpGen,
598 SourceLocation Loc, bool IsThreads);
600 /// \brief Emit an implicit/explicit barrier for OpenMP threads.
601 /// \param Kind Directive for which this implicit barrier call must be
602 /// generated. Must be OMPD_barrier for explicit barrier generation.
603 /// \param EmitChecks true if need to emit checks for cancellation barriers.
604 /// \param ForceSimpleCall true simple barrier call must be emitted, false if
605 /// runtime class decides which one to emit (simple or with cancellation
608 virtual void emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
609 OpenMPDirectiveKind Kind,
610 bool EmitChecks = true,
611 bool ForceSimpleCall = false);
613 /// \brief Check if the specified \a ScheduleKind is static non-chunked.
614 /// This kind of worksharing directive is emitted without outer loop.
615 /// \param ScheduleKind Schedule kind specified in the 'schedule' clause.
616 /// \param Chunked True if chunk is specified in the clause.
618 virtual bool isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
621 /// \brief Check if the specified \a ScheduleKind is static non-chunked.
622 /// This kind of distribute directive is emitted without outer loop.
623 /// \param ScheduleKind Schedule kind specified in the 'dist_schedule' clause.
624 /// \param Chunked True if chunk is specified in the clause.
626 virtual bool isStaticNonchunked(OpenMPDistScheduleClauseKind ScheduleKind,
629 /// \brief Check if the specified \a ScheduleKind is dynamic.
630 /// This kind of worksharing directive is emitted without outer loop.
631 /// \param ScheduleKind Schedule Kind specified in the 'schedule' clause.
633 virtual bool isDynamic(OpenMPScheduleClauseKind ScheduleKind) const;
635 virtual void emitForDispatchInit(CodeGenFunction &CGF, SourceLocation Loc,
636 OpenMPScheduleClauseKind SchedKind,
637 unsigned IVSize, bool IVSigned,
638 bool Ordered, llvm::Value *UB,
639 llvm::Value *Chunk = nullptr);
641 /// \brief Call the appropriate runtime routine to initialize it before start
644 /// Depending on the loop schedule, it is nesessary to call some runtime
645 /// routine before start of the OpenMP loop to get the loop upper / lower
646 /// bounds \a LB and \a UB and stride \a ST.
648 /// \param CGF Reference to current CodeGenFunction.
649 /// \param Loc Clang source location.
650 /// \param SchedKind Schedule kind, specified by the 'schedule' clause.
651 /// \param IVSize Size of the iteration variable in bits.
652 /// \param IVSigned Sign of the interation variable.
653 /// \param Ordered true if loop is ordered, false otherwise.
654 /// \param IL Address of the output variable in which the flag of the
655 /// last iteration is returned.
656 /// \param LB Address of the output variable in which the lower iteration
657 /// number is returned.
658 /// \param UB Address of the output variable in which the upper iteration
659 /// number is returned.
660 /// \param ST Address of the output variable in which the stride value is
661 /// returned nesessary to generated the static_chunked scheduled loop.
662 /// \param Chunk Value of the chunk for the static_chunked scheduled loop.
663 /// For the default (nullptr) value, the chunk 1 will be used.
665 virtual void emitForStaticInit(CodeGenFunction &CGF, SourceLocation Loc,
666 OpenMPScheduleClauseKind SchedKind,
667 unsigned IVSize, bool IVSigned, bool Ordered,
668 Address IL, Address LB,
669 Address UB, Address ST,
670 llvm::Value *Chunk = nullptr);
673 /// \param CGF Reference to current CodeGenFunction.
674 /// \param Loc Clang source location.
675 /// \param SchedKind Schedule kind, specified by the 'dist_schedule' clause.
676 /// \param IVSize Size of the iteration variable in bits.
677 /// \param IVSigned Sign of the interation variable.
678 /// \param Ordered true if loop is ordered, false otherwise.
679 /// \param IL Address of the output variable in which the flag of the
680 /// last iteration is returned.
681 /// \param LB Address of the output variable in which the lower iteration
682 /// number is returned.
683 /// \param UB Address of the output variable in which the upper iteration
684 /// number is returned.
685 /// \param ST Address of the output variable in which the stride value is
686 /// returned nesessary to generated the static_chunked scheduled loop.
687 /// \param Chunk Value of the chunk for the static_chunked scheduled loop.
688 /// For the default (nullptr) value, the chunk 1 will be used.
690 virtual void emitDistributeStaticInit(CodeGenFunction &CGF, SourceLocation Loc,
691 OpenMPDistScheduleClauseKind SchedKind,
692 unsigned IVSize, bool IVSigned,
693 bool Ordered, Address IL, Address LB,
694 Address UB, Address ST,
695 llvm::Value *Chunk = nullptr);
697 /// \brief Call the appropriate runtime routine to notify that we finished
698 /// iteration of the ordered loop with the dynamic scheduling.
700 /// \param CGF Reference to current CodeGenFunction.
701 /// \param Loc Clang source location.
702 /// \param IVSize Size of the iteration variable in bits.
703 /// \param IVSigned Sign of the interation variable.
705 virtual void emitForOrderedIterationEnd(CodeGenFunction &CGF,
706 SourceLocation Loc, unsigned IVSize,
709 /// \brief Call the appropriate runtime routine to notify that we finished
710 /// all the work with current loop.
712 /// \param CGF Reference to current CodeGenFunction.
713 /// \param Loc Clang source location.
715 virtual void emitForStaticFinish(CodeGenFunction &CGF, SourceLocation Loc);
717 /// Call __kmpc_dispatch_next(
718 /// ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
719 /// kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
720 /// kmp_int[32|64] *p_stride);
721 /// \param IVSize Size of the iteration variable in bits.
722 /// \param IVSigned Sign of the interation variable.
723 /// \param IL Address of the output variable in which the flag of the
724 /// last iteration is returned.
725 /// \param LB Address of the output variable in which the lower iteration
726 /// number is returned.
727 /// \param UB Address of the output variable in which the upper iteration
728 /// number is returned.
729 /// \param ST Address of the output variable in which the stride value is
731 virtual llvm::Value *emitForNext(CodeGenFunction &CGF, SourceLocation Loc,
732 unsigned IVSize, bool IVSigned,
733 Address IL, Address LB,
734 Address UB, Address ST);
736 /// \brief Emits call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32
737 /// global_tid, kmp_int32 num_threads) to generate code for 'num_threads'
739 /// \param NumThreads An integer value of threads.
740 virtual void emitNumThreadsClause(CodeGenFunction &CGF,
741 llvm::Value *NumThreads,
744 /// \brief Emit call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32
745 /// global_tid, int proc_bind) to generate code for 'proc_bind' clause.
746 virtual void emitProcBindClause(CodeGenFunction &CGF,
747 OpenMPProcBindClauseKind ProcBind,
750 /// \brief Returns address of the threadprivate variable for the current
752 /// \param VD Threadprivate variable.
753 /// \param VDAddr Address of the global variable \a VD.
754 /// \param Loc Location of the reference to threadprivate var.
755 /// \return Address of the threadprivate variable for the current thread.
756 virtual Address getAddrOfThreadPrivate(CodeGenFunction &CGF,
761 /// \brief Emit a code for initialization of threadprivate variable. It emits
762 /// a call to runtime library which adds initial value to the newly created
763 /// threadprivate variable (if it is not constant) and registers destructor
764 /// for the variable (if any).
765 /// \param VD Threadprivate variable.
766 /// \param VDAddr Address of the global variable \a VD.
767 /// \param Loc Location of threadprivate declaration.
768 /// \param PerformInit true if initialization expression is not constant.
769 virtual llvm::Function *
770 emitThreadPrivateVarDefinition(const VarDecl *VD, Address VDAddr,
771 SourceLocation Loc, bool PerformInit,
772 CodeGenFunction *CGF = nullptr);
774 /// \brief Emit flush of the variables specified in 'omp flush' directive.
775 /// \param Vars List of variables to flush.
776 virtual void emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *> Vars,
779 /// \brief Emit task region for the task directive. The task region is
780 /// emitted in several steps:
781 /// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32
782 /// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
783 /// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the
785 /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
786 /// TaskFunction(gtid, tt->part_id, tt->shareds);
789 /// 2. Copy a list of shared variables to field shareds of the resulting
790 /// structure kmp_task_t returned by the previous call (if any).
791 /// 3. Copy a pointer to destructions function to field destructions of the
792 /// resulting structure kmp_task_t.
793 /// 4. Emit a call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid,
794 /// kmp_task_t *new_task), where new_task is a resulting structure from
796 /// \param D Current task directive.
797 /// \param Tied true if the task is tied (the task is tied to the thread that
798 /// can suspend its task region), false - untied (the task is not tied to any
800 /// \param NumberOfParts Number of parts for untied task.
801 /// \param Final Contains either constant bool value, or llvm::Value * of i1
802 /// type for final clause. If the value is true, the task forces all of its
803 /// child tasks to become final and included tasks.
804 /// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32
805 /// /*part_id*/, captured_struct */*__context*/);
806 /// \param SharedsTy A type which contains references the shared variables.
807 /// \param Shareds Context with the list of shared variables from the \p
809 /// \param IfCond Not a nullptr if 'if' clause was specified, nullptr
811 /// \param PrivateVars List of references to private variables for the task
813 /// \param PrivateCopies List of private copies for each private variable in
815 /// \param FirstprivateVars List of references to private variables for the
817 /// \param FirstprivateCopies List of private copies for each private variable
818 /// in \p FirstprivateVars.
819 /// \param FirstprivateInits List of references to auto generated variables
820 /// used for initialization of a single array element. Used if firstprivate
821 /// variable is of array type.
822 /// \param Dependences List of dependences for the 'task' construct, including
823 /// original expression and dependency type.
824 virtual void emitTaskCall(
825 CodeGenFunction &CGF, SourceLocation Loc, const OMPExecutableDirective &D,
826 bool Tied, llvm::PointerIntPair<llvm::Value *, 1, bool> Final,
827 unsigned NumberOfParts, llvm::Value *TaskFunction, QualType SharedsTy,
828 Address Shareds, const Expr *IfCond, ArrayRef<const Expr *> PrivateVars,
829 ArrayRef<const Expr *> PrivateCopies,
830 ArrayRef<const Expr *> FirstprivateVars,
831 ArrayRef<const Expr *> FirstprivateCopies,
832 ArrayRef<const Expr *> FirstprivateInits,
833 ArrayRef<std::pair<OpenMPDependClauseKind, const Expr *>> Dependences);
835 /// Emit task region for the taskloop directive. The taskloop region is
836 /// emitted in several steps:
837 /// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32
838 /// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
839 /// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the
841 /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
842 /// TaskFunction(gtid, tt->part_id, tt->shareds);
845 /// 2. Copy a list of shared variables to field shareds of the resulting
846 /// structure kmp_task_t returned by the previous call (if any).
847 /// 3. Copy a pointer to destructions function to field destructions of the
848 /// resulting structure kmp_task_t.
849 /// 4. Emit a call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t
850 /// *task, int if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int
851 /// nogroup, int sched, kmp_uint64 grainsize, void *task_dup ), where new_task
852 /// is a resulting structure from
854 /// \param D Current task directive.
855 /// \param Tied true if the task is tied (the task is tied to the thread that
856 /// can suspend its task region), false - untied (the task is not tied to any
858 /// \param Final Contains either constant bool value, or llvm::Value * of i1
859 /// type for final clause. If the value is true, the task forces all of its
860 /// child tasks to become final and included tasks.
861 /// \param Nogroup true if nogroup clause was specified, false otherwise.
862 /// \param NumberOfParts Number of parts in untied taskloops.
863 /// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32
864 /// /*part_id*/, captured_struct */*__context*/);
865 /// \param SharedsTy A type which contains references the shared variables.
866 /// \param Shareds Context with the list of shared variables from the \p
868 /// \param IfCond Not a nullptr if 'if' clause was specified, nullptr
870 /// \param PrivateVars List of references to private variables for the task
872 /// \param PrivateCopies List of private copies for each private variable in
874 /// \param FirstprivateVars List of references to private variables for the
876 /// \param FirstprivateCopies List of private copies for each private variable
877 /// in \p FirstprivateVars.
878 /// \param FirstprivateInits List of references to auto generated variables
879 /// used for initialization of a single array element. Used if firstprivate
880 /// variable is of array type.
881 virtual void emitTaskLoopCall(
882 CodeGenFunction &CGF, SourceLocation Loc, const OMPLoopDirective &D,
883 bool Tied, llvm::PointerIntPair<llvm::Value *, 1, bool> Final,
884 bool Nogroup, unsigned NumberOfParts, llvm::Value *TaskFunction,
885 QualType SharedsTy, Address Shareds, const Expr *IfCond,
886 ArrayRef<const Expr *> PrivateVars, ArrayRef<const Expr *> PrivateCopies,
887 ArrayRef<const Expr *> FirstprivateVars,
888 ArrayRef<const Expr *> FirstprivateCopies,
889 ArrayRef<const Expr *> FirstprivateInits);
891 /// \brief Emit code for the directive that does not require outlining.
893 /// \param InnermostKind Kind of innermost directive (for simple directives it
894 /// is a directive itself, for combined - its innermost directive).
895 /// \param CodeGen Code generation sequence for the \a D directive.
896 /// \param HasCancel true if region has inner cancel directive, false
898 virtual void emitInlinedDirective(CodeGenFunction &CGF,
899 OpenMPDirectiveKind InnermostKind,
900 const RegionCodeGenTy &CodeGen,
901 bool HasCancel = false);
902 /// \brief Emit a code for reduction clause. Next code should be emitted for
906 /// static kmp_critical_name lock = { 0 };
908 /// void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
910 /// *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
915 /// void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
916 /// switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
917 /// RedList, reduce_func, &<lock>)) {
920 /// <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
922 /// __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
926 /// Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
933 /// \param Privates List of private copies for original reduction arguments.
934 /// \param LHSExprs List of LHS in \a ReductionOps reduction operations.
935 /// \param RHSExprs List of RHS in \a ReductionOps reduction operations.
936 /// \param ReductionOps List of reduction operations in form 'LHS binop RHS'
937 /// or 'operator binop(LHS, RHS)'.
938 /// \param WithNowait true if parent directive has also nowait clause, false
940 virtual void emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
941 ArrayRef<const Expr *> Privates,
942 ArrayRef<const Expr *> LHSExprs,
943 ArrayRef<const Expr *> RHSExprs,
944 ArrayRef<const Expr *> ReductionOps,
945 bool WithNowait, bool SimpleReduction);
947 /// \brief Emit code for 'taskwait' directive.
948 virtual void emitTaskwaitCall(CodeGenFunction &CGF, SourceLocation Loc);
950 /// \brief Emit code for 'cancellation point' construct.
951 /// \param CancelRegion Region kind for which the cancellation point must be
954 virtual void emitCancellationPointCall(CodeGenFunction &CGF,
956 OpenMPDirectiveKind CancelRegion);
958 /// \brief Emit code for 'cancel' construct.
959 /// \param IfCond Condition in the associated 'if' clause, if it was
960 /// specified, nullptr otherwise.
961 /// \param CancelRegion Region kind for which the cancel must be emitted.
963 virtual void emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
965 OpenMPDirectiveKind CancelRegion);
967 /// \brief Emit outilined function for 'target' directive.
968 /// \param D Directive to emit.
969 /// \param ParentName Name of the function that encloses the target region.
970 /// \param OutlinedFn Outlined function value to be defined by this call.
971 /// \param OutlinedFnID Outlined function ID value to be defined by this call.
972 /// \param IsOffloadEntry True if the outlined function is an offload entry.
973 /// \param CodeGen Code generation sequence for the \a D directive.
974 /// An oulined function may not be an entry if, e.g. the if clause always
975 /// evaluates to false.
976 virtual void emitTargetOutlinedFunction(const OMPExecutableDirective &D,
977 StringRef ParentName,
978 llvm::Function *&OutlinedFn,
979 llvm::Constant *&OutlinedFnID,
981 const RegionCodeGenTy &CodeGen);
983 /// \brief Emit the target offloading code associated with \a D. The emitted
984 /// code attempts offloading the execution to the device, an the event of
985 /// a failure it executes the host version outlined in \a OutlinedFn.
986 /// \param D Directive to emit.
987 /// \param OutlinedFn Host version of the code to be offloaded.
988 /// \param OutlinedFnID ID of host version of the code to be offloaded.
989 /// \param IfCond Expression evaluated in if clause associated with the target
990 /// directive, or null if no if clause is used.
991 /// \param Device Expression evaluated in device clause associated with the
992 /// target directive, or null if no device clause is used.
993 /// \param CapturedVars Values captured in the current region.
994 virtual void emitTargetCall(CodeGenFunction &CGF,
995 const OMPExecutableDirective &D,
996 llvm::Value *OutlinedFn,
997 llvm::Value *OutlinedFnID, const Expr *IfCond,
999 ArrayRef<llvm::Value *> CapturedVars);
1001 /// \brief Emit the target regions enclosed in \a GD function definition or
1002 /// the function itself in case it is a valid device function. Returns true if
1003 /// \a GD was dealt with successfully.
1004 /// \param GD Function to scan.
1005 virtual bool emitTargetFunctions(GlobalDecl GD);
1007 /// \brief Emit the global variable if it is a valid device global variable.
1008 /// Returns true if \a GD was dealt with successfully.
1009 /// \param GD Variable declaration to emit.
1010 virtual bool emitTargetGlobalVariable(GlobalDecl GD);
1012 /// \brief Emit the global \a GD if it is meaningful for the target. Returns
1013 /// if it was emitted succesfully.
1014 /// \param GD Global to scan.
1015 virtual bool emitTargetGlobal(GlobalDecl GD);
1017 /// \brief Creates the offloading descriptor in the event any target region
1018 /// was emitted in the current module and return the function that registers
1020 virtual llvm::Function *emitRegistrationFunction();
1022 /// \brief Emits code for teams call of the \a OutlinedFn with
1023 /// variables captured in a record which address is stored in \a
1025 /// \param OutlinedFn Outlined function to be run by team masters. Type of
1026 /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*).
1027 /// \param CapturedVars A pointer to the record with the references to
1028 /// variables used in \a OutlinedFn function.
1030 virtual void emitTeamsCall(CodeGenFunction &CGF,
1031 const OMPExecutableDirective &D,
1032 SourceLocation Loc, llvm::Value *OutlinedFn,
1033 ArrayRef<llvm::Value *> CapturedVars);
1035 /// \brief Emits call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32
1036 /// global_tid, kmp_int32 num_teams, kmp_int32 thread_limit) to generate code
1037 /// for num_teams clause.
1038 /// \param NumTeams An integer expression of teams.
1039 /// \param ThreadLimit An integer expression of threads.
1040 virtual void emitNumTeamsClause(CodeGenFunction &CGF, const Expr *NumTeams,
1041 const Expr *ThreadLimit, SourceLocation Loc);
1044 } // namespace CodeGen
1045 } // namespace clang