Path: blob/main/contrib/llvm-project/clang/lib/CodeGen/CGOpenMPRuntime.h
35233 views
//===----- CGOpenMPRuntime.h - Interface to OpenMP Runtimes -----*- C++ -*-===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This provides a class for OpenMP runtime code generation.9//10//===----------------------------------------------------------------------===//1112#ifndef LLVM_CLANG_LIB_CODEGEN_CGOPENMPRUNTIME_H13#define LLVM_CLANG_LIB_CODEGEN_CGOPENMPRUNTIME_H1415#include "CGValue.h"16#include "clang/AST/DeclOpenMP.h"17#include "clang/AST/GlobalDecl.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/PointerIntPair.h"23#include "llvm/ADT/SmallPtrSet.h"24#include "llvm/ADT/StringMap.h"25#include "llvm/ADT/StringSet.h"26#include "llvm/Frontend/OpenMP/OMPConstants.h"27#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"28#include "llvm/IR/Function.h"29#include "llvm/IR/ValueHandle.h"30#include "llvm/Support/AtomicOrdering.h"3132namespace llvm {33class ArrayType;34class Constant;35class FunctionType;36class GlobalVariable;37class Type;38class Value;39class OpenMPIRBuilder;40} // namespace llvm4142namespace clang {43class Expr;44class OMPDependClause;45class OMPExecutableDirective;46class OMPLoopDirective;47class VarDecl;48class OMPDeclareReductionDecl;4950namespace CodeGen {51class Address;52class CodeGenFunction;53class CodeGenModule;5455/// A basic class for pre|post-action for advanced codegen sequence for OpenMP56/// region.57class PrePostActionTy {58public:59explicit PrePostActionTy() {}60virtual void Enter(CodeGenFunction &CGF) {}61virtual void Exit(CodeGenFunction &CGF) {}62virtual ~PrePostActionTy() {}63};6465/// Class provides a way to call simple version of codegen for OpenMP region, or66/// an advanced with possible pre|post-actions in codegen.67class RegionCodeGenTy final {68intptr_t CodeGen;69typedef void (*CodeGenTy)(intptr_t, CodeGenFunction &, PrePostActionTy &);70CodeGenTy Callback;71mutable PrePostActionTy *PrePostAction;72RegionCodeGenTy() = delete;73template <typename Callable>74static void CallbackFn(intptr_t CodeGen, CodeGenFunction &CGF,75PrePostActionTy &Action) {76return (*reinterpret_cast<Callable *>(CodeGen))(CGF, Action);77}7879public:80template <typename Callable>81RegionCodeGenTy(82Callable &&CodeGen,83std::enable_if_t<!std::is_same<std::remove_reference_t<Callable>,84RegionCodeGenTy>::value> * = nullptr)85: CodeGen(reinterpret_cast<intptr_t>(&CodeGen)),86Callback(CallbackFn<std::remove_reference_t<Callable>>),87PrePostAction(nullptr) {}88void setAction(PrePostActionTy &Action) const { PrePostAction = &Action; }89void operator()(CodeGenFunction &CGF) const;90};9192struct OMPTaskDataTy final {93SmallVector<const Expr *, 4> PrivateVars;94SmallVector<const Expr *, 4> PrivateCopies;95SmallVector<const Expr *, 4> FirstprivateVars;96SmallVector<const Expr *, 4> FirstprivateCopies;97SmallVector<const Expr *, 4> FirstprivateInits;98SmallVector<const Expr *, 4> LastprivateVars;99SmallVector<const Expr *, 4> LastprivateCopies;100SmallVector<const Expr *, 4> ReductionVars;101SmallVector<const Expr *, 4> ReductionOrigs;102SmallVector<const Expr *, 4> ReductionCopies;103SmallVector<const Expr *, 4> ReductionOps;104SmallVector<CanonicalDeclPtr<const VarDecl>, 4> PrivateLocals;105struct DependData {106OpenMPDependClauseKind DepKind = OMPC_DEPEND_unknown;107const Expr *IteratorExpr = nullptr;108SmallVector<const Expr *, 4> DepExprs;109explicit DependData() = default;110DependData(OpenMPDependClauseKind DepKind, const Expr *IteratorExpr)111: DepKind(DepKind), IteratorExpr(IteratorExpr) {}112};113SmallVector<DependData, 4> Dependences;114llvm::PointerIntPair<llvm::Value *, 1, bool> Final;115llvm::PointerIntPair<llvm::Value *, 1, bool> Schedule;116llvm::PointerIntPair<llvm::Value *, 1, bool> Priority;117llvm::Value *Reductions = nullptr;118unsigned NumberOfParts = 0;119bool Tied = true;120bool Nogroup = false;121bool IsReductionWithTaskMod = false;122bool IsWorksharingReduction = false;123bool HasNowaitClause = false;124};125126/// Class intended to support codegen of all kind of the reduction clauses.127class ReductionCodeGen {128private:129/// Data required for codegen of reduction clauses.130struct ReductionData {131/// Reference to the item shared between tasks to reduce into.132const Expr *Shared = nullptr;133/// Reference to the original item.134const Expr *Ref = nullptr;135/// Helper expression for generation of private copy.136const Expr *Private = nullptr;137/// Helper expression for generation reduction operation.138const Expr *ReductionOp = nullptr;139ReductionData(const Expr *Shared, const Expr *Ref, const Expr *Private,140const Expr *ReductionOp)141: Shared(Shared), Ref(Ref), Private(Private), ReductionOp(ReductionOp) {142}143};144/// List of reduction-based clauses.145SmallVector<ReductionData, 4> ClausesData;146147/// List of addresses of shared variables/expressions.148SmallVector<std::pair<LValue, LValue>, 4> SharedAddresses;149/// List of addresses of original variables/expressions.150SmallVector<std::pair<LValue, LValue>, 4> OrigAddresses;151/// Sizes of the reduction items in chars.152SmallVector<std::pair<llvm::Value *, llvm::Value *>, 4> Sizes;153/// Base declarations for the reduction items.154SmallVector<const VarDecl *, 4> BaseDecls;155156/// Emits lvalue for shared expression.157LValue emitSharedLValue(CodeGenFunction &CGF, const Expr *E);158/// Emits upper bound for shared expression (if array section).159LValue emitSharedLValueUB(CodeGenFunction &CGF, const Expr *E);160/// Performs aggregate initialization.161/// \param N Number of reduction item in the common list.162/// \param PrivateAddr Address of the corresponding private item.163/// \param SharedAddr Address of the original shared variable.164/// \param DRD Declare reduction construct used for reduction item.165void emitAggregateInitialization(CodeGenFunction &CGF, unsigned N,166Address PrivateAddr, Address SharedAddr,167const OMPDeclareReductionDecl *DRD);168169public:170ReductionCodeGen(ArrayRef<const Expr *> Shareds, ArrayRef<const Expr *> Origs,171ArrayRef<const Expr *> Privates,172ArrayRef<const Expr *> ReductionOps);173/// Emits lvalue for the shared and original reduction item.174/// \param N Number of the reduction item.175void emitSharedOrigLValue(CodeGenFunction &CGF, unsigned N);176/// Emits the code for the variable-modified type, if required.177/// \param N Number of the reduction item.178void emitAggregateType(CodeGenFunction &CGF, unsigned N);179/// Emits the code for the variable-modified type, if required.180/// \param N Number of the reduction item.181/// \param Size Size of the type in chars.182void emitAggregateType(CodeGenFunction &CGF, unsigned N, llvm::Value *Size);183/// Performs initialization of the private copy for the reduction item.184/// \param N Number of the reduction item.185/// \param PrivateAddr Address of the corresponding private item.186/// \param DefaultInit Default initialization sequence that should be187/// performed if no reduction specific initialization is found.188/// \param SharedAddr Address of the original shared variable.189void190emitInitialization(CodeGenFunction &CGF, unsigned N, Address PrivateAddr,191Address SharedAddr,192llvm::function_ref<bool(CodeGenFunction &)> DefaultInit);193/// Returns true if the private copy requires cleanups.194bool needCleanups(unsigned N);195/// Emits cleanup code for the reduction item.196/// \param N Number of the reduction item.197/// \param PrivateAddr Address of the corresponding private item.198void emitCleanups(CodeGenFunction &CGF, unsigned N, Address PrivateAddr);199/// Adjusts \p PrivatedAddr for using instead of the original variable200/// address in normal operations.201/// \param N Number of the reduction item.202/// \param PrivateAddr Address of the corresponding private item.203Address adjustPrivateAddress(CodeGenFunction &CGF, unsigned N,204Address PrivateAddr);205/// Returns LValue for the reduction item.206LValue getSharedLValue(unsigned N) const { return SharedAddresses[N].first; }207/// Returns LValue for the original reduction item.208LValue getOrigLValue(unsigned N) const { return OrigAddresses[N].first; }209/// Returns the size of the reduction item (in chars and total number of210/// elements in the item), or nullptr, if the size is a constant.211std::pair<llvm::Value *, llvm::Value *> getSizes(unsigned N) const {212return Sizes[N];213}214/// Returns the base declaration of the reduction item.215const VarDecl *getBaseDecl(unsigned N) const { return BaseDecls[N]; }216/// Returns the base declaration of the reduction item.217const Expr *getRefExpr(unsigned N) const { return ClausesData[N].Ref; }218/// Returns true if the initialization of the reduction item uses initializer219/// from declare reduction construct.220bool usesReductionInitializer(unsigned N) const;221/// Return the type of the private item.222QualType getPrivateType(unsigned N) const {223return cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl())224->getType();225}226};227228class CGOpenMPRuntime {229public:230/// Allows to disable automatic handling of functions used in target regions231/// as those marked as `omp declare target`.232class DisableAutoDeclareTargetRAII {233CodeGenModule &CGM;234bool SavedShouldMarkAsGlobal = false;235236public:237DisableAutoDeclareTargetRAII(CodeGenModule &CGM);238~DisableAutoDeclareTargetRAII();239};240241/// Manages list of nontemporal decls for the specified directive.242class NontemporalDeclsRAII {243CodeGenModule &CGM;244const bool NeedToPush;245246public:247NontemporalDeclsRAII(CodeGenModule &CGM, const OMPLoopDirective &S);248~NontemporalDeclsRAII();249};250251/// Manages list of nontemporal decls for the specified directive.252class UntiedTaskLocalDeclsRAII {253CodeGenModule &CGM;254const bool NeedToPush;255256public:257UntiedTaskLocalDeclsRAII(258CodeGenFunction &CGF,259const llvm::MapVector<CanonicalDeclPtr<const VarDecl>,260std::pair<Address, Address>> &LocalVars);261~UntiedTaskLocalDeclsRAII();262};263264/// Maps the expression for the lastprivate variable to the global copy used265/// to store new value because original variables are not mapped in inner266/// parallel regions. Only private copies are captured but we need also to267/// store private copy in shared address.268/// Also, stores the expression for the private loop counter and it269/// threaprivate name.270struct LastprivateConditionalData {271llvm::MapVector<CanonicalDeclPtr<const Decl>, SmallString<16>>272DeclToUniqueName;273LValue IVLVal;274llvm::Function *Fn = nullptr;275bool Disabled = false;276};277/// Manages list of lastprivate conditional decls for the specified directive.278class LastprivateConditionalRAII {279enum class ActionToDo {280DoNotPush,281PushAsLastprivateConditional,282DisableLastprivateConditional,283};284CodeGenModule &CGM;285ActionToDo Action = ActionToDo::DoNotPush;286287/// Check and try to disable analysis of inner regions for changes in288/// lastprivate conditional.289void tryToDisableInnerAnalysis(const OMPExecutableDirective &S,290llvm::DenseSet<CanonicalDeclPtr<const Decl>>291&NeedToAddForLPCsAsDisabled) const;292293LastprivateConditionalRAII(CodeGenFunction &CGF,294const OMPExecutableDirective &S);295296public:297explicit LastprivateConditionalRAII(CodeGenFunction &CGF,298const OMPExecutableDirective &S,299LValue IVLVal);300static LastprivateConditionalRAII disable(CodeGenFunction &CGF,301const OMPExecutableDirective &S);302~LastprivateConditionalRAII();303};304305llvm::OpenMPIRBuilder &getOMPBuilder() { return OMPBuilder; }306307protected:308CodeGenModule &CGM;309310/// An OpenMP-IR-Builder instance.311llvm::OpenMPIRBuilder OMPBuilder;312313/// Helper to determine the min/max number of threads/teams for \p D.314void computeMinAndMaxThreadsAndTeams(const OMPExecutableDirective &D,315CodeGenFunction &CGF,316int32_t &MinThreadsVal,317int32_t &MaxThreadsVal,318int32_t &MinTeamsVal,319int32_t &MaxTeamsVal);320321/// Helper to emit outlined function for 'target' directive.322/// \param D Directive to emit.323/// \param ParentName Name of the function that encloses the target region.324/// \param OutlinedFn Outlined function value to be defined by this call.325/// \param OutlinedFnID Outlined function ID value to be defined by this call.326/// \param IsOffloadEntry True if the outlined function is an offload entry.327/// \param CodeGen Lambda codegen specific to an accelerator device.328/// An outlined function may not be an entry if, e.g. the if clause always329/// evaluates to false.330virtual void emitTargetOutlinedFunctionHelper(const OMPExecutableDirective &D,331StringRef ParentName,332llvm::Function *&OutlinedFn,333llvm::Constant *&OutlinedFnID,334bool IsOffloadEntry,335const RegionCodeGenTy &CodeGen);336337/// Returns pointer to ident_t type.338llvm::Type *getIdentTyPointerTy();339340/// Gets thread id value for the current thread.341///342llvm::Value *getThreadID(CodeGenFunction &CGF, SourceLocation Loc);343344/// Get the function name of an outlined region.345std::string getOutlinedHelperName(StringRef Name) const;346std::string getOutlinedHelperName(CodeGenFunction &CGF) const;347348/// Get the function name of a reduction function.349std::string getReductionFuncName(StringRef Name) const;350351/// Emits \p Callee function call with arguments \p Args with location \p Loc.352void emitCall(CodeGenFunction &CGF, SourceLocation Loc,353llvm::FunctionCallee Callee,354ArrayRef<llvm::Value *> Args = std::nullopt) const;355356/// Emits address of the word in a memory where current thread id is357/// stored.358virtual Address emitThreadIDAddress(CodeGenFunction &CGF, SourceLocation Loc);359360void setLocThreadIdInsertPt(CodeGenFunction &CGF,361bool AtCurrentPoint = false);362void clearLocThreadIdInsertPt(CodeGenFunction &CGF);363364/// Check if the default location must be constant.365/// Default is false to support OMPT/OMPD.366virtual bool isDefaultLocationConstant() const { return false; }367368/// Returns additional flags that can be stored in reserved_2 field of the369/// default location.370virtual unsigned getDefaultLocationReserved2Flags() const { return 0; }371372/// Returns default flags for the barriers depending on the directive, for373/// which this barier is going to be emitted.374static unsigned getDefaultFlagsForBarriers(OpenMPDirectiveKind Kind);375376/// Get the LLVM type for the critical name.377llvm::ArrayType *getKmpCriticalNameTy() const {return KmpCriticalNameTy;}378379/// Returns corresponding lock object for the specified critical region380/// name. If the lock object does not exist it is created, otherwise the381/// reference to the existing copy is returned.382/// \param CriticalName Name of the critical region.383///384llvm::Value *getCriticalRegionLock(StringRef CriticalName);385386protected:387/// Map for SourceLocation and OpenMP runtime library debug locations.388typedef llvm::DenseMap<SourceLocation, llvm::Value *> OpenMPDebugLocMapTy;389OpenMPDebugLocMapTy OpenMPDebugLocMap;390/// The type for a microtask which gets passed to __kmpc_fork_call().391/// Original representation is:392/// typedef void (kmpc_micro)(kmp_int32 global_tid, kmp_int32 bound_tid,...);393llvm::FunctionType *Kmpc_MicroTy = nullptr;394/// Stores debug location and ThreadID for the function.395struct DebugLocThreadIdTy {396llvm::Value *DebugLoc;397llvm::Value *ThreadID;398/// Insert point for the service instructions.399llvm::AssertingVH<llvm::Instruction> ServiceInsertPt = nullptr;400};401/// Map of local debug location, ThreadId and functions.402typedef llvm::DenseMap<llvm::Function *, DebugLocThreadIdTy>403OpenMPLocThreadIDMapTy;404OpenMPLocThreadIDMapTy OpenMPLocThreadIDMap;405/// Map of UDRs and corresponding combiner/initializer.406typedef llvm::DenseMap<const OMPDeclareReductionDecl *,407std::pair<llvm::Function *, llvm::Function *>>408UDRMapTy;409UDRMapTy UDRMap;410/// Map of functions and locally defined UDRs.411typedef llvm::DenseMap<llvm::Function *,412SmallVector<const OMPDeclareReductionDecl *, 4>>413FunctionUDRMapTy;414FunctionUDRMapTy FunctionUDRMap;415/// Map from the user-defined mapper declaration to its corresponding416/// functions.417llvm::DenseMap<const OMPDeclareMapperDecl *, llvm::Function *> UDMMap;418/// Map of functions and their local user-defined mappers.419using FunctionUDMMapTy =420llvm::DenseMap<llvm::Function *,421SmallVector<const OMPDeclareMapperDecl *, 4>>;422FunctionUDMMapTy FunctionUDMMap;423/// Maps local variables marked as lastprivate conditional to their internal424/// types.425llvm::DenseMap<llvm::Function *,426llvm::DenseMap<CanonicalDeclPtr<const Decl>,427std::tuple<QualType, const FieldDecl *,428const FieldDecl *, LValue>>>429LastprivateConditionalToTypes;430/// Maps function to the position of the untied task locals stack.431llvm::DenseMap<llvm::Function *, unsigned> FunctionToUntiedTaskStackMap;432/// Type kmp_critical_name, originally defined as typedef kmp_int32433/// kmp_critical_name[8];434llvm::ArrayType *KmpCriticalNameTy;435/// An ordered map of auto-generated variables to their unique names.436/// It stores variables with the following names: 1) ".gomp_critical_user_" +437/// <critical_section_name> + ".var" for "omp critical" directives; 2)438/// <mangled_name_for_global_var> + ".cache." for cache for threadprivate439/// variables.440llvm::StringMap<llvm::AssertingVH<llvm::GlobalVariable>,441llvm::BumpPtrAllocator> InternalVars;442/// Type typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *);443llvm::Type *KmpRoutineEntryPtrTy = nullptr;444QualType KmpRoutineEntryPtrQTy;445/// Type typedef struct kmp_task {446/// void * shareds; /**< pointer to block of pointers to447/// shared vars */448/// kmp_routine_entry_t routine; /**< pointer to routine to call for449/// executing task */450/// kmp_int32 part_id; /**< part id for the task */451/// kmp_routine_entry_t destructors; /* pointer to function to invoke452/// deconstructors of firstprivate C++ objects */453/// } kmp_task_t;454QualType KmpTaskTQTy;455/// Saved kmp_task_t for task directive.456QualType SavedKmpTaskTQTy;457/// Saved kmp_task_t for taskloop-based directive.458QualType SavedKmpTaskloopTQTy;459/// Type typedef struct kmp_depend_info {460/// kmp_intptr_t base_addr;461/// size_t len;462/// struct {463/// bool in:1;464/// bool out:1;465/// } flags;466/// } kmp_depend_info_t;467QualType KmpDependInfoTy;468/// Type typedef struct kmp_task_affinity_info {469/// kmp_intptr_t base_addr;470/// size_t len;471/// struct {472/// bool flag1 : 1;473/// bool flag2 : 1;474/// kmp_int32 reserved : 30;475/// } flags;476/// } kmp_task_affinity_info_t;477QualType KmpTaskAffinityInfoTy;478/// struct kmp_dim { // loop bounds info casted to kmp_int64479/// kmp_int64 lo; // lower480/// kmp_int64 up; // upper481/// kmp_int64 st; // stride482/// };483QualType KmpDimTy;484485bool ShouldMarkAsGlobal = true;486/// List of the emitted declarations.487llvm::DenseSet<CanonicalDeclPtr<const Decl>> AlreadyEmittedTargetDecls;488/// List of the global variables with their addresses that should not be489/// emitted for the target.490llvm::StringMap<llvm::WeakTrackingVH> EmittedNonTargetVariables;491492/// List of variables that can become declare target implicitly and, thus,493/// must be emitted.494llvm::SmallDenseSet<const VarDecl *> DeferredGlobalVariables;495496using NontemporalDeclsSet = llvm::SmallDenseSet<CanonicalDeclPtr<const Decl>>;497/// Stack for list of declarations in current context marked as nontemporal.498/// The set is the union of all current stack elements.499llvm::SmallVector<NontemporalDeclsSet, 4> NontemporalDeclsStack;500501using UntiedLocalVarsAddressesMap =502llvm::MapVector<CanonicalDeclPtr<const VarDecl>,503std::pair<Address, Address>>;504llvm::SmallVector<UntiedLocalVarsAddressesMap, 4> UntiedLocalVarsStack;505506/// Stack for list of addresses of declarations in current context marked as507/// lastprivate conditional. The set is the union of all current stack508/// elements.509llvm::SmallVector<LastprivateConditionalData, 4> LastprivateConditionalStack;510511/// Flag for keeping track of weather a requires unified_shared_memory512/// directive is present.513bool HasRequiresUnifiedSharedMemory = false;514515/// Atomic ordering from the omp requires directive.516llvm::AtomicOrdering RequiresAtomicOrdering = llvm::AtomicOrdering::Monotonic;517518/// Flag for keeping track of weather a target region has been emitted.519bool HasEmittedTargetRegion = false;520521/// Flag for keeping track of weather a device routine has been emitted.522/// Device routines are specific to the523bool HasEmittedDeclareTargetRegion = false;524525/// Start scanning from statement \a S and emit all target regions526/// found along the way.527/// \param S Starting statement.528/// \param ParentName Name of the function declaration that is being scanned.529void scanForTargetRegionsFunctions(const Stmt *S, StringRef ParentName);530531/// Build type kmp_routine_entry_t (if not built yet).532void emitKmpRoutineEntryT(QualType KmpInt32Ty);533534/// Returns pointer to kmpc_micro type.535llvm::Type *getKmpc_MicroPointerTy();536537/// If the specified mangled name is not in the module, create and538/// return threadprivate cache object. This object is a pointer's worth of539/// storage that's reserved for use by the OpenMP runtime.540/// \param VD Threadprivate variable.541/// \return Cache variable for the specified threadprivate.542llvm::Constant *getOrCreateThreadPrivateCache(const VarDecl *VD);543544/// Set of threadprivate variables with the generated initializer.545llvm::StringSet<> ThreadPrivateWithDefinition;546547/// Set of declare target variables with the generated initializer.548llvm::StringSet<> DeclareTargetWithDefinition;549550/// Emits initialization code for the threadprivate variables.551/// \param VDAddr Address of the global variable \a VD.552/// \param Ctor Pointer to a global init function for \a VD.553/// \param CopyCtor Pointer to a global copy function for \a VD.554/// \param Dtor Pointer to a global destructor function for \a VD.555/// \param Loc Location of threadprivate declaration.556void emitThreadPrivateVarInit(CodeGenFunction &CGF, Address VDAddr,557llvm::Value *Ctor, llvm::Value *CopyCtor,558llvm::Value *Dtor, SourceLocation Loc);559560/// Emit the array initialization or deletion portion for user-defined mapper561/// code generation.562void emitUDMapperArrayInitOrDel(CodeGenFunction &MapperCGF,563llvm::Value *Handle, llvm::Value *BasePtr,564llvm::Value *Ptr, llvm::Value *Size,565llvm::Value *MapType, llvm::Value *MapName,566CharUnits ElementSize,567llvm::BasicBlock *ExitBB, bool IsInit);568569struct TaskResultTy {570llvm::Value *NewTask = nullptr;571llvm::Function *TaskEntry = nullptr;572llvm::Value *NewTaskNewTaskTTy = nullptr;573LValue TDBase;574const RecordDecl *KmpTaskTQTyRD = nullptr;575llvm::Value *TaskDupFn = nullptr;576};577/// Emit task region for the task directive. The task region is emitted in578/// several steps:579/// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32580/// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,581/// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the582/// function:583/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {584/// TaskFunction(gtid, tt->part_id, tt->shareds);585/// return 0;586/// }587/// 2. Copy a list of shared variables to field shareds of the resulting588/// structure kmp_task_t returned by the previous call (if any).589/// 3. Copy a pointer to destructions function to field destructions of the590/// resulting structure kmp_task_t.591/// \param D Current task directive.592/// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32593/// /*part_id*/, captured_struct */*__context*/);594/// \param SharedsTy A type which contains references the shared variables.595/// \param Shareds Context with the list of shared variables from the \p596/// TaskFunction.597/// \param Data Additional data for task generation like tiednsee, final598/// state, list of privates etc.599TaskResultTy emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,600const OMPExecutableDirective &D,601llvm::Function *TaskFunction, QualType SharedsTy,602Address Shareds, const OMPTaskDataTy &Data);603604/// Emit update for lastprivate conditional data.605void emitLastprivateConditionalUpdate(CodeGenFunction &CGF, LValue IVLVal,606StringRef UniqueDeclName, LValue LVal,607SourceLocation Loc);608609/// Returns the number of the elements and the address of the depobj610/// dependency array.611/// \return Number of elements in depobj array and the pointer to the array of612/// dependencies.613std::pair<llvm::Value *, LValue> getDepobjElements(CodeGenFunction &CGF,614LValue DepobjLVal,615SourceLocation Loc);616617SmallVector<llvm::Value *, 4>618emitDepobjElementsSizes(CodeGenFunction &CGF, QualType &KmpDependInfoTy,619const OMPTaskDataTy::DependData &Data);620621void emitDepobjElements(CodeGenFunction &CGF, QualType &KmpDependInfoTy,622LValue PosLVal, const OMPTaskDataTy::DependData &Data,623Address DependenciesArray);624625public:626explicit CGOpenMPRuntime(CodeGenModule &CGM);627virtual ~CGOpenMPRuntime() {}628virtual void clear();629630/// Emits object of ident_t type with info for source location.631/// \param Flags Flags for OpenMP location.632/// \param EmitLoc emit source location with debug-info is off.633///634llvm::Value *emitUpdateLocation(CodeGenFunction &CGF, SourceLocation Loc,635unsigned Flags = 0, bool EmitLoc = false);636637/// Emit the number of teams for a target directive. Inspect the num_teams638/// clause associated with a teams construct combined or closely nested639/// with the target directive.640///641/// Emit a team of size one for directives such as 'target parallel' that642/// have no associated teams construct.643///644/// Otherwise, return nullptr.645const Expr *getNumTeamsExprForTargetDirective(CodeGenFunction &CGF,646const OMPExecutableDirective &D,647int32_t &MinTeamsVal,648int32_t &MaxTeamsVal);649llvm::Value *emitNumTeamsForTargetDirective(CodeGenFunction &CGF,650const OMPExecutableDirective &D);651652/// Check for a number of threads upper bound constant value (stored in \p653/// UpperBound), or expression (returned). If the value is conditional (via an654/// if-clause), store the condition in \p CondExpr. Similarly, a potential655/// thread limit expression is stored in \p ThreadLimitExpr. If \p656/// UpperBoundOnly is true, no expression evaluation is perfomed.657const Expr *getNumThreadsExprForTargetDirective(658CodeGenFunction &CGF, const OMPExecutableDirective &D,659int32_t &UpperBound, bool UpperBoundOnly,660llvm::Value **CondExpr = nullptr, const Expr **ThreadLimitExpr = nullptr);661662/// Emit an expression that denotes the number of threads a target region663/// shall use. Will generate "i32 0" to allow the runtime to choose.664llvm::Value *665emitNumThreadsForTargetDirective(CodeGenFunction &CGF,666const OMPExecutableDirective &D);667668/// Return the trip count of loops associated with constructs / 'target teams669/// distribute' and 'teams distribute parallel for'. \param SizeEmitter Emits670/// the int64 value for the number of iterations of the associated loop.671llvm::Value *emitTargetNumIterationsCall(672CodeGenFunction &CGF, const OMPExecutableDirective &D,673llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,674const OMPLoopDirective &D)>675SizeEmitter);676677/// Returns true if the current target is a GPU.678virtual bool isGPU() const { return false; }679680/// Check if the variable length declaration is delayed:681virtual bool isDelayedVariableLengthDecl(CodeGenFunction &CGF,682const VarDecl *VD) const {683return false;684};685686/// Get call to __kmpc_alloc_shared687virtual std::pair<llvm::Value *, llvm::Value *>688getKmpcAllocShared(CodeGenFunction &CGF, const VarDecl *VD) {689llvm_unreachable("not implemented");690}691692/// Get call to __kmpc_free_shared693virtual void getKmpcFreeShared(694CodeGenFunction &CGF,695const std::pair<llvm::Value *, llvm::Value *> &AddrSizePair) {696llvm_unreachable("not implemented");697}698699/// Emits code for OpenMP 'if' clause using specified \a CodeGen700/// function. Here is the logic:701/// if (Cond) {702/// ThenGen();703/// } else {704/// ElseGen();705/// }706void emitIfClause(CodeGenFunction &CGF, const Expr *Cond,707const RegionCodeGenTy &ThenGen,708const RegionCodeGenTy &ElseGen);709710/// Checks if the \p Body is the \a CompoundStmt and returns its child711/// statement iff there is only one that is not evaluatable at the compile712/// time.713static const Stmt *getSingleCompoundChild(ASTContext &Ctx, const Stmt *Body);714715/// Get the platform-specific name separator.716std::string getName(ArrayRef<StringRef> Parts) const;717718/// Emit code for the specified user defined reduction construct.719virtual void emitUserDefinedReduction(CodeGenFunction *CGF,720const OMPDeclareReductionDecl *D);721/// Get combiner/initializer for the specified user-defined reduction, if any.722virtual std::pair<llvm::Function *, llvm::Function *>723getUserDefinedReduction(const OMPDeclareReductionDecl *D);724725/// Emit the function for the user defined mapper construct.726void emitUserDefinedMapper(const OMPDeclareMapperDecl *D,727CodeGenFunction *CGF = nullptr);728/// Get the function for the specified user-defined mapper. If it does not729/// exist, create one.730llvm::Function *731getOrCreateUserDefinedMapperFunc(const OMPDeclareMapperDecl *D);732733/// Emits outlined function for the specified OpenMP parallel directive734/// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID,735/// kmp_int32 BoundID, struct context_vars*).736/// \param CGF Reference to current CodeGenFunction.737/// \param D OpenMP directive.738/// \param ThreadIDVar Variable for thread id in the current OpenMP region.739/// \param InnermostKind Kind of innermost directive (for simple directives it740/// is a directive itself, for combined - its innermost directive).741/// \param CodeGen Code generation sequence for the \a D directive.742virtual llvm::Function *emitParallelOutlinedFunction(743CodeGenFunction &CGF, const OMPExecutableDirective &D,744const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,745const RegionCodeGenTy &CodeGen);746747/// Emits outlined function for the specified OpenMP teams directive748/// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID,749/// kmp_int32 BoundID, struct context_vars*).750/// \param CGF Reference to current CodeGenFunction.751/// \param D OpenMP directive.752/// \param ThreadIDVar Variable for thread id in the current OpenMP region.753/// \param InnermostKind Kind of innermost directive (for simple directives it754/// is a directive itself, for combined - its innermost directive).755/// \param CodeGen Code generation sequence for the \a D directive.756virtual llvm::Function *emitTeamsOutlinedFunction(757CodeGenFunction &CGF, const OMPExecutableDirective &D,758const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,759const RegionCodeGenTy &CodeGen);760761/// Emits outlined function for the OpenMP task directive \a D. This762/// outlined function has type void(*)(kmp_int32 ThreadID, struct task_t*763/// TaskT).764/// \param D OpenMP directive.765/// \param ThreadIDVar Variable for thread id in the current OpenMP region.766/// \param PartIDVar Variable for partition id in the current OpenMP untied767/// task region.768/// \param TaskTVar Variable for task_t argument.769/// \param InnermostKind Kind of innermost directive (for simple directives it770/// is a directive itself, for combined - its innermost directive).771/// \param CodeGen Code generation sequence for the \a D directive.772/// \param Tied true if task is generated for tied task, false otherwise.773/// \param NumberOfParts Number of parts in untied task. Ignored for tied774/// tasks.775///776virtual llvm::Function *emitTaskOutlinedFunction(777const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,778const VarDecl *PartIDVar, const VarDecl *TaskTVar,779OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,780bool Tied, unsigned &NumberOfParts);781782/// Cleans up references to the objects in finished function.783///784virtual void functionFinished(CodeGenFunction &CGF);785786/// Emits code for parallel or serial call of the \a OutlinedFn with787/// variables captured in a record which address is stored in \a788/// CapturedStruct.789/// \param OutlinedFn Outlined function to be run in parallel threads. Type of790/// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*).791/// \param CapturedVars A pointer to the record with the references to792/// variables used in \a OutlinedFn function.793/// \param IfCond Condition in the associated 'if' clause, if it was794/// specified, nullptr otherwise.795/// \param NumThreads The value corresponding to the num_threads clause, if796/// any, or nullptr.797///798virtual void emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,799llvm::Function *OutlinedFn,800ArrayRef<llvm::Value *> CapturedVars,801const Expr *IfCond, llvm::Value *NumThreads);802803/// Emits a critical region.804/// \param CriticalName Name of the critical region.805/// \param CriticalOpGen Generator for the statement associated with the given806/// critical region.807/// \param Hint Value of the 'hint' clause (optional).808virtual void emitCriticalRegion(CodeGenFunction &CGF, StringRef CriticalName,809const RegionCodeGenTy &CriticalOpGen,810SourceLocation Loc,811const Expr *Hint = nullptr);812813/// Emits a master region.814/// \param MasterOpGen Generator for the statement associated with the given815/// master region.816virtual void emitMasterRegion(CodeGenFunction &CGF,817const RegionCodeGenTy &MasterOpGen,818SourceLocation Loc);819820/// Emits a masked region.821/// \param MaskedOpGen Generator for the statement associated with the given822/// masked region.823virtual void emitMaskedRegion(CodeGenFunction &CGF,824const RegionCodeGenTy &MaskedOpGen,825SourceLocation Loc,826const Expr *Filter = nullptr);827828/// Emits code for a taskyield directive.829virtual void emitTaskyieldCall(CodeGenFunction &CGF, SourceLocation Loc);830831/// Emit __kmpc_error call for error directive832/// extern void __kmpc_error(ident_t *loc, int severity, const char *message);833virtual void emitErrorCall(CodeGenFunction &CGF, SourceLocation Loc, Expr *ME,834bool IsFatal);835836/// Emit a taskgroup region.837/// \param TaskgroupOpGen Generator for the statement associated with the838/// given taskgroup region.839virtual void emitTaskgroupRegion(CodeGenFunction &CGF,840const RegionCodeGenTy &TaskgroupOpGen,841SourceLocation Loc);842843/// Emits a single region.844/// \param SingleOpGen Generator for the statement associated with the given845/// single region.846virtual void emitSingleRegion(CodeGenFunction &CGF,847const RegionCodeGenTy &SingleOpGen,848SourceLocation Loc,849ArrayRef<const Expr *> CopyprivateVars,850ArrayRef<const Expr *> DestExprs,851ArrayRef<const Expr *> SrcExprs,852ArrayRef<const Expr *> AssignmentOps);853854/// Emit an ordered region.855/// \param OrderedOpGen Generator for the statement associated with the given856/// ordered region.857virtual void emitOrderedRegion(CodeGenFunction &CGF,858const RegionCodeGenTy &OrderedOpGen,859SourceLocation Loc, bool IsThreads);860861/// Emit an implicit/explicit barrier for OpenMP threads.862/// \param Kind Directive for which this implicit barrier call must be863/// generated. Must be OMPD_barrier for explicit barrier generation.864/// \param EmitChecks true if need to emit checks for cancellation barriers.865/// \param ForceSimpleCall true simple barrier call must be emitted, false if866/// runtime class decides which one to emit (simple or with cancellation867/// checks).868///869virtual void emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,870OpenMPDirectiveKind Kind,871bool EmitChecks = true,872bool ForceSimpleCall = false);873874/// Check if the specified \a ScheduleKind is static non-chunked.875/// This kind of worksharing directive is emitted without outer loop.876/// \param ScheduleKind Schedule kind specified in the 'schedule' clause.877/// \param Chunked True if chunk is specified in the clause.878///879virtual bool isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,880bool Chunked) const;881882/// Check if the specified \a ScheduleKind is static non-chunked.883/// This kind of distribute directive is emitted without outer loop.884/// \param ScheduleKind Schedule kind specified in the 'dist_schedule' clause.885/// \param Chunked True if chunk is specified in the clause.886///887virtual bool isStaticNonchunked(OpenMPDistScheduleClauseKind ScheduleKind,888bool Chunked) const;889890/// Check if the specified \a ScheduleKind is static chunked.891/// \param ScheduleKind Schedule kind specified in the 'schedule' clause.892/// \param Chunked True if chunk is specified in the clause.893///894virtual bool isStaticChunked(OpenMPScheduleClauseKind ScheduleKind,895bool Chunked) const;896897/// Check if the specified \a ScheduleKind is static non-chunked.898/// \param ScheduleKind Schedule kind specified in the 'dist_schedule' clause.899/// \param Chunked True if chunk is specified in the clause.900///901virtual bool isStaticChunked(OpenMPDistScheduleClauseKind ScheduleKind,902bool Chunked) const;903904/// Check if the specified \a ScheduleKind is dynamic.905/// This kind of worksharing directive is emitted without outer loop.906/// \param ScheduleKind Schedule Kind specified in the 'schedule' clause.907///908virtual bool isDynamic(OpenMPScheduleClauseKind ScheduleKind) const;909910/// struct with the values to be passed to the dispatch runtime function911struct DispatchRTInput {912/// Loop lower bound913llvm::Value *LB = nullptr;914/// Loop upper bound915llvm::Value *UB = nullptr;916/// Chunk size specified using 'schedule' clause (nullptr if chunk917/// was not specified)918llvm::Value *Chunk = nullptr;919DispatchRTInput() = default;920DispatchRTInput(llvm::Value *LB, llvm::Value *UB, llvm::Value *Chunk)921: LB(LB), UB(UB), Chunk(Chunk) {}922};923924/// Call the appropriate runtime routine to initialize it before start925/// of loop.926927/// This is used for non static scheduled types and when the ordered928/// clause is present on the loop construct.929/// Depending on the loop schedule, it is necessary to call some runtime930/// routine before start of the OpenMP loop to get the loop upper / lower931/// bounds \a LB and \a UB and stride \a ST.932///933/// \param CGF Reference to current CodeGenFunction.934/// \param Loc Clang source location.935/// \param ScheduleKind Schedule kind, specified by the 'schedule' clause.936/// \param IVSize Size of the iteration variable in bits.937/// \param IVSigned Sign of the iteration variable.938/// \param Ordered true if loop is ordered, false otherwise.939/// \param DispatchValues struct containing llvm values for lower bound, upper940/// bound, and chunk expression.941/// For the default (nullptr) value, the chunk 1 will be used.942///943virtual void emitForDispatchInit(CodeGenFunction &CGF, SourceLocation Loc,944const OpenMPScheduleTy &ScheduleKind,945unsigned IVSize, bool IVSigned, bool Ordered,946const DispatchRTInput &DispatchValues);947948/// This is used for non static scheduled types and when the ordered949/// clause is present on the loop construct.950///951/// \param CGF Reference to current CodeGenFunction.952/// \param Loc Clang source location.953///954virtual void emitForDispatchDeinit(CodeGenFunction &CGF, SourceLocation Loc);955956/// Struct with the values to be passed to the static runtime function957struct StaticRTInput {958/// Size of the iteration variable in bits.959unsigned IVSize = 0;960/// Sign of the iteration variable.961bool IVSigned = false;962/// true if loop is ordered, false otherwise.963bool Ordered = false;964/// Address of the output variable in which the flag of the last iteration965/// is returned.966Address IL = Address::invalid();967/// Address of the output variable in which the lower iteration number is968/// returned.969Address LB = Address::invalid();970/// Address of the output variable in which the upper iteration number is971/// returned.972Address UB = Address::invalid();973/// Address of the output variable in which the stride value is returned974/// necessary to generated the static_chunked scheduled loop.975Address ST = Address::invalid();976/// Value of the chunk for the static_chunked scheduled loop. For the977/// default (nullptr) value, the chunk 1 will be used.978llvm::Value *Chunk = nullptr;979StaticRTInput(unsigned IVSize, bool IVSigned, bool Ordered, Address IL,980Address LB, Address UB, Address ST,981llvm::Value *Chunk = nullptr)982: IVSize(IVSize), IVSigned(IVSigned), Ordered(Ordered), IL(IL), LB(LB),983UB(UB), ST(ST), Chunk(Chunk) {}984};985/// Call the appropriate runtime routine to initialize it before start986/// of loop.987///988/// This is used only in case of static schedule, when the user did not989/// specify a ordered clause on the loop construct.990/// Depending on the loop schedule, it is necessary to call some runtime991/// routine before start of the OpenMP loop to get the loop upper / lower992/// bounds LB and UB and stride ST.993///994/// \param CGF Reference to current CodeGenFunction.995/// \param Loc Clang source location.996/// \param DKind Kind of the directive.997/// \param ScheduleKind Schedule kind, specified by the 'schedule' clause.998/// \param Values Input arguments for the construct.999///1000virtual void emitForStaticInit(CodeGenFunction &CGF, SourceLocation Loc,1001OpenMPDirectiveKind DKind,1002const OpenMPScheduleTy &ScheduleKind,1003const StaticRTInput &Values);10041005///1006/// \param CGF Reference to current CodeGenFunction.1007/// \param Loc Clang source location.1008/// \param SchedKind Schedule kind, specified by the 'dist_schedule' clause.1009/// \param Values Input arguments for the construct.1010///1011virtual void emitDistributeStaticInit(CodeGenFunction &CGF,1012SourceLocation Loc,1013OpenMPDistScheduleClauseKind SchedKind,1014const StaticRTInput &Values);10151016/// Call the appropriate runtime routine to notify that we finished1017/// iteration of the ordered loop with the dynamic scheduling.1018///1019/// \param CGF Reference to current CodeGenFunction.1020/// \param Loc Clang source location.1021/// \param IVSize Size of the iteration variable in bits.1022/// \param IVSigned Sign of the iteration variable.1023///1024virtual void emitForOrderedIterationEnd(CodeGenFunction &CGF,1025SourceLocation Loc, unsigned IVSize,1026bool IVSigned);10271028/// Call the appropriate runtime routine to notify that we finished1029/// all the work with current loop.1030///1031/// \param CGF Reference to current CodeGenFunction.1032/// \param Loc Clang source location.1033/// \param DKind Kind of the directive for which the static finish is emitted.1034///1035virtual void emitForStaticFinish(CodeGenFunction &CGF, SourceLocation Loc,1036OpenMPDirectiveKind DKind);10371038/// Call __kmpc_dispatch_next(1039/// ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,1040/// kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,1041/// kmp_int[32|64] *p_stride);1042/// \param IVSize Size of the iteration variable in bits.1043/// \param IVSigned Sign of the iteration variable.1044/// \param IL Address of the output variable in which the flag of the1045/// last iteration is returned.1046/// \param LB Address of the output variable in which the lower iteration1047/// number is returned.1048/// \param UB Address of the output variable in which the upper iteration1049/// number is returned.1050/// \param ST Address of the output variable in which the stride value is1051/// returned.1052virtual llvm::Value *emitForNext(CodeGenFunction &CGF, SourceLocation Loc,1053unsigned IVSize, bool IVSigned,1054Address IL, Address LB,1055Address UB, Address ST);10561057/// Emits call to void __kmpc_push_num_threads(ident_t *loc, kmp_int321058/// global_tid, kmp_int32 num_threads) to generate code for 'num_threads'1059/// clause.1060/// \param NumThreads An integer value of threads.1061virtual void emitNumThreadsClause(CodeGenFunction &CGF,1062llvm::Value *NumThreads,1063SourceLocation Loc);10641065/// Emit call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int321066/// global_tid, int proc_bind) to generate code for 'proc_bind' clause.1067virtual void emitProcBindClause(CodeGenFunction &CGF,1068llvm::omp::ProcBindKind ProcBind,1069SourceLocation Loc);10701071/// Returns address of the threadprivate variable for the current1072/// thread.1073/// \param VD Threadprivate variable.1074/// \param VDAddr Address of the global variable \a VD.1075/// \param Loc Location of the reference to threadprivate var.1076/// \return Address of the threadprivate variable for the current thread.1077virtual Address getAddrOfThreadPrivate(CodeGenFunction &CGF,1078const VarDecl *VD, Address VDAddr,1079SourceLocation Loc);10801081/// Returns the address of the variable marked as declare target with link1082/// clause OR as declare target with to clause and unified memory.1083virtual ConstantAddress getAddrOfDeclareTargetVar(const VarDecl *VD);10841085/// Emit a code for initialization of threadprivate variable. It emits1086/// a call to runtime library which adds initial value to the newly created1087/// threadprivate variable (if it is not constant) and registers destructor1088/// for the variable (if any).1089/// \param VD Threadprivate variable.1090/// \param VDAddr Address of the global variable \a VD.1091/// \param Loc Location of threadprivate declaration.1092/// \param PerformInit true if initialization expression is not constant.1093virtual llvm::Function *1094emitThreadPrivateVarDefinition(const VarDecl *VD, Address VDAddr,1095SourceLocation Loc, bool PerformInit,1096CodeGenFunction *CGF = nullptr);10971098/// Emit code for handling declare target functions in the runtime.1099/// \param FD Declare target function.1100/// \param Addr Address of the global \a FD.1101/// \param PerformInit true if initialization expression is not constant.1102virtual void emitDeclareTargetFunction(const FunctionDecl *FD,1103llvm::GlobalValue *GV);11041105/// Creates artificial threadprivate variable with name \p Name and type \p1106/// VarType.1107/// \param VarType Type of the artificial threadprivate variable.1108/// \param Name Name of the artificial threadprivate variable.1109virtual Address getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,1110QualType VarType,1111StringRef Name);11121113/// Emit flush of the variables specified in 'omp flush' directive.1114/// \param Vars List of variables to flush.1115virtual void emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *> Vars,1116SourceLocation Loc, llvm::AtomicOrdering AO);11171118/// Emit task region for the task directive. The task region is1119/// emitted in several steps:1120/// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int321121/// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,1122/// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the1123/// function:1124/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {1125/// TaskFunction(gtid, tt->part_id, tt->shareds);1126/// return 0;1127/// }1128/// 2. Copy a list of shared variables to field shareds of the resulting1129/// structure kmp_task_t returned by the previous call (if any).1130/// 3. Copy a pointer to destructions function to field destructions of the1131/// resulting structure kmp_task_t.1132/// 4. Emit a call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid,1133/// kmp_task_t *new_task), where new_task is a resulting structure from1134/// previous items.1135/// \param D Current task directive.1136/// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i321137/// /*part_id*/, captured_struct */*__context*/);1138/// \param SharedsTy A type which contains references the shared variables.1139/// \param Shareds Context with the list of shared variables from the \p1140/// TaskFunction.1141/// \param IfCond Not a nullptr if 'if' clause was specified, nullptr1142/// otherwise.1143/// \param Data Additional data for task generation like tiednsee, final1144/// state, list of privates etc.1145virtual void emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,1146const OMPExecutableDirective &D,1147llvm::Function *TaskFunction, QualType SharedsTy,1148Address Shareds, const Expr *IfCond,1149const OMPTaskDataTy &Data);11501151/// Emit task region for the taskloop directive. The taskloop region is1152/// emitted in several steps:1153/// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int321154/// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,1155/// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the1156/// function:1157/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {1158/// TaskFunction(gtid, tt->part_id, tt->shareds);1159/// return 0;1160/// }1161/// 2. Copy a list of shared variables to field shareds of the resulting1162/// structure kmp_task_t returned by the previous call (if any).1163/// 3. Copy a pointer to destructions function to field destructions of the1164/// resulting structure kmp_task_t.1165/// 4. Emit a call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t1166/// *task, int if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int1167/// nogroup, int sched, kmp_uint64 grainsize, void *task_dup ), where new_task1168/// is a resulting structure from1169/// previous items.1170/// \param D Current task directive.1171/// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i321172/// /*part_id*/, captured_struct */*__context*/);1173/// \param SharedsTy A type which contains references the shared variables.1174/// \param Shareds Context with the list of shared variables from the \p1175/// TaskFunction.1176/// \param IfCond Not a nullptr if 'if' clause was specified, nullptr1177/// otherwise.1178/// \param Data Additional data for task generation like tiednsee, final1179/// state, list of privates etc.1180virtual void emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,1181const OMPLoopDirective &D,1182llvm::Function *TaskFunction,1183QualType SharedsTy, Address Shareds,1184const Expr *IfCond, const OMPTaskDataTy &Data);11851186/// Emit code for the directive that does not require outlining.1187///1188/// \param InnermostKind Kind of innermost directive (for simple directives it1189/// is a directive itself, for combined - its innermost directive).1190/// \param CodeGen Code generation sequence for the \a D directive.1191/// \param HasCancel true if region has inner cancel directive, false1192/// otherwise.1193virtual void emitInlinedDirective(CodeGenFunction &CGF,1194OpenMPDirectiveKind InnermostKind,1195const RegionCodeGenTy &CodeGen,1196bool HasCancel = false);11971198/// Emits reduction function.1199/// \param ReducerName Name of the function calling the reduction.1200/// \param ArgsElemType Array type containing pointers to reduction variables.1201/// \param Privates List of private copies for original reduction arguments.1202/// \param LHSExprs List of LHS in \a ReductionOps reduction operations.1203/// \param RHSExprs List of RHS in \a ReductionOps reduction operations.1204/// \param ReductionOps List of reduction operations in form 'LHS binop RHS'1205/// or 'operator binop(LHS, RHS)'.1206llvm::Function *emitReductionFunction(1207StringRef ReducerName, SourceLocation Loc, llvm::Type *ArgsElemType,1208ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> LHSExprs,1209ArrayRef<const Expr *> RHSExprs, ArrayRef<const Expr *> ReductionOps);12101211/// Emits single reduction combiner1212void emitSingleReductionCombiner(CodeGenFunction &CGF,1213const Expr *ReductionOp,1214const Expr *PrivateRef,1215const DeclRefExpr *LHS,1216const DeclRefExpr *RHS);12171218struct ReductionOptionsTy {1219bool WithNowait;1220bool SimpleReduction;1221OpenMPDirectiveKind ReductionKind;1222};1223/// Emit a code for reduction clause. Next code should be emitted for1224/// reduction:1225/// \code1226///1227/// static kmp_critical_name lock = { 0 };1228///1229/// void reduce_func(void *lhs[<n>], void *rhs[<n>]) {1230/// ...1231/// *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);1232/// ...1233/// }1234///1235/// ...1236/// void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};1237/// switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),1238/// RedList, reduce_func, &<lock>)) {1239/// case 1:1240/// ...1241/// <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);1242/// ...1243/// __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);1244/// break;1245/// case 2:1246/// ...1247/// Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));1248/// ...1249/// break;1250/// default:;1251/// }1252/// \endcode1253///1254/// \param Privates List of private copies for original reduction arguments.1255/// \param LHSExprs List of LHS in \a ReductionOps reduction operations.1256/// \param RHSExprs List of RHS in \a ReductionOps reduction operations.1257/// \param ReductionOps List of reduction operations in form 'LHS binop RHS'1258/// or 'operator binop(LHS, RHS)'.1259/// \param Options List of options for reduction codegen:1260/// WithNowait true if parent directive has also nowait clause, false1261/// otherwise.1262/// SimpleReduction Emit reduction operation only. Used for omp simd1263/// directive on the host.1264/// ReductionKind The kind of reduction to perform.1265virtual void emitReduction(CodeGenFunction &CGF, SourceLocation Loc,1266ArrayRef<const Expr *> Privates,1267ArrayRef<const Expr *> LHSExprs,1268ArrayRef<const Expr *> RHSExprs,1269ArrayRef<const Expr *> ReductionOps,1270ReductionOptionsTy Options);12711272/// Emit a code for initialization of task reduction clause. Next code1273/// should be emitted for reduction:1274/// \code1275///1276/// _taskred_item_t red_data[n];1277/// ...1278/// red_data[i].shar = &shareds[i];1279/// red_data[i].orig = &origs[i];1280/// red_data[i].size = sizeof(origs[i]);1281/// red_data[i].f_init = (void*)RedInit<i>;1282/// red_data[i].f_fini = (void*)RedDest<i>;1283/// red_data[i].f_comb = (void*)RedOp<i>;1284/// red_data[i].flags = <Flag_i>;1285/// ...1286/// void* tg1 = __kmpc_taskred_init(gtid, n, red_data);1287/// \endcode1288/// For reduction clause with task modifier it emits the next call:1289/// \code1290///1291/// _taskred_item_t red_data[n];1292/// ...1293/// red_data[i].shar = &shareds[i];1294/// red_data[i].orig = &origs[i];1295/// red_data[i].size = sizeof(origs[i]);1296/// red_data[i].f_init = (void*)RedInit<i>;1297/// red_data[i].f_fini = (void*)RedDest<i>;1298/// red_data[i].f_comb = (void*)RedOp<i>;1299/// red_data[i].flags = <Flag_i>;1300/// ...1301/// void* tg1 = __kmpc_taskred_modifier_init(loc, gtid, is_worksharing, n,1302/// red_data);1303/// \endcode1304/// \param LHSExprs List of LHS in \a Data.ReductionOps reduction operations.1305/// \param RHSExprs List of RHS in \a Data.ReductionOps reduction operations.1306/// \param Data Additional data for task generation like tiedness, final1307/// state, list of privates, reductions etc.1308virtual llvm::Value *emitTaskReductionInit(CodeGenFunction &CGF,1309SourceLocation Loc,1310ArrayRef<const Expr *> LHSExprs,1311ArrayRef<const Expr *> RHSExprs,1312const OMPTaskDataTy &Data);13131314/// Emits the following code for reduction clause with task modifier:1315/// \code1316/// __kmpc_task_reduction_modifier_fini(loc, gtid, is_worksharing);1317/// \endcode1318virtual void emitTaskReductionFini(CodeGenFunction &CGF, SourceLocation Loc,1319bool IsWorksharingReduction);13201321/// Required to resolve existing problems in the runtime. Emits threadprivate1322/// variables to store the size of the VLAs/array sections for1323/// initializer/combiner/finalizer functions.1324/// \param RCG Allows to reuse an existing data for the reductions.1325/// \param N Reduction item for which fixups must be emitted.1326virtual void emitTaskReductionFixups(CodeGenFunction &CGF, SourceLocation Loc,1327ReductionCodeGen &RCG, unsigned N);13281329/// Get the address of `void *` type of the privatue copy of the reduction1330/// item specified by the \p SharedLVal.1331/// \param ReductionsPtr Pointer to the reduction data returned by the1332/// emitTaskReductionInit function.1333/// \param SharedLVal Address of the original reduction item.1334virtual Address getTaskReductionItem(CodeGenFunction &CGF, SourceLocation Loc,1335llvm::Value *ReductionsPtr,1336LValue SharedLVal);13371338/// Emit code for 'taskwait' directive.1339virtual void emitTaskwaitCall(CodeGenFunction &CGF, SourceLocation Loc,1340const OMPTaskDataTy &Data);13411342/// Emit code for 'cancellation point' construct.1343/// \param CancelRegion Region kind for which the cancellation point must be1344/// emitted.1345///1346virtual void emitCancellationPointCall(CodeGenFunction &CGF,1347SourceLocation Loc,1348OpenMPDirectiveKind CancelRegion);13491350/// Emit code for 'cancel' construct.1351/// \param IfCond Condition in the associated 'if' clause, if it was1352/// specified, nullptr otherwise.1353/// \param CancelRegion Region kind for which the cancel must be emitted.1354///1355virtual void emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,1356const Expr *IfCond,1357OpenMPDirectiveKind CancelRegion);13581359/// Emit outilined function for 'target' directive.1360/// \param D Directive to emit.1361/// \param ParentName Name of the function that encloses the target region.1362/// \param OutlinedFn Outlined function value to be defined by this call.1363/// \param OutlinedFnID Outlined function ID value to be defined by this call.1364/// \param IsOffloadEntry True if the outlined function is an offload entry.1365/// \param CodeGen Code generation sequence for the \a D directive.1366/// An outlined function may not be an entry if, e.g. the if clause always1367/// evaluates to false.1368virtual void emitTargetOutlinedFunction(const OMPExecutableDirective &D,1369StringRef ParentName,1370llvm::Function *&OutlinedFn,1371llvm::Constant *&OutlinedFnID,1372bool IsOffloadEntry,1373const RegionCodeGenTy &CodeGen);13741375/// Emit the target offloading code associated with \a D. The emitted1376/// code attempts offloading the execution to the device, an the event of1377/// a failure it executes the host version outlined in \a OutlinedFn.1378/// \param D Directive to emit.1379/// \param OutlinedFn Host version of the code to be offloaded.1380/// \param OutlinedFnID ID of host version of the code to be offloaded.1381/// \param IfCond Expression evaluated in if clause associated with the target1382/// directive, or null if no if clause is used.1383/// \param Device Expression evaluated in device clause associated with the1384/// target directive, or null if no device clause is used and device modifier.1385/// \param SizeEmitter Callback to emit number of iterations for loop-based1386/// directives.1387virtual void emitTargetCall(1388CodeGenFunction &CGF, const OMPExecutableDirective &D,1389llvm::Function *OutlinedFn, llvm::Value *OutlinedFnID, const Expr *IfCond,1390llvm::PointerIntPair<const Expr *, 2, OpenMPDeviceClauseModifier> Device,1391llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,1392const OMPLoopDirective &D)>1393SizeEmitter);13941395/// Emit the target regions enclosed in \a GD function definition or1396/// the function itself in case it is a valid device function. Returns true if1397/// \a GD was dealt with successfully.1398/// \param GD Function to scan.1399virtual bool emitTargetFunctions(GlobalDecl GD);14001401/// Emit the global variable if it is a valid device global variable.1402/// Returns true if \a GD was dealt with successfully.1403/// \param GD Variable declaration to emit.1404virtual bool emitTargetGlobalVariable(GlobalDecl GD);14051406/// Checks if the provided global decl \a GD is a declare target variable and1407/// registers it when emitting code for the host.1408virtual void registerTargetGlobalVariable(const VarDecl *VD,1409llvm::Constant *Addr);14101411/// Emit the global \a GD if it is meaningful for the target. Returns1412/// if it was emitted successfully.1413/// \param GD Global to scan.1414virtual bool emitTargetGlobal(GlobalDecl GD);14151416/// Creates all the offload entries in the current compilation unit1417/// along with the associated metadata.1418void createOffloadEntriesAndInfoMetadata();14191420/// Emits code for teams call of the \a OutlinedFn with1421/// variables captured in a record which address is stored in \a1422/// CapturedStruct.1423/// \param OutlinedFn Outlined function to be run by team masters. Type of1424/// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*).1425/// \param CapturedVars A pointer to the record with the references to1426/// variables used in \a OutlinedFn function.1427///1428virtual void emitTeamsCall(CodeGenFunction &CGF,1429const OMPExecutableDirective &D,1430SourceLocation Loc, llvm::Function *OutlinedFn,1431ArrayRef<llvm::Value *> CapturedVars);14321433/// Emits call to void __kmpc_push_num_teams(ident_t *loc, kmp_int321434/// global_tid, kmp_int32 num_teams, kmp_int32 thread_limit) to generate code1435/// for num_teams clause.1436/// \param NumTeams An integer expression of teams.1437/// \param ThreadLimit An integer expression of threads.1438virtual void emitNumTeamsClause(CodeGenFunction &CGF, const Expr *NumTeams,1439const Expr *ThreadLimit, SourceLocation Loc);14401441/// Emits call to void __kmpc_set_thread_limit(ident_t *loc, kmp_int321442/// global_tid, kmp_int32 thread_limit) to generate code for1443/// thread_limit clause on target directive1444/// \param ThreadLimit An integer expression of threads.1445virtual void emitThreadLimitClause(CodeGenFunction &CGF,1446const Expr *ThreadLimit,1447SourceLocation Loc);14481449/// Struct that keeps all the relevant information that should be kept1450/// throughout a 'target data' region.1451class TargetDataInfo : public llvm::OpenMPIRBuilder::TargetDataInfo {1452public:1453explicit TargetDataInfo() : llvm::OpenMPIRBuilder::TargetDataInfo() {}1454explicit TargetDataInfo(bool RequiresDevicePointerInfo,1455bool SeparateBeginEndCalls)1456: llvm::OpenMPIRBuilder::TargetDataInfo(RequiresDevicePointerInfo,1457SeparateBeginEndCalls) {}1458/// Map between the a declaration of a capture and the corresponding new1459/// llvm address where the runtime returns the device pointers.1460llvm::DenseMap<const ValueDecl *, llvm::Value *> CaptureDeviceAddrMap;1461};14621463/// Emit the target data mapping code associated with \a D.1464/// \param D Directive to emit.1465/// \param IfCond Expression evaluated in if clause associated with the1466/// target directive, or null if no device clause is used.1467/// \param Device Expression evaluated in device clause associated with the1468/// target directive, or null if no device clause is used.1469/// \param Info A record used to store information that needs to be preserved1470/// until the region is closed.1471virtual void emitTargetDataCalls(CodeGenFunction &CGF,1472const OMPExecutableDirective &D,1473const Expr *IfCond, const Expr *Device,1474const RegionCodeGenTy &CodeGen,1475CGOpenMPRuntime::TargetDataInfo &Info);14761477/// Emit the data mapping/movement code associated with the directive1478/// \a D that should be of the form 'target [{enter|exit} data | update]'.1479/// \param D Directive to emit.1480/// \param IfCond Expression evaluated in if clause associated with the target1481/// directive, or null if no if clause is used.1482/// \param Device Expression evaluated in device clause associated with the1483/// target directive, or null if no device clause is used.1484virtual void emitTargetDataStandAloneCall(CodeGenFunction &CGF,1485const OMPExecutableDirective &D,1486const Expr *IfCond,1487const Expr *Device);14881489/// Marks function \a Fn with properly mangled versions of vector functions.1490/// \param FD Function marked as 'declare simd'.1491/// \param Fn LLVM function that must be marked with 'declare simd'1492/// attributes.1493virtual void emitDeclareSimdFunction(const FunctionDecl *FD,1494llvm::Function *Fn);14951496/// Emit initialization for doacross loop nesting support.1497/// \param D Loop-based construct used in doacross nesting construct.1498virtual void emitDoacrossInit(CodeGenFunction &CGF, const OMPLoopDirective &D,1499ArrayRef<Expr *> NumIterations);15001501/// Emit code for doacross ordered directive with 'depend' clause.1502/// \param C 'depend' clause with 'sink|source' dependency kind.1503virtual void emitDoacrossOrdered(CodeGenFunction &CGF,1504const OMPDependClause *C);15051506/// Emit code for doacross ordered directive with 'doacross' clause.1507/// \param C 'doacross' clause with 'sink|source' dependence type.1508virtual void emitDoacrossOrdered(CodeGenFunction &CGF,1509const OMPDoacrossClause *C);15101511/// Translates the native parameter of outlined function if this is required1512/// for target.1513/// \param FD Field decl from captured record for the parameter.1514/// \param NativeParam Parameter itself.1515virtual const VarDecl *translateParameter(const FieldDecl *FD,1516const VarDecl *NativeParam) const {1517return NativeParam;1518}15191520/// Gets the address of the native argument basing on the address of the1521/// target-specific parameter.1522/// \param NativeParam Parameter itself.1523/// \param TargetParam Corresponding target-specific parameter.1524virtual Address getParameterAddress(CodeGenFunction &CGF,1525const VarDecl *NativeParam,1526const VarDecl *TargetParam) const;15271528/// Choose default schedule type and chunk value for the1529/// dist_schedule clause.1530virtual void getDefaultDistScheduleAndChunk(CodeGenFunction &CGF,1531const OMPLoopDirective &S, OpenMPDistScheduleClauseKind &ScheduleKind,1532llvm::Value *&Chunk) const {}15331534/// Choose default schedule type and chunk value for the1535/// schedule clause.1536virtual void getDefaultScheduleAndChunk(CodeGenFunction &CGF,1537const OMPLoopDirective &S, OpenMPScheduleClauseKind &ScheduleKind,1538const Expr *&ChunkExpr) const;15391540/// Emits call of the outlined function with the provided arguments,1541/// translating these arguments to correct target-specific arguments.1542virtual void1543emitOutlinedFunctionCall(CodeGenFunction &CGF, SourceLocation Loc,1544llvm::FunctionCallee OutlinedFn,1545ArrayRef<llvm::Value *> Args = std::nullopt) const;15461547/// Emits OpenMP-specific function prolog.1548/// Required for device constructs.1549virtual void emitFunctionProlog(CodeGenFunction &CGF, const Decl *D);15501551/// Gets the OpenMP-specific address of the local variable.1552virtual Address getAddressOfLocalVariable(CodeGenFunction &CGF,1553const VarDecl *VD);15541555/// Marks the declaration as already emitted for the device code and returns1556/// true, if it was marked already, and false, otherwise.1557bool markAsGlobalTarget(GlobalDecl GD);15581559/// Emit deferred declare target variables marked for deferred emission.1560void emitDeferredTargetDecls() const;15611562/// Adjust some parameters for the target-based directives, like addresses of1563/// the variables captured by reference in lambdas.1564virtual void1565adjustTargetSpecificDataForLambdas(CodeGenFunction &CGF,1566const OMPExecutableDirective &D) const;15671568/// Perform check on requires decl to ensure that target architecture1569/// supports unified addressing1570virtual void processRequiresDirective(const OMPRequiresDecl *D);15711572/// Gets default memory ordering as specified in requires directive.1573llvm::AtomicOrdering getDefaultMemoryOrdering() const;15741575/// Checks if the variable has associated OMPAllocateDeclAttr attribute with1576/// the predefined allocator and translates it into the corresponding address1577/// space.1578virtual bool hasAllocateAttributeForGlobalVar(const VarDecl *VD, LangAS &AS);15791580/// Return whether the unified_shared_memory has been specified.1581bool hasRequiresUnifiedSharedMemory() const;15821583/// Checks if the \p VD variable is marked as nontemporal declaration in1584/// current context.1585bool isNontemporalDecl(const ValueDecl *VD) const;15861587/// Create specialized alloca to handle lastprivate conditionals.1588Address emitLastprivateConditionalInit(CodeGenFunction &CGF,1589const VarDecl *VD);15901591/// Checks if the provided \p LVal is lastprivate conditional and emits the1592/// code to update the value of the original variable.1593/// \code1594/// lastprivate(conditional: a)1595/// ...1596/// <type> a;1597/// lp_a = ...;1598/// #pragma omp critical(a)1599/// if (last_iv_a <= iv) {1600/// last_iv_a = iv;1601/// global_a = lp_a;1602/// }1603/// \endcode1604virtual void checkAndEmitLastprivateConditional(CodeGenFunction &CGF,1605const Expr *LHS);16061607/// Checks if the lastprivate conditional was updated in inner region and1608/// writes the value.1609/// \code1610/// lastprivate(conditional: a)1611/// ...1612/// <type> a;bool Fired = false;1613/// #pragma omp ... shared(a)1614/// {1615/// lp_a = ...;1616/// Fired = true;1617/// }1618/// if (Fired) {1619/// #pragma omp critical(a)1620/// if (last_iv_a <= iv) {1621/// last_iv_a = iv;1622/// global_a = lp_a;1623/// }1624/// Fired = false;1625/// }1626/// \endcode1627virtual void checkAndEmitSharedLastprivateConditional(1628CodeGenFunction &CGF, const OMPExecutableDirective &D,1629const llvm::DenseSet<CanonicalDeclPtr<const VarDecl>> &IgnoredDecls);16301631/// Gets the address of the global copy used for lastprivate conditional1632/// update, if any.1633/// \param PrivLVal LValue for the private copy.1634/// \param VD Original lastprivate declaration.1635virtual void emitLastprivateConditionalFinalUpdate(CodeGenFunction &CGF,1636LValue PrivLVal,1637const VarDecl *VD,1638SourceLocation Loc);16391640/// Emits list of dependecies based on the provided data (array of1641/// dependence/expression pairs).1642/// \returns Pointer to the first element of the array casted to VoidPtr type.1643std::pair<llvm::Value *, Address>1644emitDependClause(CodeGenFunction &CGF,1645ArrayRef<OMPTaskDataTy::DependData> Dependencies,1646SourceLocation Loc);16471648/// Emits list of dependecies based on the provided data (array of1649/// dependence/expression pairs) for depobj construct. In this case, the1650/// variable is allocated in dynamically. \returns Pointer to the first1651/// element of the array casted to VoidPtr type.1652Address emitDepobjDependClause(CodeGenFunction &CGF,1653const OMPTaskDataTy::DependData &Dependencies,1654SourceLocation Loc);16551656/// Emits the code to destroy the dependency object provided in depobj1657/// directive.1658void emitDestroyClause(CodeGenFunction &CGF, LValue DepobjLVal,1659SourceLocation Loc);16601661/// Updates the dependency kind in the specified depobj object.1662/// \param DepobjLVal LValue for the main depobj object.1663/// \param NewDepKind New dependency kind.1664void emitUpdateClause(CodeGenFunction &CGF, LValue DepobjLVal,1665OpenMPDependClauseKind NewDepKind, SourceLocation Loc);16661667/// Initializes user defined allocators specified in the uses_allocators1668/// clauses.1669void emitUsesAllocatorsInit(CodeGenFunction &CGF, const Expr *Allocator,1670const Expr *AllocatorTraits);16711672/// Destroys user defined allocators specified in the uses_allocators clause.1673void emitUsesAllocatorsFini(CodeGenFunction &CGF, const Expr *Allocator);16741675/// Returns true if the variable is a local variable in untied task.1676bool isLocalVarInUntiedTask(CodeGenFunction &CGF, const VarDecl *VD) const;1677};16781679/// Class supports emissionof SIMD-only code.1680class CGOpenMPSIMDRuntime final : public CGOpenMPRuntime {1681public:1682explicit CGOpenMPSIMDRuntime(CodeGenModule &CGM) : CGOpenMPRuntime(CGM) {}1683~CGOpenMPSIMDRuntime() override {}16841685/// Emits outlined function for the specified OpenMP parallel directive1686/// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID,1687/// kmp_int32 BoundID, struct context_vars*).1688/// \param CGF Reference to current CodeGenFunction.1689/// \param D OpenMP directive.1690/// \param ThreadIDVar Variable for thread id in the current OpenMP region.1691/// \param InnermostKind Kind of innermost directive (for simple directives it1692/// is a directive itself, for combined - its innermost directive).1693/// \param CodeGen Code generation sequence for the \a D directive.1694llvm::Function *emitParallelOutlinedFunction(1695CodeGenFunction &CGF, const OMPExecutableDirective &D,1696const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,1697const RegionCodeGenTy &CodeGen) override;16981699/// Emits outlined function for the specified OpenMP teams directive1700/// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID,1701/// kmp_int32 BoundID, struct context_vars*).1702/// \param CGF Reference to current CodeGenFunction.1703/// \param D OpenMP directive.1704/// \param ThreadIDVar Variable for thread id in the current OpenMP region.1705/// \param InnermostKind Kind of innermost directive (for simple directives it1706/// is a directive itself, for combined - its innermost directive).1707/// \param CodeGen Code generation sequence for the \a D directive.1708llvm::Function *emitTeamsOutlinedFunction(1709CodeGenFunction &CGF, const OMPExecutableDirective &D,1710const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,1711const RegionCodeGenTy &CodeGen) override;17121713/// Emits outlined function for the OpenMP task directive \a D. This1714/// outlined function has type void(*)(kmp_int32 ThreadID, struct task_t*1715/// TaskT).1716/// \param D OpenMP directive.1717/// \param ThreadIDVar Variable for thread id in the current OpenMP region.1718/// \param PartIDVar Variable for partition id in the current OpenMP untied1719/// task region.1720/// \param TaskTVar Variable for task_t argument.1721/// \param InnermostKind Kind of innermost directive (for simple directives it1722/// is a directive itself, for combined - its innermost directive).1723/// \param CodeGen Code generation sequence for the \a D directive.1724/// \param Tied true if task is generated for tied task, false otherwise.1725/// \param NumberOfParts Number of parts in untied task. Ignored for tied1726/// tasks.1727///1728llvm::Function *emitTaskOutlinedFunction(1729const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,1730const VarDecl *PartIDVar, const VarDecl *TaskTVar,1731OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,1732bool Tied, unsigned &NumberOfParts) override;17331734/// Emits code for parallel or serial call of the \a OutlinedFn with1735/// variables captured in a record which address is stored in \a1736/// CapturedStruct.1737/// \param OutlinedFn Outlined function to be run in parallel threads. Type of1738/// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*).1739/// \param CapturedVars A pointer to the record with the references to1740/// variables used in \a OutlinedFn function.1741/// \param IfCond Condition in the associated 'if' clause, if it was1742/// specified, nullptr otherwise.1743/// \param NumThreads The value corresponding to the num_threads clause, if1744/// any, or nullptr.1745///1746void emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,1747llvm::Function *OutlinedFn,1748ArrayRef<llvm::Value *> CapturedVars,1749const Expr *IfCond, llvm::Value *NumThreads) override;17501751/// Emits a critical region.1752/// \param CriticalName Name of the critical region.1753/// \param CriticalOpGen Generator for the statement associated with the given1754/// critical region.1755/// \param Hint Value of the 'hint' clause (optional).1756void emitCriticalRegion(CodeGenFunction &CGF, StringRef CriticalName,1757const RegionCodeGenTy &CriticalOpGen,1758SourceLocation Loc,1759const Expr *Hint = nullptr) override;17601761/// Emits a master region.1762/// \param MasterOpGen Generator for the statement associated with the given1763/// master region.1764void emitMasterRegion(CodeGenFunction &CGF,1765const RegionCodeGenTy &MasterOpGen,1766SourceLocation Loc) override;17671768/// Emits a masked region.1769/// \param MaskedOpGen Generator for the statement associated with the given1770/// masked region.1771void emitMaskedRegion(CodeGenFunction &CGF,1772const RegionCodeGenTy &MaskedOpGen, SourceLocation Loc,1773const Expr *Filter = nullptr) override;17741775/// Emits a masked region.1776/// \param MaskedOpGen Generator for the statement associated with the given1777/// masked region.17781779/// Emits code for a taskyield directive.1780void emitTaskyieldCall(CodeGenFunction &CGF, SourceLocation Loc) override;17811782/// Emit a taskgroup region.1783/// \param TaskgroupOpGen Generator for the statement associated with the1784/// given taskgroup region.1785void emitTaskgroupRegion(CodeGenFunction &CGF,1786const RegionCodeGenTy &TaskgroupOpGen,1787SourceLocation Loc) override;17881789/// Emits a single region.1790/// \param SingleOpGen Generator for the statement associated with the given1791/// single region.1792void emitSingleRegion(CodeGenFunction &CGF,1793const RegionCodeGenTy &SingleOpGen, SourceLocation Loc,1794ArrayRef<const Expr *> CopyprivateVars,1795ArrayRef<const Expr *> DestExprs,1796ArrayRef<const Expr *> SrcExprs,1797ArrayRef<const Expr *> AssignmentOps) override;17981799/// Emit an ordered region.1800/// \param OrderedOpGen Generator for the statement associated with the given1801/// ordered region.1802void emitOrderedRegion(CodeGenFunction &CGF,1803const RegionCodeGenTy &OrderedOpGen,1804SourceLocation Loc, bool IsThreads) override;18051806/// Emit an implicit/explicit barrier for OpenMP threads.1807/// \param Kind Directive for which this implicit barrier call must be1808/// generated. Must be OMPD_barrier for explicit barrier generation.1809/// \param EmitChecks true if need to emit checks for cancellation barriers.1810/// \param ForceSimpleCall true simple barrier call must be emitted, false if1811/// runtime class decides which one to emit (simple or with cancellation1812/// checks).1813///1814void emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,1815OpenMPDirectiveKind Kind, bool EmitChecks = true,1816bool ForceSimpleCall = false) override;18171818/// This is used for non static scheduled types and when the ordered1819/// clause is present on the loop construct.1820/// Depending on the loop schedule, it is necessary to call some runtime1821/// routine before start of the OpenMP loop to get the loop upper / lower1822/// bounds \a LB and \a UB and stride \a ST.1823///1824/// \param CGF Reference to current CodeGenFunction.1825/// \param Loc Clang source location.1826/// \param ScheduleKind Schedule kind, specified by the 'schedule' clause.1827/// \param IVSize Size of the iteration variable in bits.1828/// \param IVSigned Sign of the iteration variable.1829/// \param Ordered true if loop is ordered, false otherwise.1830/// \param DispatchValues struct containing llvm values for lower bound, upper1831/// bound, and chunk expression.1832/// For the default (nullptr) value, the chunk 1 will be used.1833///1834void emitForDispatchInit(CodeGenFunction &CGF, SourceLocation Loc,1835const OpenMPScheduleTy &ScheduleKind,1836unsigned IVSize, bool IVSigned, bool Ordered,1837const DispatchRTInput &DispatchValues) override;18381839/// This is used for non static scheduled types and when the ordered1840/// clause is present on the loop construct.1841///1842/// \param CGF Reference to current CodeGenFunction.1843/// \param Loc Clang source location.1844///1845void emitForDispatchDeinit(CodeGenFunction &CGF, SourceLocation Loc) override;18461847/// Call the appropriate runtime routine to initialize it before start1848/// of loop.1849///1850/// This is used only in case of static schedule, when the user did not1851/// specify a ordered clause on the loop construct.1852/// Depending on the loop schedule, it is necessary to call some runtime1853/// routine before start of the OpenMP loop to get the loop upper / lower1854/// bounds LB and UB and stride ST.1855///1856/// \param CGF Reference to current CodeGenFunction.1857/// \param Loc Clang source location.1858/// \param DKind Kind of the directive.1859/// \param ScheduleKind Schedule kind, specified by the 'schedule' clause.1860/// \param Values Input arguments for the construct.1861///1862void emitForStaticInit(CodeGenFunction &CGF, SourceLocation Loc,1863OpenMPDirectiveKind DKind,1864const OpenMPScheduleTy &ScheduleKind,1865const StaticRTInput &Values) override;18661867///1868/// \param CGF Reference to current CodeGenFunction.1869/// \param Loc Clang source location.1870/// \param SchedKind Schedule kind, specified by the 'dist_schedule' clause.1871/// \param Values Input arguments for the construct.1872///1873void emitDistributeStaticInit(CodeGenFunction &CGF, SourceLocation Loc,1874OpenMPDistScheduleClauseKind SchedKind,1875const StaticRTInput &Values) override;18761877/// Call the appropriate runtime routine to notify that we finished1878/// iteration of the ordered loop with the dynamic scheduling.1879///1880/// \param CGF Reference to current CodeGenFunction.1881/// \param Loc Clang source location.1882/// \param IVSize Size of the iteration variable in bits.1883/// \param IVSigned Sign of the iteration variable.1884///1885void emitForOrderedIterationEnd(CodeGenFunction &CGF, SourceLocation Loc,1886unsigned IVSize, bool IVSigned) override;18871888/// Call the appropriate runtime routine to notify that we finished1889/// all the work with current loop.1890///1891/// \param CGF Reference to current CodeGenFunction.1892/// \param Loc Clang source location.1893/// \param DKind Kind of the directive for which the static finish is emitted.1894///1895void emitForStaticFinish(CodeGenFunction &CGF, SourceLocation Loc,1896OpenMPDirectiveKind DKind) override;18971898/// Call __kmpc_dispatch_next(1899/// ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,1900/// kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,1901/// kmp_int[32|64] *p_stride);1902/// \param IVSize Size of the iteration variable in bits.1903/// \param IVSigned Sign of the iteration variable.1904/// \param IL Address of the output variable in which the flag of the1905/// last iteration is returned.1906/// \param LB Address of the output variable in which the lower iteration1907/// number is returned.1908/// \param UB Address of the output variable in which the upper iteration1909/// number is returned.1910/// \param ST Address of the output variable in which the stride value is1911/// returned.1912llvm::Value *emitForNext(CodeGenFunction &CGF, SourceLocation Loc,1913unsigned IVSize, bool IVSigned, Address IL,1914Address LB, Address UB, Address ST) override;19151916/// Emits call to void __kmpc_push_num_threads(ident_t *loc, kmp_int321917/// global_tid, kmp_int32 num_threads) to generate code for 'num_threads'1918/// clause.1919/// \param NumThreads An integer value of threads.1920void emitNumThreadsClause(CodeGenFunction &CGF, llvm::Value *NumThreads,1921SourceLocation Loc) override;19221923/// Emit call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int321924/// global_tid, int proc_bind) to generate code for 'proc_bind' clause.1925void emitProcBindClause(CodeGenFunction &CGF,1926llvm::omp::ProcBindKind ProcBind,1927SourceLocation Loc) override;19281929/// Returns address of the threadprivate variable for the current1930/// thread.1931/// \param VD Threadprivate variable.1932/// \param VDAddr Address of the global variable \a VD.1933/// \param Loc Location of the reference to threadprivate var.1934/// \return Address of the threadprivate variable for the current thread.1935Address getAddrOfThreadPrivate(CodeGenFunction &CGF, const VarDecl *VD,1936Address VDAddr, SourceLocation Loc) override;19371938/// Emit a code for initialization of threadprivate variable. It emits1939/// a call to runtime library which adds initial value to the newly created1940/// threadprivate variable (if it is not constant) and registers destructor1941/// for the variable (if any).1942/// \param VD Threadprivate variable.1943/// \param VDAddr Address of the global variable \a VD.1944/// \param Loc Location of threadprivate declaration.1945/// \param PerformInit true if initialization expression is not constant.1946llvm::Function *1947emitThreadPrivateVarDefinition(const VarDecl *VD, Address VDAddr,1948SourceLocation Loc, bool PerformInit,1949CodeGenFunction *CGF = nullptr) override;19501951/// Creates artificial threadprivate variable with name \p Name and type \p1952/// VarType.1953/// \param VarType Type of the artificial threadprivate variable.1954/// \param Name Name of the artificial threadprivate variable.1955Address getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,1956QualType VarType,1957StringRef Name) override;19581959/// Emit flush of the variables specified in 'omp flush' directive.1960/// \param Vars List of variables to flush.1961void emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *> Vars,1962SourceLocation Loc, llvm::AtomicOrdering AO) override;19631964/// Emit task region for the task directive. The task region is1965/// emitted in several steps:1966/// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int321967/// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,1968/// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the1969/// function:1970/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {1971/// TaskFunction(gtid, tt->part_id, tt->shareds);1972/// return 0;1973/// }1974/// 2. Copy a list of shared variables to field shareds of the resulting1975/// structure kmp_task_t returned by the previous call (if any).1976/// 3. Copy a pointer to destructions function to field destructions of the1977/// resulting structure kmp_task_t.1978/// 4. Emit a call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid,1979/// kmp_task_t *new_task), where new_task is a resulting structure from1980/// previous items.1981/// \param D Current task directive.1982/// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i321983/// /*part_id*/, captured_struct */*__context*/);1984/// \param SharedsTy A type which contains references the shared variables.1985/// \param Shareds Context with the list of shared variables from the \p1986/// TaskFunction.1987/// \param IfCond Not a nullptr if 'if' clause was specified, nullptr1988/// otherwise.1989/// \param Data Additional data for task generation like tiednsee, final1990/// state, list of privates etc.1991void emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,1992const OMPExecutableDirective &D,1993llvm::Function *TaskFunction, QualType SharedsTy,1994Address Shareds, const Expr *IfCond,1995const OMPTaskDataTy &Data) override;19961997/// Emit task region for the taskloop directive. The taskloop region is1998/// emitted in several steps:1999/// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int322000/// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,2001/// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the2002/// function:2003/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {2004/// TaskFunction(gtid, tt->part_id, tt->shareds);2005/// return 0;2006/// }2007/// 2. Copy a list of shared variables to field shareds of the resulting2008/// structure kmp_task_t returned by the previous call (if any).2009/// 3. Copy a pointer to destructions function to field destructions of the2010/// resulting structure kmp_task_t.2011/// 4. Emit a call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t2012/// *task, int if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int2013/// nogroup, int sched, kmp_uint64 grainsize, void *task_dup ), where new_task2014/// is a resulting structure from2015/// previous items.2016/// \param D Current task directive.2017/// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i322018/// /*part_id*/, captured_struct */*__context*/);2019/// \param SharedsTy A type which contains references the shared variables.2020/// \param Shareds Context with the list of shared variables from the \p2021/// TaskFunction.2022/// \param IfCond Not a nullptr if 'if' clause was specified, nullptr2023/// otherwise.2024/// \param Data Additional data for task generation like tiednsee, final2025/// state, list of privates etc.2026void emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,2027const OMPLoopDirective &D, llvm::Function *TaskFunction,2028QualType SharedsTy, Address Shareds, const Expr *IfCond,2029const OMPTaskDataTy &Data) override;20302031/// Emit a code for reduction clause. Next code should be emitted for2032/// reduction:2033/// \code2034///2035/// static kmp_critical_name lock = { 0 };2036///2037/// void reduce_func(void *lhs[<n>], void *rhs[<n>]) {2038/// ...2039/// *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);2040/// ...2041/// }2042///2043/// ...2044/// void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};2045/// switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),2046/// RedList, reduce_func, &<lock>)) {2047/// case 1:2048/// ...2049/// <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);2050/// ...2051/// __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);2052/// break;2053/// case 2:2054/// ...2055/// Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));2056/// ...2057/// break;2058/// default:;2059/// }2060/// \endcode2061///2062/// \param Privates List of private copies for original reduction arguments.2063/// \param LHSExprs List of LHS in \a ReductionOps reduction operations.2064/// \param RHSExprs List of RHS in \a ReductionOps reduction operations.2065/// \param ReductionOps List of reduction operations in form 'LHS binop RHS'2066/// or 'operator binop(LHS, RHS)'.2067/// \param Options List of options for reduction codegen:2068/// WithNowait true if parent directive has also nowait clause, false2069/// otherwise.2070/// SimpleReduction Emit reduction operation only. Used for omp simd2071/// directive on the host.2072/// ReductionKind The kind of reduction to perform.2073void emitReduction(CodeGenFunction &CGF, SourceLocation Loc,2074ArrayRef<const Expr *> Privates,2075ArrayRef<const Expr *> LHSExprs,2076ArrayRef<const Expr *> RHSExprs,2077ArrayRef<const Expr *> ReductionOps,2078ReductionOptionsTy Options) override;20792080/// Emit a code for initialization of task reduction clause. Next code2081/// should be emitted for reduction:2082/// \code2083///2084/// _taskred_item_t red_data[n];2085/// ...2086/// red_data[i].shar = &shareds[i];2087/// red_data[i].orig = &origs[i];2088/// red_data[i].size = sizeof(origs[i]);2089/// red_data[i].f_init = (void*)RedInit<i>;2090/// red_data[i].f_fini = (void*)RedDest<i>;2091/// red_data[i].f_comb = (void*)RedOp<i>;2092/// red_data[i].flags = <Flag_i>;2093/// ...2094/// void* tg1 = __kmpc_taskred_init(gtid, n, red_data);2095/// \endcode2096/// For reduction clause with task modifier it emits the next call:2097/// \code2098///2099/// _taskred_item_t red_data[n];2100/// ...2101/// red_data[i].shar = &shareds[i];2102/// red_data[i].orig = &origs[i];2103/// red_data[i].size = sizeof(origs[i]);2104/// red_data[i].f_init = (void*)RedInit<i>;2105/// red_data[i].f_fini = (void*)RedDest<i>;2106/// red_data[i].f_comb = (void*)RedOp<i>;2107/// red_data[i].flags = <Flag_i>;2108/// ...2109/// void* tg1 = __kmpc_taskred_modifier_init(loc, gtid, is_worksharing, n,2110/// red_data);2111/// \endcode2112/// \param LHSExprs List of LHS in \a Data.ReductionOps reduction operations.2113/// \param RHSExprs List of RHS in \a Data.ReductionOps reduction operations.2114/// \param Data Additional data for task generation like tiedness, final2115/// state, list of privates, reductions etc.2116llvm::Value *emitTaskReductionInit(CodeGenFunction &CGF, SourceLocation Loc,2117ArrayRef<const Expr *> LHSExprs,2118ArrayRef<const Expr *> RHSExprs,2119const OMPTaskDataTy &Data) override;21202121/// Emits the following code for reduction clause with task modifier:2122/// \code2123/// __kmpc_task_reduction_modifier_fini(loc, gtid, is_worksharing);2124/// \endcode2125void emitTaskReductionFini(CodeGenFunction &CGF, SourceLocation Loc,2126bool IsWorksharingReduction) override;21272128/// Required to resolve existing problems in the runtime. Emits threadprivate2129/// variables to store the size of the VLAs/array sections for2130/// initializer/combiner/finalizer functions + emits threadprivate variable to2131/// store the pointer to the original reduction item for the custom2132/// initializer defined by declare reduction construct.2133/// \param RCG Allows to reuse an existing data for the reductions.2134/// \param N Reduction item for which fixups must be emitted.2135void emitTaskReductionFixups(CodeGenFunction &CGF, SourceLocation Loc,2136ReductionCodeGen &RCG, unsigned N) override;21372138/// Get the address of `void *` type of the privatue copy of the reduction2139/// item specified by the \p SharedLVal.2140/// \param ReductionsPtr Pointer to the reduction data returned by the2141/// emitTaskReductionInit function.2142/// \param SharedLVal Address of the original reduction item.2143Address getTaskReductionItem(CodeGenFunction &CGF, SourceLocation Loc,2144llvm::Value *ReductionsPtr,2145LValue SharedLVal) override;21462147/// Emit code for 'taskwait' directive.2148void emitTaskwaitCall(CodeGenFunction &CGF, SourceLocation Loc,2149const OMPTaskDataTy &Data) override;21502151/// Emit code for 'cancellation point' construct.2152/// \param CancelRegion Region kind for which the cancellation point must be2153/// emitted.2154///2155void emitCancellationPointCall(CodeGenFunction &CGF, SourceLocation Loc,2156OpenMPDirectiveKind CancelRegion) override;21572158/// Emit code for 'cancel' construct.2159/// \param IfCond Condition in the associated 'if' clause, if it was2160/// specified, nullptr otherwise.2161/// \param CancelRegion Region kind for which the cancel must be emitted.2162///2163void emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,2164const Expr *IfCond,2165OpenMPDirectiveKind CancelRegion) override;21662167/// Emit outilined function for 'target' directive.2168/// \param D Directive to emit.2169/// \param ParentName Name of the function that encloses the target region.2170/// \param OutlinedFn Outlined function value to be defined by this call.2171/// \param OutlinedFnID Outlined function ID value to be defined by this call.2172/// \param IsOffloadEntry True if the outlined function is an offload entry.2173/// \param CodeGen Code generation sequence for the \a D directive.2174/// An outlined function may not be an entry if, e.g. the if clause always2175/// evaluates to false.2176void emitTargetOutlinedFunction(const OMPExecutableDirective &D,2177StringRef ParentName,2178llvm::Function *&OutlinedFn,2179llvm::Constant *&OutlinedFnID,2180bool IsOffloadEntry,2181const RegionCodeGenTy &CodeGen) override;21822183/// Emit the target offloading code associated with \a D. The emitted2184/// code attempts offloading the execution to the device, an the event of2185/// a failure it executes the host version outlined in \a OutlinedFn.2186/// \param D Directive to emit.2187/// \param OutlinedFn Host version of the code to be offloaded.2188/// \param OutlinedFnID ID of host version of the code to be offloaded.2189/// \param IfCond Expression evaluated in if clause associated with the target2190/// directive, or null if no if clause is used.2191/// \param Device Expression evaluated in device clause associated with the2192/// target directive, or null if no device clause is used and device modifier.2193void emitTargetCall(2194CodeGenFunction &CGF, const OMPExecutableDirective &D,2195llvm::Function *OutlinedFn, llvm::Value *OutlinedFnID, const Expr *IfCond,2196llvm::PointerIntPair<const Expr *, 2, OpenMPDeviceClauseModifier> Device,2197llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,2198const OMPLoopDirective &D)>2199SizeEmitter) override;22002201/// Emit the target regions enclosed in \a GD function definition or2202/// the function itself in case it is a valid device function. Returns true if2203/// \a GD was dealt with successfully.2204/// \param GD Function to scan.2205bool emitTargetFunctions(GlobalDecl GD) override;22062207/// Emit the global variable if it is a valid device global variable.2208/// Returns true if \a GD was dealt with successfully.2209/// \param GD Variable declaration to emit.2210bool emitTargetGlobalVariable(GlobalDecl GD) override;22112212/// Emit the global \a GD if it is meaningful for the target. Returns2213/// if it was emitted successfully.2214/// \param GD Global to scan.2215bool emitTargetGlobal(GlobalDecl GD) override;22162217/// Emits code for teams call of the \a OutlinedFn with2218/// variables captured in a record which address is stored in \a2219/// CapturedStruct.2220/// \param OutlinedFn Outlined function to be run by team masters. Type of2221/// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*).2222/// \param CapturedVars A pointer to the record with the references to2223/// variables used in \a OutlinedFn function.2224///2225void emitTeamsCall(CodeGenFunction &CGF, const OMPExecutableDirective &D,2226SourceLocation Loc, llvm::Function *OutlinedFn,2227ArrayRef<llvm::Value *> CapturedVars) override;22282229/// Emits call to void __kmpc_push_num_teams(ident_t *loc, kmp_int322230/// global_tid, kmp_int32 num_teams, kmp_int32 thread_limit) to generate code2231/// for num_teams clause.2232/// \param NumTeams An integer expression of teams.2233/// \param ThreadLimit An integer expression of threads.2234void emitNumTeamsClause(CodeGenFunction &CGF, const Expr *NumTeams,2235const Expr *ThreadLimit, SourceLocation Loc) override;22362237/// Emit the target data mapping code associated with \a D.2238/// \param D Directive to emit.2239/// \param IfCond Expression evaluated in if clause associated with the2240/// target directive, or null if no device clause is used.2241/// \param Device Expression evaluated in device clause associated with the2242/// target directive, or null if no device clause is used.2243/// \param Info A record used to store information that needs to be preserved2244/// until the region is closed.2245void emitTargetDataCalls(CodeGenFunction &CGF,2246const OMPExecutableDirective &D, const Expr *IfCond,2247const Expr *Device, const RegionCodeGenTy &CodeGen,2248CGOpenMPRuntime::TargetDataInfo &Info) override;22492250/// Emit the data mapping/movement code associated with the directive2251/// \a D that should be of the form 'target [{enter|exit} data | update]'.2252/// \param D Directive to emit.2253/// \param IfCond Expression evaluated in if clause associated with the target2254/// directive, or null if no if clause is used.2255/// \param Device Expression evaluated in device clause associated with the2256/// target directive, or null if no device clause is used.2257void emitTargetDataStandAloneCall(CodeGenFunction &CGF,2258const OMPExecutableDirective &D,2259const Expr *IfCond,2260const Expr *Device) override;22612262/// Emit initialization for doacross loop nesting support.2263/// \param D Loop-based construct used in doacross nesting construct.2264void emitDoacrossInit(CodeGenFunction &CGF, const OMPLoopDirective &D,2265ArrayRef<Expr *> NumIterations) override;22662267/// Emit code for doacross ordered directive with 'depend' clause.2268/// \param C 'depend' clause with 'sink|source' dependency kind.2269void emitDoacrossOrdered(CodeGenFunction &CGF,2270const OMPDependClause *C) override;22712272/// Emit code for doacross ordered directive with 'doacross' clause.2273/// \param C 'doacross' clause with 'sink|source' dependence type.2274void emitDoacrossOrdered(CodeGenFunction &CGF,2275const OMPDoacrossClause *C) override;22762277/// Translates the native parameter of outlined function if this is required2278/// for target.2279/// \param FD Field decl from captured record for the parameter.2280/// \param NativeParam Parameter itself.2281const VarDecl *translateParameter(const FieldDecl *FD,2282const VarDecl *NativeParam) const override;22832284/// Gets the address of the native argument basing on the address of the2285/// target-specific parameter.2286/// \param NativeParam Parameter itself.2287/// \param TargetParam Corresponding target-specific parameter.2288Address getParameterAddress(CodeGenFunction &CGF, const VarDecl *NativeParam,2289const VarDecl *TargetParam) const override;22902291/// Gets the OpenMP-specific address of the local variable.2292Address getAddressOfLocalVariable(CodeGenFunction &CGF,2293const VarDecl *VD) override {2294return Address::invalid();2295}2296};22972298} // namespace CodeGen2299// Utility for openmp doacross clause kind2300namespace {2301template <typename T> class OMPDoacrossKind {2302public:2303bool isSink(const T *) { return false; }2304bool isSource(const T *) { return false; }2305};2306template <> class OMPDoacrossKind<OMPDependClause> {2307public:2308bool isSink(const OMPDependClause *C) {2309return C->getDependencyKind() == OMPC_DEPEND_sink;2310}2311bool isSource(const OMPDependClause *C) {2312return C->getDependencyKind() == OMPC_DEPEND_source;2313}2314};2315template <> class OMPDoacrossKind<OMPDoacrossClause> {2316public:2317bool isSource(const OMPDoacrossClause *C) {2318return C->getDependenceType() == OMPC_DOACROSS_source ||2319C->getDependenceType() == OMPC_DOACROSS_source_omp_cur_iteration;2320}2321bool isSink(const OMPDoacrossClause *C) {2322return C->getDependenceType() == OMPC_DOACROSS_sink ||2323C->getDependenceType() == OMPC_DOACROSS_sink_omp_cur_iteration;2324}2325};2326} // namespace2327} // namespace clang23282329#endif233023312332