Index: head/contrib/llvm-project/openmp/runtime/src/kmp.h =================================================================== --- head/contrib/llvm-project/openmp/runtime/src/kmp.h (revision 364731) +++ head/contrib/llvm-project/openmp/runtime/src/kmp.h (revision 364732) @@ -1,3913 +1,3907 @@ /*! \file */ /* * kmp.h -- KPTS runtime header file. */ //===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #ifndef KMP_H #define KMP_H #include "kmp_config.h" /* #define BUILD_PARALLEL_ORDERED 1 */ /* This fix replaces gettimeofday with clock_gettime for better scalability on the Altix. Requires user code to be linked with -lrt. */ //#define FIX_SGI_CLOCK /* Defines for OpenMP 3.0 tasking and auto scheduling */ #ifndef KMP_STATIC_STEAL_ENABLED #define KMP_STATIC_STEAL_ENABLED 1 #endif #define TASK_CURRENT_NOT_QUEUED 0 #define TASK_CURRENT_QUEUED 1 #ifdef BUILD_TIED_TASK_STACK #define TASK_STACK_EMPTY 0 // entries when the stack is empty #define TASK_STACK_BLOCK_BITS 5 // Used in TASK_STACK_SIZE and TASK_STACK_MASK // Number of entries in each task stack array #define TASK_STACK_BLOCK_SIZE (1 << TASK_STACK_BLOCK_BITS) // Mask for determining index into stack block #define TASK_STACK_INDEX_MASK (TASK_STACK_BLOCK_SIZE - 1) #endif // BUILD_TIED_TASK_STACK #define TASK_NOT_PUSHED 1 #define TASK_SUCCESSFULLY_PUSHED 0 #define TASK_TIED 1 #define TASK_UNTIED 0 #define TASK_EXPLICIT 1 #define TASK_IMPLICIT 0 #define TASK_PROXY 1 #define TASK_FULL 0 #define TASK_DETACHABLE 1 #define TASK_UNDETACHABLE 0 #define KMP_CANCEL_THREADS #define KMP_THREAD_ATTR // Android does not have pthread_cancel. Undefine KMP_CANCEL_THREADS if being // built on Android #if defined(__ANDROID__) #undef KMP_CANCEL_THREADS #endif #include #include #include #include #include #include /* include don't use; problems with /MD on Windows* OS NT due to bad Microsoft library. Some macros provided below to replace these functions */ #ifndef __ABSOFT_WIN #include #endif #include #include #include #include "kmp_os.h" #include "kmp_safe_c_api.h" #if KMP_STATS_ENABLED class kmp_stats_list; #endif #if KMP_USE_HIER_SCHED // Only include hierarchical scheduling if affinity is supported #undef KMP_USE_HIER_SCHED #define KMP_USE_HIER_SCHED KMP_AFFINITY_SUPPORTED #endif #if KMP_USE_HWLOC && KMP_AFFINITY_SUPPORTED #include "hwloc.h" #ifndef HWLOC_OBJ_NUMANODE #define HWLOC_OBJ_NUMANODE HWLOC_OBJ_NODE #endif #ifndef HWLOC_OBJ_PACKAGE #define HWLOC_OBJ_PACKAGE HWLOC_OBJ_SOCKET #endif #if HWLOC_API_VERSION >= 0x00020000 // hwloc 2.0 changed type of depth of object from unsigned to int typedef int kmp_hwloc_depth_t; #else typedef unsigned int kmp_hwloc_depth_t; #endif #endif #if KMP_ARCH_X86 || KMP_ARCH_X86_64 #include #endif #include "kmp_debug.h" #include "kmp_lock.h" #include "kmp_version.h" #if USE_DEBUGGER #include "kmp_debugger.h" #endif #include "kmp_i18n.h" #define KMP_HANDLE_SIGNALS (KMP_OS_UNIX || KMP_OS_WINDOWS) #include "kmp_wrapper_malloc.h" #if KMP_OS_UNIX #include #if !defined NSIG && defined _NSIG #define NSIG _NSIG #endif #endif #if KMP_OS_LINUX #pragma weak clock_gettime #endif #if OMPT_SUPPORT #include "ompt-internal.h" #endif // Affinity format function #include "kmp_str.h" // 0 - no fast memory allocation, alignment: 8-byte on x86, 16-byte on x64. // 3 - fast allocation using sync, non-sync free lists of any size, non-self // free lists of limited size. #ifndef USE_FAST_MEMORY #define USE_FAST_MEMORY 3 #endif #ifndef KMP_NESTED_HOT_TEAMS #define KMP_NESTED_HOT_TEAMS 0 #define USE_NESTED_HOT_ARG(x) #else #if KMP_NESTED_HOT_TEAMS #define USE_NESTED_HOT_ARG(x) , x #else #define USE_NESTED_HOT_ARG(x) #endif #endif // Assume using BGET compare_exchange instruction instead of lock by default. #ifndef USE_CMP_XCHG_FOR_BGET #define USE_CMP_XCHG_FOR_BGET 1 #endif // Test to see if queuing lock is better than bootstrap lock for bget // #ifndef USE_QUEUING_LOCK_FOR_BGET // #define USE_QUEUING_LOCK_FOR_BGET // #endif #define KMP_NSEC_PER_SEC 1000000000L #define KMP_USEC_PER_SEC 1000000L /*! @ingroup BASIC_TYPES @{ */ /*! Values for bit flags used in the ident_t to describe the fields. */ enum { /*! Use trampoline for internal microtasks */ KMP_IDENT_IMB = 0x01, /*! Use c-style ident structure */ KMP_IDENT_KMPC = 0x02, /* 0x04 is no longer used */ /*! Entry point generated by auto-parallelization */ KMP_IDENT_AUTOPAR = 0x08, /*! Compiler generates atomic reduction option for kmpc_reduce* */ KMP_IDENT_ATOMIC_REDUCE = 0x10, /*! To mark a 'barrier' directive in user code */ KMP_IDENT_BARRIER_EXPL = 0x20, /*! To Mark implicit barriers. */ KMP_IDENT_BARRIER_IMPL = 0x0040, KMP_IDENT_BARRIER_IMPL_MASK = 0x01C0, KMP_IDENT_BARRIER_IMPL_FOR = 0x0040, KMP_IDENT_BARRIER_IMPL_SECTIONS = 0x00C0, KMP_IDENT_BARRIER_IMPL_SINGLE = 0x0140, KMP_IDENT_BARRIER_IMPL_WORKSHARE = 0x01C0, /*! To mark a static loop in OMPT callbacks */ KMP_IDENT_WORK_LOOP = 0x200, /*! To mark a sections directive in OMPT callbacks */ KMP_IDENT_WORK_SECTIONS = 0x400, /*! To mark a distribute construct in OMPT callbacks */ KMP_IDENT_WORK_DISTRIBUTE = 0x800, /*! Atomic hint; bottom four bits as omp_sync_hint_t. Top four reserved and not currently used. If one day we need more bits, then we can use an invalid combination of hints to mean that another, larger field should be used in a different flag. */ KMP_IDENT_ATOMIC_HINT_MASK = 0xFF0000, KMP_IDENT_ATOMIC_HINT_UNCONTENDED = 0x010000, KMP_IDENT_ATOMIC_HINT_CONTENDED = 0x020000, KMP_IDENT_ATOMIC_HINT_NONSPECULATIVE = 0x040000, KMP_IDENT_ATOMIC_HINT_SPECULATIVE = 0x080000, }; /*! * The ident structure that describes a source location. */ typedef struct ident { kmp_int32 reserved_1; /**< might be used in Fortran; see above */ kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags; KMP_IDENT_KMPC identifies this union member */ kmp_int32 reserved_2; /**< not really used in Fortran any more; see above */ #if USE_ITT_BUILD /* but currently used for storing region-specific ITT */ /* contextual information. */ #endif /* USE_ITT_BUILD */ kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for C++ */ char const *psource; /**< String describing the source location. The string is composed of semi-colon separated fields which describe the source file, the function and a pair of line numbers that delimit the construct. */ } ident_t; /*! @} */ // Some forward declarations. typedef union kmp_team kmp_team_t; typedef struct kmp_taskdata kmp_taskdata_t; typedef union kmp_task_team kmp_task_team_t; typedef union kmp_team kmp_team_p; typedef union kmp_info kmp_info_p; typedef union kmp_root kmp_root_p; #ifdef __cplusplus extern "C" { #endif /* ------------------------------------------------------------------------ */ /* Pack two 32-bit signed integers into a 64-bit signed integer */ /* ToDo: Fix word ordering for big-endian machines. */ #define KMP_PACK_64(HIGH_32, LOW_32) \ ((kmp_int64)((((kmp_uint64)(HIGH_32)) << 32) | (kmp_uint64)(LOW_32))) // Generic string manipulation macros. Assume that _x is of type char * #define SKIP_WS(_x) \ { \ while (*(_x) == ' ' || *(_x) == '\t') \ (_x)++; \ } #define SKIP_DIGITS(_x) \ { \ while (*(_x) >= '0' && *(_x) <= '9') \ (_x)++; \ } #define SKIP_TOKEN(_x) \ { \ while ((*(_x) >= '0' && *(_x) <= '9') || (*(_x) >= 'a' && *(_x) <= 'z') || \ (*(_x) >= 'A' && *(_x) <= 'Z') || *(_x) == '_') \ (_x)++; \ } #define SKIP_TO(_x, _c) \ { \ while (*(_x) != '\0' && *(_x) != (_c)) \ (_x)++; \ } /* ------------------------------------------------------------------------ */ #define KMP_MAX(x, y) ((x) > (y) ? (x) : (y)) #define KMP_MIN(x, y) ((x) < (y) ? (x) : (y)) /* ------------------------------------------------------------------------ */ /* Enumeration types */ enum kmp_state_timer { ts_stop, ts_start, ts_pause, ts_last_state }; enum dynamic_mode { dynamic_default, #ifdef USE_LOAD_BALANCE dynamic_load_balance, #endif /* USE_LOAD_BALANCE */ dynamic_random, dynamic_thread_limit, dynamic_max }; /* external schedule constants, duplicate enum omp_sched in omp.h in order to * not include it here */ #ifndef KMP_SCHED_TYPE_DEFINED #define KMP_SCHED_TYPE_DEFINED typedef enum kmp_sched { kmp_sched_lower = 0, // lower and upper bounds are for routine parameter check // Note: need to adjust __kmp_sch_map global array in case enum is changed kmp_sched_static = 1, // mapped to kmp_sch_static_chunked (33) kmp_sched_dynamic = 2, // mapped to kmp_sch_dynamic_chunked (35) kmp_sched_guided = 3, // mapped to kmp_sch_guided_chunked (36) kmp_sched_auto = 4, // mapped to kmp_sch_auto (38) kmp_sched_upper_std = 5, // upper bound for standard schedules kmp_sched_lower_ext = 100, // lower bound of Intel extension schedules kmp_sched_trapezoidal = 101, // mapped to kmp_sch_trapezoidal (39) #if KMP_STATIC_STEAL_ENABLED kmp_sched_static_steal = 102, // mapped to kmp_sch_static_steal (44) #endif kmp_sched_upper, kmp_sched_default = kmp_sched_static, // default scheduling kmp_sched_monotonic = 0x80000000 } kmp_sched_t; #endif /*! @ingroup WORK_SHARING * Describes the loop schedule to be used for a parallel for loop. */ enum sched_type : kmp_int32 { kmp_sch_lower = 32, /**< lower bound for unordered values */ kmp_sch_static_chunked = 33, kmp_sch_static = 34, /**< static unspecialized */ kmp_sch_dynamic_chunked = 35, kmp_sch_guided_chunked = 36, /**< guided unspecialized */ kmp_sch_runtime = 37, kmp_sch_auto = 38, /**< auto */ kmp_sch_trapezoidal = 39, /* accessible only through KMP_SCHEDULE environment variable */ kmp_sch_static_greedy = 40, kmp_sch_static_balanced = 41, /* accessible only through KMP_SCHEDULE environment variable */ kmp_sch_guided_iterative_chunked = 42, kmp_sch_guided_analytical_chunked = 43, /* accessible only through KMP_SCHEDULE environment variable */ kmp_sch_static_steal = 44, /* static with chunk adjustment (e.g., simd) */ kmp_sch_static_balanced_chunked = 45, kmp_sch_guided_simd = 46, /**< guided with chunk adjustment */ kmp_sch_runtime_simd = 47, /**< runtime with chunk adjustment */ /* accessible only through KMP_SCHEDULE environment variable */ kmp_sch_upper, /**< upper bound for unordered values */ kmp_ord_lower = 64, /**< lower bound for ordered values, must be power of 2 */ kmp_ord_static_chunked = 65, kmp_ord_static = 66, /**< ordered static unspecialized */ kmp_ord_dynamic_chunked = 67, kmp_ord_guided_chunked = 68, kmp_ord_runtime = 69, kmp_ord_auto = 70, /**< ordered auto */ kmp_ord_trapezoidal = 71, kmp_ord_upper, /**< upper bound for ordered values */ /* Schedules for Distribute construct */ kmp_distribute_static_chunked = 91, /**< distribute static chunked */ kmp_distribute_static = 92, /**< distribute static unspecialized */ /* For the "nomerge" versions, kmp_dispatch_next*() will always return a single iteration/chunk, even if the loop is serialized. For the schedule types listed above, the entire iteration vector is returned if the loop is serialized. This doesn't work for gcc/gcomp sections. */ kmp_nm_lower = 160, /**< lower bound for nomerge values */ kmp_nm_static_chunked = (kmp_sch_static_chunked - kmp_sch_lower + kmp_nm_lower), kmp_nm_static = 162, /**< static unspecialized */ kmp_nm_dynamic_chunked = 163, kmp_nm_guided_chunked = 164, /**< guided unspecialized */ kmp_nm_runtime = 165, kmp_nm_auto = 166, /**< auto */ kmp_nm_trapezoidal = 167, /* accessible only through KMP_SCHEDULE environment variable */ kmp_nm_static_greedy = 168, kmp_nm_static_balanced = 169, /* accessible only through KMP_SCHEDULE environment variable */ kmp_nm_guided_iterative_chunked = 170, kmp_nm_guided_analytical_chunked = 171, kmp_nm_static_steal = 172, /* accessible only through OMP_SCHEDULE environment variable */ kmp_nm_ord_static_chunked = 193, kmp_nm_ord_static = 194, /**< ordered static unspecialized */ kmp_nm_ord_dynamic_chunked = 195, kmp_nm_ord_guided_chunked = 196, kmp_nm_ord_runtime = 197, kmp_nm_ord_auto = 198, /**< auto */ kmp_nm_ord_trapezoidal = 199, kmp_nm_upper, /**< upper bound for nomerge values */ /* Support for OpenMP 4.5 monotonic and nonmonotonic schedule modifiers. Since we need to distinguish the three possible cases (no modifier, monotonic modifier, nonmonotonic modifier), we need separate bits for each modifier. The absence of monotonic does not imply nonmonotonic, especially since 4.5 says that the behaviour of the "no modifier" case is implementation defined in 4.5, but will become "nonmonotonic" in 5.0. Since we're passing a full 32 bit value, we can use a couple of high bits for these flags; out of paranoia we avoid the sign bit. These modifiers can be or-ed into non-static schedules by the compiler to pass the additional information. They will be stripped early in the processing in __kmp_dispatch_init when setting up schedules, so most of the code won't ever see schedules with these bits set. */ kmp_sch_modifier_monotonic = (1 << 29), /**< Set if the monotonic schedule modifier was present */ kmp_sch_modifier_nonmonotonic = (1 << 30), /**< Set if the nonmonotonic schedule modifier was present */ #define SCHEDULE_WITHOUT_MODIFIERS(s) \ (enum sched_type)( \ (s) & ~(kmp_sch_modifier_nonmonotonic | kmp_sch_modifier_monotonic)) #define SCHEDULE_HAS_MONOTONIC(s) (((s)&kmp_sch_modifier_monotonic) != 0) #define SCHEDULE_HAS_NONMONOTONIC(s) (((s)&kmp_sch_modifier_nonmonotonic) != 0) #define SCHEDULE_HAS_NO_MODIFIERS(s) \ (((s) & (kmp_sch_modifier_nonmonotonic | kmp_sch_modifier_monotonic)) == 0) #define SCHEDULE_GET_MODIFIERS(s) \ ((enum sched_type)( \ (s) & (kmp_sch_modifier_nonmonotonic | kmp_sch_modifier_monotonic))) #define SCHEDULE_SET_MODIFIERS(s, m) \ (s = (enum sched_type)((kmp_int32)s | (kmp_int32)m)) #define SCHEDULE_NONMONOTONIC 0 #define SCHEDULE_MONOTONIC 1 kmp_sch_default = kmp_sch_static /**< default scheduling algorithm */ }; // Apply modifiers on internal kind to standard kind static inline void __kmp_sched_apply_mods_stdkind(kmp_sched_t *kind, enum sched_type internal_kind) { if (SCHEDULE_HAS_MONOTONIC(internal_kind)) { *kind = (kmp_sched_t)((int)*kind | (int)kmp_sched_monotonic); } } // Apply modifiers on standard kind to internal kind static inline void __kmp_sched_apply_mods_intkind(kmp_sched_t kind, enum sched_type *internal_kind) { if ((int)kind & (int)kmp_sched_monotonic) { *internal_kind = (enum sched_type)((int)*internal_kind | (int)kmp_sch_modifier_monotonic); } } // Get standard schedule without modifiers static inline kmp_sched_t __kmp_sched_without_mods(kmp_sched_t kind) { return (kmp_sched_t)((int)kind & ~((int)kmp_sched_monotonic)); } /* Type to keep runtime schedule set via OMP_SCHEDULE or omp_set_schedule() */ typedef union kmp_r_sched { struct { enum sched_type r_sched_type; int chunk; }; kmp_int64 sched; } kmp_r_sched_t; extern enum sched_type __kmp_sch_map[]; // map OMP 3.0 schedule types with our // internal schedule types enum library_type { library_none, library_serial, library_turnaround, library_throughput }; #if KMP_OS_LINUX enum clock_function_type { clock_function_gettimeofday, clock_function_clock_gettime }; #endif /* KMP_OS_LINUX */ #if KMP_MIC_SUPPORTED enum mic_type { non_mic, mic1, mic2, mic3, dummy }; #endif /* -- fast reduction stuff ------------------------------------------------ */ #undef KMP_FAST_REDUCTION_BARRIER #define KMP_FAST_REDUCTION_BARRIER 1 #undef KMP_FAST_REDUCTION_CORE_DUO #if KMP_ARCH_X86 || KMP_ARCH_X86_64 #define KMP_FAST_REDUCTION_CORE_DUO 1 #endif enum _reduction_method { reduction_method_not_defined = 0, critical_reduce_block = (1 << 8), atomic_reduce_block = (2 << 8), tree_reduce_block = (3 << 8), empty_reduce_block = (4 << 8) }; // Description of the packed_reduction_method variable: // The packed_reduction_method variable consists of two enum types variables // that are packed together into 0-th byte and 1-st byte: // 0: (packed_reduction_method & 0x000000FF) is a 'enum barrier_type' value of // barrier that will be used in fast reduction: bs_plain_barrier or // bs_reduction_barrier // 1: (packed_reduction_method & 0x0000FF00) is a reduction method that will // be used in fast reduction; // Reduction method is of 'enum _reduction_method' type and it's defined the way // so that the bits of 0-th byte are empty, so no need to execute a shift // instruction while packing/unpacking #if KMP_FAST_REDUCTION_BARRIER #define PACK_REDUCTION_METHOD_AND_BARRIER(reduction_method, barrier_type) \ ((reduction_method) | (barrier_type)) #define UNPACK_REDUCTION_METHOD(packed_reduction_method) \ ((enum _reduction_method)((packed_reduction_method) & (0x0000FF00))) #define UNPACK_REDUCTION_BARRIER(packed_reduction_method) \ ((enum barrier_type)((packed_reduction_method) & (0x000000FF))) #else #define PACK_REDUCTION_METHOD_AND_BARRIER(reduction_method, barrier_type) \ (reduction_method) #define UNPACK_REDUCTION_METHOD(packed_reduction_method) \ (packed_reduction_method) #define UNPACK_REDUCTION_BARRIER(packed_reduction_method) (bs_plain_barrier) #endif #define TEST_REDUCTION_METHOD(packed_reduction_method, which_reduction_block) \ ((UNPACK_REDUCTION_METHOD(packed_reduction_method)) == \ (which_reduction_block)) #if KMP_FAST_REDUCTION_BARRIER #define TREE_REDUCE_BLOCK_WITH_REDUCTION_BARRIER \ (PACK_REDUCTION_METHOD_AND_BARRIER(tree_reduce_block, bs_reduction_barrier)) #define TREE_REDUCE_BLOCK_WITH_PLAIN_BARRIER \ (PACK_REDUCTION_METHOD_AND_BARRIER(tree_reduce_block, bs_plain_barrier)) #endif typedef int PACKED_REDUCTION_METHOD_T; /* -- end of fast reduction stuff ----------------------------------------- */ #if KMP_OS_WINDOWS #define USE_CBLKDATA #if KMP_MSVC_COMPAT #pragma warning(push) #pragma warning(disable : 271 310) #endif #include #if KMP_MSVC_COMPAT #pragma warning(pop) #endif #endif #if KMP_OS_UNIX #include #include #endif /* Only Linux* OS and Windows* OS support thread affinity. */ #if KMP_AFFINITY_SUPPORTED // GROUP_AFFINITY is already defined for _MSC_VER>=1600 (VS2010 and later). #if KMP_OS_WINDOWS #if _MSC_VER < 1600 && KMP_MSVC_COMPAT typedef struct GROUP_AFFINITY { KAFFINITY Mask; WORD Group; WORD Reserved[3]; } GROUP_AFFINITY; #endif /* _MSC_VER < 1600 */ #if KMP_GROUP_AFFINITY extern int __kmp_num_proc_groups; #else static const int __kmp_num_proc_groups = 1; #endif /* KMP_GROUP_AFFINITY */ typedef DWORD (*kmp_GetActiveProcessorCount_t)(WORD); extern kmp_GetActiveProcessorCount_t __kmp_GetActiveProcessorCount; typedef WORD (*kmp_GetActiveProcessorGroupCount_t)(void); extern kmp_GetActiveProcessorGroupCount_t __kmp_GetActiveProcessorGroupCount; typedef BOOL (*kmp_GetThreadGroupAffinity_t)(HANDLE, GROUP_AFFINITY *); extern kmp_GetThreadGroupAffinity_t __kmp_GetThreadGroupAffinity; typedef BOOL (*kmp_SetThreadGroupAffinity_t)(HANDLE, const GROUP_AFFINITY *, GROUP_AFFINITY *); extern kmp_SetThreadGroupAffinity_t __kmp_SetThreadGroupAffinity; #endif /* KMP_OS_WINDOWS */ #if KMP_USE_HWLOC extern hwloc_topology_t __kmp_hwloc_topology; extern int __kmp_hwloc_error; extern int __kmp_numa_detected; extern int __kmp_tile_depth; #endif extern size_t __kmp_affin_mask_size; #define KMP_AFFINITY_CAPABLE() (__kmp_affin_mask_size > 0) #define KMP_AFFINITY_DISABLE() (__kmp_affin_mask_size = 0) #define KMP_AFFINITY_ENABLE(mask_size) (__kmp_affin_mask_size = mask_size) #define KMP_CPU_SET_ITERATE(i, mask) \ for (i = (mask)->begin(); (int)i != (mask)->end(); i = (mask)->next(i)) #define KMP_CPU_SET(i, mask) (mask)->set(i) #define KMP_CPU_ISSET(i, mask) (mask)->is_set(i) #define KMP_CPU_CLR(i, mask) (mask)->clear(i) #define KMP_CPU_ZERO(mask) (mask)->zero() #define KMP_CPU_COPY(dest, src) (dest)->copy(src) #define KMP_CPU_AND(dest, src) (dest)->bitwise_and(src) #define KMP_CPU_COMPLEMENT(max_bit_number, mask) (mask)->bitwise_not() #define KMP_CPU_UNION(dest, src) (dest)->bitwise_or(src) #define KMP_CPU_ALLOC(ptr) (ptr = __kmp_affinity_dispatch->allocate_mask()) #define KMP_CPU_FREE(ptr) __kmp_affinity_dispatch->deallocate_mask(ptr) #define KMP_CPU_ALLOC_ON_STACK(ptr) KMP_CPU_ALLOC(ptr) #define KMP_CPU_FREE_FROM_STACK(ptr) KMP_CPU_FREE(ptr) #define KMP_CPU_INTERNAL_ALLOC(ptr) KMP_CPU_ALLOC(ptr) #define KMP_CPU_INTERNAL_FREE(ptr) KMP_CPU_FREE(ptr) #define KMP_CPU_INDEX(arr, i) __kmp_affinity_dispatch->index_mask_array(arr, i) #define KMP_CPU_ALLOC_ARRAY(arr, n) \ (arr = __kmp_affinity_dispatch->allocate_mask_array(n)) #define KMP_CPU_FREE_ARRAY(arr, n) \ __kmp_affinity_dispatch->deallocate_mask_array(arr) #define KMP_CPU_INTERNAL_ALLOC_ARRAY(arr, n) KMP_CPU_ALLOC_ARRAY(arr, n) #define KMP_CPU_INTERNAL_FREE_ARRAY(arr, n) KMP_CPU_FREE_ARRAY(arr, n) #define __kmp_get_system_affinity(mask, abort_bool) \ (mask)->get_system_affinity(abort_bool) #define __kmp_set_system_affinity(mask, abort_bool) \ (mask)->set_system_affinity(abort_bool) #define __kmp_get_proc_group(mask) (mask)->get_proc_group() class KMPAffinity { public: class Mask { public: void *operator new(size_t n); void operator delete(void *p); void *operator new[](size_t n); void operator delete[](void *p); virtual ~Mask() {} // Set bit i to 1 virtual void set(int i) {} // Return bit i virtual bool is_set(int i) const { return false; } // Set bit i to 0 virtual void clear(int i) {} // Zero out entire mask virtual void zero() {} // Copy src into this mask virtual void copy(const Mask *src) {} // this &= rhs virtual void bitwise_and(const Mask *rhs) {} // this |= rhs virtual void bitwise_or(const Mask *rhs) {} // this = ~this virtual void bitwise_not() {} // API for iterating over an affinity mask // for (int i = mask->begin(); i != mask->end(); i = mask->next(i)) virtual int begin() const { return 0; } virtual int end() const { return 0; } virtual int next(int previous) const { return 0; } // Set the system's affinity to this affinity mask's value virtual int set_system_affinity(bool abort_on_error) const { return -1; } // Set this affinity mask to the current system affinity virtual int get_system_affinity(bool abort_on_error) { return -1; } // Only 1 DWORD in the mask should have any procs set. // Return the appropriate index, or -1 for an invalid mask. virtual int get_proc_group() const { return -1; } }; void *operator new(size_t n); void operator delete(void *p); // Need virtual destructor virtual ~KMPAffinity() = default; // Determine if affinity is capable virtual void determine_capable(const char *env_var) {} // Bind the current thread to os proc virtual void bind_thread(int proc) {} // Factory functions to allocate/deallocate a mask virtual Mask *allocate_mask() { return nullptr; } virtual void deallocate_mask(Mask *m) {} virtual Mask *allocate_mask_array(int num) { return nullptr; } virtual void deallocate_mask_array(Mask *m) {} virtual Mask *index_mask_array(Mask *m, int index) { return nullptr; } static void pick_api(); static void destroy_api(); enum api_type { NATIVE_OS #if KMP_USE_HWLOC , HWLOC #endif }; virtual api_type get_api_type() const { KMP_ASSERT(0); return NATIVE_OS; } private: static bool picked_api; }; typedef KMPAffinity::Mask kmp_affin_mask_t; extern KMPAffinity *__kmp_affinity_dispatch; // Declare local char buffers with this size for printing debug and info // messages, using __kmp_affinity_print_mask(). #define KMP_AFFIN_MASK_PRINT_LEN 1024 enum affinity_type { affinity_none = 0, affinity_physical, affinity_logical, affinity_compact, affinity_scatter, affinity_explicit, affinity_balanced, affinity_disabled, // not used outsize the env var parser affinity_default }; enum affinity_gran { affinity_gran_fine = 0, affinity_gran_thread, affinity_gran_core, affinity_gran_tile, affinity_gran_numa, affinity_gran_package, affinity_gran_node, #if KMP_GROUP_AFFINITY // The "group" granularity isn't necesssarily coarser than all of the // other levels, but we put it last in the enum. affinity_gran_group, #endif /* KMP_GROUP_AFFINITY */ affinity_gran_default }; enum affinity_top_method { affinity_top_method_all = 0, // try all (supported) methods, in order #if KMP_ARCH_X86 || KMP_ARCH_X86_64 affinity_top_method_apicid, affinity_top_method_x2apicid, #endif /* KMP_ARCH_X86 || KMP_ARCH_X86_64 */ affinity_top_method_cpuinfo, // KMP_CPUINFO_FILE is usable on Windows* OS, too #if KMP_GROUP_AFFINITY affinity_top_method_group, #endif /* KMP_GROUP_AFFINITY */ affinity_top_method_flat, #if KMP_USE_HWLOC affinity_top_method_hwloc, #endif affinity_top_method_default }; #define affinity_respect_mask_default (-1) extern enum affinity_type __kmp_affinity_type; /* Affinity type */ extern enum affinity_gran __kmp_affinity_gran; /* Affinity granularity */ extern int __kmp_affinity_gran_levels; /* corresponding int value */ extern int __kmp_affinity_dups; /* Affinity duplicate masks */ extern enum affinity_top_method __kmp_affinity_top_method; extern int __kmp_affinity_compact; /* Affinity 'compact' value */ extern int __kmp_affinity_offset; /* Affinity offset value */ extern int __kmp_affinity_verbose; /* Was verbose specified for KMP_AFFINITY? */ extern int __kmp_affinity_warnings; /* KMP_AFFINITY warnings enabled ? */ extern int __kmp_affinity_respect_mask; // Respect process' init affinity mask? extern char *__kmp_affinity_proclist; /* proc ID list */ extern kmp_affin_mask_t *__kmp_affinity_masks; extern unsigned __kmp_affinity_num_masks; extern void __kmp_affinity_bind_thread(int which); extern kmp_affin_mask_t *__kmp_affin_fullMask; extern char *__kmp_cpuinfo_file; #endif /* KMP_AFFINITY_SUPPORTED */ // This needs to be kept in sync with the values in omp.h !!! typedef enum kmp_proc_bind_t { proc_bind_false = 0, proc_bind_true, proc_bind_master, proc_bind_close, proc_bind_spread, proc_bind_intel, // use KMP_AFFINITY interface proc_bind_default } kmp_proc_bind_t; typedef struct kmp_nested_proc_bind_t { kmp_proc_bind_t *bind_types; int size; int used; } kmp_nested_proc_bind_t; extern kmp_nested_proc_bind_t __kmp_nested_proc_bind; extern int __kmp_display_affinity; extern char *__kmp_affinity_format; static const size_t KMP_AFFINITY_FORMAT_SIZE = 512; #if KMP_AFFINITY_SUPPORTED #define KMP_PLACE_ALL (-1) #define KMP_PLACE_UNDEFINED (-2) // Is KMP_AFFINITY is being used instead of OMP_PROC_BIND/OMP_PLACES? #define KMP_AFFINITY_NON_PROC_BIND \ ((__kmp_nested_proc_bind.bind_types[0] == proc_bind_false || \ __kmp_nested_proc_bind.bind_types[0] == proc_bind_intel) && \ (__kmp_affinity_num_masks > 0 || __kmp_affinity_type == affinity_balanced)) #endif /* KMP_AFFINITY_SUPPORTED */ extern int __kmp_affinity_num_places; typedef enum kmp_cancel_kind_t { cancel_noreq = 0, cancel_parallel = 1, cancel_loop = 2, cancel_sections = 3, cancel_taskgroup = 4 } kmp_cancel_kind_t; // KMP_HW_SUBSET support: typedef struct kmp_hws_item { int num; int offset; } kmp_hws_item_t; extern kmp_hws_item_t __kmp_hws_socket; extern kmp_hws_item_t __kmp_hws_node; extern kmp_hws_item_t __kmp_hws_tile; extern kmp_hws_item_t __kmp_hws_core; extern kmp_hws_item_t __kmp_hws_proc; extern int __kmp_hws_requested; extern int __kmp_hws_abs_flag; // absolute or per-item number requested /* ------------------------------------------------------------------------ */ #define KMP_PAD(type, sz) \ (sizeof(type) + (sz - ((sizeof(type) - 1) % (sz)) - 1)) // We need to avoid using -1 as a GTID as +1 is added to the gtid // when storing it in a lock, and the value 0 is reserved. #define KMP_GTID_DNE (-2) /* Does not exist */ #define KMP_GTID_SHUTDOWN (-3) /* Library is shutting down */ #define KMP_GTID_MONITOR (-4) /* Monitor thread ID */ #define KMP_GTID_UNKNOWN (-5) /* Is not known */ #define KMP_GTID_MIN (-6) /* Minimal gtid for low bound check in DEBUG */ /* OpenMP 5.0 Memory Management support */ #ifndef __OMP_H // Duplicate type definitions from omp.h typedef uintptr_t omp_uintptr_t; typedef enum { omp_atk_threadmodel = 1, omp_atk_alignment = 2, omp_atk_access = 3, omp_atk_pool_size = 4, omp_atk_fallback = 5, omp_atk_fb_data = 6, omp_atk_pinned = 7, omp_atk_partition = 8 } omp_alloctrait_key_t; typedef enum { omp_atv_false = 0, omp_atv_true = 1, omp_atv_default = 2, omp_atv_contended = 3, omp_atv_uncontended = 4, omp_atv_sequential = 5, omp_atv_private = 6, omp_atv_all = 7, omp_atv_thread = 8, omp_atv_pteam = 9, omp_atv_cgroup = 10, omp_atv_default_mem_fb = 11, omp_atv_null_fb = 12, omp_atv_abort_fb = 13, omp_atv_allocator_fb = 14, omp_atv_environment = 15, omp_atv_nearest = 16, omp_atv_blocked = 17, omp_atv_interleaved = 18 } omp_alloctrait_value_t; typedef void *omp_memspace_handle_t; extern omp_memspace_handle_t const omp_default_mem_space; extern omp_memspace_handle_t const omp_large_cap_mem_space; extern omp_memspace_handle_t const omp_const_mem_space; extern omp_memspace_handle_t const omp_high_bw_mem_space; extern omp_memspace_handle_t const omp_low_lat_mem_space; typedef struct { omp_alloctrait_key_t key; omp_uintptr_t value; } omp_alloctrait_t; typedef void *omp_allocator_handle_t; extern omp_allocator_handle_t const omp_null_allocator; extern omp_allocator_handle_t const omp_default_mem_alloc; extern omp_allocator_handle_t const omp_large_cap_mem_alloc; extern omp_allocator_handle_t const omp_const_mem_alloc; extern omp_allocator_handle_t const omp_high_bw_mem_alloc; extern omp_allocator_handle_t const omp_low_lat_mem_alloc; extern omp_allocator_handle_t const omp_cgroup_mem_alloc; extern omp_allocator_handle_t const omp_pteam_mem_alloc; extern omp_allocator_handle_t const omp_thread_mem_alloc; extern omp_allocator_handle_t const kmp_max_mem_alloc; extern omp_allocator_handle_t __kmp_def_allocator; // end of duplicate type definitions from omp.h #endif extern int __kmp_memkind_available; typedef omp_memspace_handle_t kmp_memspace_t; // placeholder typedef struct kmp_allocator_t { omp_memspace_handle_t memspace; void **memkind; // pointer to memkind int alignment; omp_alloctrait_value_t fb; kmp_allocator_t *fb_data; kmp_uint64 pool_size; kmp_uint64 pool_used; } kmp_allocator_t; extern omp_allocator_handle_t __kmpc_init_allocator(int gtid, omp_memspace_handle_t, int ntraits, omp_alloctrait_t traits[]); extern void __kmpc_destroy_allocator(int gtid, omp_allocator_handle_t al); extern void __kmpc_set_default_allocator(int gtid, omp_allocator_handle_t al); extern omp_allocator_handle_t __kmpc_get_default_allocator(int gtid); extern void *__kmpc_alloc(int gtid, size_t sz, omp_allocator_handle_t al); extern void __kmpc_free(int gtid, void *ptr, omp_allocator_handle_t al); extern void __kmp_init_memkind(); extern void __kmp_fini_memkind(); /* ------------------------------------------------------------------------ */ #define KMP_UINT64_MAX \ (~((kmp_uint64)1 << ((sizeof(kmp_uint64) * (1 << 3)) - 1))) #define KMP_MIN_NTH 1 #ifndef KMP_MAX_NTH #if defined(PTHREAD_THREADS_MAX) && PTHREAD_THREADS_MAX < INT_MAX #define KMP_MAX_NTH PTHREAD_THREADS_MAX #else #define KMP_MAX_NTH INT_MAX #endif #endif /* KMP_MAX_NTH */ #ifdef PTHREAD_STACK_MIN #define KMP_MIN_STKSIZE PTHREAD_STACK_MIN #else #define KMP_MIN_STKSIZE ((size_t)(32 * 1024)) #endif #define KMP_MAX_STKSIZE (~((size_t)1 << ((sizeof(size_t) * (1 << 3)) - 1))) #if KMP_ARCH_X86 #define KMP_DEFAULT_STKSIZE ((size_t)(2 * 1024 * 1024)) #elif KMP_ARCH_X86_64 #define KMP_DEFAULT_STKSIZE ((size_t)(4 * 1024 * 1024)) #define KMP_BACKUP_STKSIZE ((size_t)(2 * 1024 * 1024)) #else #define KMP_DEFAULT_STKSIZE ((size_t)(1024 * 1024)) #endif #define KMP_DEFAULT_MALLOC_POOL_INCR ((size_t)(1024 * 1024)) #define KMP_MIN_MALLOC_POOL_INCR ((size_t)(4 * 1024)) #define KMP_MAX_MALLOC_POOL_INCR \ (~((size_t)1 << ((sizeof(size_t) * (1 << 3)) - 1))) #define KMP_MIN_STKOFFSET (0) #define KMP_MAX_STKOFFSET KMP_MAX_STKSIZE #if KMP_OS_DARWIN #define KMP_DEFAULT_STKOFFSET KMP_MIN_STKOFFSET #else #define KMP_DEFAULT_STKOFFSET CACHE_LINE #endif #define KMP_MIN_STKPADDING (0) #define KMP_MAX_STKPADDING (2 * 1024 * 1024) #define KMP_BLOCKTIME_MULTIPLIER \ (1000) /* number of blocktime units per second */ #define KMP_MIN_BLOCKTIME (0) #define KMP_MAX_BLOCKTIME \ (INT_MAX) /* Must be this for "infinite" setting the work */ #define KMP_DEFAULT_BLOCKTIME (200) /* __kmp_blocktime is in milliseconds */ #if KMP_USE_MONITOR #define KMP_DEFAULT_MONITOR_STKSIZE ((size_t)(64 * 1024)) #define KMP_MIN_MONITOR_WAKEUPS (1) // min times monitor wakes up per second #define KMP_MAX_MONITOR_WAKEUPS (1000) // max times monitor can wake up per sec /* Calculate new number of monitor wakeups for a specific block time based on previous monitor_wakeups. Only allow increasing number of wakeups */ #define KMP_WAKEUPS_FROM_BLOCKTIME(blocktime, monitor_wakeups) \ (((blocktime) == KMP_MAX_BLOCKTIME) \ ? (monitor_wakeups) \ : ((blocktime) == KMP_MIN_BLOCKTIME) \ ? KMP_MAX_MONITOR_WAKEUPS \ : ((monitor_wakeups) > (KMP_BLOCKTIME_MULTIPLIER / (blocktime))) \ ? (monitor_wakeups) \ : (KMP_BLOCKTIME_MULTIPLIER) / (blocktime)) /* Calculate number of intervals for a specific block time based on monitor_wakeups */ #define KMP_INTERVALS_FROM_BLOCKTIME(blocktime, monitor_wakeups) \ (((blocktime) + (KMP_BLOCKTIME_MULTIPLIER / (monitor_wakeups)) - 1) / \ (KMP_BLOCKTIME_MULTIPLIER / (monitor_wakeups))) #else #define KMP_BLOCKTIME(team, tid) \ (get__bt_set(team, tid) ? get__blocktime(team, tid) : __kmp_dflt_blocktime) #if KMP_OS_UNIX && (KMP_ARCH_X86 || KMP_ARCH_X86_64) // HW TSC is used to reduce overhead (clock tick instead of nanosecond). extern kmp_uint64 __kmp_ticks_per_msec; #if KMP_COMPILER_ICC #define KMP_NOW() ((kmp_uint64)_rdtsc()) #else #define KMP_NOW() __kmp_hardware_timestamp() #endif #define KMP_NOW_MSEC() (KMP_NOW() / __kmp_ticks_per_msec) #define KMP_BLOCKTIME_INTERVAL(team, tid) \ (KMP_BLOCKTIME(team, tid) * __kmp_ticks_per_msec) #define KMP_BLOCKING(goal, count) ((goal) > KMP_NOW()) #else // System time is retrieved sporadically while blocking. extern kmp_uint64 __kmp_now_nsec(); #define KMP_NOW() __kmp_now_nsec() #define KMP_NOW_MSEC() (KMP_NOW() / KMP_USEC_PER_SEC) #define KMP_BLOCKTIME_INTERVAL(team, tid) \ (KMP_BLOCKTIME(team, tid) * KMP_USEC_PER_SEC) #define KMP_BLOCKING(goal, count) ((count) % 1000 != 0 || (goal) > KMP_NOW()) #endif #endif // KMP_USE_MONITOR #define KMP_MIN_STATSCOLS 40 #define KMP_MAX_STATSCOLS 4096 #define KMP_DEFAULT_STATSCOLS 80 #define KMP_MIN_INTERVAL 0 #define KMP_MAX_INTERVAL (INT_MAX - 1) #define KMP_DEFAULT_INTERVAL 0 #define KMP_MIN_CHUNK 1 #define KMP_MAX_CHUNK (INT_MAX - 1) #define KMP_DEFAULT_CHUNK 1 #define KMP_DFLT_DISP_NUM_BUFF 7 #define KMP_MAX_ORDERED 8 #define KMP_MAX_FIELDS 32 #define KMP_MAX_BRANCH_BITS 31 #define KMP_MAX_ACTIVE_LEVELS_LIMIT INT_MAX #define KMP_MAX_DEFAULT_DEVICE_LIMIT INT_MAX #define KMP_MAX_TASK_PRIORITY_LIMIT INT_MAX /* Minimum number of threads before switch to TLS gtid (experimentally determined) */ /* josh TODO: what about OS X* tuning? */ #if KMP_ARCH_X86 || KMP_ARCH_X86_64 #define KMP_TLS_GTID_MIN 5 #else #define KMP_TLS_GTID_MIN INT_MAX #endif #define KMP_MASTER_TID(tid) ((tid) == 0) #define KMP_WORKER_TID(tid) ((tid) != 0) #define KMP_MASTER_GTID(gtid) (__kmp_tid_from_gtid((gtid)) == 0) #define KMP_WORKER_GTID(gtid) (__kmp_tid_from_gtid((gtid)) != 0) #define KMP_INITIAL_GTID(gtid) ((gtid) == 0) #ifndef TRUE #define FALSE 0 #define TRUE (!FALSE) #endif /* NOTE: all of the following constants must be even */ #if KMP_OS_WINDOWS #define KMP_INIT_WAIT 64U /* initial number of spin-tests */ #define KMP_NEXT_WAIT 32U /* susequent number of spin-tests */ #elif KMP_OS_CNK #define KMP_INIT_WAIT 16U /* initial number of spin-tests */ #define KMP_NEXT_WAIT 8U /* susequent number of spin-tests */ #elif KMP_OS_LINUX #define KMP_INIT_WAIT 1024U /* initial number of spin-tests */ #define KMP_NEXT_WAIT 512U /* susequent number of spin-tests */ #elif KMP_OS_DARWIN /* TODO: tune for KMP_OS_DARWIN */ #define KMP_INIT_WAIT 1024U /* initial number of spin-tests */ #define KMP_NEXT_WAIT 512U /* susequent number of spin-tests */ #elif KMP_OS_DRAGONFLY /* TODO: tune for KMP_OS_DRAGONFLY */ #define KMP_INIT_WAIT 1024U /* initial number of spin-tests */ #define KMP_NEXT_WAIT 512U /* susequent number of spin-tests */ #elif KMP_OS_FREEBSD /* TODO: tune for KMP_OS_FREEBSD */ #define KMP_INIT_WAIT 1024U /* initial number of spin-tests */ #define KMP_NEXT_WAIT 512U /* susequent number of spin-tests */ #elif KMP_OS_NETBSD /* TODO: tune for KMP_OS_NETBSD */ #define KMP_INIT_WAIT 1024U /* initial number of spin-tests */ #define KMP_NEXT_WAIT 512U /* susequent number of spin-tests */ #elif KMP_OS_HURD /* TODO: tune for KMP_OS_HURD */ #define KMP_INIT_WAIT 1024U /* initial number of spin-tests */ #define KMP_NEXT_WAIT 512U /* susequent number of spin-tests */ #elif KMP_OS_OPENBSD /* TODO: tune for KMP_OS_OPENBSD */ #define KMP_INIT_WAIT 1024U /* initial number of spin-tests */ #define KMP_NEXT_WAIT 512U /* susequent number of spin-tests */ #endif #if KMP_ARCH_X86 || KMP_ARCH_X86_64 typedef struct kmp_cpuid { kmp_uint32 eax; kmp_uint32 ebx; kmp_uint32 ecx; kmp_uint32 edx; } kmp_cpuid_t; typedef struct kmp_cpuinfo { int initialized; // If 0, other fields are not initialized. int signature; // CPUID(1).EAX int family; // CPUID(1).EAX[27:20]+CPUID(1).EAX[11:8] (Extended Family+Family) int model; // ( CPUID(1).EAX[19:16] << 4 ) + CPUID(1).EAX[7:4] ( ( Extended // Model << 4 ) + Model) int stepping; // CPUID(1).EAX[3:0] ( Stepping ) int sse2; // 0 if SSE2 instructions are not supported, 1 otherwise. int rtm; // 0 if RTM instructions are not supported, 1 otherwise. int cpu_stackoffset; int apic_id; int physical_id; int logical_id; kmp_uint64 frequency; // Nominal CPU frequency in Hz. char name[3 * sizeof(kmp_cpuid_t)]; // CPUID(0x80000002,0x80000003,0x80000004) } kmp_cpuinfo_t; extern void __kmp_query_cpuid(kmp_cpuinfo_t *p); #if KMP_OS_UNIX // subleaf is only needed for cache and topology discovery and can be set to // zero in most cases static inline void __kmp_x86_cpuid(int leaf, int subleaf, struct kmp_cpuid *p) { __asm__ __volatile__("cpuid" : "=a"(p->eax), "=b"(p->ebx), "=c"(p->ecx), "=d"(p->edx) : "a"(leaf), "c"(subleaf)); } // Load p into FPU control word static inline void __kmp_load_x87_fpu_control_word(const kmp_int16 *p) { __asm__ __volatile__("fldcw %0" : : "m"(*p)); } // Store FPU control word into p static inline void __kmp_store_x87_fpu_control_word(kmp_int16 *p) { __asm__ __volatile__("fstcw %0" : "=m"(*p)); } static inline void __kmp_clear_x87_fpu_status_word() { #if KMP_MIC // 32-bit protected mode x87 FPU state struct x87_fpu_state { unsigned cw; unsigned sw; unsigned tw; unsigned fip; unsigned fips; unsigned fdp; unsigned fds; }; struct x87_fpu_state fpu_state = {0, 0, 0, 0, 0, 0, 0}; __asm__ __volatile__("fstenv %0\n\t" // store FP env "andw $0x7f00, %1\n\t" // clear 0-7,15 bits of FP SW "fldenv %0\n\t" // load FP env back : "+m"(fpu_state), "+m"(fpu_state.sw)); #else __asm__ __volatile__("fnclex"); #endif // KMP_MIC } #if __SSE__ static inline void __kmp_load_mxcsr(const kmp_uint32 *p) { _mm_setcsr(*p); } static inline void __kmp_store_mxcsr(kmp_uint32 *p) { *p = _mm_getcsr(); } #else static inline void __kmp_load_mxcsr(const kmp_uint32 *p) {} static inline void __kmp_store_mxcsr(kmp_uint32 *p) { *p = 0; } #endif #else // Windows still has these as external functions in assembly file extern void __kmp_x86_cpuid(int mode, int mode2, struct kmp_cpuid *p); extern void __kmp_load_x87_fpu_control_word(const kmp_int16 *p); extern void __kmp_store_x87_fpu_control_word(kmp_int16 *p); extern void __kmp_clear_x87_fpu_status_word(); static inline void __kmp_load_mxcsr(const kmp_uint32 *p) { _mm_setcsr(*p); } static inline void __kmp_store_mxcsr(kmp_uint32 *p) { *p = _mm_getcsr(); } #endif // KMP_OS_UNIX #define KMP_X86_MXCSR_MASK 0xffffffc0 /* ignore status flags (6 lsb) */ #if KMP_ARCH_X86 extern void __kmp_x86_pause(void); #elif KMP_MIC // Performance testing on KNC (C0QS-7120 P/A/X/D, 61-core, 16 GB Memory) showed // regression after removal of extra PAUSE from spin loops. Changing // the delay from 100 to 300 showed even better performance than double PAUSE // on Spec OMP2001 and LCPC tasking tests, no regressions on EPCC. static inline void __kmp_x86_pause(void) { _mm_delay_32(300); } #else static inline void __kmp_x86_pause(void) { _mm_pause(); } #endif #define KMP_CPU_PAUSE() __kmp_x86_pause() #elif KMP_ARCH_PPC64 #define KMP_PPC64_PRI_LOW() __asm__ volatile("or 1, 1, 1") #define KMP_PPC64_PRI_MED() __asm__ volatile("or 2, 2, 2") #define KMP_PPC64_PRI_LOC_MB() __asm__ volatile("" : : : "memory") #define KMP_CPU_PAUSE() \ do { \ KMP_PPC64_PRI_LOW(); \ KMP_PPC64_PRI_MED(); \ KMP_PPC64_PRI_LOC_MB(); \ } while (0) #else #define KMP_CPU_PAUSE() /* nothing to do */ #endif #define KMP_INIT_YIELD(count) \ { (count) = __kmp_yield_init; } #define KMP_OVERSUBSCRIBED \ (TCR_4(__kmp_nth) > (__kmp_avail_proc ? __kmp_avail_proc : __kmp_xproc)) #define KMP_TRY_YIELD \ ((__kmp_use_yield == 1) || (__kmp_use_yield == 2 && (KMP_OVERSUBSCRIBED))) #define KMP_TRY_YIELD_OVERSUB \ ((__kmp_use_yield == 1 || __kmp_use_yield == 2) && (KMP_OVERSUBSCRIBED)) #define KMP_YIELD(cond) \ { \ KMP_CPU_PAUSE(); \ if ((cond) && (KMP_TRY_YIELD)) \ __kmp_yield(); \ } #define KMP_YIELD_OVERSUB() \ { \ KMP_CPU_PAUSE(); \ if ((KMP_TRY_YIELD_OVERSUB)) \ __kmp_yield(); \ } // Note the decrement of 2 in the following Macros. With KMP_LIBRARY=turnaround, // there should be no yielding since initial value from KMP_INIT_YIELD() is odd. #define KMP_YIELD_SPIN(count) \ { \ KMP_CPU_PAUSE(); \ if (KMP_TRY_YIELD) { \ (count) -= 2; \ if (!(count)) { \ __kmp_yield(); \ (count) = __kmp_yield_next; \ } \ } \ } #define KMP_YIELD_OVERSUB_ELSE_SPIN(count) \ { \ KMP_CPU_PAUSE(); \ if ((KMP_TRY_YIELD_OVERSUB)) \ __kmp_yield(); \ else if (__kmp_use_yield == 1) { \ (count) -= 2; \ if (!(count)) { \ __kmp_yield(); \ (count) = __kmp_yield_next; \ } \ } \ } /* ------------------------------------------------------------------------ */ /* Support datatypes for the orphaned construct nesting checks. */ /* ------------------------------------------------------------------------ */ enum cons_type { ct_none, ct_parallel, ct_pdo, ct_pdo_ordered, ct_psections, ct_psingle, ct_critical, ct_ordered_in_parallel, ct_ordered_in_pdo, ct_master, ct_reduce, ct_barrier }; #define IS_CONS_TYPE_ORDERED(ct) ((ct) == ct_pdo_ordered) struct cons_data { ident_t const *ident; enum cons_type type; int prev; kmp_user_lock_p name; /* address exclusively for critical section name comparison */ }; struct cons_header { int p_top, w_top, s_top; int stack_size, stack_top; struct cons_data *stack_data; }; struct kmp_region_info { char *text; int offset[KMP_MAX_FIELDS]; int length[KMP_MAX_FIELDS]; }; /* ---------------------------------------------------------------------- */ /* ---------------------------------------------------------------------- */ #if KMP_OS_WINDOWS typedef HANDLE kmp_thread_t; typedef DWORD kmp_key_t; #endif /* KMP_OS_WINDOWS */ #if KMP_OS_UNIX typedef pthread_t kmp_thread_t; typedef pthread_key_t kmp_key_t; #endif extern kmp_key_t __kmp_gtid_threadprivate_key; typedef struct kmp_sys_info { long maxrss; /* the maximum resident set size utilized (in kilobytes) */ long minflt; /* the number of page faults serviced without any I/O */ long majflt; /* the number of page faults serviced that required I/O */ long nswap; /* the number of times a process was "swapped" out of memory */ long inblock; /* the number of times the file system had to perform input */ long oublock; /* the number of times the file system had to perform output */ long nvcsw; /* the number of times a context switch was voluntarily */ long nivcsw; /* the number of times a context switch was forced */ } kmp_sys_info_t; #if USE_ITT_BUILD // We cannot include "kmp_itt.h" due to circular dependency. Declare the only // required type here. Later we will check the type meets requirements. typedef int kmp_itt_mark_t; #define KMP_ITT_DEBUG 0 #endif /* USE_ITT_BUILD */ typedef kmp_int32 kmp_critical_name[8]; /*! @ingroup PARALLEL The type for a microtask which gets passed to @ref __kmpc_fork_call(). The arguments to the outlined function are @param global_tid the global thread identity of the thread executing the function. @param bound_tid the local identity of the thread executing the function @param ... pointers to shared variables accessed by the function. */ typedef void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid, ...); typedef void (*kmpc_micro_bound)(kmp_int32 *bound_tid, kmp_int32 *bound_nth, ...); /*! @ingroup THREADPRIVATE @{ */ /* --------------------------------------------------------------------------- */ /* Threadprivate initialization/finalization function declarations */ /* for non-array objects: __kmpc_threadprivate_register() */ /*! Pointer to the constructor function. The first argument is the this pointer */ typedef void *(*kmpc_ctor)(void *); /*! Pointer to the destructor function. The first argument is the this pointer */ typedef void (*kmpc_dtor)( void * /*, size_t */); /* 2nd arg: magic number for KCC unused by Intel compiler */ /*! Pointer to an alternate constructor. The first argument is the this pointer. */ typedef void *(*kmpc_cctor)(void *, void *); /* for array objects: __kmpc_threadprivate_register_vec() */ /* First arg: "this" pointer */ /* Last arg: number of array elements */ /*! Array constructor. First argument is the this pointer Second argument the number of array elements. */ typedef void *(*kmpc_ctor_vec)(void *, size_t); /*! Pointer to the array destructor function. The first argument is the this pointer Second argument the number of array elements. */ typedef void (*kmpc_dtor_vec)(void *, size_t); /*! Array constructor. First argument is the this pointer Third argument the number of array elements. */ typedef void *(*kmpc_cctor_vec)(void *, void *, size_t); /* function unused by compiler */ /*! @} */ /* keeps tracked of threadprivate cache allocations for cleanup later */ typedef struct kmp_cached_addr { void **addr; /* address of allocated cache */ void ***compiler_cache; /* pointer to compiler's cache */ void *data; /* pointer to global data */ struct kmp_cached_addr *next; /* pointer to next cached address */ } kmp_cached_addr_t; struct private_data { struct private_data *next; /* The next descriptor in the list */ void *data; /* The data buffer for this descriptor */ int more; /* The repeat count for this descriptor */ size_t size; /* The data size for this descriptor */ }; struct private_common { struct private_common *next; struct private_common *link; void *gbl_addr; void *par_addr; /* par_addr == gbl_addr for MASTER thread */ size_t cmn_size; }; struct shared_common { struct shared_common *next; struct private_data *pod_init; void *obj_init; void *gbl_addr; union { kmpc_ctor ctor; kmpc_ctor_vec ctorv; } ct; union { kmpc_cctor cctor; kmpc_cctor_vec cctorv; } cct; union { kmpc_dtor dtor; kmpc_dtor_vec dtorv; } dt; size_t vec_len; int is_vec; size_t cmn_size; }; #define KMP_HASH_TABLE_LOG2 9 /* log2 of the hash table size */ #define KMP_HASH_TABLE_SIZE \ (1 << KMP_HASH_TABLE_LOG2) /* size of the hash table */ #define KMP_HASH_SHIFT 3 /* throw away this many low bits from the address */ #define KMP_HASH(x) \ ((((kmp_uintptr_t)x) >> KMP_HASH_SHIFT) & (KMP_HASH_TABLE_SIZE - 1)) struct common_table { struct private_common *data[KMP_HASH_TABLE_SIZE]; }; struct shared_table { struct shared_common *data[KMP_HASH_TABLE_SIZE]; }; /* ------------------------------------------------------------------------ */ #if KMP_USE_HIER_SCHED // Shared barrier data that exists inside a single unit of the scheduling // hierarchy typedef struct kmp_hier_private_bdata_t { kmp_int32 num_active; kmp_uint64 index; kmp_uint64 wait_val[2]; } kmp_hier_private_bdata_t; #endif typedef struct kmp_sched_flags { unsigned ordered : 1; unsigned nomerge : 1; unsigned contains_last : 1; #if KMP_USE_HIER_SCHED unsigned use_hier : 1; unsigned unused : 28; #else unsigned unused : 29; #endif } kmp_sched_flags_t; KMP_BUILD_ASSERT(sizeof(kmp_sched_flags_t) == 4); #if KMP_STATIC_STEAL_ENABLED typedef struct KMP_ALIGN_CACHE dispatch_private_info32 { kmp_int32 count; kmp_int32 ub; /* Adding KMP_ALIGN_CACHE here doesn't help / can hurt performance */ kmp_int32 lb; kmp_int32 st; kmp_int32 tc; kmp_int32 static_steal_counter; /* for static_steal only; maybe better to put after ub */ kmp_lock_t *th_steal_lock; // lock used for chunk stealing // KMP_ALIGN( 16 ) ensures ( if the KMP_ALIGN macro is turned on ) // a) parm3 is properly aligned and // b) all parm1-4 are in the same cache line. // Because of parm1-4 are used together, performance seems to be better // if they are in the same line (not measured though). struct KMP_ALIGN(32) { // AC: changed 16 to 32 in order to simplify template kmp_int32 parm1; // structures in kmp_dispatch.cpp. This should kmp_int32 parm2; // make no real change at least while padding is off. kmp_int32 parm3; kmp_int32 parm4; }; kmp_uint32 ordered_lower; kmp_uint32 ordered_upper; #if KMP_OS_WINDOWS // This var can be placed in the hole between 'tc' and 'parm1', instead of // 'static_steal_counter'. It would be nice to measure execution times. // Conditional if/endif can be removed at all. kmp_int32 last_upper; #endif /* KMP_OS_WINDOWS */ } dispatch_private_info32_t; typedef struct KMP_ALIGN_CACHE dispatch_private_info64 { kmp_int64 count; // current chunk number for static & static-steal scheduling kmp_int64 ub; /* upper-bound */ /* Adding KMP_ALIGN_CACHE here doesn't help / can hurt performance */ kmp_int64 lb; /* lower-bound */ kmp_int64 st; /* stride */ kmp_int64 tc; /* trip count (number of iterations) */ kmp_int64 static_steal_counter; /* for static_steal only; maybe better to put after ub */ kmp_lock_t *th_steal_lock; // lock used for chunk stealing /* parm[1-4] are used in different ways by different scheduling algorithms */ // KMP_ALIGN( 32 ) ensures ( if the KMP_ALIGN macro is turned on ) // a) parm3 is properly aligned and // b) all parm1-4 are in the same cache line. // Because of parm1-4 are used together, performance seems to be better // if they are in the same line (not measured though). struct KMP_ALIGN(32) { kmp_int64 parm1; kmp_int64 parm2; kmp_int64 parm3; kmp_int64 parm4; }; kmp_uint64 ordered_lower; kmp_uint64 ordered_upper; #if KMP_OS_WINDOWS // This var can be placed in the hole between 'tc' and 'parm1', instead of // 'static_steal_counter'. It would be nice to measure execution times. // Conditional if/endif can be removed at all. kmp_int64 last_upper; #endif /* KMP_OS_WINDOWS */ } dispatch_private_info64_t; #else /* KMP_STATIC_STEAL_ENABLED */ typedef struct KMP_ALIGN_CACHE dispatch_private_info32 { kmp_int32 lb; kmp_int32 ub; kmp_int32 st; kmp_int32 tc; kmp_int32 parm1; kmp_int32 parm2; kmp_int32 parm3; kmp_int32 parm4; kmp_int32 count; kmp_uint32 ordered_lower; kmp_uint32 ordered_upper; #if KMP_OS_WINDOWS kmp_int32 last_upper; #endif /* KMP_OS_WINDOWS */ } dispatch_private_info32_t; typedef struct KMP_ALIGN_CACHE dispatch_private_info64 { kmp_int64 lb; /* lower-bound */ kmp_int64 ub; /* upper-bound */ kmp_int64 st; /* stride */ kmp_int64 tc; /* trip count (number of iterations) */ /* parm[1-4] are used in different ways by different scheduling algorithms */ kmp_int64 parm1; kmp_int64 parm2; kmp_int64 parm3; kmp_int64 parm4; kmp_int64 count; /* current chunk number for static scheduling */ kmp_uint64 ordered_lower; kmp_uint64 ordered_upper; #if KMP_OS_WINDOWS kmp_int64 last_upper; #endif /* KMP_OS_WINDOWS */ } dispatch_private_info64_t; #endif /* KMP_STATIC_STEAL_ENABLED */ typedef struct KMP_ALIGN_CACHE dispatch_private_info { union private_info { dispatch_private_info32_t p32; dispatch_private_info64_t p64; } u; enum sched_type schedule; /* scheduling algorithm */ kmp_sched_flags_t flags; /* flags (e.g., ordered, nomerge, etc.) */ kmp_int32 ordered_bumped; // To retain the structure size after making ordered_iteration scalar kmp_int32 ordered_dummy[KMP_MAX_ORDERED - 3]; // Stack of buffers for nest of serial regions struct dispatch_private_info *next; kmp_int32 type_size; /* the size of types in private_info */ #if KMP_USE_HIER_SCHED kmp_int32 hier_id; void *parent; /* hierarchical scheduling parent pointer */ #endif enum cons_type pushed_ws; } dispatch_private_info_t; typedef struct dispatch_shared_info32 { /* chunk index under dynamic, number of idle threads under static-steal; iteration index otherwise */ volatile kmp_uint32 iteration; volatile kmp_uint32 num_done; volatile kmp_uint32 ordered_iteration; // Dummy to retain the structure size after making ordered_iteration scalar kmp_int32 ordered_dummy[KMP_MAX_ORDERED - 1]; } dispatch_shared_info32_t; typedef struct dispatch_shared_info64 { /* chunk index under dynamic, number of idle threads under static-steal; iteration index otherwise */ volatile kmp_uint64 iteration; volatile kmp_uint64 num_done; volatile kmp_uint64 ordered_iteration; // Dummy to retain the structure size after making ordered_iteration scalar kmp_int64 ordered_dummy[KMP_MAX_ORDERED - 3]; } dispatch_shared_info64_t; typedef struct dispatch_shared_info { union shared_info { dispatch_shared_info32_t s32; dispatch_shared_info64_t s64; } u; volatile kmp_uint32 buffer_index; volatile kmp_int32 doacross_buf_idx; // teamwise index volatile kmp_uint32 *doacross_flags; // shared array of iteration flags (0/1) kmp_int32 doacross_num_done; // count finished threads #if KMP_USE_HIER_SCHED void *hier; #endif #if KMP_USE_HWLOC // When linking with libhwloc, the ORDERED EPCC test slows down on big // machines (> 48 cores). Performance analysis showed that a cache thrash // was occurring and this padding helps alleviate the problem. char padding[64]; #endif } dispatch_shared_info_t; typedef struct kmp_disp { /* Vector for ORDERED SECTION */ void (*th_deo_fcn)(int *gtid, int *cid, ident_t *); /* Vector for END ORDERED SECTION */ void (*th_dxo_fcn)(int *gtid, int *cid, ident_t *); dispatch_shared_info_t *th_dispatch_sh_current; dispatch_private_info_t *th_dispatch_pr_current; dispatch_private_info_t *th_disp_buffer; kmp_int32 th_disp_index; kmp_int32 th_doacross_buf_idx; // thread's doacross buffer index volatile kmp_uint32 *th_doacross_flags; // pointer to shared array of flags kmp_int64 *th_doacross_info; // info on loop bounds #if KMP_USE_INTERNODE_ALIGNMENT char more_padding[INTERNODE_CACHE_LINE]; #endif } kmp_disp_t; /* ------------------------------------------------------------------------ */ /* Barrier stuff */ /* constants for barrier state update */ #define KMP_INIT_BARRIER_STATE 0 /* should probably start from zero */ #define KMP_BARRIER_SLEEP_BIT 0 /* bit used for suspend/sleep part of state */ #define KMP_BARRIER_UNUSED_BIT 1 // bit that must never be set for valid state #define KMP_BARRIER_BUMP_BIT 2 /* lsb used for bump of go/arrived state */ #define KMP_BARRIER_SLEEP_STATE (1 << KMP_BARRIER_SLEEP_BIT) #define KMP_BARRIER_UNUSED_STATE (1 << KMP_BARRIER_UNUSED_BIT) #define KMP_BARRIER_STATE_BUMP (1 << KMP_BARRIER_BUMP_BIT) #if (KMP_BARRIER_SLEEP_BIT >= KMP_BARRIER_BUMP_BIT) #error "Barrier sleep bit must be smaller than barrier bump bit" #endif #if (KMP_BARRIER_UNUSED_BIT >= KMP_BARRIER_BUMP_BIT) #error "Barrier unused bit must be smaller than barrier bump bit" #endif // Constants for release barrier wait state: currently, hierarchical only #define KMP_BARRIER_NOT_WAITING 0 // Normal state; worker not in wait_sleep #define KMP_BARRIER_OWN_FLAG \ 1 // Normal state; worker waiting on own b_go flag in release #define KMP_BARRIER_PARENT_FLAG \ 2 // Special state; worker waiting on parent's b_go flag in release #define KMP_BARRIER_SWITCH_TO_OWN_FLAG \ 3 // Special state; tells worker to shift from parent to own b_go #define KMP_BARRIER_SWITCHING \ 4 // Special state; worker resets appropriate flag on wake-up #define KMP_NOT_SAFE_TO_REAP \ 0 // Thread th_reap_state: not safe to reap (tasking) #define KMP_SAFE_TO_REAP 1 // Thread th_reap_state: safe to reap (not tasking) enum barrier_type { bs_plain_barrier = 0, /* 0, All non-fork/join barriers (except reduction barriers if enabled) */ bs_forkjoin_barrier, /* 1, All fork/join (parallel region) barriers */ #if KMP_FAST_REDUCTION_BARRIER bs_reduction_barrier, /* 2, All barriers that are used in reduction */ #endif // KMP_FAST_REDUCTION_BARRIER bs_last_barrier /* Just a placeholder to mark the end */ }; // to work with reduction barriers just like with plain barriers #if !KMP_FAST_REDUCTION_BARRIER #define bs_reduction_barrier bs_plain_barrier #endif // KMP_FAST_REDUCTION_BARRIER typedef enum kmp_bar_pat { /* Barrier communication patterns */ bp_linear_bar = 0, /* Single level (degenerate) tree */ bp_tree_bar = 1, /* Balanced tree with branching factor 2^n */ bp_hyper_bar = 2, /* Hypercube-embedded tree with min branching factor 2^n */ bp_hierarchical_bar = 3, /* Machine hierarchy tree */ bp_last_bar /* Placeholder to mark the end */ } kmp_bar_pat_e; #define KMP_BARRIER_ICV_PUSH 1 /* Record for holding the values of the internal controls stack records */ typedef struct kmp_internal_control { int serial_nesting_level; /* corresponds to the value of the th_team_serialized field */ kmp_int8 dynamic; /* internal control for dynamic adjustment of threads (per thread) */ kmp_int8 bt_set; /* internal control for whether blocktime is explicitly set */ int blocktime; /* internal control for blocktime */ #if KMP_USE_MONITOR int bt_intervals; /* internal control for blocktime intervals */ #endif int nproc; /* internal control for #threads for next parallel region (per thread) */ int thread_limit; /* internal control for thread-limit-var */ int max_active_levels; /* internal control for max_active_levels */ kmp_r_sched_t sched; /* internal control for runtime schedule {sched,chunk} pair */ kmp_proc_bind_t proc_bind; /* internal control for affinity */ kmp_int32 default_device; /* internal control for default device */ struct kmp_internal_control *next; } kmp_internal_control_t; static inline void copy_icvs(kmp_internal_control_t *dst, kmp_internal_control_t *src) { *dst = *src; } /* Thread barrier needs volatile barrier fields */ typedef struct KMP_ALIGN_CACHE kmp_bstate { // th_fixed_icvs is aligned by virtue of kmp_bstate being aligned (and all // uses of it). It is not explicitly aligned below, because we *don't* want // it to be padded -- instead, we fit b_go into the same cache line with // th_fixed_icvs, enabling NGO cache lines stores in the hierarchical barrier. kmp_internal_control_t th_fixed_icvs; // Initial ICVs for the thread // Tuck b_go into end of th_fixed_icvs cache line, so it can be stored with // same NGO store volatile kmp_uint64 b_go; // STATE => task should proceed (hierarchical) KMP_ALIGN_CACHE volatile kmp_uint64 b_arrived; // STATE => task reached synch point. kmp_uint32 *skip_per_level; kmp_uint32 my_level; kmp_int32 parent_tid; kmp_int32 old_tid; kmp_uint32 depth; struct kmp_bstate *parent_bar; kmp_team_t *team; kmp_uint64 leaf_state; kmp_uint32 nproc; kmp_uint8 base_leaf_kids; kmp_uint8 leaf_kids; kmp_uint8 offset; kmp_uint8 wait_flag; kmp_uint8 use_oncore_barrier; #if USE_DEBUGGER // The following field is intended for the debugger solely. Only the worker // thread itself accesses this field: the worker increases it by 1 when it // arrives to a barrier. KMP_ALIGN_CACHE kmp_uint b_worker_arrived; #endif /* USE_DEBUGGER */ } kmp_bstate_t; union KMP_ALIGN_CACHE kmp_barrier_union { double b_align; /* use worst case alignment */ char b_pad[KMP_PAD(kmp_bstate_t, CACHE_LINE)]; kmp_bstate_t bb; }; typedef union kmp_barrier_union kmp_balign_t; /* Team barrier needs only non-volatile arrived counter */ union KMP_ALIGN_CACHE kmp_barrier_team_union { double b_align; /* use worst case alignment */ char b_pad[CACHE_LINE]; struct { kmp_uint64 b_arrived; /* STATE => task reached synch point. */ #if USE_DEBUGGER // The following two fields are indended for the debugger solely. Only // master of the team accesses these fields: the first one is increased by // 1 when master arrives to a barrier, the second one is increased by one // when all the threads arrived. kmp_uint b_master_arrived; kmp_uint b_team_arrived; #endif }; }; typedef union kmp_barrier_team_union kmp_balign_team_t; /* Padding for Linux* OS pthreads condition variables and mutexes used to signal threads when a condition changes. This is to workaround an NPTL bug where padding was added to pthread_cond_t which caused the initialization routine to write outside of the structure if compiled on pre-NPTL threads. */ #if KMP_OS_WINDOWS typedef struct kmp_win32_mutex { /* The Lock */ CRITICAL_SECTION cs; } kmp_win32_mutex_t; typedef struct kmp_win32_cond { /* Count of the number of waiters. */ int waiters_count_; /* Serialize access to */ kmp_win32_mutex_t waiters_count_lock_; /* Number of threads to release via a or a */ int release_count_; /* Keeps track of the current "generation" so that we don't allow */ /* one thread to steal all the "releases" from the broadcast. */ int wait_generation_count_; /* A manual-reset event that's used to block and release waiting threads. */ HANDLE event_; } kmp_win32_cond_t; #endif #if KMP_OS_UNIX union KMP_ALIGN_CACHE kmp_cond_union { double c_align; char c_pad[CACHE_LINE]; pthread_cond_t c_cond; }; typedef union kmp_cond_union kmp_cond_align_t; union KMP_ALIGN_CACHE kmp_mutex_union { double m_align; char m_pad[CACHE_LINE]; pthread_mutex_t m_mutex; }; typedef union kmp_mutex_union kmp_mutex_align_t; #endif /* KMP_OS_UNIX */ typedef struct kmp_desc_base { void *ds_stackbase; size_t ds_stacksize; int ds_stackgrow; kmp_thread_t ds_thread; volatile int ds_tid; int ds_gtid; #if KMP_OS_WINDOWS volatile int ds_alive; DWORD ds_thread_id; /* ds_thread keeps thread handle on Windows* OS. It is enough for RTL purposes. However, debugger support (libomp_db) cannot work with handles, because they uncomparable. For example, debugger requests info about thread with handle h. h is valid within debugger process, and meaningless within debugee process. Even if h is duped by call to DuplicateHandle(), so the result h' is valid within debugee process, but it is a *new* handle which does *not* equal to any other handle in debugee... The only way to compare handles is convert them to system-wide ids. GetThreadId() function is available only in Longhorn and Server 2003. :-( In contrast, GetCurrentThreadId() is available on all Windows* OS flavours (including Windows* 95). Thus, we have to get thread id by call to GetCurrentThreadId() from within the thread and save it to let libomp_db identify threads. */ #endif /* KMP_OS_WINDOWS */ } kmp_desc_base_t; typedef union KMP_ALIGN_CACHE kmp_desc { double ds_align; /* use worst case alignment */ char ds_pad[KMP_PAD(kmp_desc_base_t, CACHE_LINE)]; kmp_desc_base_t ds; } kmp_desc_t; typedef struct kmp_local { volatile int this_construct; /* count of single's encountered by thread */ void *reduce_data; #if KMP_USE_BGET void *bget_data; void *bget_list; #if !USE_CMP_XCHG_FOR_BGET #ifdef USE_QUEUING_LOCK_FOR_BGET kmp_lock_t bget_lock; /* Lock for accessing bget free list */ #else kmp_bootstrap_lock_t bget_lock; // Lock for accessing bget free list. Must be // bootstrap lock so we can use it at library // shutdown. #endif /* USE_LOCK_FOR_BGET */ #endif /* ! USE_CMP_XCHG_FOR_BGET */ #endif /* KMP_USE_BGET */ PACKED_REDUCTION_METHOD_T packed_reduction_method; /* stored by __kmpc_reduce*(), used by __kmpc_end_reduce*() */ } kmp_local_t; #define KMP_CHECK_UPDATE(a, b) \ if ((a) != (b)) \ (a) = (b) #define KMP_CHECK_UPDATE_SYNC(a, b) \ if ((a) != (b)) \ TCW_SYNC_PTR((a), (b)) #define get__blocktime(xteam, xtid) \ ((xteam)->t.t_threads[(xtid)]->th.th_current_task->td_icvs.blocktime) #define get__bt_set(xteam, xtid) \ ((xteam)->t.t_threads[(xtid)]->th.th_current_task->td_icvs.bt_set) #if KMP_USE_MONITOR #define get__bt_intervals(xteam, xtid) \ ((xteam)->t.t_threads[(xtid)]->th.th_current_task->td_icvs.bt_intervals) #endif #define get__dynamic_2(xteam, xtid) \ ((xteam)->t.t_threads[(xtid)]->th.th_current_task->td_icvs.dynamic) #define get__nproc_2(xteam, xtid) \ ((xteam)->t.t_threads[(xtid)]->th.th_current_task->td_icvs.nproc) #define get__sched_2(xteam, xtid) \ ((xteam)->t.t_threads[(xtid)]->th.th_current_task->td_icvs.sched) #define set__blocktime_team(xteam, xtid, xval) \ (((xteam)->t.t_threads[(xtid)]->th.th_current_task->td_icvs.blocktime) = \ (xval)) #if KMP_USE_MONITOR #define set__bt_intervals_team(xteam, xtid, xval) \ (((xteam)->t.t_threads[(xtid)]->th.th_current_task->td_icvs.bt_intervals) = \ (xval)) #endif #define set__bt_set_team(xteam, xtid, xval) \ (((xteam)->t.t_threads[(xtid)]->th.th_current_task->td_icvs.bt_set) = (xval)) #define set__dynamic(xthread, xval) \ (((xthread)->th.th_current_task->td_icvs.dynamic) = (xval)) #define get__dynamic(xthread) \ (((xthread)->th.th_current_task->td_icvs.dynamic) ? (FTN_TRUE) : (FTN_FALSE)) #define set__nproc(xthread, xval) \ (((xthread)->th.th_current_task->td_icvs.nproc) = (xval)) #define set__thread_limit(xthread, xval) \ (((xthread)->th.th_current_task->td_icvs.thread_limit) = (xval)) #define set__max_active_levels(xthread, xval) \ (((xthread)->th.th_current_task->td_icvs.max_active_levels) = (xval)) #define get__max_active_levels(xthread) \ ((xthread)->th.th_current_task->td_icvs.max_active_levels) #define set__sched(xthread, xval) \ (((xthread)->th.th_current_task->td_icvs.sched) = (xval)) #define set__proc_bind(xthread, xval) \ (((xthread)->th.th_current_task->td_icvs.proc_bind) = (xval)) #define get__proc_bind(xthread) \ ((xthread)->th.th_current_task->td_icvs.proc_bind) // OpenMP tasking data structures typedef enum kmp_tasking_mode { tskm_immediate_exec = 0, tskm_extra_barrier = 1, tskm_task_teams = 2, tskm_max = 2 } kmp_tasking_mode_t; extern kmp_tasking_mode_t __kmp_tasking_mode; /* determines how/when to execute tasks */ extern int __kmp_task_stealing_constraint; extern int __kmp_enable_task_throttling; extern kmp_int32 __kmp_default_device; // Set via OMP_DEFAULT_DEVICE if // specified, defaults to 0 otherwise // Set via OMP_MAX_TASK_PRIORITY if specified, defaults to 0 otherwise extern kmp_int32 __kmp_max_task_priority; // Set via KMP_TASKLOOP_MIN_TASKS if specified, defaults to 0 otherwise extern kmp_uint64 __kmp_taskloop_min_tasks; /* NOTE: kmp_taskdata_t and kmp_task_t structures allocated in single block with taskdata first */ #define KMP_TASK_TO_TASKDATA(task) (((kmp_taskdata_t *)task) - 1) #define KMP_TASKDATA_TO_TASK(taskdata) (kmp_task_t *)(taskdata + 1) // The tt_found_tasks flag is a signal to all threads in the team that tasks // were spawned and queued since the previous barrier release. #define KMP_TASKING_ENABLED(task_team) \ (TCR_SYNC_4((task_team)->tt.tt_found_tasks) == TRUE) /*! @ingroup BASIC_TYPES @{ */ /*! */ typedef kmp_int32 (*kmp_routine_entry_t)(kmp_int32, void *); typedef union kmp_cmplrdata { kmp_int32 priority; /**< priority specified by user for the task */ kmp_routine_entry_t destructors; /* pointer to function to invoke deconstructors of firstprivate C++ objects */ /* future data */ } kmp_cmplrdata_t; /* sizeof_kmp_task_t passed as arg to kmpc_omp_task call */ /*! */ typedef struct kmp_task { /* GEH: Shouldn't this be aligned somehow? */ void *shareds; /**< pointer to block of pointers to shared vars */ kmp_routine_entry_t routine; /**< pointer to routine to call for executing task */ kmp_int32 part_id; /**< part id for the task */ kmp_cmplrdata_t data1; /* Two known optional additions: destructors and priority */ kmp_cmplrdata_t data2; /* Process destructors first, priority second */ /* future data */ /* private vars */ } kmp_task_t; /*! @} */ typedef struct kmp_taskgroup { std::atomic count; // number of allocated and incomplete tasks std::atomic cancel_request; // request for cancellation of this taskgroup struct kmp_taskgroup *parent; // parent taskgroup // Block of data to perform task reduction void *reduce_data; // reduction related info kmp_int32 reduce_num_data; // number of data items to reduce } kmp_taskgroup_t; // forward declarations typedef union kmp_depnode kmp_depnode_t; typedef struct kmp_depnode_list kmp_depnode_list_t; typedef struct kmp_dephash_entry kmp_dephash_entry_t; // Compiler sends us this info: typedef struct kmp_depend_info { kmp_intptr_t base_addr; size_t len; struct { bool in : 1; bool out : 1; bool mtx : 1; } flags; } kmp_depend_info_t; // Internal structures to work with task dependencies: struct kmp_depnode_list { kmp_depnode_t *node; kmp_depnode_list_t *next; }; // Max number of mutexinoutset dependencies per node #define MAX_MTX_DEPS 4 typedef struct kmp_base_depnode { kmp_depnode_list_t *successors; /* used under lock */ kmp_task_t *task; /* non-NULL if depnode is active, used under lock */ kmp_lock_t *mtx_locks[MAX_MTX_DEPS]; /* lock mutexinoutset dependent tasks */ kmp_int32 mtx_num_locks; /* number of locks in mtx_locks array */ kmp_lock_t lock; /* guards shared fields: task, successors */ #if KMP_SUPPORT_GRAPH_OUTPUT kmp_uint32 id; #endif std::atomic npredecessors; std::atomic nrefs; } kmp_base_depnode_t; union KMP_ALIGN_CACHE kmp_depnode { double dn_align; /* use worst case alignment */ char dn_pad[KMP_PAD(kmp_base_depnode_t, CACHE_LINE)]; kmp_base_depnode_t dn; }; struct kmp_dephash_entry { kmp_intptr_t addr; kmp_depnode_t *last_out; kmp_depnode_list_t *last_ins; kmp_depnode_list_t *last_mtxs; kmp_int32 last_flag; kmp_lock_t *mtx_lock; /* is referenced by depnodes w/mutexinoutset dep */ kmp_dephash_entry_t *next_in_bucket; }; typedef struct kmp_dephash { kmp_dephash_entry_t **buckets; size_t size; size_t generation; kmp_uint32 nelements; kmp_uint32 nconflicts; } kmp_dephash_t; typedef struct kmp_task_affinity_info { kmp_intptr_t base_addr; size_t len; struct { bool flag1 : 1; bool flag2 : 1; kmp_int32 reserved : 30; } flags; } kmp_task_affinity_info_t; typedef enum kmp_event_type_t { KMP_EVENT_UNINITIALIZED = 0, KMP_EVENT_ALLOW_COMPLETION = 1 } kmp_event_type_t; typedef struct { kmp_event_type_t type; kmp_tas_lock_t lock; union { kmp_task_t *task; } ed; } kmp_event_t; #ifdef BUILD_TIED_TASK_STACK /* Tied Task stack definitions */ typedef struct kmp_stack_block { kmp_taskdata_t *sb_block[TASK_STACK_BLOCK_SIZE]; struct kmp_stack_block *sb_next; struct kmp_stack_block *sb_prev; } kmp_stack_block_t; typedef struct kmp_task_stack { kmp_stack_block_t ts_first_block; // first block of stack entries kmp_taskdata_t **ts_top; // pointer to the top of stack kmp_int32 ts_entries; // number of entries on the stack } kmp_task_stack_t; #endif // BUILD_TIED_TASK_STACK typedef struct kmp_tasking_flags { /* Total struct must be exactly 32 bits */ /* Compiler flags */ /* Total compiler flags must be 16 bits */ unsigned tiedness : 1; /* task is either tied (1) or untied (0) */ unsigned final : 1; /* task is final(1) so execute immediately */ unsigned merged_if0 : 1; /* no __kmpc_task_{begin/complete}_if0 calls in if0 code path */ unsigned destructors_thunk : 1; /* set if the compiler creates a thunk to invoke destructors from the runtime */ unsigned proxy : 1; /* task is a proxy task (it will be executed outside the context of the RTL) */ unsigned priority_specified : 1; /* set if the compiler provides priority setting for the task */ unsigned detachable : 1; /* 1 == can detach */ unsigned reserved : 9; /* reserved for compiler use */ /* Library flags */ /* Total library flags must be 16 bits */ unsigned tasktype : 1; /* task is either explicit(1) or implicit (0) */ unsigned task_serial : 1; // task is executed immediately (1) or deferred (0) unsigned tasking_ser : 1; // all tasks in team are either executed immediately // (1) or may be deferred (0) unsigned team_serial : 1; // entire team is serial (1) [1 thread] or parallel // (0) [>= 2 threads] /* If either team_serial or tasking_ser is set, task team may be NULL */ /* Task State Flags: */ unsigned started : 1; /* 1==started, 0==not started */ unsigned executing : 1; /* 1==executing, 0==not executing */ unsigned complete : 1; /* 1==complete, 0==not complete */ unsigned freed : 1; /* 1==freed, 0==allocated */ unsigned native : 1; /* 1==gcc-compiled task, 0==intel */ unsigned reserved31 : 7; /* reserved for library use */ } kmp_tasking_flags_t; struct kmp_taskdata { /* aligned during dynamic allocation */ kmp_int32 td_task_id; /* id, assigned by debugger */ kmp_tasking_flags_t td_flags; /* task flags */ kmp_team_t *td_team; /* team for this task */ kmp_info_p *td_alloc_thread; /* thread that allocated data structures */ /* Currently not used except for perhaps IDB */ kmp_taskdata_t *td_parent; /* parent task */ kmp_int32 td_level; /* task nesting level */ std::atomic td_untied_count; // untied task active parts counter ident_t *td_ident; /* task identifier */ // Taskwait data. ident_t *td_taskwait_ident; kmp_uint32 td_taskwait_counter; kmp_int32 td_taskwait_thread; /* gtid + 1 of thread encountered taskwait */ KMP_ALIGN_CACHE kmp_internal_control_t td_icvs; /* Internal control variables for the task */ KMP_ALIGN_CACHE std::atomic td_allocated_child_tasks; /* Child tasks (+ current task) not yet deallocated */ std::atomic td_incomplete_child_tasks; /* Child tasks not yet complete */ kmp_taskgroup_t *td_taskgroup; // Each task keeps pointer to its current taskgroup kmp_dephash_t *td_dephash; // Dependencies for children tasks are tracked from here kmp_depnode_t *td_depnode; // Pointer to graph node if this task has dependencies kmp_task_team_t *td_task_team; kmp_int32 td_size_alloc; // The size of task structure, including shareds etc. #if defined(KMP_GOMP_COMPAT) // 4 or 8 byte integers for the loop bounds in GOMP_taskloop kmp_int32 td_size_loop_bounds; #endif kmp_taskdata_t *td_last_tied; // keep tied task for task scheduling constraint #if defined(KMP_GOMP_COMPAT) // GOMP sends in a copy function for copy constructors void (*td_copy_func)(void *, void *); #endif kmp_event_t td_allow_completion_event; #if OMPT_SUPPORT ompt_task_info_t ompt_task_info; #endif }; // struct kmp_taskdata // Make sure padding above worked KMP_BUILD_ASSERT(sizeof(kmp_taskdata_t) % sizeof(void *) == 0); // Data for task team but per thread typedef struct kmp_base_thread_data { kmp_info_p *td_thr; // Pointer back to thread info // Used only in __kmp_execute_tasks_template, maybe not avail until task is // queued? kmp_bootstrap_lock_t td_deque_lock; // Lock for accessing deque kmp_taskdata_t * *td_deque; // Deque of tasks encountered by td_thr, dynamically allocated kmp_int32 td_deque_size; // Size of deck kmp_uint32 td_deque_head; // Head of deque (will wrap) kmp_uint32 td_deque_tail; // Tail of deque (will wrap) kmp_int32 td_deque_ntasks; // Number of tasks in deque // GEH: shouldn't this be volatile since used in while-spin? kmp_int32 td_deque_last_stolen; // Thread number of last successful steal #ifdef BUILD_TIED_TASK_STACK kmp_task_stack_t td_susp_tied_tasks; // Stack of suspended tied tasks for task // scheduling constraint #endif // BUILD_TIED_TASK_STACK } kmp_base_thread_data_t; #define TASK_DEQUE_BITS 8 // Used solely to define INITIAL_TASK_DEQUE_SIZE #define INITIAL_TASK_DEQUE_SIZE (1 << TASK_DEQUE_BITS) #define TASK_DEQUE_SIZE(td) ((td).td_deque_size) #define TASK_DEQUE_MASK(td) ((td).td_deque_size - 1) typedef union KMP_ALIGN_CACHE kmp_thread_data { kmp_base_thread_data_t td; double td_align; /* use worst case alignment */ char td_pad[KMP_PAD(kmp_base_thread_data_t, CACHE_LINE)]; } kmp_thread_data_t; // Data for task teams which are used when tasking is enabled for the team typedef struct kmp_base_task_team { kmp_bootstrap_lock_t tt_threads_lock; /* Lock used to allocate per-thread part of task team */ /* must be bootstrap lock since used at library shutdown*/ kmp_task_team_t *tt_next; /* For linking the task team free list */ kmp_thread_data_t *tt_threads_data; /* Array of per-thread structures for task team */ /* Data survives task team deallocation */ kmp_int32 tt_found_tasks; /* Have we found tasks and queued them while executing this team? */ /* TRUE means tt_threads_data is set up and initialized */ kmp_int32 tt_nproc; /* #threads in team */ kmp_int32 tt_max_threads; // # entries allocated for threads_data array kmp_int32 tt_found_proxy_tasks; // found proxy tasks since last barrier kmp_int32 tt_untied_task_encountered; KMP_ALIGN_CACHE std::atomic tt_unfinished_threads; /* #threads still active */ KMP_ALIGN_CACHE volatile kmp_uint32 tt_active; /* is the team still actively executing tasks */ } kmp_base_task_team_t; union KMP_ALIGN_CACHE kmp_task_team { kmp_base_task_team_t tt; double tt_align; /* use worst case alignment */ char tt_pad[KMP_PAD(kmp_base_task_team_t, CACHE_LINE)]; }; #if (USE_FAST_MEMORY == 3) || (USE_FAST_MEMORY == 5) // Free lists keep same-size free memory slots for fast memory allocation // routines typedef struct kmp_free_list { void *th_free_list_self; // Self-allocated tasks free list void *th_free_list_sync; // Self-allocated tasks stolen/returned by other // threads void *th_free_list_other; // Non-self free list (to be returned to owner's // sync list) } kmp_free_list_t; #endif #if KMP_NESTED_HOT_TEAMS // Hot teams array keeps hot teams and their sizes for given thread. Hot teams // are not put in teams pool, and they don't put threads in threads pool. typedef struct kmp_hot_team_ptr { kmp_team_p *hot_team; // pointer to hot_team of given nesting level kmp_int32 hot_team_nth; // number of threads allocated for the hot_team } kmp_hot_team_ptr_t; #endif typedef struct kmp_teams_size { kmp_int32 nteams; // number of teams in a league kmp_int32 nth; // number of threads in each team of the league } kmp_teams_size_t; // This struct stores a thread that acts as a "root" for a contention // group. Contention groups are rooted at kmp_root threads, but also at // each master thread of each team created in the teams construct. // This struct therefore also stores a thread_limit associated with // that contention group, and a counter to track the number of threads // active in that contention group. Each thread has a list of these: CG // root threads have an entry in their list in which cg_root refers to // the thread itself, whereas other workers in the CG will have a // single entry where cg_root is same as the entry containing their CG // root. When a thread encounters a teams construct, it will add a new // entry to the front of its list, because it now roots a new CG. typedef struct kmp_cg_root { kmp_info_p *cg_root; // "root" thread for a contention group // The CG root's limit comes from OMP_THREAD_LIMIT for root threads, or // thread_limit clause for teams masters kmp_int32 cg_thread_limit; kmp_int32 cg_nthreads; // Count of active threads in CG rooted at cg_root struct kmp_cg_root *up; // pointer to higher level CG root in list } kmp_cg_root_t; // OpenMP thread data structures typedef struct KMP_ALIGN_CACHE kmp_base_info { /* Start with the readonly data which is cache aligned and padded. This is written before the thread starts working by the master. Uber masters may update themselves later. Usage does not consider serialized regions. */ kmp_desc_t th_info; kmp_team_p *th_team; /* team we belong to */ kmp_root_p *th_root; /* pointer to root of task hierarchy */ kmp_info_p *th_next_pool; /* next available thread in the pool */ kmp_disp_t *th_dispatch; /* thread's dispatch data */ int th_in_pool; /* in thread pool (32 bits for TCR/TCW) */ /* The following are cached from the team info structure */ /* TODO use these in more places as determined to be needed via profiling */ int th_team_nproc; /* number of threads in a team */ kmp_info_p *th_team_master; /* the team's master thread */ int th_team_serialized; /* team is serialized */ microtask_t th_teams_microtask; /* save entry address for teams construct */ int th_teams_level; /* save initial level of teams construct */ /* it is 0 on device but may be any on host */ /* The blocktime info is copied from the team struct to the thread struct */ /* at the start of a barrier, and the values stored in the team are used */ /* at points in the code where the team struct is no longer guaranteed */ /* to exist (from the POV of worker threads). */ #if KMP_USE_MONITOR int th_team_bt_intervals; int th_team_bt_set; #else kmp_uint64 th_team_bt_intervals; #endif #if KMP_AFFINITY_SUPPORTED kmp_affin_mask_t *th_affin_mask; /* thread's current affinity mask */ #endif omp_allocator_handle_t th_def_allocator; /* default allocator */ /* The data set by the master at reinit, then R/W by the worker */ KMP_ALIGN_CACHE int th_set_nproc; /* if > 0, then only use this request for the next fork */ #if KMP_NESTED_HOT_TEAMS kmp_hot_team_ptr_t *th_hot_teams; /* array of hot teams */ #endif kmp_proc_bind_t th_set_proc_bind; /* if != proc_bind_default, use request for next fork */ kmp_teams_size_t th_teams_size; /* number of teams/threads in teams construct */ #if KMP_AFFINITY_SUPPORTED int th_current_place; /* place currently bound to */ int th_new_place; /* place to bind to in par reg */ int th_first_place; /* first place in partition */ int th_last_place; /* last place in partition */ #endif int th_prev_level; /* previous level for affinity format */ int th_prev_num_threads; /* previous num_threads for affinity format */ #if USE_ITT_BUILD kmp_uint64 th_bar_arrive_time; /* arrival to barrier timestamp */ kmp_uint64 th_bar_min_time; /* minimum arrival time at the barrier */ kmp_uint64 th_frame_time; /* frame timestamp */ #endif /* USE_ITT_BUILD */ kmp_local_t th_local; struct private_common *th_pri_head; /* Now the data only used by the worker (after initial allocation) */ /* TODO the first serial team should actually be stored in the info_t structure. this will help reduce initial allocation overhead */ KMP_ALIGN_CACHE kmp_team_p *th_serial_team; /*serialized team held in reserve*/ #if OMPT_SUPPORT ompt_thread_info_t ompt_thread_info; #endif /* The following are also read by the master during reinit */ struct common_table *th_pri_common; volatile kmp_uint32 th_spin_here; /* thread-local location for spinning */ /* while awaiting queuing lock acquire */ volatile void *th_sleep_loc; // this points at a kmp_flag ident_t *th_ident; unsigned th_x; // Random number generator data unsigned th_a; // Random number generator data /* Tasking-related data for the thread */ kmp_task_team_t *th_task_team; // Task team struct kmp_taskdata_t *th_current_task; // Innermost Task being executed kmp_uint8 th_task_state; // alternating 0/1 for task team identification kmp_uint8 *th_task_state_memo_stack; // Stack holding memos of th_task_state // at nested levels kmp_uint32 th_task_state_top; // Top element of th_task_state_memo_stack kmp_uint32 th_task_state_stack_sz; // Size of th_task_state_memo_stack kmp_uint32 th_reap_state; // Non-zero indicates thread is not // tasking, thus safe to reap /* More stuff for keeping track of active/sleeping threads (this part is written by the worker thread) */ kmp_uint8 th_active_in_pool; // included in count of #active threads in pool int th_active; // ! sleeping; 32 bits for TCR/TCW struct cons_header *th_cons; // used for consistency check #if KMP_USE_HIER_SCHED // used for hierarchical scheduling kmp_hier_private_bdata_t *th_hier_bar_data; #endif /* Add the syncronizing data which is cache aligned and padded. */ KMP_ALIGN_CACHE kmp_balign_t th_bar[bs_last_barrier]; KMP_ALIGN_CACHE volatile kmp_int32 th_next_waiting; /* gtid+1 of next thread on lock wait queue, 0 if none */ #if (USE_FAST_MEMORY == 3) || (USE_FAST_MEMORY == 5) #define NUM_LISTS 4 kmp_free_list_t th_free_lists[NUM_LISTS]; // Free lists for fast memory // allocation routines #endif #if KMP_OS_WINDOWS kmp_win32_cond_t th_suspend_cv; kmp_win32_mutex_t th_suspend_mx; std::atomic th_suspend_init; #endif #if KMP_OS_UNIX kmp_cond_align_t th_suspend_cv; kmp_mutex_align_t th_suspend_mx; std::atomic th_suspend_init_count; #endif #if USE_ITT_BUILD kmp_itt_mark_t th_itt_mark_single; // alignment ??? #endif /* USE_ITT_BUILD */ #if KMP_STATS_ENABLED kmp_stats_list *th_stats; #endif #if KMP_OS_UNIX std::atomic th_blocking; #endif kmp_cg_root_t *th_cg_roots; // list of cg_roots associated with this thread } kmp_base_info_t; typedef union KMP_ALIGN_CACHE kmp_info { double th_align; /* use worst case alignment */ char th_pad[KMP_PAD(kmp_base_info_t, CACHE_LINE)]; kmp_base_info_t th; } kmp_info_t; // OpenMP thread team data structures typedef struct kmp_base_data { volatile kmp_uint32 t_value; } kmp_base_data_t; typedef union KMP_ALIGN_CACHE kmp_sleep_team { double dt_align; /* use worst case alignment */ char dt_pad[KMP_PAD(kmp_base_data_t, CACHE_LINE)]; kmp_base_data_t dt; } kmp_sleep_team_t; typedef union KMP_ALIGN_CACHE kmp_ordered_team { double dt_align; /* use worst case alignment */ char dt_pad[KMP_PAD(kmp_base_data_t, CACHE_LINE)]; kmp_base_data_t dt; } kmp_ordered_team_t; typedef int (*launch_t)(int gtid); /* Minimum number of ARGV entries to malloc if necessary */ #define KMP_MIN_MALLOC_ARGV_ENTRIES 100 // Set up how many argv pointers will fit in cache lines containing // t_inline_argv. Historically, we have supported at least 96 bytes. Using a // larger value for more space between the master write/worker read section and // read/write by all section seems to buy more performance on EPCC PARALLEL. #if KMP_ARCH_X86 || KMP_ARCH_X86_64 #define KMP_INLINE_ARGV_BYTES \ (4 * CACHE_LINE - \ ((3 * KMP_PTR_SKIP + 2 * sizeof(int) + 2 * sizeof(kmp_int8) + \ sizeof(kmp_int16) + sizeof(kmp_uint32)) % \ CACHE_LINE)) #else #define KMP_INLINE_ARGV_BYTES \ (2 * CACHE_LINE - ((3 * KMP_PTR_SKIP + 2 * sizeof(int)) % CACHE_LINE)) #endif #define KMP_INLINE_ARGV_ENTRIES (int)(KMP_INLINE_ARGV_BYTES / KMP_PTR_SKIP) typedef struct KMP_ALIGN_CACHE kmp_base_team { // Synchronization Data // --------------------------------------------------------------------------- KMP_ALIGN_CACHE kmp_ordered_team_t t_ordered; kmp_balign_team_t t_bar[bs_last_barrier]; std::atomic t_construct; // count of single directive encountered by team char pad[sizeof(kmp_lock_t)]; // padding to maintain performance on big iron // [0] - parallel / [1] - worksharing task reduction data shared by taskgroups std::atomic t_tg_reduce_data[2]; // to support task modifier std::atomic t_tg_fini_counter[2]; // sync end of task reductions // Master only // --------------------------------------------------------------------------- KMP_ALIGN_CACHE int t_master_tid; // tid of master in parent team int t_master_this_cons; // "this_construct" single counter of master in parent // team ident_t *t_ident; // if volatile, have to change too much other crud to // volatile too kmp_team_p *t_parent; // parent team kmp_team_p *t_next_pool; // next free team in the team pool kmp_disp_t *t_dispatch; // thread's dispatch data kmp_task_team_t *t_task_team[2]; // Task team struct; switch between 2 kmp_proc_bind_t t_proc_bind; // bind type for par region #if USE_ITT_BUILD kmp_uint64 t_region_time; // region begin timestamp #endif /* USE_ITT_BUILD */ // Master write, workers read // -------------------------------------------------------------------------- KMP_ALIGN_CACHE void **t_argv; int t_argc; int t_nproc; // number of threads in team microtask_t t_pkfn; launch_t t_invoke; // procedure to launch the microtask #if OMPT_SUPPORT ompt_team_info_t ompt_team_info; ompt_lw_taskteam_t *ompt_serialized_team_info; #endif #if KMP_ARCH_X86 || KMP_ARCH_X86_64 kmp_int8 t_fp_control_saved; kmp_int8 t_pad2b; kmp_int16 t_x87_fpu_control_word; // FP control regs kmp_uint32 t_mxcsr; #endif /* KMP_ARCH_X86 || KMP_ARCH_X86_64 */ void *t_inline_argv[KMP_INLINE_ARGV_ENTRIES]; KMP_ALIGN_CACHE kmp_info_t **t_threads; kmp_taskdata_t *t_implicit_task_taskdata; // Taskdata for the thread's implicit task int t_level; // nested parallel level KMP_ALIGN_CACHE int t_max_argc; int t_max_nproc; // max threads this team can handle (dynamically expandable) int t_serialized; // levels deep of serialized teams dispatch_shared_info_t *t_disp_buffer; // buffers for dispatch system int t_id; // team's id, assigned by debugger. int t_active_level; // nested active parallel level kmp_r_sched_t t_sched; // run-time schedule for the team #if KMP_AFFINITY_SUPPORTED int t_first_place; // first & last place in parent thread's partition. int t_last_place; // Restore these values to master after par region. #endif // KMP_AFFINITY_SUPPORTED int t_display_affinity; int t_size_changed; // team size was changed?: 0: no, 1: yes, -1: changed via // omp_set_num_threads() call omp_allocator_handle_t t_def_allocator; /* default allocator */ // Read/write by workers as well #if (KMP_ARCH_X86 || KMP_ARCH_X86_64) // Using CACHE_LINE=64 reduces memory footprint, but causes a big perf // regression of epcc 'parallel' and 'barrier' on fxe256lin01. This extra // padding serves to fix the performance of epcc 'parallel' and 'barrier' when // CACHE_LINE=64. TODO: investigate more and get rid if this padding. char dummy_padding[1024]; #endif // Internal control stack for additional nested teams. KMP_ALIGN_CACHE kmp_internal_control_t *t_control_stack_top; // for SERIALIZED teams nested 2 or more levels deep // typed flag to store request state of cancellation std::atomic t_cancel_request; int t_master_active; // save on fork, restore on join void *t_copypriv_data; // team specific pointer to copyprivate data array #if KMP_OS_WINDOWS std::atomic t_copyin_counter; #endif #if USE_ITT_BUILD void *t_stack_id; // team specific stack stitching id (for ittnotify) #endif /* USE_ITT_BUILD */ } kmp_base_team_t; union KMP_ALIGN_CACHE kmp_team { kmp_base_team_t t; double t_align; /* use worst case alignment */ char t_pad[KMP_PAD(kmp_base_team_t, CACHE_LINE)]; }; typedef union KMP_ALIGN_CACHE kmp_time_global { double dt_align; /* use worst case alignment */ char dt_pad[KMP_PAD(kmp_base_data_t, CACHE_LINE)]; kmp_base_data_t dt; } kmp_time_global_t; typedef struct kmp_base_global { /* cache-aligned */ kmp_time_global_t g_time; /* non cache-aligned */ volatile int g_abort; volatile int g_done; int g_dynamic; enum dynamic_mode g_dynamic_mode; } kmp_base_global_t; typedef union KMP_ALIGN_CACHE kmp_global { kmp_base_global_t g; double g_align; /* use worst case alignment */ char g_pad[KMP_PAD(kmp_base_global_t, CACHE_LINE)]; } kmp_global_t; typedef struct kmp_base_root { // TODO: GEH - combine r_active with r_in_parallel then r_active == // (r_in_parallel>= 0) // TODO: GEH - then replace r_active with t_active_levels if we can to reduce // the synch overhead or keeping r_active volatile int r_active; /* TRUE if some region in a nest has > 1 thread */ // keeps a count of active parallel regions per root std::atomic r_in_parallel; // GEH: This is misnamed, should be r_active_levels kmp_team_t *r_root_team; kmp_team_t *r_hot_team; kmp_info_t *r_uber_thread; kmp_lock_t r_begin_lock; volatile int r_begin; int r_blocktime; /* blocktime for this root and descendants */ } kmp_base_root_t; typedef union KMP_ALIGN_CACHE kmp_root { kmp_base_root_t r; double r_align; /* use worst case alignment */ char r_pad[KMP_PAD(kmp_base_root_t, CACHE_LINE)]; } kmp_root_t; struct fortran_inx_info { kmp_int32 data; }; /* ------------------------------------------------------------------------ */ extern int __kmp_settings; extern int __kmp_duplicate_library_ok; #if USE_ITT_BUILD extern int __kmp_forkjoin_frames; extern int __kmp_forkjoin_frames_mode; #endif extern PACKED_REDUCTION_METHOD_T __kmp_force_reduction_method; extern int __kmp_determ_red; #ifdef KMP_DEBUG extern int kmp_a_debug; extern int kmp_b_debug; extern int kmp_c_debug; extern int kmp_d_debug; extern int kmp_e_debug; extern int kmp_f_debug; #endif /* KMP_DEBUG */ /* For debug information logging using rotating buffer */ #define KMP_DEBUG_BUF_LINES_INIT 512 #define KMP_DEBUG_BUF_LINES_MIN 1 #define KMP_DEBUG_BUF_CHARS_INIT 128 #define KMP_DEBUG_BUF_CHARS_MIN 2 extern int __kmp_debug_buf; /* TRUE means use buffer, FALSE means print to stderr */ extern int __kmp_debug_buf_lines; /* How many lines of debug stored in buffer */ extern int __kmp_debug_buf_chars; /* How many characters allowed per line in buffer */ extern int __kmp_debug_buf_atomic; /* TRUE means use atomic update of buffer entry pointer */ extern char *__kmp_debug_buffer; /* Debug buffer itself */ extern std::atomic __kmp_debug_count; /* Counter for number of lines printed in buffer so far */ extern int __kmp_debug_buf_warn_chars; /* Keep track of char increase recommended in warnings */ /* end rotating debug buffer */ #ifdef KMP_DEBUG extern int __kmp_par_range; /* +1 => only go par for constructs in range */ #define KMP_PAR_RANGE_ROUTINE_LEN 1024 extern char __kmp_par_range_routine[KMP_PAR_RANGE_ROUTINE_LEN]; #define KMP_PAR_RANGE_FILENAME_LEN 1024 extern char __kmp_par_range_filename[KMP_PAR_RANGE_FILENAME_LEN]; extern int __kmp_par_range_lb; extern int __kmp_par_range_ub; #endif /* For printing out dynamic storage map for threads and teams */ extern int __kmp_storage_map; /* True means print storage map for threads and teams */ extern int __kmp_storage_map_verbose; /* True means storage map includes placement info */ extern int __kmp_storage_map_verbose_specified; #if KMP_ARCH_X86 || KMP_ARCH_X86_64 extern kmp_cpuinfo_t __kmp_cpuinfo; #endif extern volatile int __kmp_init_serial; extern volatile int __kmp_init_gtid; extern volatile int __kmp_init_common; extern volatile int __kmp_init_middle; extern volatile int __kmp_init_parallel; #if KMP_USE_MONITOR extern volatile int __kmp_init_monitor; #endif extern volatile int __kmp_init_user_locks; extern int __kmp_init_counter; extern int __kmp_root_counter; extern int __kmp_version; /* list of address of allocated caches for commons */ extern kmp_cached_addr_t *__kmp_threadpriv_cache_list; /* Barrier algorithm types and options */ extern kmp_uint32 __kmp_barrier_gather_bb_dflt; extern kmp_uint32 __kmp_barrier_release_bb_dflt; extern kmp_bar_pat_e __kmp_barrier_gather_pat_dflt; extern kmp_bar_pat_e __kmp_barrier_release_pat_dflt; extern kmp_uint32 __kmp_barrier_gather_branch_bits[bs_last_barrier]; extern kmp_uint32 __kmp_barrier_release_branch_bits[bs_last_barrier]; extern kmp_bar_pat_e __kmp_barrier_gather_pattern[bs_last_barrier]; extern kmp_bar_pat_e __kmp_barrier_release_pattern[bs_last_barrier]; extern char const *__kmp_barrier_branch_bit_env_name[bs_last_barrier]; extern char const *__kmp_barrier_pattern_env_name[bs_last_barrier]; extern char const *__kmp_barrier_type_name[bs_last_barrier]; extern char const *__kmp_barrier_pattern_name[bp_last_bar]; /* Global Locks */ extern kmp_bootstrap_lock_t __kmp_initz_lock; /* control initialization */ extern kmp_bootstrap_lock_t __kmp_forkjoin_lock; /* control fork/join access */ extern kmp_bootstrap_lock_t __kmp_task_team_lock; extern kmp_bootstrap_lock_t __kmp_exit_lock; /* exit() is not always thread-safe */ #if KMP_USE_MONITOR extern kmp_bootstrap_lock_t __kmp_monitor_lock; /* control monitor thread creation */ #endif extern kmp_bootstrap_lock_t __kmp_tp_cached_lock; /* used for the hack to allow threadprivate cache and __kmp_threads expansion to co-exist */ extern kmp_lock_t __kmp_global_lock; /* control OS/global access */ extern kmp_queuing_lock_t __kmp_dispatch_lock; /* control dispatch access */ extern kmp_lock_t __kmp_debug_lock; /* control I/O access for KMP_DEBUG */ extern enum library_type __kmp_library; extern enum sched_type __kmp_sched; /* default runtime scheduling */ extern enum sched_type __kmp_static; /* default static scheduling method */ extern enum sched_type __kmp_guided; /* default guided scheduling method */ extern enum sched_type __kmp_auto; /* default auto scheduling method */ extern int __kmp_chunk; /* default runtime chunk size */ extern size_t __kmp_stksize; /* stack size per thread */ #if KMP_USE_MONITOR extern size_t __kmp_monitor_stksize; /* stack size for monitor thread */ #endif extern size_t __kmp_stkoffset; /* stack offset per thread */ extern int __kmp_stkpadding; /* Should we pad root thread(s) stack */ extern size_t __kmp_malloc_pool_incr; /* incremental size of pool for kmp_malloc() */ extern int __kmp_env_stksize; /* was KMP_STACKSIZE specified? */ extern int __kmp_env_blocktime; /* was KMP_BLOCKTIME specified? */ extern int __kmp_env_checks; /* was KMP_CHECKS specified? */ extern int __kmp_env_consistency_check; // was KMP_CONSISTENCY_CHECK specified? extern int __kmp_generate_warnings; /* should we issue warnings? */ extern int __kmp_reserve_warn; /* have we issued reserve_threads warning? */ #ifdef DEBUG_SUSPEND extern int __kmp_suspend_count; /* count inside __kmp_suspend_template() */ #endif extern kmp_int32 __kmp_use_yield; extern kmp_int32 __kmp_use_yield_exp_set; extern kmp_uint32 __kmp_yield_init; extern kmp_uint32 __kmp_yield_next; /* ------------------------------------------------------------------------- */ extern int __kmp_allThreadsSpecified; extern size_t __kmp_align_alloc; /* following data protected by initialization routines */ extern int __kmp_xproc; /* number of processors in the system */ extern int __kmp_avail_proc; /* number of processors available to the process */ extern size_t __kmp_sys_min_stksize; /* system-defined minimum stack size */ extern int __kmp_sys_max_nth; /* system-imposed maximum number of threads */ // maximum total number of concurrently-existing threads on device extern int __kmp_max_nth; // maximum total number of concurrently-existing threads in a contention group extern int __kmp_cg_max_nth; extern int __kmp_teams_max_nth; // max threads used in a teams construct extern int __kmp_threads_capacity; /* capacity of the arrays __kmp_threads and __kmp_root */ extern int __kmp_dflt_team_nth; /* default number of threads in a parallel region a la OMP_NUM_THREADS */ extern int __kmp_dflt_team_nth_ub; /* upper bound on "" determined at serial initialization */ extern int __kmp_tp_capacity; /* capacity of __kmp_threads if threadprivate is used (fixed) */ extern int __kmp_tp_cached; /* whether threadprivate cache has been created (__kmpc_threadprivate_cached()) */ extern int __kmp_dflt_blocktime; /* number of milliseconds to wait before blocking (env setting) */ #if KMP_USE_MONITOR extern int __kmp_monitor_wakeups; /* number of times monitor wakes up per second */ extern int __kmp_bt_intervals; /* number of monitor timestamp intervals before blocking */ #endif #ifdef KMP_ADJUST_BLOCKTIME extern int __kmp_zero_bt; /* whether blocktime has been forced to zero */ #endif /* KMP_ADJUST_BLOCKTIME */ #ifdef KMP_DFLT_NTH_CORES extern int __kmp_ncores; /* Total number of cores for threads placement */ #endif /* Number of millisecs to delay on abort for Intel(R) VTune(TM) tools */ extern int __kmp_abort_delay; extern int __kmp_need_register_atfork_specified; extern int __kmp_need_register_atfork; /* At initialization, call pthread_atfork to install fork handler */ extern int __kmp_gtid_mode; /* Method of getting gtid, values: 0 - not set, will be set at runtime 1 - using stack search 2 - dynamic TLS (pthread_getspecific(Linux* OS/OS X*) or TlsGetValue(Windows* OS)) 3 - static TLS (__declspec(thread) __kmp_gtid), Linux* OS .so only. */ extern int __kmp_adjust_gtid_mode; /* If true, adjust method based on #threads */ #ifdef KMP_TDATA_GTID extern KMP_THREAD_LOCAL int __kmp_gtid; #endif extern int __kmp_tls_gtid_min; /* #threads below which use sp search for gtid */ extern int __kmp_foreign_tp; // If true, separate TP var for each foreign thread #if KMP_ARCH_X86 || KMP_ARCH_X86_64 extern int __kmp_inherit_fp_control; // copy fp creg(s) parent->workers at fork extern kmp_int16 __kmp_init_x87_fpu_control_word; // init thread's FP ctrl reg extern kmp_uint32 __kmp_init_mxcsr; /* init thread's mxscr */ #endif /* KMP_ARCH_X86 || KMP_ARCH_X86_64 */ // max_active_levels for nested parallelism enabled by default via // OMP_MAX_ACTIVE_LEVELS, OMP_NESTED, OMP_NUM_THREADS, and OMP_PROC_BIND extern int __kmp_dflt_max_active_levels; // Indicates whether value of __kmp_dflt_max_active_levels was already // explicitly set by OMP_MAX_ACTIVE_LEVELS or OMP_NESTED=false extern bool __kmp_dflt_max_active_levels_set; extern int __kmp_dispatch_num_buffers; /* max possible dynamic loops in concurrent execution per team */ #if KMP_NESTED_HOT_TEAMS extern int __kmp_hot_teams_mode; extern int __kmp_hot_teams_max_level; #endif #if KMP_OS_LINUX extern enum clock_function_type __kmp_clock_function; extern int __kmp_clock_function_param; #endif /* KMP_OS_LINUX */ #if KMP_MIC_SUPPORTED extern enum mic_type __kmp_mic_type; #endif #ifdef USE_LOAD_BALANCE extern double __kmp_load_balance_interval; // load balance algorithm interval #endif /* USE_LOAD_BALANCE */ // OpenMP 3.1 - Nested num threads array typedef struct kmp_nested_nthreads_t { int *nth; int size; int used; } kmp_nested_nthreads_t; extern kmp_nested_nthreads_t __kmp_nested_nth; #if KMP_USE_ADAPTIVE_LOCKS // Parameters for the speculative lock backoff system. struct kmp_adaptive_backoff_params_t { // Number of soft retries before it counts as a hard retry. kmp_uint32 max_soft_retries; // Badness is a bit mask : 0,1,3,7,15,... on each hard failure we move one to // the right kmp_uint32 max_badness; }; extern kmp_adaptive_backoff_params_t __kmp_adaptive_backoff_params; #if KMP_DEBUG_ADAPTIVE_LOCKS extern const char *__kmp_speculative_statsfile; #endif #endif // KMP_USE_ADAPTIVE_LOCKS extern int __kmp_display_env; /* TRUE or FALSE */ extern int __kmp_display_env_verbose; /* TRUE if OMP_DISPLAY_ENV=VERBOSE */ extern int __kmp_omp_cancellation; /* TRUE or FALSE */ /* ------------------------------------------------------------------------- */ /* the following are protected by the fork/join lock */ /* write: lock read: anytime */ extern kmp_info_t **__kmp_threads; /* Descriptors for the threads */ /* read/write: lock */ extern volatile kmp_team_t *__kmp_team_pool; extern volatile kmp_info_t *__kmp_thread_pool; extern kmp_info_t *__kmp_thread_pool_insert_pt; // total num threads reachable from some root thread including all root threads extern volatile int __kmp_nth; /* total number of threads reachable from some root thread including all root threads, and those in the thread pool */ extern volatile int __kmp_all_nth; extern std::atomic __kmp_thread_pool_active_nth; extern kmp_root_t **__kmp_root; /* root of thread hierarchy */ /* end data protected by fork/join lock */ /* ------------------------------------------------------------------------- */ #define __kmp_get_gtid() __kmp_get_global_thread_id() #define __kmp_entry_gtid() __kmp_get_global_thread_id_reg() #define __kmp_get_tid() (__kmp_tid_from_gtid(__kmp_get_gtid())) #define __kmp_get_team() (__kmp_threads[(__kmp_get_gtid())]->th.th_team) #define __kmp_get_thread() (__kmp_thread_from_gtid(__kmp_get_gtid())) // AT: Which way is correct? // AT: 1. nproc = __kmp_threads[ ( gtid ) ] -> th.th_team -> t.t_nproc; // AT: 2. nproc = __kmp_threads[ ( gtid ) ] -> th.th_team_nproc; #define __kmp_get_team_num_threads(gtid) \ (__kmp_threads[(gtid)]->th.th_team->t.t_nproc) static inline bool KMP_UBER_GTID(int gtid) { KMP_DEBUG_ASSERT(gtid >= KMP_GTID_MIN); KMP_DEBUG_ASSERT(gtid < __kmp_threads_capacity); return (gtid >= 0 && __kmp_root[gtid] && __kmp_threads[gtid] && __kmp_threads[gtid] == __kmp_root[gtid]->r.r_uber_thread); } static inline int __kmp_tid_from_gtid(int gtid) { KMP_DEBUG_ASSERT(gtid >= 0); return __kmp_threads[gtid]->th.th_info.ds.ds_tid; } static inline int __kmp_gtid_from_tid(int tid, const kmp_team_t *team) { KMP_DEBUG_ASSERT(tid >= 0 && team); return team->t.t_threads[tid]->th.th_info.ds.ds_gtid; } static inline int __kmp_gtid_from_thread(const kmp_info_t *thr) { KMP_DEBUG_ASSERT(thr); return thr->th.th_info.ds.ds_gtid; } static inline kmp_info_t *__kmp_thread_from_gtid(int gtid) { KMP_DEBUG_ASSERT(gtid >= 0); return __kmp_threads[gtid]; } static inline kmp_team_t *__kmp_team_from_gtid(int gtid) { KMP_DEBUG_ASSERT(gtid >= 0); return __kmp_threads[gtid]->th.th_team; } /* ------------------------------------------------------------------------- */ extern kmp_global_t __kmp_global; /* global status */ extern kmp_info_t __kmp_monitor; // For Debugging Support Library extern std::atomic __kmp_team_counter; // For Debugging Support Library extern std::atomic __kmp_task_counter; #if USE_DEBUGGER #define _KMP_GEN_ID(counter) \ (__kmp_debugging ? KMP_ATOMIC_INC(&counter) + 1 : ~0) #else #define _KMP_GEN_ID(counter) (~0) #endif /* USE_DEBUGGER */ #define KMP_GEN_TASK_ID() _KMP_GEN_ID(__kmp_task_counter) #define KMP_GEN_TEAM_ID() _KMP_GEN_ID(__kmp_team_counter) /* ------------------------------------------------------------------------ */ extern void __kmp_print_storage_map_gtid(int gtid, void *p1, void *p2, size_t size, char const *format, ...); extern void __kmp_serial_initialize(void); extern void __kmp_middle_initialize(void); extern void __kmp_parallel_initialize(void); extern void __kmp_internal_begin(void); extern void __kmp_internal_end_library(int gtid); extern void __kmp_internal_end_thread(int gtid); extern void __kmp_internal_end_atexit(void); extern void __kmp_internal_end_dtor(void); extern void __kmp_internal_end_dest(void *); extern int __kmp_register_root(int initial_thread); extern void __kmp_unregister_root(int gtid); extern int __kmp_ignore_mppbeg(void); extern int __kmp_ignore_mppend(void); extern int __kmp_enter_single(int gtid, ident_t *id_ref, int push_ws); extern void __kmp_exit_single(int gtid); extern void __kmp_parallel_deo(int *gtid_ref, int *cid_ref, ident_t *loc_ref); extern void __kmp_parallel_dxo(int *gtid_ref, int *cid_ref, ident_t *loc_ref); #ifdef USE_LOAD_BALANCE extern int __kmp_get_load_balance(int); #endif extern int __kmp_get_global_thread_id(void); extern int __kmp_get_global_thread_id_reg(void); extern void __kmp_exit_thread(int exit_status); extern void __kmp_abort(char const *format, ...); extern void __kmp_abort_thread(void); KMP_NORETURN extern void __kmp_abort_process(void); extern void __kmp_warn(char const *format, ...); extern void __kmp_set_num_threads(int new_nth, int gtid); // Returns current thread (pointer to kmp_info_t). Current thread *must* be // registered. static inline kmp_info_t *__kmp_entry_thread() { int gtid = __kmp_entry_gtid(); return __kmp_threads[gtid]; } extern void __kmp_set_max_active_levels(int gtid, int new_max_active_levels); extern int __kmp_get_max_active_levels(int gtid); extern int __kmp_get_ancestor_thread_num(int gtid, int level); extern int __kmp_get_team_size(int gtid, int level); extern void __kmp_set_schedule(int gtid, kmp_sched_t new_sched, int chunk); extern void __kmp_get_schedule(int gtid, kmp_sched_t *sched, int *chunk); extern unsigned short __kmp_get_random(kmp_info_t *thread); extern void __kmp_init_random(kmp_info_t *thread); extern kmp_r_sched_t __kmp_get_schedule_global(void); extern void __kmp_adjust_num_threads(int new_nproc); extern void __kmp_check_stksize(size_t *val); extern void *___kmp_allocate(size_t size KMP_SRC_LOC_DECL); extern void *___kmp_page_allocate(size_t size KMP_SRC_LOC_DECL); extern void ___kmp_free(void *ptr KMP_SRC_LOC_DECL); #define __kmp_allocate(size) ___kmp_allocate((size)KMP_SRC_LOC_CURR) #define __kmp_page_allocate(size) ___kmp_page_allocate((size)KMP_SRC_LOC_CURR) #define __kmp_free(ptr) ___kmp_free((ptr)KMP_SRC_LOC_CURR) #if USE_FAST_MEMORY extern void *___kmp_fast_allocate(kmp_info_t *this_thr, size_t size KMP_SRC_LOC_DECL); extern void ___kmp_fast_free(kmp_info_t *this_thr, void *ptr KMP_SRC_LOC_DECL); extern void __kmp_free_fast_memory(kmp_info_t *this_thr); extern void __kmp_initialize_fast_memory(kmp_info_t *this_thr); #define __kmp_fast_allocate(this_thr, size) \ ___kmp_fast_allocate((this_thr), (size)KMP_SRC_LOC_CURR) #define __kmp_fast_free(this_thr, ptr) \ ___kmp_fast_free((this_thr), (ptr)KMP_SRC_LOC_CURR) #endif extern void *___kmp_thread_malloc(kmp_info_t *th, size_t size KMP_SRC_LOC_DECL); extern void *___kmp_thread_calloc(kmp_info_t *th, size_t nelem, size_t elsize KMP_SRC_LOC_DECL); extern void *___kmp_thread_realloc(kmp_info_t *th, void *ptr, size_t size KMP_SRC_LOC_DECL); extern void ___kmp_thread_free(kmp_info_t *th, void *ptr KMP_SRC_LOC_DECL); #define __kmp_thread_malloc(th, size) \ ___kmp_thread_malloc((th), (size)KMP_SRC_LOC_CURR) #define __kmp_thread_calloc(th, nelem, elsize) \ ___kmp_thread_calloc((th), (nelem), (elsize)KMP_SRC_LOC_CURR) #define __kmp_thread_realloc(th, ptr, size) \ ___kmp_thread_realloc((th), (ptr), (size)KMP_SRC_LOC_CURR) #define __kmp_thread_free(th, ptr) \ ___kmp_thread_free((th), (ptr)KMP_SRC_LOC_CURR) #define KMP_INTERNAL_MALLOC(sz) malloc(sz) #define KMP_INTERNAL_FREE(p) free(p) #define KMP_INTERNAL_REALLOC(p, sz) realloc((p), (sz)) #define KMP_INTERNAL_CALLOC(n, sz) calloc((n), (sz)) extern void __kmp_push_num_threads(ident_t *loc, int gtid, int num_threads); extern void __kmp_push_proc_bind(ident_t *loc, int gtid, kmp_proc_bind_t proc_bind); extern void __kmp_push_num_teams(ident_t *loc, int gtid, int num_teams, int num_threads); extern void __kmp_yield(); extern void __kmpc_dispatch_init_4(ident_t *loc, kmp_int32 gtid, enum sched_type schedule, kmp_int32 lb, kmp_int32 ub, kmp_int32 st, kmp_int32 chunk); extern void __kmpc_dispatch_init_4u(ident_t *loc, kmp_int32 gtid, enum sched_type schedule, kmp_uint32 lb, kmp_uint32 ub, kmp_int32 st, kmp_int32 chunk); extern void __kmpc_dispatch_init_8(ident_t *loc, kmp_int32 gtid, enum sched_type schedule, kmp_int64 lb, kmp_int64 ub, kmp_int64 st, kmp_int64 chunk); extern void __kmpc_dispatch_init_8u(ident_t *loc, kmp_int32 gtid, enum sched_type schedule, kmp_uint64 lb, kmp_uint64 ub, kmp_int64 st, kmp_int64 chunk); extern int __kmpc_dispatch_next_4(ident_t *loc, kmp_int32 gtid, kmp_int32 *p_last, kmp_int32 *p_lb, kmp_int32 *p_ub, kmp_int32 *p_st); extern int __kmpc_dispatch_next_4u(ident_t *loc, kmp_int32 gtid, kmp_int32 *p_last, kmp_uint32 *p_lb, kmp_uint32 *p_ub, kmp_int32 *p_st); extern int __kmpc_dispatch_next_8(ident_t *loc, kmp_int32 gtid, kmp_int32 *p_last, kmp_int64 *p_lb, kmp_int64 *p_ub, kmp_int64 *p_st); extern int __kmpc_dispatch_next_8u(ident_t *loc, kmp_int32 gtid, kmp_int32 *p_last, kmp_uint64 *p_lb, kmp_uint64 *p_ub, kmp_int64 *p_st); extern void __kmpc_dispatch_fini_4(ident_t *loc, kmp_int32 gtid); extern void __kmpc_dispatch_fini_8(ident_t *loc, kmp_int32 gtid); extern void __kmpc_dispatch_fini_4u(ident_t *loc, kmp_int32 gtid); extern void __kmpc_dispatch_fini_8u(ident_t *loc, kmp_int32 gtid); #ifdef KMP_GOMP_COMPAT extern void __kmp_aux_dispatch_init_4(ident_t *loc, kmp_int32 gtid, enum sched_type schedule, kmp_int32 lb, kmp_int32 ub, kmp_int32 st, kmp_int32 chunk, int push_ws); extern void __kmp_aux_dispatch_init_4u(ident_t *loc, kmp_int32 gtid, enum sched_type schedule, kmp_uint32 lb, kmp_uint32 ub, kmp_int32 st, kmp_int32 chunk, int push_ws); extern void __kmp_aux_dispatch_init_8(ident_t *loc, kmp_int32 gtid, enum sched_type schedule, kmp_int64 lb, kmp_int64 ub, kmp_int64 st, kmp_int64 chunk, int push_ws); extern void __kmp_aux_dispatch_init_8u(ident_t *loc, kmp_int32 gtid, enum sched_type schedule, kmp_uint64 lb, kmp_uint64 ub, kmp_int64 st, kmp_int64 chunk, int push_ws); extern void __kmp_aux_dispatch_fini_chunk_4(ident_t *loc, kmp_int32 gtid); extern void __kmp_aux_dispatch_fini_chunk_8(ident_t *loc, kmp_int32 gtid); extern void __kmp_aux_dispatch_fini_chunk_4u(ident_t *loc, kmp_int32 gtid); extern void __kmp_aux_dispatch_fini_chunk_8u(ident_t *loc, kmp_int32 gtid); #endif /* KMP_GOMP_COMPAT */ extern kmp_uint32 __kmp_eq_4(kmp_uint32 value, kmp_uint32 checker); extern kmp_uint32 __kmp_neq_4(kmp_uint32 value, kmp_uint32 checker); extern kmp_uint32 __kmp_lt_4(kmp_uint32 value, kmp_uint32 checker); extern kmp_uint32 __kmp_ge_4(kmp_uint32 value, kmp_uint32 checker); extern kmp_uint32 __kmp_le_4(kmp_uint32 value, kmp_uint32 checker); extern kmp_uint32 __kmp_wait_4(kmp_uint32 volatile *spinner, kmp_uint32 checker, kmp_uint32 (*pred)(kmp_uint32, kmp_uint32), void *obj); extern void __kmp_wait_4_ptr(void *spinner, kmp_uint32 checker, kmp_uint32 (*pred)(void *, kmp_uint32), void *obj); class kmp_flag_32; class kmp_flag_64; class kmp_flag_oncore; extern void __kmp_wait_64(kmp_info_t *this_thr, kmp_flag_64 *flag, int final_spin #if USE_ITT_BUILD , void *itt_sync_obj #endif ); extern void __kmp_release_64(kmp_flag_64 *flag); extern void __kmp_infinite_loop(void); extern void __kmp_cleanup(void); #if KMP_HANDLE_SIGNALS extern int __kmp_handle_signals; extern void __kmp_install_signals(int parallel_init); extern void __kmp_remove_signals(void); #endif extern void __kmp_clear_system_time(void); extern void __kmp_read_system_time(double *delta); extern void __kmp_check_stack_overlap(kmp_info_t *thr); extern void __kmp_expand_host_name(char *buffer, size_t size); extern void __kmp_expand_file_name(char *result, size_t rlen, char *pattern); #if KMP_ARCH_X86 || KMP_ARCH_X86_64 extern void __kmp_initialize_system_tick(void); /* Initialize timer tick value */ #endif extern void __kmp_runtime_initialize(void); /* machine specific initialization */ extern void __kmp_runtime_destroy(void); #if KMP_AFFINITY_SUPPORTED extern char *__kmp_affinity_print_mask(char *buf, int buf_len, kmp_affin_mask_t *mask); extern kmp_str_buf_t *__kmp_affinity_str_buf_mask(kmp_str_buf_t *buf, kmp_affin_mask_t *mask); extern void __kmp_affinity_initialize(void); extern void __kmp_affinity_uninitialize(void); extern void __kmp_affinity_set_init_mask( int gtid, int isa_root); /* set affinity according to KMP_AFFINITY */ extern void __kmp_affinity_set_place(int gtid); extern void __kmp_affinity_determine_capable(const char *env_var); extern int __kmp_aux_set_affinity(void **mask); extern int __kmp_aux_get_affinity(void **mask); extern int __kmp_aux_get_affinity_max_proc(); extern int __kmp_aux_set_affinity_mask_proc(int proc, void **mask); extern int __kmp_aux_unset_affinity_mask_proc(int proc, void **mask); extern int __kmp_aux_get_affinity_mask_proc(int proc, void **mask); extern void __kmp_balanced_affinity(kmp_info_t *th, int team_size); #if KMP_OS_LINUX || KMP_OS_FREEBSD extern int kmp_set_thread_affinity_mask_initial(void); #endif #endif /* KMP_AFFINITY_SUPPORTED */ // No need for KMP_AFFINITY_SUPPORTED guard as only one field in the // format string is for affinity, so platforms that do not support // affinity can still use the other fields, e.g., %n for num_threads extern size_t __kmp_aux_capture_affinity(int gtid, const char *format, kmp_str_buf_t *buffer); extern void __kmp_aux_display_affinity(int gtid, const char *format); extern void __kmp_cleanup_hierarchy(); extern void __kmp_get_hierarchy(kmp_uint32 nproc, kmp_bstate_t *thr_bar); #if KMP_USE_FUTEX extern int __kmp_futex_determine_capable(void); #endif // KMP_USE_FUTEX extern void __kmp_gtid_set_specific(int gtid); extern int __kmp_gtid_get_specific(void); extern double __kmp_read_cpu_time(void); extern int __kmp_read_system_info(struct kmp_sys_info *info); #if KMP_USE_MONITOR extern void __kmp_create_monitor(kmp_info_t *th); #endif extern void *__kmp_launch_thread(kmp_info_t *thr); extern void __kmp_create_worker(int gtid, kmp_info_t *th, size_t stack_size); #if KMP_OS_WINDOWS extern int __kmp_still_running(kmp_info_t *th); extern int __kmp_is_thread_alive(kmp_info_t *th, DWORD *exit_val); extern void __kmp_free_handle(kmp_thread_t tHandle); #endif #if KMP_USE_MONITOR extern void __kmp_reap_monitor(kmp_info_t *th); #endif extern void __kmp_reap_worker(kmp_info_t *th); extern void __kmp_terminate_thread(int gtid); extern int __kmp_try_suspend_mx(kmp_info_t *th); extern void __kmp_lock_suspend_mx(kmp_info_t *th); extern void __kmp_unlock_suspend_mx(kmp_info_t *th); extern void __kmp_suspend_32(int th_gtid, kmp_flag_32 *flag); extern void __kmp_suspend_64(int th_gtid, kmp_flag_64 *flag); extern void __kmp_suspend_oncore(int th_gtid, kmp_flag_oncore *flag); extern void __kmp_resume_32(int target_gtid, kmp_flag_32 *flag); extern void __kmp_resume_64(int target_gtid, kmp_flag_64 *flag); extern void __kmp_resume_oncore(int target_gtid, kmp_flag_oncore *flag); extern void __kmp_elapsed(double *); extern void __kmp_elapsed_tick(double *); extern void __kmp_enable(int old_state); extern void __kmp_disable(int *old_state); extern void __kmp_thread_sleep(int millis); extern void __kmp_common_initialize(void); extern void __kmp_common_destroy(void); extern void __kmp_common_destroy_gtid(int gtid); #if KMP_OS_UNIX extern void __kmp_register_atfork(void); #endif extern void __kmp_suspend_initialize(void); extern void __kmp_suspend_initialize_thread(kmp_info_t *th); extern void __kmp_suspend_uninitialize_thread(kmp_info_t *th); extern kmp_info_t *__kmp_allocate_thread(kmp_root_t *root, kmp_team_t *team, int tid); extern kmp_team_t * __kmp_allocate_team(kmp_root_t *root, int new_nproc, int max_nproc, #if OMPT_SUPPORT ompt_data_t ompt_parallel_data, #endif kmp_proc_bind_t proc_bind, kmp_internal_control_t *new_icvs, int argc USE_NESTED_HOT_ARG(kmp_info_t *thr)); extern void __kmp_free_thread(kmp_info_t *); extern void __kmp_free_team(kmp_root_t *, kmp_team_t *USE_NESTED_HOT_ARG(kmp_info_t *)); extern kmp_team_t *__kmp_reap_team(kmp_team_t *); /* ------------------------------------------------------------------------ */ extern void __kmp_initialize_bget(kmp_info_t *th); extern void __kmp_finalize_bget(kmp_info_t *th); KMP_EXPORT void *kmpc_malloc(size_t size); KMP_EXPORT void *kmpc_aligned_malloc(size_t size, size_t alignment); KMP_EXPORT void *kmpc_calloc(size_t nelem, size_t elsize); KMP_EXPORT void *kmpc_realloc(void *ptr, size_t size); KMP_EXPORT void kmpc_free(void *ptr); /* declarations for internal use */ extern int __kmp_barrier(enum barrier_type bt, int gtid, int is_split, size_t reduce_size, void *reduce_data, void (*reduce)(void *, void *)); extern void __kmp_end_split_barrier(enum barrier_type bt, int gtid); extern int __kmp_barrier_gomp_cancel(int gtid); /*! * Tell the fork call which compiler generated the fork call, and therefore how * to deal with the call. */ enum fork_context_e { fork_context_gnu, /**< Called from GNU generated code, so must not invoke the microtask internally. */ fork_context_intel, /**< Called from Intel generated code. */ fork_context_last }; extern int __kmp_fork_call(ident_t *loc, int gtid, enum fork_context_e fork_context, kmp_int32 argc, microtask_t microtask, launch_t invoker, -/* TODO: revert workaround for Intel(R) 64 tracker #96 */ -#if (KMP_ARCH_ARM || KMP_ARCH_X86_64 || KMP_ARCH_AARCH64) && KMP_OS_LINUX - va_list *ap -#else - va_list ap -#endif - ); + kmp_va_list ap); extern void __kmp_join_call(ident_t *loc, int gtid #if OMPT_SUPPORT , enum fork_context_e fork_context #endif , int exit_teams = 0); extern void __kmp_serialized_parallel(ident_t *id, kmp_int32 gtid); extern void __kmp_internal_fork(ident_t *id, int gtid, kmp_team_t *team); extern void __kmp_internal_join(ident_t *id, int gtid, kmp_team_t *team); extern int __kmp_invoke_task_func(int gtid); extern void __kmp_run_before_invoked_task(int gtid, int tid, kmp_info_t *this_thr, kmp_team_t *team); extern void __kmp_run_after_invoked_task(int gtid, int tid, kmp_info_t *this_thr, kmp_team_t *team); // should never have been exported KMP_EXPORT int __kmpc_invoke_task_func(int gtid); extern int __kmp_invoke_teams_master(int gtid); extern void __kmp_teams_master(int gtid); extern int __kmp_aux_get_team_num(); extern int __kmp_aux_get_num_teams(); extern void __kmp_save_internal_controls(kmp_info_t *thread); extern void __kmp_user_set_library(enum library_type arg); extern void __kmp_aux_set_library(enum library_type arg); extern void __kmp_aux_set_stacksize(size_t arg); extern void __kmp_aux_set_blocktime(int arg, kmp_info_t *thread, int tid); extern void __kmp_aux_set_defaults(char const *str, int len); /* Functions called from __kmp_aux_env_initialize() in kmp_settings.cpp */ void kmpc_set_blocktime(int arg); void ompc_set_nested(int flag); void ompc_set_dynamic(int flag); void ompc_set_num_threads(int arg); extern void __kmp_push_current_task_to_thread(kmp_info_t *this_thr, kmp_team_t *team, int tid); extern void __kmp_pop_current_task_from_thread(kmp_info_t *this_thr); extern kmp_task_t *__kmp_task_alloc(ident_t *loc_ref, kmp_int32 gtid, kmp_tasking_flags_t *flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds, kmp_routine_entry_t task_entry); extern void __kmp_init_implicit_task(ident_t *loc_ref, kmp_info_t *this_thr, kmp_team_t *team, int tid, int set_curr_task); extern void __kmp_finish_implicit_task(kmp_info_t *this_thr); extern void __kmp_free_implicit_task(kmp_info_t *this_thr); extern kmp_event_t *__kmpc_task_allow_completion_event(ident_t *loc_ref, int gtid, kmp_task_t *task); extern void __kmp_fulfill_event(kmp_event_t *event); int __kmp_execute_tasks_32(kmp_info_t *thread, kmp_int32 gtid, kmp_flag_32 *flag, int final_spin, int *thread_finished, #if USE_ITT_BUILD void *itt_sync_obj, #endif /* USE_ITT_BUILD */ kmp_int32 is_constrained); int __kmp_execute_tasks_64(kmp_info_t *thread, kmp_int32 gtid, kmp_flag_64 *flag, int final_spin, int *thread_finished, #if USE_ITT_BUILD void *itt_sync_obj, #endif /* USE_ITT_BUILD */ kmp_int32 is_constrained); int __kmp_execute_tasks_oncore(kmp_info_t *thread, kmp_int32 gtid, kmp_flag_oncore *flag, int final_spin, int *thread_finished, #if USE_ITT_BUILD void *itt_sync_obj, #endif /* USE_ITT_BUILD */ kmp_int32 is_constrained); extern void __kmp_free_task_team(kmp_info_t *thread, kmp_task_team_t *task_team); extern void __kmp_reap_task_teams(void); extern void __kmp_wait_to_unref_task_teams(void); extern void __kmp_task_team_setup(kmp_info_t *this_thr, kmp_team_t *team, int always); extern void __kmp_task_team_sync(kmp_info_t *this_thr, kmp_team_t *team); extern void __kmp_task_team_wait(kmp_info_t *this_thr, kmp_team_t *team #if USE_ITT_BUILD , void *itt_sync_obj #endif /* USE_ITT_BUILD */ , int wait = 1); extern void __kmp_tasking_barrier(kmp_team_t *team, kmp_info_t *thread, int gtid); extern int __kmp_is_address_mapped(void *addr); extern kmp_uint64 __kmp_hardware_timestamp(void); #if KMP_OS_UNIX extern int __kmp_read_from_file(char const *path, char const *format, ...); #endif /* ------------------------------------------------------------------------ */ // // Assembly routines that have no compiler intrinsic replacement // extern int __kmp_invoke_microtask(microtask_t pkfn, int gtid, int npr, int argc, void *argv[] #if OMPT_SUPPORT , void **exit_frame_ptr #endif ); /* ------------------------------------------------------------------------ */ KMP_EXPORT void __kmpc_begin(ident_t *, kmp_int32 flags); KMP_EXPORT void __kmpc_end(ident_t *); KMP_EXPORT void __kmpc_threadprivate_register_vec(ident_t *, void *data, kmpc_ctor_vec ctor, kmpc_cctor_vec cctor, kmpc_dtor_vec dtor, size_t vector_length); KMP_EXPORT void __kmpc_threadprivate_register(ident_t *, void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor); KMP_EXPORT void *__kmpc_threadprivate(ident_t *, kmp_int32 global_tid, void *data, size_t size); KMP_EXPORT kmp_int32 __kmpc_global_thread_num(ident_t *); KMP_EXPORT kmp_int32 __kmpc_global_num_threads(ident_t *); KMP_EXPORT kmp_int32 __kmpc_bound_thread_num(ident_t *); KMP_EXPORT kmp_int32 __kmpc_bound_num_threads(ident_t *); KMP_EXPORT kmp_int32 __kmpc_ok_to_fork(ident_t *); KMP_EXPORT void __kmpc_fork_call(ident_t *, kmp_int32 nargs, kmpc_micro microtask, ...); KMP_EXPORT void __kmpc_serialized_parallel(ident_t *, kmp_int32 global_tid); KMP_EXPORT void __kmpc_end_serialized_parallel(ident_t *, kmp_int32 global_tid); KMP_EXPORT void __kmpc_flush(ident_t *); KMP_EXPORT void __kmpc_barrier(ident_t *, kmp_int32 global_tid); KMP_EXPORT kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid); KMP_EXPORT void __kmpc_end_master(ident_t *, kmp_int32 global_tid); KMP_EXPORT void __kmpc_ordered(ident_t *, kmp_int32 global_tid); KMP_EXPORT void __kmpc_end_ordered(ident_t *, kmp_int32 global_tid); KMP_EXPORT void __kmpc_critical(ident_t *, kmp_int32 global_tid, kmp_critical_name *); KMP_EXPORT void __kmpc_end_critical(ident_t *, kmp_int32 global_tid, kmp_critical_name *); KMP_EXPORT void __kmpc_critical_with_hint(ident_t *, kmp_int32 global_tid, kmp_critical_name *, uint32_t hint); KMP_EXPORT kmp_int32 __kmpc_barrier_master(ident_t *, kmp_int32 global_tid); KMP_EXPORT void __kmpc_end_barrier_master(ident_t *, kmp_int32 global_tid); KMP_EXPORT kmp_int32 __kmpc_barrier_master_nowait(ident_t *, kmp_int32 global_tid); KMP_EXPORT kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid); KMP_EXPORT void __kmpc_end_single(ident_t *, kmp_int32 global_tid); KMP_EXPORT void KMPC_FOR_STATIC_INIT(ident_t *loc, kmp_int32 global_tid, kmp_int32 schedtype, kmp_int32 *plastiter, kmp_int *plower, kmp_int *pupper, kmp_int *pstride, kmp_int incr, kmp_int chunk); KMP_EXPORT void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid); KMP_EXPORT void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid, size_t cpy_size, void *cpy_data, void (*cpy_func)(void *, void *), kmp_int32 didit); extern void KMPC_SET_NUM_THREADS(int arg); extern void KMPC_SET_DYNAMIC(int flag); extern void KMPC_SET_NESTED(int flag); /* OMP 3.0 tasking interface routines */ KMP_EXPORT kmp_int32 __kmpc_omp_task(ident_t *loc_ref, kmp_int32 gtid, kmp_task_t *new_task); KMP_EXPORT kmp_task_t *__kmpc_omp_task_alloc(ident_t *loc_ref, kmp_int32 gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds, kmp_routine_entry_t task_entry); KMP_EXPORT kmp_task_t *__kmpc_omp_target_task_alloc(ident_t *loc_ref, kmp_int32 gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds, kmp_routine_entry_t task_entry, kmp_int64 device_id); KMP_EXPORT void __kmpc_omp_task_begin_if0(ident_t *loc_ref, kmp_int32 gtid, kmp_task_t *task); KMP_EXPORT void __kmpc_omp_task_complete_if0(ident_t *loc_ref, kmp_int32 gtid, kmp_task_t *task); KMP_EXPORT kmp_int32 __kmpc_omp_task_parts(ident_t *loc_ref, kmp_int32 gtid, kmp_task_t *new_task); KMP_EXPORT kmp_int32 __kmpc_omp_taskwait(ident_t *loc_ref, kmp_int32 gtid); KMP_EXPORT kmp_int32 __kmpc_omp_taskyield(ident_t *loc_ref, kmp_int32 gtid, int end_part); #if TASK_UNUSED void __kmpc_omp_task_begin(ident_t *loc_ref, kmp_int32 gtid, kmp_task_t *task); void __kmpc_omp_task_complete(ident_t *loc_ref, kmp_int32 gtid, kmp_task_t *task); #endif // TASK_UNUSED /* ------------------------------------------------------------------------ */ KMP_EXPORT void __kmpc_taskgroup(ident_t *loc, int gtid); KMP_EXPORT void __kmpc_end_taskgroup(ident_t *loc, int gtid); KMP_EXPORT kmp_int32 __kmpc_omp_task_with_deps( ident_t *loc_ref, kmp_int32 gtid, kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list); KMP_EXPORT void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32 gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list); extern kmp_int32 __kmp_omp_task(kmp_int32 gtid, kmp_task_t *new_task, bool serialize_immediate); KMP_EXPORT kmp_int32 __kmpc_cancel(ident_t *loc_ref, kmp_int32 gtid, kmp_int32 cncl_kind); KMP_EXPORT kmp_int32 __kmpc_cancellationpoint(ident_t *loc_ref, kmp_int32 gtid, kmp_int32 cncl_kind); KMP_EXPORT kmp_int32 __kmpc_cancel_barrier(ident_t *loc_ref, kmp_int32 gtid); KMP_EXPORT int __kmp_get_cancellation_status(int cancel_kind); KMP_EXPORT void __kmpc_proxy_task_completed(kmp_int32 gtid, kmp_task_t *ptask); KMP_EXPORT void __kmpc_proxy_task_completed_ooo(kmp_task_t *ptask); KMP_EXPORT void __kmpc_taskloop(ident_t *loc, kmp_int32 gtid, kmp_task_t *task, kmp_int32 if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, kmp_int32 nogroup, kmp_int32 sched, kmp_uint64 grainsize, void *task_dup); KMP_EXPORT void *__kmpc_task_reduction_init(int gtid, int num_data, void *data); KMP_EXPORT void *__kmpc_taskred_init(int gtid, int num_data, void *data); KMP_EXPORT void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void *d); KMP_EXPORT void *__kmpc_task_reduction_modifier_init(ident_t *loc, int gtid, int is_ws, int num, void *data); KMP_EXPORT void *__kmpc_taskred_modifier_init(ident_t *loc, int gtid, int is_ws, int num, void *data); KMP_EXPORT void __kmpc_task_reduction_modifier_fini(ident_t *loc, int gtid, int is_ws); KMP_EXPORT kmp_int32 __kmpc_omp_reg_task_with_affinity( ident_t *loc_ref, kmp_int32 gtid, kmp_task_t *new_task, kmp_int32 naffins, kmp_task_affinity_info_t *affin_list); /* Lock interface routines (fast versions with gtid passed in) */ KMP_EXPORT void __kmpc_init_lock(ident_t *loc, kmp_int32 gtid, void **user_lock); KMP_EXPORT void __kmpc_init_nest_lock(ident_t *loc, kmp_int32 gtid, void **user_lock); KMP_EXPORT void __kmpc_destroy_lock(ident_t *loc, kmp_int32 gtid, void **user_lock); KMP_EXPORT void __kmpc_destroy_nest_lock(ident_t *loc, kmp_int32 gtid, void **user_lock); KMP_EXPORT void __kmpc_set_lock(ident_t *loc, kmp_int32 gtid, void **user_lock); KMP_EXPORT void __kmpc_set_nest_lock(ident_t *loc, kmp_int32 gtid, void **user_lock); KMP_EXPORT void __kmpc_unset_lock(ident_t *loc, kmp_int32 gtid, void **user_lock); KMP_EXPORT void __kmpc_unset_nest_lock(ident_t *loc, kmp_int32 gtid, void **user_lock); KMP_EXPORT int __kmpc_test_lock(ident_t *loc, kmp_int32 gtid, void **user_lock); KMP_EXPORT int __kmpc_test_nest_lock(ident_t *loc, kmp_int32 gtid, void **user_lock); KMP_EXPORT void __kmpc_init_lock_with_hint(ident_t *loc, kmp_int32 gtid, void **user_lock, uintptr_t hint); KMP_EXPORT void __kmpc_init_nest_lock_with_hint(ident_t *loc, kmp_int32 gtid, void **user_lock, uintptr_t hint); /* Interface to fast scalable reduce methods routines */ KMP_EXPORT kmp_int32 __kmpc_reduce_nowait( ident_t *loc, kmp_int32 global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck); KMP_EXPORT void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid, kmp_critical_name *lck); KMP_EXPORT kmp_int32 __kmpc_reduce( ident_t *loc, kmp_int32 global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck); KMP_EXPORT void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid, kmp_critical_name *lck); /* Internal fast reduction routines */ extern PACKED_REDUCTION_METHOD_T __kmp_determine_reduction_method( ident_t *loc, kmp_int32 global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck); // this function is for testing set/get/determine reduce method KMP_EXPORT kmp_int32 __kmp_get_reduce_method(void); KMP_EXPORT kmp_uint64 __kmpc_get_taskid(); KMP_EXPORT kmp_uint64 __kmpc_get_parent_taskid(); // C++ port // missing 'extern "C"' declarations KMP_EXPORT kmp_int32 __kmpc_in_parallel(ident_t *loc); KMP_EXPORT void __kmpc_pop_num_threads(ident_t *loc, kmp_int32 global_tid); KMP_EXPORT void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid, kmp_int32 num_threads); KMP_EXPORT void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid, int proc_bind); KMP_EXPORT void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid, kmp_int32 num_teams, kmp_int32 num_threads); KMP_EXPORT void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro microtask, ...); struct kmp_dim { // loop bounds info casted to kmp_int64 kmp_int64 lo; // lower kmp_int64 up; // upper kmp_int64 st; // stride }; KMP_EXPORT void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32 num_dims, const struct kmp_dim *dims); KMP_EXPORT void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, const kmp_int64 *vec); KMP_EXPORT void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, const kmp_int64 *vec); KMP_EXPORT void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid); KMP_EXPORT void *__kmpc_threadprivate_cached(ident_t *loc, kmp_int32 global_tid, void *data, size_t size, void ***cache); // Symbols for MS mutual detection. extern int _You_must_link_with_exactly_one_OpenMP_library; extern int _You_must_link_with_Intel_OpenMP_library; #if KMP_OS_WINDOWS && (KMP_VERSION_MAJOR > 4) extern int _You_must_link_with_Microsoft_OpenMP_library; #endif // The routines below are not exported. // Consider making them 'static' in corresponding source files. void kmp_threadprivate_insert_private_data(int gtid, void *pc_addr, void *data_addr, size_t pc_size); struct private_common *kmp_threadprivate_insert(int gtid, void *pc_addr, void *data_addr, size_t pc_size); void __kmp_threadprivate_resize_cache(int newCapacity); void __kmp_cleanup_threadprivate_caches(); // ompc_, kmpc_ entries moved from omp.h. #if KMP_OS_WINDOWS #define KMPC_CONVENTION __cdecl #else #define KMPC_CONVENTION #endif #ifndef __OMP_H typedef enum omp_sched_t { omp_sched_static = 1, omp_sched_dynamic = 2, omp_sched_guided = 3, omp_sched_auto = 4 } omp_sched_t; typedef void *kmp_affinity_mask_t; #endif KMP_EXPORT void KMPC_CONVENTION ompc_set_max_active_levels(int); KMP_EXPORT void KMPC_CONVENTION ompc_set_schedule(omp_sched_t, int); KMP_EXPORT int KMPC_CONVENTION ompc_get_ancestor_thread_num(int); KMP_EXPORT int KMPC_CONVENTION ompc_get_team_size(int); KMP_EXPORT int KMPC_CONVENTION kmpc_set_affinity_mask_proc(int, kmp_affinity_mask_t *); KMP_EXPORT int KMPC_CONVENTION kmpc_unset_affinity_mask_proc(int, kmp_affinity_mask_t *); KMP_EXPORT int KMPC_CONVENTION kmpc_get_affinity_mask_proc(int, kmp_affinity_mask_t *); KMP_EXPORT void KMPC_CONVENTION kmpc_set_stacksize(int); KMP_EXPORT void KMPC_CONVENTION kmpc_set_stacksize_s(size_t); KMP_EXPORT void KMPC_CONVENTION kmpc_set_library(int); KMP_EXPORT void KMPC_CONVENTION kmpc_set_defaults(char const *); KMP_EXPORT void KMPC_CONVENTION kmpc_set_disp_num_buffers(int); enum kmp_target_offload_kind { tgt_disabled = 0, tgt_default = 1, tgt_mandatory = 2 }; typedef enum kmp_target_offload_kind kmp_target_offload_kind_t; // Set via OMP_TARGET_OFFLOAD if specified, defaults to tgt_default otherwise extern kmp_target_offload_kind_t __kmp_target_offload; extern int __kmpc_get_target_offload(); // Constants used in libomptarget #define KMP_DEVICE_DEFAULT -1 // This is libomptarget's default device. #define KMP_HOST_DEVICE -10 // This is what it is in libomptarget, go figure. #define KMP_DEVICE_ALL -11 // This is libomptarget's "all devices". // OMP Pause Resource // The following enum is used both to set the status in __kmp_pause_status, and // as the internal equivalent of the externally-visible omp_pause_resource_t. typedef enum kmp_pause_status_t { kmp_not_paused = 0, // status is not paused, or, requesting resume kmp_soft_paused = 1, // status is soft-paused, or, requesting soft pause kmp_hard_paused = 2 // status is hard-paused, or, requesting hard pause } kmp_pause_status_t; // This stores the pause state of the runtime extern kmp_pause_status_t __kmp_pause_status; extern int __kmpc_pause_resource(kmp_pause_status_t level); extern int __kmp_pause_resource(kmp_pause_status_t level); // Soft resume sets __kmp_pause_status, and wakes up all threads. extern void __kmp_resume_if_soft_paused(); // Hard resume simply resets the status to not paused. Library will appear to // be uninitialized after hard pause. Let OMP constructs trigger required // initializations. static inline void __kmp_resume_if_hard_paused() { if (__kmp_pause_status == kmp_hard_paused) { __kmp_pause_status = kmp_not_paused; } } extern void __kmp_omp_display_env(int verbose); #ifdef __cplusplus } #endif #endif /* KMP_H */ Index: head/contrib/llvm-project/openmp/runtime/src/kmp_csupport.cpp =================================================================== --- head/contrib/llvm-project/openmp/runtime/src/kmp_csupport.cpp (revision 364731) +++ head/contrib/llvm-project/openmp/runtime/src/kmp_csupport.cpp (revision 364732) @@ -1,4240 +1,4228 @@ /* * kmp_csupport.cpp -- kfront linkage support for OpenMP. */ //===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #define __KMP_IMP #include "omp.h" /* extern "C" declarations of user-visible routines */ #include "kmp.h" #include "kmp_error.h" #include "kmp_i18n.h" #include "kmp_itt.h" #include "kmp_lock.h" #include "kmp_stats.h" #include "ompt-specific.h" #define MAX_MESSAGE 512 // flags will be used in future, e.g. to implement openmp_strict library // restrictions /*! * @ingroup STARTUP_SHUTDOWN * @param loc in source location information * @param flags in for future use (currently ignored) * * Initialize the runtime library. This call is optional; if it is not made then * it will be implicitly called by attempts to use other library functions. */ void __kmpc_begin(ident_t *loc, kmp_int32 flags) { // By default __kmpc_begin() is no-op. char *env; if ((env = getenv("KMP_INITIAL_THREAD_BIND")) != NULL && __kmp_str_match_true(env)) { __kmp_middle_initialize(); KC_TRACE(10, ("__kmpc_begin: middle initialization called\n")); } else if (__kmp_ignore_mppbeg() == FALSE) { // By default __kmp_ignore_mppbeg() returns TRUE. __kmp_internal_begin(); KC_TRACE(10, ("__kmpc_begin: called\n")); } } /*! * @ingroup STARTUP_SHUTDOWN * @param loc source location information * * Shutdown the runtime library. This is also optional, and even if called will * not do anything unless the `KMP_IGNORE_MPPEND` environment variable is set to * zero. */ void __kmpc_end(ident_t *loc) { // By default, __kmp_ignore_mppend() returns TRUE which makes __kmpc_end() // call no-op. However, this can be overridden with KMP_IGNORE_MPPEND // environment variable. If KMP_IGNORE_MPPEND is 0, __kmp_ignore_mppend() // returns FALSE and __kmpc_end() will unregister this root (it can cause // library shut down). if (__kmp_ignore_mppend() == FALSE) { KC_TRACE(10, ("__kmpc_end: called\n")); KA_TRACE(30, ("__kmpc_end\n")); __kmp_internal_end_thread(-1); } #if KMP_OS_WINDOWS && OMPT_SUPPORT // Normal exit process on Windows does not allow worker threads of the final // parallel region to finish reporting their events, so shutting down the // library here fixes the issue at least for the cases where __kmpc_end() is // placed properly. if (ompt_enabled.enabled) __kmp_internal_end_library(__kmp_gtid_get_specific()); #endif } /*! @ingroup THREAD_STATES @param loc Source location information. @return The global thread index of the active thread. This function can be called in any context. If the runtime has ony been entered at the outermost level from a single (necessarily non-OpenMP*) thread, then the thread number is that which would be returned by omp_get_thread_num() in the outermost active parallel construct. (Or zero if there is no active parallel construct, since the master thread is necessarily thread zero). If multiple non-OpenMP threads all enter an OpenMP construct then this will be a unique thread identifier among all the threads created by the OpenMP runtime (but the value cannot be defined in terms of OpenMP thread ids returned by omp_get_thread_num()). */ kmp_int32 __kmpc_global_thread_num(ident_t *loc) { kmp_int32 gtid = __kmp_entry_gtid(); KC_TRACE(10, ("__kmpc_global_thread_num: T#%d\n", gtid)); return gtid; } /*! @ingroup THREAD_STATES @param loc Source location information. @return The number of threads under control of the OpenMP* runtime This function can be called in any context. It returns the total number of threads under the control of the OpenMP runtime. That is not a number that can be determined by any OpenMP standard calls, since the library may be called from more than one non-OpenMP thread, and this reflects the total over all such calls. Similarly the runtime maintains underlying threads even when they are not active (since the cost of creating and destroying OS threads is high), this call counts all such threads even if they are not waiting for work. */ kmp_int32 __kmpc_global_num_threads(ident_t *loc) { KC_TRACE(10, ("__kmpc_global_num_threads: num_threads = %d\n", __kmp_all_nth)); return TCR_4(__kmp_all_nth); } /*! @ingroup THREAD_STATES @param loc Source location information. @return The thread number of the calling thread in the innermost active parallel construct. */ kmp_int32 __kmpc_bound_thread_num(ident_t *loc) { KC_TRACE(10, ("__kmpc_bound_thread_num: called\n")); return __kmp_tid_from_gtid(__kmp_entry_gtid()); } /*! @ingroup THREAD_STATES @param loc Source location information. @return The number of threads in the innermost active parallel construct. */ kmp_int32 __kmpc_bound_num_threads(ident_t *loc) { KC_TRACE(10, ("__kmpc_bound_num_threads: called\n")); return __kmp_entry_thread()->th.th_team->t.t_nproc; } /*! * @ingroup DEPRECATED * @param loc location description * * This function need not be called. It always returns TRUE. */ kmp_int32 __kmpc_ok_to_fork(ident_t *loc) { #ifndef KMP_DEBUG return TRUE; #else const char *semi2; const char *semi3; int line_no; if (__kmp_par_range == 0) { return TRUE; } semi2 = loc->psource; if (semi2 == NULL) { return TRUE; } semi2 = strchr(semi2, ';'); if (semi2 == NULL) { return TRUE; } semi2 = strchr(semi2 + 1, ';'); if (semi2 == NULL) { return TRUE; } if (__kmp_par_range_filename[0]) { const char *name = semi2 - 1; while ((name > loc->psource) && (*name != '/') && (*name != ';')) { name--; } if ((*name == '/') || (*name == ';')) { name++; } if (strncmp(__kmp_par_range_filename, name, semi2 - name)) { return __kmp_par_range < 0; } } semi3 = strchr(semi2 + 1, ';'); if (__kmp_par_range_routine[0]) { if ((semi3 != NULL) && (semi3 > semi2) && (strncmp(__kmp_par_range_routine, semi2 + 1, semi3 - semi2 - 1))) { return __kmp_par_range < 0; } } if (KMP_SSCANF(semi3 + 1, "%d", &line_no) == 1) { if ((line_no >= __kmp_par_range_lb) && (line_no <= __kmp_par_range_ub)) { return __kmp_par_range > 0; } return __kmp_par_range < 0; } return TRUE; #endif /* KMP_DEBUG */ } /*! @ingroup THREAD_STATES @param loc Source location information. @return 1 if this thread is executing inside an active parallel region, zero if not. */ kmp_int32 __kmpc_in_parallel(ident_t *loc) { return __kmp_entry_thread()->th.th_root->r.r_active; } /*! @ingroup PARALLEL @param loc source location information @param global_tid global thread number @param num_threads number of threads requested for this parallel construct Set the number of threads to be used by the next fork spawned by this thread. This call is only required if the parallel construct has a `num_threads` clause. */ void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid, kmp_int32 num_threads) { KA_TRACE(20, ("__kmpc_push_num_threads: enter T#%d num_threads=%d\n", global_tid, num_threads)); __kmp_push_num_threads(loc, global_tid, num_threads); } void __kmpc_pop_num_threads(ident_t *loc, kmp_int32 global_tid) { KA_TRACE(20, ("__kmpc_pop_num_threads: enter\n")); /* the num_threads are automatically popped */ } void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid, kmp_int32 proc_bind) { KA_TRACE(20, ("__kmpc_push_proc_bind: enter T#%d proc_bind=%d\n", global_tid, proc_bind)); __kmp_push_proc_bind(loc, global_tid, (kmp_proc_bind_t)proc_bind); } /*! @ingroup PARALLEL @param loc source location information @param argc total number of arguments in the ellipsis @param microtask pointer to callback routine consisting of outlined parallel construct @param ... pointers to shared variables that aren't global Do the actual fork and call the microtask in the relevant number of threads. */ void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro microtask, ...) { int gtid = __kmp_entry_gtid(); #if (KMP_STATS_ENABLED) // If we were in a serial region, then stop the serial timer, record // the event, and start parallel region timer stats_state_e previous_state = KMP_GET_THREAD_STATE(); if (previous_state == stats_state_e::SERIAL_REGION) { KMP_EXCHANGE_PARTITIONED_TIMER(OMP_parallel_overhead); } else { KMP_PUSH_PARTITIONED_TIMER(OMP_parallel_overhead); } int inParallel = __kmpc_in_parallel(loc); if (inParallel) { KMP_COUNT_BLOCK(OMP_NESTED_PARALLEL); } else { KMP_COUNT_BLOCK(OMP_PARALLEL); } #endif // maybe to save thr_state is enough here { va_list ap; va_start(ap, microtask); #if OMPT_SUPPORT ompt_frame_t *ompt_frame; if (ompt_enabled.enabled) { kmp_info_t *master_th = __kmp_threads[gtid]; kmp_team_t *parent_team = master_th->th.th_team; ompt_lw_taskteam_t *lwt = parent_team->t.ompt_serialized_team_info; if (lwt) ompt_frame = &(lwt->ompt_task_info.frame); else { int tid = __kmp_tid_from_gtid(gtid); ompt_frame = &( parent_team->t.t_implicit_task_taskdata[tid].ompt_task_info.frame); } ompt_frame->enter_frame.ptr = OMPT_GET_FRAME_ADDRESS(0); OMPT_STORE_RETURN_ADDRESS(gtid); } #endif #if INCLUDE_SSC_MARKS SSC_MARK_FORKING(); #endif __kmp_fork_call(loc, gtid, fork_context_intel, argc, VOLATILE_CAST(microtask_t) microtask, // "wrapped" task VOLATILE_CAST(launch_t) __kmp_invoke_task_func, -/* TODO: revert workaround for Intel(R) 64 tracker #96 */ -#if (KMP_ARCH_X86_64 || KMP_ARCH_ARM || KMP_ARCH_AARCH64) && KMP_OS_LINUX - &ap -#else - ap -#endif - ); + kmp_va_addr_of(ap)); #if INCLUDE_SSC_MARKS SSC_MARK_JOINING(); #endif __kmp_join_call(loc, gtid #if OMPT_SUPPORT , fork_context_intel #endif ); va_end(ap); } #if KMP_STATS_ENABLED if (previous_state == stats_state_e::SERIAL_REGION) { KMP_EXCHANGE_PARTITIONED_TIMER(OMP_serial); } else { KMP_POP_PARTITIONED_TIMER(); } #endif // KMP_STATS_ENABLED } /*! @ingroup PARALLEL @param loc source location information @param global_tid global thread number @param num_teams number of teams requested for the teams construct @param num_threads number of threads per team requested for the teams construct Set the number of teams to be used by the teams construct. This call is only required if the teams construct has a `num_teams` clause or a `thread_limit` clause (or both). */ void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid, kmp_int32 num_teams, kmp_int32 num_threads) { KA_TRACE(20, ("__kmpc_push_num_teams: enter T#%d num_teams=%d num_threads=%d\n", global_tid, num_teams, num_threads)); __kmp_push_num_teams(loc, global_tid, num_teams, num_threads); } /*! @ingroup PARALLEL @param loc source location information @param argc total number of arguments in the ellipsis @param microtask pointer to callback routine consisting of outlined teams construct @param ... pointers to shared variables that aren't global Do the actual fork and call the microtask in the relevant number of threads. */ void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro microtask, ...) { int gtid = __kmp_entry_gtid(); kmp_info_t *this_thr = __kmp_threads[gtid]; va_list ap; va_start(ap, microtask); #if KMP_STATS_ENABLED KMP_COUNT_BLOCK(OMP_TEAMS); stats_state_e previous_state = KMP_GET_THREAD_STATE(); if (previous_state == stats_state_e::SERIAL_REGION) { KMP_EXCHANGE_PARTITIONED_TIMER(OMP_teams_overhead); } else { KMP_PUSH_PARTITIONED_TIMER(OMP_teams_overhead); } #endif // remember teams entry point and nesting level this_thr->th.th_teams_microtask = microtask; this_thr->th.th_teams_level = this_thr->th.th_team->t.t_level; // AC: can be >0 on host #if OMPT_SUPPORT kmp_team_t *parent_team = this_thr->th.th_team; int tid = __kmp_tid_from_gtid(gtid); if (ompt_enabled.enabled) { parent_team->t.t_implicit_task_taskdata[tid] .ompt_task_info.frame.enter_frame.ptr = OMPT_GET_FRAME_ADDRESS(0); } OMPT_STORE_RETURN_ADDRESS(gtid); #endif // check if __kmpc_push_num_teams called, set default number of teams // otherwise if (this_thr->th.th_teams_size.nteams == 0) { __kmp_push_num_teams(loc, gtid, 0, 0); } KMP_DEBUG_ASSERT(this_thr->th.th_set_nproc >= 1); KMP_DEBUG_ASSERT(this_thr->th.th_teams_size.nteams >= 1); KMP_DEBUG_ASSERT(this_thr->th.th_teams_size.nth >= 1); - __kmp_fork_call(loc, gtid, fork_context_intel, argc, - VOLATILE_CAST(microtask_t) - __kmp_teams_master, // "wrapped" task - VOLATILE_CAST(launch_t) __kmp_invoke_teams_master, -#if (KMP_ARCH_X86_64 || KMP_ARCH_ARM || KMP_ARCH_AARCH64) && KMP_OS_LINUX - &ap -#else - ap -#endif - ); + __kmp_fork_call( + loc, gtid, fork_context_intel, argc, + VOLATILE_CAST(microtask_t) __kmp_teams_master, // "wrapped" task + VOLATILE_CAST(launch_t) __kmp_invoke_teams_master, kmp_va_addr_of(ap)); __kmp_join_call(loc, gtid #if OMPT_SUPPORT , fork_context_intel #endif ); // Pop current CG root off list KMP_DEBUG_ASSERT(this_thr->th.th_cg_roots); kmp_cg_root_t *tmp = this_thr->th.th_cg_roots; this_thr->th.th_cg_roots = tmp->up; KA_TRACE(100, ("__kmpc_fork_teams: Thread %p popping node %p and moving up" " to node %p. cg_nthreads was %d\n", this_thr, tmp, this_thr->th.th_cg_roots, tmp->cg_nthreads)); KMP_DEBUG_ASSERT(tmp->cg_nthreads); int i = tmp->cg_nthreads--; if (i == 1) { // check is we are the last thread in CG (not always the case) __kmp_free(tmp); } // Restore current task's thread_limit from CG root KMP_DEBUG_ASSERT(this_thr->th.th_cg_roots); this_thr->th.th_current_task->td_icvs.thread_limit = this_thr->th.th_cg_roots->cg_thread_limit; this_thr->th.th_teams_microtask = NULL; this_thr->th.th_teams_level = 0; *(kmp_int64 *)(&this_thr->th.th_teams_size) = 0L; va_end(ap); #if KMP_STATS_ENABLED if (previous_state == stats_state_e::SERIAL_REGION) { KMP_EXCHANGE_PARTITIONED_TIMER(OMP_serial); } else { KMP_POP_PARTITIONED_TIMER(); } #endif // KMP_STATS_ENABLED } // I don't think this function should ever have been exported. // The __kmpc_ prefix was misapplied. I'm fairly certain that no generated // openmp code ever called it, but it's been exported from the RTL for so // long that I'm afraid to remove the definition. int __kmpc_invoke_task_func(int gtid) { return __kmp_invoke_task_func(gtid); } /*! @ingroup PARALLEL @param loc source location information @param global_tid global thread number Enter a serialized parallel construct. This interface is used to handle a conditional parallel region, like this, @code #pragma omp parallel if (condition) @endcode when the condition is false. */ void __kmpc_serialized_parallel(ident_t *loc, kmp_int32 global_tid) { // The implementation is now in kmp_runtime.cpp so that it can share static // functions with kmp_fork_call since the tasks to be done are similar in // each case. #if OMPT_SUPPORT OMPT_STORE_RETURN_ADDRESS(global_tid); #endif __kmp_serialized_parallel(loc, global_tid); } /*! @ingroup PARALLEL @param loc source location information @param global_tid global thread number Leave a serialized parallel construct. */ void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32 global_tid) { kmp_internal_control_t *top; kmp_info_t *this_thr; kmp_team_t *serial_team; KC_TRACE(10, ("__kmpc_end_serialized_parallel: called by T#%d\n", global_tid)); /* skip all this code for autopar serialized loops since it results in unacceptable overhead */ if (loc != NULL && (loc->flags & KMP_IDENT_AUTOPAR)) return; // Not autopar code if (!TCR_4(__kmp_init_parallel)) __kmp_parallel_initialize(); __kmp_resume_if_soft_paused(); this_thr = __kmp_threads[global_tid]; serial_team = this_thr->th.th_serial_team; kmp_task_team_t *task_team = this_thr->th.th_task_team; // we need to wait for the proxy tasks before finishing the thread if (task_team != NULL && task_team->tt.tt_found_proxy_tasks) __kmp_task_team_wait(this_thr, serial_team USE_ITT_BUILD_ARG(NULL)); KMP_MB(); KMP_DEBUG_ASSERT(serial_team); KMP_ASSERT(serial_team->t.t_serialized); KMP_DEBUG_ASSERT(this_thr->th.th_team == serial_team); KMP_DEBUG_ASSERT(serial_team != this_thr->th.th_root->r.r_root_team); KMP_DEBUG_ASSERT(serial_team->t.t_threads); KMP_DEBUG_ASSERT(serial_team->t.t_threads[0] == this_thr); #if OMPT_SUPPORT if (ompt_enabled.enabled && this_thr->th.ompt_thread_info.state != ompt_state_overhead) { OMPT_CUR_TASK_INFO(this_thr)->frame.exit_frame = ompt_data_none; if (ompt_enabled.ompt_callback_implicit_task) { ompt_callbacks.ompt_callback(ompt_callback_implicit_task)( ompt_scope_end, NULL, OMPT_CUR_TASK_DATA(this_thr), 1, OMPT_CUR_TASK_INFO(this_thr)->thread_num, ompt_task_implicit); } // reset clear the task id only after unlinking the task ompt_data_t *parent_task_data; __ompt_get_task_info_internal(1, NULL, &parent_task_data, NULL, NULL, NULL); if (ompt_enabled.ompt_callback_parallel_end) { ompt_callbacks.ompt_callback(ompt_callback_parallel_end)( &(serial_team->t.ompt_team_info.parallel_data), parent_task_data, ompt_parallel_invoker_program | ompt_parallel_team, OMPT_LOAD_RETURN_ADDRESS(global_tid)); } __ompt_lw_taskteam_unlink(this_thr); this_thr->th.ompt_thread_info.state = ompt_state_overhead; } #endif /* If necessary, pop the internal control stack values and replace the team * values */ top = serial_team->t.t_control_stack_top; if (top && top->serial_nesting_level == serial_team->t.t_serialized) { copy_icvs(&serial_team->t.t_threads[0]->th.th_current_task->td_icvs, top); serial_team->t.t_control_stack_top = top->next; __kmp_free(top); } // if( serial_team -> t.t_serialized > 1 ) serial_team->t.t_level--; /* pop dispatch buffers stack */ KMP_DEBUG_ASSERT(serial_team->t.t_dispatch->th_disp_buffer); { dispatch_private_info_t *disp_buffer = serial_team->t.t_dispatch->th_disp_buffer; serial_team->t.t_dispatch->th_disp_buffer = serial_team->t.t_dispatch->th_disp_buffer->next; __kmp_free(disp_buffer); } this_thr->th.th_def_allocator = serial_team->t.t_def_allocator; // restore --serial_team->t.t_serialized; if (serial_team->t.t_serialized == 0) { /* return to the parallel section */ #if KMP_ARCH_X86 || KMP_ARCH_X86_64 if (__kmp_inherit_fp_control && serial_team->t.t_fp_control_saved) { __kmp_clear_x87_fpu_status_word(); __kmp_load_x87_fpu_control_word(&serial_team->t.t_x87_fpu_control_word); __kmp_load_mxcsr(&serial_team->t.t_mxcsr); } #endif /* KMP_ARCH_X86 || KMP_ARCH_X86_64 */ this_thr->th.th_team = serial_team->t.t_parent; this_thr->th.th_info.ds.ds_tid = serial_team->t.t_master_tid; /* restore values cached in the thread */ this_thr->th.th_team_nproc = serial_team->t.t_parent->t.t_nproc; /* JPH */ this_thr->th.th_team_master = serial_team->t.t_parent->t.t_threads[0]; /* JPH */ this_thr->th.th_team_serialized = this_thr->th.th_team->t.t_serialized; /* TODO the below shouldn't need to be adjusted for serialized teams */ this_thr->th.th_dispatch = &this_thr->th.th_team->t.t_dispatch[serial_team->t.t_master_tid]; __kmp_pop_current_task_from_thread(this_thr); KMP_ASSERT(this_thr->th.th_current_task->td_flags.executing == 0); this_thr->th.th_current_task->td_flags.executing = 1; if (__kmp_tasking_mode != tskm_immediate_exec) { // Copy the task team from the new child / old parent team to the thread. this_thr->th.th_task_team = this_thr->th.th_team->t.t_task_team[this_thr->th.th_task_state]; KA_TRACE(20, ("__kmpc_end_serialized_parallel: T#%d restoring task_team %p / " "team %p\n", global_tid, this_thr->th.th_task_team, this_thr->th.th_team)); } } else { if (__kmp_tasking_mode != tskm_immediate_exec) { KA_TRACE(20, ("__kmpc_end_serialized_parallel: T#%d decreasing nesting " "depth of serial team %p to %d\n", global_tid, serial_team, serial_team->t.t_serialized)); } } if (__kmp_env_consistency_check) __kmp_pop_parallel(global_tid, NULL); #if OMPT_SUPPORT if (ompt_enabled.enabled) this_thr->th.ompt_thread_info.state = ((this_thr->th.th_team_serialized) ? ompt_state_work_serial : ompt_state_work_parallel); #endif } /*! @ingroup SYNCHRONIZATION @param loc source location information. Execute flush. This is implemented as a full memory fence. (Though depending on the memory ordering convention obeyed by the compiler even that may not be necessary). */ void __kmpc_flush(ident_t *loc) { KC_TRACE(10, ("__kmpc_flush: called\n")); /* need explicit __mf() here since use volatile instead in library */ KMP_MB(); /* Flush all pending memory write invalidates. */ #if (KMP_ARCH_X86 || KMP_ARCH_X86_64) #if KMP_MIC // fence-style instructions do not exist, but lock; xaddl $0,(%rsp) can be used. // We shouldn't need it, though, since the ABI rules require that // * If the compiler generates NGO stores it also generates the fence // * If users hand-code NGO stores they should insert the fence // therefore no incomplete unordered stores should be visible. #else // C74404 // This is to address non-temporal store instructions (sfence needed). // The clflush instruction is addressed either (mfence needed). // Probably the non-temporal load monvtdqa instruction should also be // addressed. // mfence is a SSE2 instruction. Do not execute it if CPU is not SSE2. if (!__kmp_cpuinfo.initialized) { __kmp_query_cpuid(&__kmp_cpuinfo); } if (!__kmp_cpuinfo.sse2) { // CPU cannot execute SSE2 instructions. } else { #if KMP_COMPILER_ICC _mm_mfence(); #elif KMP_COMPILER_MSVC MemoryBarrier(); #else __sync_synchronize(); #endif // KMP_COMPILER_ICC } #endif // KMP_MIC #elif (KMP_ARCH_ARM || KMP_ARCH_AARCH64 || KMP_ARCH_MIPS || KMP_ARCH_MIPS64 || \ KMP_ARCH_RISCV64) // Nothing to see here move along #elif KMP_ARCH_PPC64 // Nothing needed here (we have a real MB above). #if KMP_OS_CNK // The flushing thread needs to yield here; this prevents a // busy-waiting thread from saturating the pipeline. flush is // often used in loops like this: // while (!flag) { // #pragma omp flush(flag) // } // and adding the yield here is good for at least a 10x speedup // when running >2 threads per core (on the NAS LU benchmark). __kmp_yield(); #endif #else #error Unknown or unsupported architecture #endif #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.ompt_callback_flush) { ompt_callbacks.ompt_callback(ompt_callback_flush)( __ompt_get_thread_data_internal(), OMPT_GET_RETURN_ADDRESS(0)); } #endif } /* -------------------------------------------------------------------------- */ /*! @ingroup SYNCHRONIZATION @param loc source location information @param global_tid thread id. Execute a barrier. */ void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid) { KMP_COUNT_BLOCK(OMP_BARRIER); KC_TRACE(10, ("__kmpc_barrier: called T#%d\n", global_tid)); if (!TCR_4(__kmp_init_parallel)) __kmp_parallel_initialize(); __kmp_resume_if_soft_paused(); if (__kmp_env_consistency_check) { if (loc == 0) { KMP_WARNING(ConstructIdentInvalid); // ??? What does it mean for the user? } __kmp_check_barrier(global_tid, ct_barrier, loc); } #if OMPT_SUPPORT ompt_frame_t *ompt_frame; if (ompt_enabled.enabled) { __ompt_get_task_info_internal(0, NULL, NULL, &ompt_frame, NULL, NULL); if (ompt_frame->enter_frame.ptr == NULL) ompt_frame->enter_frame.ptr = OMPT_GET_FRAME_ADDRESS(0); OMPT_STORE_RETURN_ADDRESS(global_tid); } #endif __kmp_threads[global_tid]->th.th_ident = loc; // TODO: explicit barrier_wait_id: // this function is called when 'barrier' directive is present or // implicit barrier at the end of a worksharing construct. // 1) better to add a per-thread barrier counter to a thread data structure // 2) set to 0 when a new team is created // 4) no sync is required __kmp_barrier(bs_plain_barrier, global_tid, FALSE, 0, NULL, NULL); #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled) { ompt_frame->enter_frame = ompt_data_none; } #endif } /* The BARRIER for a MASTER section is always explicit */ /*! @ingroup WORK_SHARING @param loc source location information. @param global_tid global thread number . @return 1 if this thread should execute the master block, 0 otherwise. */ kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid) { int status = 0; KC_TRACE(10, ("__kmpc_master: called T#%d\n", global_tid)); if (!TCR_4(__kmp_init_parallel)) __kmp_parallel_initialize(); __kmp_resume_if_soft_paused(); if (KMP_MASTER_GTID(global_tid)) { KMP_COUNT_BLOCK(OMP_MASTER); KMP_PUSH_PARTITIONED_TIMER(OMP_master); status = 1; } #if OMPT_SUPPORT && OMPT_OPTIONAL if (status) { if (ompt_enabled.ompt_callback_master) { kmp_info_t *this_thr = __kmp_threads[global_tid]; kmp_team_t *team = this_thr->th.th_team; int tid = __kmp_tid_from_gtid(global_tid); ompt_callbacks.ompt_callback(ompt_callback_master)( ompt_scope_begin, &(team->t.ompt_team_info.parallel_data), &(team->t.t_implicit_task_taskdata[tid].ompt_task_info.task_data), OMPT_GET_RETURN_ADDRESS(0)); } } #endif if (__kmp_env_consistency_check) { #if KMP_USE_DYNAMIC_LOCK if (status) __kmp_push_sync(global_tid, ct_master, loc, NULL, 0); else __kmp_check_sync(global_tid, ct_master, loc, NULL, 0); #else if (status) __kmp_push_sync(global_tid, ct_master, loc, NULL); else __kmp_check_sync(global_tid, ct_master, loc, NULL); #endif } return status; } /*! @ingroup WORK_SHARING @param loc source location information. @param global_tid global thread number . Mark the end of a master region. This should only be called by the thread that executes the master region. */ void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid) { KC_TRACE(10, ("__kmpc_end_master: called T#%d\n", global_tid)); KMP_DEBUG_ASSERT(KMP_MASTER_GTID(global_tid)); KMP_POP_PARTITIONED_TIMER(); #if OMPT_SUPPORT && OMPT_OPTIONAL kmp_info_t *this_thr = __kmp_threads[global_tid]; kmp_team_t *team = this_thr->th.th_team; if (ompt_enabled.ompt_callback_master) { int tid = __kmp_tid_from_gtid(global_tid); ompt_callbacks.ompt_callback(ompt_callback_master)( ompt_scope_end, &(team->t.ompt_team_info.parallel_data), &(team->t.t_implicit_task_taskdata[tid].ompt_task_info.task_data), OMPT_GET_RETURN_ADDRESS(0)); } #endif if (__kmp_env_consistency_check) { if (global_tid < 0) KMP_WARNING(ThreadIdentInvalid); if (KMP_MASTER_GTID(global_tid)) __kmp_pop_sync(global_tid, ct_master, loc); } } /*! @ingroup WORK_SHARING @param loc source location information. @param gtid global thread number. Start execution of an ordered construct. */ void __kmpc_ordered(ident_t *loc, kmp_int32 gtid) { int cid = 0; kmp_info_t *th; KMP_DEBUG_ASSERT(__kmp_init_serial); KC_TRACE(10, ("__kmpc_ordered: called T#%d\n", gtid)); if (!TCR_4(__kmp_init_parallel)) __kmp_parallel_initialize(); __kmp_resume_if_soft_paused(); #if USE_ITT_BUILD __kmp_itt_ordered_prep(gtid); // TODO: ordered_wait_id #endif /* USE_ITT_BUILD */ th = __kmp_threads[gtid]; #if OMPT_SUPPORT && OMPT_OPTIONAL kmp_team_t *team; ompt_wait_id_t lck; void *codeptr_ra; if (ompt_enabled.enabled) { OMPT_STORE_RETURN_ADDRESS(gtid); team = __kmp_team_from_gtid(gtid); lck = (ompt_wait_id_t)(uintptr_t)&team->t.t_ordered.dt.t_value; /* OMPT state update */ th->th.ompt_thread_info.wait_id = lck; th->th.ompt_thread_info.state = ompt_state_wait_ordered; /* OMPT event callback */ codeptr_ra = OMPT_LOAD_RETURN_ADDRESS(gtid); if (ompt_enabled.ompt_callback_mutex_acquire) { ompt_callbacks.ompt_callback(ompt_callback_mutex_acquire)( ompt_mutex_ordered, omp_lock_hint_none, kmp_mutex_impl_spin, lck, codeptr_ra); } } #endif if (th->th.th_dispatch->th_deo_fcn != 0) (*th->th.th_dispatch->th_deo_fcn)(>id, &cid, loc); else __kmp_parallel_deo(>id, &cid, loc); #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled) { /* OMPT state update */ th->th.ompt_thread_info.state = ompt_state_work_parallel; th->th.ompt_thread_info.wait_id = 0; /* OMPT event callback */ if (ompt_enabled.ompt_callback_mutex_acquired) { ompt_callbacks.ompt_callback(ompt_callback_mutex_acquired)( ompt_mutex_ordered, (ompt_wait_id_t)(uintptr_t)lck, codeptr_ra); } } #endif #if USE_ITT_BUILD __kmp_itt_ordered_start(gtid); #endif /* USE_ITT_BUILD */ } /*! @ingroup WORK_SHARING @param loc source location information. @param gtid global thread number. End execution of an ordered construct. */ void __kmpc_end_ordered(ident_t *loc, kmp_int32 gtid) { int cid = 0; kmp_info_t *th; KC_TRACE(10, ("__kmpc_end_ordered: called T#%d\n", gtid)); #if USE_ITT_BUILD __kmp_itt_ordered_end(gtid); // TODO: ordered_wait_id #endif /* USE_ITT_BUILD */ th = __kmp_threads[gtid]; if (th->th.th_dispatch->th_dxo_fcn != 0) (*th->th.th_dispatch->th_dxo_fcn)(>id, &cid, loc); else __kmp_parallel_dxo(>id, &cid, loc); #if OMPT_SUPPORT && OMPT_OPTIONAL OMPT_STORE_RETURN_ADDRESS(gtid); if (ompt_enabled.ompt_callback_mutex_released) { ompt_callbacks.ompt_callback(ompt_callback_mutex_released)( ompt_mutex_ordered, (ompt_wait_id_t)(uintptr_t)&__kmp_team_from_gtid(gtid) ->t.t_ordered.dt.t_value, OMPT_LOAD_RETURN_ADDRESS(gtid)); } #endif } #if KMP_USE_DYNAMIC_LOCK static __forceinline void __kmp_init_indirect_csptr(kmp_critical_name *crit, ident_t const *loc, kmp_int32 gtid, kmp_indirect_locktag_t tag) { // Pointer to the allocated indirect lock is written to crit, while indexing // is ignored. void *idx; kmp_indirect_lock_t **lck; lck = (kmp_indirect_lock_t **)crit; kmp_indirect_lock_t *ilk = __kmp_allocate_indirect_lock(&idx, gtid, tag); KMP_I_LOCK_FUNC(ilk, init)(ilk->lock); KMP_SET_I_LOCK_LOCATION(ilk, loc); KMP_SET_I_LOCK_FLAGS(ilk, kmp_lf_critical_section); KA_TRACE(20, ("__kmp_init_indirect_csptr: initialized indirect lock #%d\n", tag)); #if USE_ITT_BUILD __kmp_itt_critical_creating(ilk->lock, loc); #endif int status = KMP_COMPARE_AND_STORE_PTR(lck, nullptr, ilk); if (status == 0) { #if USE_ITT_BUILD __kmp_itt_critical_destroyed(ilk->lock); #endif // We don't really need to destroy the unclaimed lock here since it will be // cleaned up at program exit. // KMP_D_LOCK_FUNC(&idx, destroy)((kmp_dyna_lock_t *)&idx); } KMP_DEBUG_ASSERT(*lck != NULL); } // Fast-path acquire tas lock #define KMP_ACQUIRE_TAS_LOCK(lock, gtid) \ { \ kmp_tas_lock_t *l = (kmp_tas_lock_t *)lock; \ kmp_int32 tas_free = KMP_LOCK_FREE(tas); \ kmp_int32 tas_busy = KMP_LOCK_BUSY(gtid + 1, tas); \ if (KMP_ATOMIC_LD_RLX(&l->lk.poll) != tas_free || \ !__kmp_atomic_compare_store_acq(&l->lk.poll, tas_free, tas_busy)) { \ kmp_uint32 spins; \ KMP_FSYNC_PREPARE(l); \ KMP_INIT_YIELD(spins); \ kmp_backoff_t backoff = __kmp_spin_backoff_params; \ do { \ if (TCR_4(__kmp_nth) > \ (__kmp_avail_proc ? __kmp_avail_proc : __kmp_xproc)) { \ KMP_YIELD(TRUE); \ } else { \ KMP_YIELD_SPIN(spins); \ } \ __kmp_spin_backoff(&backoff); \ } while ( \ KMP_ATOMIC_LD_RLX(&l->lk.poll) != tas_free || \ !__kmp_atomic_compare_store_acq(&l->lk.poll, tas_free, tas_busy)); \ } \ KMP_FSYNC_ACQUIRED(l); \ } // Fast-path test tas lock #define KMP_TEST_TAS_LOCK(lock, gtid, rc) \ { \ kmp_tas_lock_t *l = (kmp_tas_lock_t *)lock; \ kmp_int32 tas_free = KMP_LOCK_FREE(tas); \ kmp_int32 tas_busy = KMP_LOCK_BUSY(gtid + 1, tas); \ rc = KMP_ATOMIC_LD_RLX(&l->lk.poll) == tas_free && \ __kmp_atomic_compare_store_acq(&l->lk.poll, tas_free, tas_busy); \ } // Fast-path release tas lock #define KMP_RELEASE_TAS_LOCK(lock, gtid) \ { KMP_ATOMIC_ST_REL(&((kmp_tas_lock_t *)lock)->lk.poll, KMP_LOCK_FREE(tas)); } #if KMP_USE_FUTEX #include #include #ifndef FUTEX_WAIT #define FUTEX_WAIT 0 #endif #ifndef FUTEX_WAKE #define FUTEX_WAKE 1 #endif // Fast-path acquire futex lock #define KMP_ACQUIRE_FUTEX_LOCK(lock, gtid) \ { \ kmp_futex_lock_t *ftx = (kmp_futex_lock_t *)lock; \ kmp_int32 gtid_code = (gtid + 1) << 1; \ KMP_MB(); \ KMP_FSYNC_PREPARE(ftx); \ kmp_int32 poll_val; \ while ((poll_val = KMP_COMPARE_AND_STORE_RET32( \ &(ftx->lk.poll), KMP_LOCK_FREE(futex), \ KMP_LOCK_BUSY(gtid_code, futex))) != KMP_LOCK_FREE(futex)) { \ kmp_int32 cond = KMP_LOCK_STRIP(poll_val) & 1; \ if (!cond) { \ if (!KMP_COMPARE_AND_STORE_RET32(&(ftx->lk.poll), poll_val, \ poll_val | \ KMP_LOCK_BUSY(1, futex))) { \ continue; \ } \ poll_val |= KMP_LOCK_BUSY(1, futex); \ } \ kmp_int32 rc; \ if ((rc = syscall(__NR_futex, &(ftx->lk.poll), FUTEX_WAIT, poll_val, \ NULL, NULL, 0)) != 0) { \ continue; \ } \ gtid_code |= 1; \ } \ KMP_FSYNC_ACQUIRED(ftx); \ } // Fast-path test futex lock #define KMP_TEST_FUTEX_LOCK(lock, gtid, rc) \ { \ kmp_futex_lock_t *ftx = (kmp_futex_lock_t *)lock; \ if (KMP_COMPARE_AND_STORE_ACQ32(&(ftx->lk.poll), KMP_LOCK_FREE(futex), \ KMP_LOCK_BUSY(gtid + 1 << 1, futex))) { \ KMP_FSYNC_ACQUIRED(ftx); \ rc = TRUE; \ } else { \ rc = FALSE; \ } \ } // Fast-path release futex lock #define KMP_RELEASE_FUTEX_LOCK(lock, gtid) \ { \ kmp_futex_lock_t *ftx = (kmp_futex_lock_t *)lock; \ KMP_MB(); \ KMP_FSYNC_RELEASING(ftx); \ kmp_int32 poll_val = \ KMP_XCHG_FIXED32(&(ftx->lk.poll), KMP_LOCK_FREE(futex)); \ if (KMP_LOCK_STRIP(poll_val) & 1) { \ syscall(__NR_futex, &(ftx->lk.poll), FUTEX_WAKE, \ KMP_LOCK_BUSY(1, futex), NULL, NULL, 0); \ } \ KMP_MB(); \ KMP_YIELD_OVERSUB(); \ } #endif // KMP_USE_FUTEX #else // KMP_USE_DYNAMIC_LOCK static kmp_user_lock_p __kmp_get_critical_section_ptr(kmp_critical_name *crit, ident_t const *loc, kmp_int32 gtid) { kmp_user_lock_p *lck_pp = (kmp_user_lock_p *)crit; // Because of the double-check, the following load doesn't need to be volatile kmp_user_lock_p lck = (kmp_user_lock_p)TCR_PTR(*lck_pp); if (lck == NULL) { void *idx; // Allocate & initialize the lock. // Remember alloc'ed locks in table in order to free them in __kmp_cleanup() lck = __kmp_user_lock_allocate(&idx, gtid, kmp_lf_critical_section); __kmp_init_user_lock_with_checks(lck); __kmp_set_user_lock_location(lck, loc); #if USE_ITT_BUILD __kmp_itt_critical_creating(lck); // __kmp_itt_critical_creating() should be called *before* the first usage // of underlying lock. It is the only place where we can guarantee it. There // are chances the lock will destroyed with no usage, but it is not a // problem, because this is not real event seen by user but rather setting // name for object (lock). See more details in kmp_itt.h. #endif /* USE_ITT_BUILD */ // Use a cmpxchg instruction to slam the start of the critical section with // the lock pointer. If another thread beat us to it, deallocate the lock, // and use the lock that the other thread allocated. int status = KMP_COMPARE_AND_STORE_PTR(lck_pp, 0, lck); if (status == 0) { // Deallocate the lock and reload the value. #if USE_ITT_BUILD __kmp_itt_critical_destroyed(lck); // Let ITT know the lock is destroyed and the same memory location may be reused // for another purpose. #endif /* USE_ITT_BUILD */ __kmp_destroy_user_lock_with_checks(lck); __kmp_user_lock_free(&idx, gtid, lck); lck = (kmp_user_lock_p)TCR_PTR(*lck_pp); KMP_DEBUG_ASSERT(lck != NULL); } } return lck; } #endif // KMP_USE_DYNAMIC_LOCK /*! @ingroup WORK_SHARING @param loc source location information. @param global_tid global thread number . @param crit identity of the critical section. This could be a pointer to a lock associated with the critical section, or some other suitably unique value. Enter code protected by a `critical` construct. This function blocks until the executing thread can enter the critical section. */ void __kmpc_critical(ident_t *loc, kmp_int32 global_tid, kmp_critical_name *crit) { #if KMP_USE_DYNAMIC_LOCK #if OMPT_SUPPORT && OMPT_OPTIONAL OMPT_STORE_RETURN_ADDRESS(global_tid); #endif // OMPT_SUPPORT __kmpc_critical_with_hint(loc, global_tid, crit, omp_lock_hint_none); #else KMP_COUNT_BLOCK(OMP_CRITICAL); #if OMPT_SUPPORT && OMPT_OPTIONAL ompt_state_t prev_state = ompt_state_undefined; ompt_thread_info_t ti; #endif kmp_user_lock_p lck; KC_TRACE(10, ("__kmpc_critical: called T#%d\n", global_tid)); // TODO: add THR_OVHD_STATE KMP_PUSH_PARTITIONED_TIMER(OMP_critical_wait); KMP_CHECK_USER_LOCK_INIT(); if ((__kmp_user_lock_kind == lk_tas) && (sizeof(lck->tas.lk.poll) <= OMP_CRITICAL_SIZE)) { lck = (kmp_user_lock_p)crit; } #if KMP_USE_FUTEX else if ((__kmp_user_lock_kind == lk_futex) && (sizeof(lck->futex.lk.poll) <= OMP_CRITICAL_SIZE)) { lck = (kmp_user_lock_p)crit; } #endif else { // ticket, queuing or drdpa lck = __kmp_get_critical_section_ptr(crit, loc, global_tid); } if (__kmp_env_consistency_check) __kmp_push_sync(global_tid, ct_critical, loc, lck); // since the critical directive binds to all threads, not just the current // team we have to check this even if we are in a serialized team. // also, even if we are the uber thread, we still have to conduct the lock, // as we have to contend with sibling threads. #if USE_ITT_BUILD __kmp_itt_critical_acquiring(lck); #endif /* USE_ITT_BUILD */ #if OMPT_SUPPORT && OMPT_OPTIONAL OMPT_STORE_RETURN_ADDRESS(gtid); void *codeptr_ra = NULL; if (ompt_enabled.enabled) { ti = __kmp_threads[global_tid]->th.ompt_thread_info; /* OMPT state update */ prev_state = ti.state; ti.wait_id = (ompt_wait_id_t)(uintptr_t)lck; ti.state = ompt_state_wait_critical; /* OMPT event callback */ codeptr_ra = OMPT_LOAD_RETURN_ADDRESS(gtid); if (ompt_enabled.ompt_callback_mutex_acquire) { ompt_callbacks.ompt_callback(ompt_callback_mutex_acquire)( ompt_mutex_critical, omp_lock_hint_none, __ompt_get_mutex_impl_type(), (ompt_wait_id_t)(uintptr_t)lck, codeptr_ra); } } #endif // Value of 'crit' should be good for using as a critical_id of the critical // section directive. __kmp_acquire_user_lock_with_checks(lck, global_tid); #if USE_ITT_BUILD __kmp_itt_critical_acquired(lck); #endif /* USE_ITT_BUILD */ #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled) { /* OMPT state update */ ti.state = prev_state; ti.wait_id = 0; /* OMPT event callback */ if (ompt_enabled.ompt_callback_mutex_acquired) { ompt_callbacks.ompt_callback(ompt_callback_mutex_acquired)( ompt_mutex_critical, (ompt_wait_id_t)(uintptr_t)lck, codeptr_ra); } } #endif KMP_POP_PARTITIONED_TIMER(); KMP_PUSH_PARTITIONED_TIMER(OMP_critical); KA_TRACE(15, ("__kmpc_critical: done T#%d\n", global_tid)); #endif // KMP_USE_DYNAMIC_LOCK } #if KMP_USE_DYNAMIC_LOCK // Converts the given hint to an internal lock implementation static __forceinline kmp_dyna_lockseq_t __kmp_map_hint_to_lock(uintptr_t hint) { #if KMP_USE_TSX #define KMP_TSX_LOCK(seq) lockseq_##seq #else #define KMP_TSX_LOCK(seq) __kmp_user_lock_seq #endif #if KMP_ARCH_X86 || KMP_ARCH_X86_64 #define KMP_CPUINFO_RTM (__kmp_cpuinfo.rtm) #else #define KMP_CPUINFO_RTM 0 #endif // Hints that do not require further logic if (hint & kmp_lock_hint_hle) return KMP_TSX_LOCK(hle); if (hint & kmp_lock_hint_rtm) return KMP_CPUINFO_RTM ? KMP_TSX_LOCK(rtm) : __kmp_user_lock_seq; if (hint & kmp_lock_hint_adaptive) return KMP_CPUINFO_RTM ? KMP_TSX_LOCK(adaptive) : __kmp_user_lock_seq; // Rule out conflicting hints first by returning the default lock if ((hint & omp_lock_hint_contended) && (hint & omp_lock_hint_uncontended)) return __kmp_user_lock_seq; if ((hint & omp_lock_hint_speculative) && (hint & omp_lock_hint_nonspeculative)) return __kmp_user_lock_seq; // Do not even consider speculation when it appears to be contended if (hint & omp_lock_hint_contended) return lockseq_queuing; // Uncontended lock without speculation if ((hint & omp_lock_hint_uncontended) && !(hint & omp_lock_hint_speculative)) return lockseq_tas; // HLE lock for speculation if (hint & omp_lock_hint_speculative) return KMP_TSX_LOCK(hle); return __kmp_user_lock_seq; } #if OMPT_SUPPORT && OMPT_OPTIONAL #if KMP_USE_DYNAMIC_LOCK static kmp_mutex_impl_t __ompt_get_mutex_impl_type(void *user_lock, kmp_indirect_lock_t *ilock = 0) { if (user_lock) { switch (KMP_EXTRACT_D_TAG(user_lock)) { case 0: break; #if KMP_USE_FUTEX case locktag_futex: return kmp_mutex_impl_queuing; #endif case locktag_tas: return kmp_mutex_impl_spin; #if KMP_USE_TSX case locktag_hle: return kmp_mutex_impl_speculative; #endif default: return kmp_mutex_impl_none; } ilock = KMP_LOOKUP_I_LOCK(user_lock); } KMP_ASSERT(ilock); switch (ilock->type) { #if KMP_USE_TSX case locktag_adaptive: case locktag_rtm: return kmp_mutex_impl_speculative; #endif case locktag_nested_tas: return kmp_mutex_impl_spin; #if KMP_USE_FUTEX case locktag_nested_futex: #endif case locktag_ticket: case locktag_queuing: case locktag_drdpa: case locktag_nested_ticket: case locktag_nested_queuing: case locktag_nested_drdpa: return kmp_mutex_impl_queuing; default: return kmp_mutex_impl_none; } } #else // For locks without dynamic binding static kmp_mutex_impl_t __ompt_get_mutex_impl_type() { switch (__kmp_user_lock_kind) { case lk_tas: return kmp_mutex_impl_spin; #if KMP_USE_FUTEX case lk_futex: #endif case lk_ticket: case lk_queuing: case lk_drdpa: return kmp_mutex_impl_queuing; #if KMP_USE_TSX case lk_hle: case lk_rtm: case lk_adaptive: return kmp_mutex_impl_speculative; #endif default: return kmp_mutex_impl_none; } } #endif // KMP_USE_DYNAMIC_LOCK #endif // OMPT_SUPPORT && OMPT_OPTIONAL /*! @ingroup WORK_SHARING @param loc source location information. @param global_tid global thread number. @param crit identity of the critical section. This could be a pointer to a lock associated with the critical section, or some other suitably unique value. @param hint the lock hint. Enter code protected by a `critical` construct with a hint. The hint value is used to suggest a lock implementation. This function blocks until the executing thread can enter the critical section unless the hint suggests use of speculative execution and the hardware supports it. */ void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid, kmp_critical_name *crit, uint32_t hint) { KMP_COUNT_BLOCK(OMP_CRITICAL); kmp_user_lock_p lck; #if OMPT_SUPPORT && OMPT_OPTIONAL ompt_state_t prev_state = ompt_state_undefined; ompt_thread_info_t ti; // This is the case, if called from __kmpc_critical: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(global_tid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); #endif KC_TRACE(10, ("__kmpc_critical: called T#%d\n", global_tid)); kmp_dyna_lock_t *lk = (kmp_dyna_lock_t *)crit; // Check if it is initialized. KMP_PUSH_PARTITIONED_TIMER(OMP_critical_wait); if (*lk == 0) { kmp_dyna_lockseq_t lckseq = __kmp_map_hint_to_lock(hint); if (KMP_IS_D_LOCK(lckseq)) { KMP_COMPARE_AND_STORE_ACQ32((volatile kmp_int32 *)crit, 0, KMP_GET_D_TAG(lckseq)); } else { __kmp_init_indirect_csptr(crit, loc, global_tid, KMP_GET_I_TAG(lckseq)); } } // Branch for accessing the actual lock object and set operation. This // branching is inevitable since this lock initialization does not follow the // normal dispatch path (lock table is not used). if (KMP_EXTRACT_D_TAG(lk) != 0) { lck = (kmp_user_lock_p)lk; if (__kmp_env_consistency_check) { __kmp_push_sync(global_tid, ct_critical, loc, lck, __kmp_map_hint_to_lock(hint)); } #if USE_ITT_BUILD __kmp_itt_critical_acquiring(lck); #endif #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled) { ti = __kmp_threads[global_tid]->th.ompt_thread_info; /* OMPT state update */ prev_state = ti.state; ti.wait_id = (ompt_wait_id_t)(uintptr_t)lck; ti.state = ompt_state_wait_critical; /* OMPT event callback */ if (ompt_enabled.ompt_callback_mutex_acquire) { ompt_callbacks.ompt_callback(ompt_callback_mutex_acquire)( ompt_mutex_critical, (unsigned int)hint, __ompt_get_mutex_impl_type(crit), (ompt_wait_id_t)(uintptr_t)lck, codeptr); } } #endif #if KMP_USE_INLINED_TAS if (__kmp_user_lock_seq == lockseq_tas && !__kmp_env_consistency_check) { KMP_ACQUIRE_TAS_LOCK(lck, global_tid); } else #elif KMP_USE_INLINED_FUTEX if (__kmp_user_lock_seq == lockseq_futex && !__kmp_env_consistency_check) { KMP_ACQUIRE_FUTEX_LOCK(lck, global_tid); } else #endif { KMP_D_LOCK_FUNC(lk, set)(lk, global_tid); } } else { kmp_indirect_lock_t *ilk = *((kmp_indirect_lock_t **)lk); lck = ilk->lock; if (__kmp_env_consistency_check) { __kmp_push_sync(global_tid, ct_critical, loc, lck, __kmp_map_hint_to_lock(hint)); } #if USE_ITT_BUILD __kmp_itt_critical_acquiring(lck); #endif #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled) { ti = __kmp_threads[global_tid]->th.ompt_thread_info; /* OMPT state update */ prev_state = ti.state; ti.wait_id = (ompt_wait_id_t)(uintptr_t)lck; ti.state = ompt_state_wait_critical; /* OMPT event callback */ if (ompt_enabled.ompt_callback_mutex_acquire) { ompt_callbacks.ompt_callback(ompt_callback_mutex_acquire)( ompt_mutex_critical, (unsigned int)hint, __ompt_get_mutex_impl_type(0, ilk), (ompt_wait_id_t)(uintptr_t)lck, codeptr); } } #endif KMP_I_LOCK_FUNC(ilk, set)(lck, global_tid); } KMP_POP_PARTITIONED_TIMER(); #if USE_ITT_BUILD __kmp_itt_critical_acquired(lck); #endif /* USE_ITT_BUILD */ #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled) { /* OMPT state update */ ti.state = prev_state; ti.wait_id = 0; /* OMPT event callback */ if (ompt_enabled.ompt_callback_mutex_acquired) { ompt_callbacks.ompt_callback(ompt_callback_mutex_acquired)( ompt_mutex_critical, (ompt_wait_id_t)(uintptr_t)lck, codeptr); } } #endif KMP_PUSH_PARTITIONED_TIMER(OMP_critical); KA_TRACE(15, ("__kmpc_critical: done T#%d\n", global_tid)); } // __kmpc_critical_with_hint #endif // KMP_USE_DYNAMIC_LOCK /*! @ingroup WORK_SHARING @param loc source location information. @param global_tid global thread number . @param crit identity of the critical section. This could be a pointer to a lock associated with the critical section, or some other suitably unique value. Leave a critical section, releasing any lock that was held during its execution. */ void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid, kmp_critical_name *crit) { kmp_user_lock_p lck; KC_TRACE(10, ("__kmpc_end_critical: called T#%d\n", global_tid)); #if KMP_USE_DYNAMIC_LOCK if (KMP_IS_D_LOCK(__kmp_user_lock_seq)) { lck = (kmp_user_lock_p)crit; KMP_ASSERT(lck != NULL); if (__kmp_env_consistency_check) { __kmp_pop_sync(global_tid, ct_critical, loc); } #if USE_ITT_BUILD __kmp_itt_critical_releasing(lck); #endif #if KMP_USE_INLINED_TAS if (__kmp_user_lock_seq == lockseq_tas && !__kmp_env_consistency_check) { KMP_RELEASE_TAS_LOCK(lck, global_tid); } else #elif KMP_USE_INLINED_FUTEX if (__kmp_user_lock_seq == lockseq_futex && !__kmp_env_consistency_check) { KMP_RELEASE_FUTEX_LOCK(lck, global_tid); } else #endif { KMP_D_LOCK_FUNC(lck, unset)((kmp_dyna_lock_t *)lck, global_tid); } } else { kmp_indirect_lock_t *ilk = (kmp_indirect_lock_t *)TCR_PTR(*((kmp_indirect_lock_t **)crit)); KMP_ASSERT(ilk != NULL); lck = ilk->lock; if (__kmp_env_consistency_check) { __kmp_pop_sync(global_tid, ct_critical, loc); } #if USE_ITT_BUILD __kmp_itt_critical_releasing(lck); #endif KMP_I_LOCK_FUNC(ilk, unset)(lck, global_tid); } #else // KMP_USE_DYNAMIC_LOCK if ((__kmp_user_lock_kind == lk_tas) && (sizeof(lck->tas.lk.poll) <= OMP_CRITICAL_SIZE)) { lck = (kmp_user_lock_p)crit; } #if KMP_USE_FUTEX else if ((__kmp_user_lock_kind == lk_futex) && (sizeof(lck->futex.lk.poll) <= OMP_CRITICAL_SIZE)) { lck = (kmp_user_lock_p)crit; } #endif else { // ticket, queuing or drdpa lck = (kmp_user_lock_p)TCR_PTR(*((kmp_user_lock_p *)crit)); } KMP_ASSERT(lck != NULL); if (__kmp_env_consistency_check) __kmp_pop_sync(global_tid, ct_critical, loc); #if USE_ITT_BUILD __kmp_itt_critical_releasing(lck); #endif /* USE_ITT_BUILD */ // Value of 'crit' should be good for using as a critical_id of the critical // section directive. __kmp_release_user_lock_with_checks(lck, global_tid); #endif // KMP_USE_DYNAMIC_LOCK #if OMPT_SUPPORT && OMPT_OPTIONAL /* OMPT release event triggers after lock is released; place here to trigger * for all #if branches */ OMPT_STORE_RETURN_ADDRESS(global_tid); if (ompt_enabled.ompt_callback_mutex_released) { ompt_callbacks.ompt_callback(ompt_callback_mutex_released)( ompt_mutex_critical, (ompt_wait_id_t)(uintptr_t)lck, OMPT_LOAD_RETURN_ADDRESS(0)); } #endif KMP_POP_PARTITIONED_TIMER(); KA_TRACE(15, ("__kmpc_end_critical: done T#%d\n", global_tid)); } /*! @ingroup SYNCHRONIZATION @param loc source location information @param global_tid thread id. @return one if the thread should execute the master block, zero otherwise Start execution of a combined barrier and master. The barrier is executed inside this function. */ kmp_int32 __kmpc_barrier_master(ident_t *loc, kmp_int32 global_tid) { int status; KC_TRACE(10, ("__kmpc_barrier_master: called T#%d\n", global_tid)); if (!TCR_4(__kmp_init_parallel)) __kmp_parallel_initialize(); __kmp_resume_if_soft_paused(); if (__kmp_env_consistency_check) __kmp_check_barrier(global_tid, ct_barrier, loc); #if OMPT_SUPPORT ompt_frame_t *ompt_frame; if (ompt_enabled.enabled) { __ompt_get_task_info_internal(0, NULL, NULL, &ompt_frame, NULL, NULL); if (ompt_frame->enter_frame.ptr == NULL) ompt_frame->enter_frame.ptr = OMPT_GET_FRAME_ADDRESS(0); OMPT_STORE_RETURN_ADDRESS(global_tid); } #endif #if USE_ITT_NOTIFY __kmp_threads[global_tid]->th.th_ident = loc; #endif status = __kmp_barrier(bs_plain_barrier, global_tid, TRUE, 0, NULL, NULL); #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled) { ompt_frame->enter_frame = ompt_data_none; } #endif return (status != 0) ? 0 : 1; } /*! @ingroup SYNCHRONIZATION @param loc source location information @param global_tid thread id. Complete the execution of a combined barrier and master. This function should only be called at the completion of the master code. Other threads will still be waiting at the barrier and this call releases them. */ void __kmpc_end_barrier_master(ident_t *loc, kmp_int32 global_tid) { KC_TRACE(10, ("__kmpc_end_barrier_master: called T#%d\n", global_tid)); __kmp_end_split_barrier(bs_plain_barrier, global_tid); } /*! @ingroup SYNCHRONIZATION @param loc source location information @param global_tid thread id. @return one if the thread should execute the master block, zero otherwise Start execution of a combined barrier and master(nowait) construct. The barrier is executed inside this function. There is no equivalent "end" function, since the */ kmp_int32 __kmpc_barrier_master_nowait(ident_t *loc, kmp_int32 global_tid) { kmp_int32 ret; KC_TRACE(10, ("__kmpc_barrier_master_nowait: called T#%d\n", global_tid)); if (!TCR_4(__kmp_init_parallel)) __kmp_parallel_initialize(); __kmp_resume_if_soft_paused(); if (__kmp_env_consistency_check) { if (loc == 0) { KMP_WARNING(ConstructIdentInvalid); // ??? What does it mean for the user? } __kmp_check_barrier(global_tid, ct_barrier, loc); } #if OMPT_SUPPORT ompt_frame_t *ompt_frame; if (ompt_enabled.enabled) { __ompt_get_task_info_internal(0, NULL, NULL, &ompt_frame, NULL, NULL); if (ompt_frame->enter_frame.ptr == NULL) ompt_frame->enter_frame.ptr = OMPT_GET_FRAME_ADDRESS(0); OMPT_STORE_RETURN_ADDRESS(global_tid); } #endif #if USE_ITT_NOTIFY __kmp_threads[global_tid]->th.th_ident = loc; #endif __kmp_barrier(bs_plain_barrier, global_tid, FALSE, 0, NULL, NULL); #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled) { ompt_frame->enter_frame = ompt_data_none; } #endif ret = __kmpc_master(loc, global_tid); if (__kmp_env_consistency_check) { /* there's no __kmpc_end_master called; so the (stats) */ /* actions of __kmpc_end_master are done here */ if (global_tid < 0) { KMP_WARNING(ThreadIdentInvalid); } if (ret) { /* only one thread should do the pop since only */ /* one did the push (see __kmpc_master()) */ __kmp_pop_sync(global_tid, ct_master, loc); } } return (ret); } /* The BARRIER for a SINGLE process section is always explicit */ /*! @ingroup WORK_SHARING @param loc source location information @param global_tid global thread number @return One if this thread should execute the single construct, zero otherwise. Test whether to execute a single construct. There are no implicit barriers in the two "single" calls, rather the compiler should introduce an explicit barrier if it is required. */ kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid) { kmp_int32 rc = __kmp_enter_single(global_tid, loc, TRUE); if (rc) { // We are going to execute the single statement, so we should count it. KMP_COUNT_BLOCK(OMP_SINGLE); KMP_PUSH_PARTITIONED_TIMER(OMP_single); } #if OMPT_SUPPORT && OMPT_OPTIONAL kmp_info_t *this_thr = __kmp_threads[global_tid]; kmp_team_t *team = this_thr->th.th_team; int tid = __kmp_tid_from_gtid(global_tid); if (ompt_enabled.enabled) { if (rc) { if (ompt_enabled.ompt_callback_work) { ompt_callbacks.ompt_callback(ompt_callback_work)( ompt_work_single_executor, ompt_scope_begin, &(team->t.ompt_team_info.parallel_data), &(team->t.t_implicit_task_taskdata[tid].ompt_task_info.task_data), 1, OMPT_GET_RETURN_ADDRESS(0)); } } else { if (ompt_enabled.ompt_callback_work) { ompt_callbacks.ompt_callback(ompt_callback_work)( ompt_work_single_other, ompt_scope_begin, &(team->t.ompt_team_info.parallel_data), &(team->t.t_implicit_task_taskdata[tid].ompt_task_info.task_data), 1, OMPT_GET_RETURN_ADDRESS(0)); ompt_callbacks.ompt_callback(ompt_callback_work)( ompt_work_single_other, ompt_scope_end, &(team->t.ompt_team_info.parallel_data), &(team->t.t_implicit_task_taskdata[tid].ompt_task_info.task_data), 1, OMPT_GET_RETURN_ADDRESS(0)); } } } #endif return rc; } /*! @ingroup WORK_SHARING @param loc source location information @param global_tid global thread number Mark the end of a single construct. This function should only be called by the thread that executed the block of code protected by the `single` construct. */ void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid) { __kmp_exit_single(global_tid); KMP_POP_PARTITIONED_TIMER(); #if OMPT_SUPPORT && OMPT_OPTIONAL kmp_info_t *this_thr = __kmp_threads[global_tid]; kmp_team_t *team = this_thr->th.th_team; int tid = __kmp_tid_from_gtid(global_tid); if (ompt_enabled.ompt_callback_work) { ompt_callbacks.ompt_callback(ompt_callback_work)( ompt_work_single_executor, ompt_scope_end, &(team->t.ompt_team_info.parallel_data), &(team->t.t_implicit_task_taskdata[tid].ompt_task_info.task_data), 1, OMPT_GET_RETURN_ADDRESS(0)); } #endif } /*! @ingroup WORK_SHARING @param loc Source location @param global_tid Global thread id Mark the end of a statically scheduled loop. */ void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid) { KMP_POP_PARTITIONED_TIMER(); KE_TRACE(10, ("__kmpc_for_static_fini called T#%d\n", global_tid)); #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.ompt_callback_work) { ompt_work_t ompt_work_type = ompt_work_loop; ompt_team_info_t *team_info = __ompt_get_teaminfo(0, NULL); ompt_task_info_t *task_info = __ompt_get_task_info_object(0); // Determine workshare type if (loc != NULL) { if ((loc->flags & KMP_IDENT_WORK_LOOP) != 0) { ompt_work_type = ompt_work_loop; } else if ((loc->flags & KMP_IDENT_WORK_SECTIONS) != 0) { ompt_work_type = ompt_work_sections; } else if ((loc->flags & KMP_IDENT_WORK_DISTRIBUTE) != 0) { ompt_work_type = ompt_work_distribute; } else { // use default set above. // a warning about this case is provided in __kmpc_for_static_init } KMP_DEBUG_ASSERT(ompt_work_type); } ompt_callbacks.ompt_callback(ompt_callback_work)( ompt_work_type, ompt_scope_end, &(team_info->parallel_data), &(task_info->task_data), 0, OMPT_GET_RETURN_ADDRESS(0)); } #endif if (__kmp_env_consistency_check) __kmp_pop_workshare(global_tid, ct_pdo, loc); } // User routines which take C-style arguments (call by value) // different from the Fortran equivalent routines void ompc_set_num_threads(int arg) { // !!!!! TODO: check the per-task binding __kmp_set_num_threads(arg, __kmp_entry_gtid()); } void ompc_set_dynamic(int flag) { kmp_info_t *thread; /* For the thread-private implementation of the internal controls */ thread = __kmp_entry_thread(); __kmp_save_internal_controls(thread); set__dynamic(thread, flag ? TRUE : FALSE); } void ompc_set_nested(int flag) { kmp_info_t *thread; /* For the thread-private internal controls implementation */ thread = __kmp_entry_thread(); __kmp_save_internal_controls(thread); set__max_active_levels(thread, flag ? __kmp_dflt_max_active_levels : 1); } void ompc_set_max_active_levels(int max_active_levels) { /* TO DO */ /* we want per-task implementation of this internal control */ /* For the per-thread internal controls implementation */ __kmp_set_max_active_levels(__kmp_entry_gtid(), max_active_levels); } void ompc_set_schedule(omp_sched_t kind, int modifier) { // !!!!! TODO: check the per-task binding __kmp_set_schedule(__kmp_entry_gtid(), (kmp_sched_t)kind, modifier); } int ompc_get_ancestor_thread_num(int level) { return __kmp_get_ancestor_thread_num(__kmp_entry_gtid(), level); } int ompc_get_team_size(int level) { return __kmp_get_team_size(__kmp_entry_gtid(), level); } /* OpenMP 5.0 Affinity Format API */ void ompc_set_affinity_format(char const *format) { if (!__kmp_init_serial) { __kmp_serial_initialize(); } __kmp_strncpy_truncate(__kmp_affinity_format, KMP_AFFINITY_FORMAT_SIZE, format, KMP_STRLEN(format) + 1); } size_t ompc_get_affinity_format(char *buffer, size_t size) { size_t format_size; if (!__kmp_init_serial) { __kmp_serial_initialize(); } format_size = KMP_STRLEN(__kmp_affinity_format); if (buffer && size) { __kmp_strncpy_truncate(buffer, size, __kmp_affinity_format, format_size + 1); } return format_size; } void ompc_display_affinity(char const *format) { int gtid; if (!TCR_4(__kmp_init_middle)) { __kmp_middle_initialize(); } gtid = __kmp_get_gtid(); __kmp_aux_display_affinity(gtid, format); } size_t ompc_capture_affinity(char *buffer, size_t buf_size, char const *format) { int gtid; size_t num_required; kmp_str_buf_t capture_buf; if (!TCR_4(__kmp_init_middle)) { __kmp_middle_initialize(); } gtid = __kmp_get_gtid(); __kmp_str_buf_init(&capture_buf); num_required = __kmp_aux_capture_affinity(gtid, format, &capture_buf); if (buffer && buf_size) { __kmp_strncpy_truncate(buffer, buf_size, capture_buf.str, capture_buf.used + 1); } __kmp_str_buf_free(&capture_buf); return num_required; } void kmpc_set_stacksize(int arg) { // __kmp_aux_set_stacksize initializes the library if needed __kmp_aux_set_stacksize(arg); } void kmpc_set_stacksize_s(size_t arg) { // __kmp_aux_set_stacksize initializes the library if needed __kmp_aux_set_stacksize(arg); } void kmpc_set_blocktime(int arg) { int gtid, tid; kmp_info_t *thread; gtid = __kmp_entry_gtid(); tid = __kmp_tid_from_gtid(gtid); thread = __kmp_thread_from_gtid(gtid); __kmp_aux_set_blocktime(arg, thread, tid); } void kmpc_set_library(int arg) { // __kmp_user_set_library initializes the library if needed __kmp_user_set_library((enum library_type)arg); } void kmpc_set_defaults(char const *str) { // __kmp_aux_set_defaults initializes the library if needed __kmp_aux_set_defaults(str, KMP_STRLEN(str)); } void kmpc_set_disp_num_buffers(int arg) { // ignore after initialization because some teams have already // allocated dispatch buffers if (__kmp_init_serial == 0 && arg > 0) __kmp_dispatch_num_buffers = arg; } int kmpc_set_affinity_mask_proc(int proc, void **mask) { #if defined(KMP_STUB) || !KMP_AFFINITY_SUPPORTED return -1; #else if (!TCR_4(__kmp_init_middle)) { __kmp_middle_initialize(); } return __kmp_aux_set_affinity_mask_proc(proc, mask); #endif } int kmpc_unset_affinity_mask_proc(int proc, void **mask) { #if defined(KMP_STUB) || !KMP_AFFINITY_SUPPORTED return -1; #else if (!TCR_4(__kmp_init_middle)) { __kmp_middle_initialize(); } return __kmp_aux_unset_affinity_mask_proc(proc, mask); #endif } int kmpc_get_affinity_mask_proc(int proc, void **mask) { #if defined(KMP_STUB) || !KMP_AFFINITY_SUPPORTED return -1; #else if (!TCR_4(__kmp_init_middle)) { __kmp_middle_initialize(); } return __kmp_aux_get_affinity_mask_proc(proc, mask); #endif } /* -------------------------------------------------------------------------- */ /*! @ingroup THREADPRIVATE @param loc source location information @param gtid global thread number @param cpy_size size of the cpy_data buffer @param cpy_data pointer to data to be copied @param cpy_func helper function to call for copying data @param didit flag variable: 1=single thread; 0=not single thread __kmpc_copyprivate implements the interface for the private data broadcast needed for the copyprivate clause associated with a single region in an OpenMP* program (both C and Fortran). All threads participating in the parallel region call this routine. One of the threads (called the single thread) should have the didit variable set to 1 and all other threads should have that variable set to 0. All threads pass a pointer to a data buffer (cpy_data) that they have built. The OpenMP specification forbids the use of nowait on the single region when a copyprivate clause is present. However, @ref __kmpc_copyprivate implements a barrier internally to avoid race conditions, so the code generation for the single region should avoid generating a barrier after the call to @ref __kmpc_copyprivate. The gtid parameter is the global thread id for the current thread. The loc parameter is a pointer to source location information. Internal implementation: The single thread will first copy its descriptor address (cpy_data) to a team-private location, then the other threads will each call the function pointed to by the parameter cpy_func, which carries out the copy by copying the data using the cpy_data buffer. The cpy_func routine used for the copy and the contents of the data area defined by cpy_data and cpy_size may be built in any fashion that will allow the copy to be done. For instance, the cpy_data buffer can hold the actual data to be copied or it may hold a list of pointers to the data. The cpy_func routine must interpret the cpy_data buffer appropriately. The interface to cpy_func is as follows: @code void cpy_func( void *destination, void *source ) @endcode where void *destination is the cpy_data pointer for the thread being copied to and void *source is the cpy_data pointer for the thread being copied from. */ void __kmpc_copyprivate(ident_t *loc, kmp_int32 gtid, size_t cpy_size, void *cpy_data, void (*cpy_func)(void *, void *), kmp_int32 didit) { void **data_ptr; KC_TRACE(10, ("__kmpc_copyprivate: called T#%d\n", gtid)); KMP_MB(); data_ptr = &__kmp_team_from_gtid(gtid)->t.t_copypriv_data; if (__kmp_env_consistency_check) { if (loc == 0) { KMP_WARNING(ConstructIdentInvalid); } } // ToDo: Optimize the following two barriers into some kind of split barrier if (didit) *data_ptr = cpy_data; #if OMPT_SUPPORT ompt_frame_t *ompt_frame; if (ompt_enabled.enabled) { __ompt_get_task_info_internal(0, NULL, NULL, &ompt_frame, NULL, NULL); if (ompt_frame->enter_frame.ptr == NULL) ompt_frame->enter_frame.ptr = OMPT_GET_FRAME_ADDRESS(0); OMPT_STORE_RETURN_ADDRESS(gtid); } #endif /* This barrier is not a barrier region boundary */ #if USE_ITT_NOTIFY __kmp_threads[gtid]->th.th_ident = loc; #endif __kmp_barrier(bs_plain_barrier, gtid, FALSE, 0, NULL, NULL); if (!didit) (*cpy_func)(cpy_data, *data_ptr); // Consider next barrier a user-visible barrier for barrier region boundaries // Nesting checks are already handled by the single construct checks #if OMPT_SUPPORT if (ompt_enabled.enabled) { OMPT_STORE_RETURN_ADDRESS(gtid); } #endif #if USE_ITT_NOTIFY __kmp_threads[gtid]->th.th_ident = loc; // TODO: check if it is needed (e.g. // tasks can overwrite the location) #endif __kmp_barrier(bs_plain_barrier, gtid, FALSE, 0, NULL, NULL); #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled) { ompt_frame->enter_frame = ompt_data_none; } #endif } /* -------------------------------------------------------------------------- */ #define INIT_LOCK __kmp_init_user_lock_with_checks #define INIT_NESTED_LOCK __kmp_init_nested_user_lock_with_checks #define ACQUIRE_LOCK __kmp_acquire_user_lock_with_checks #define ACQUIRE_LOCK_TIMED __kmp_acquire_user_lock_with_checks_timed #define ACQUIRE_NESTED_LOCK __kmp_acquire_nested_user_lock_with_checks #define ACQUIRE_NESTED_LOCK_TIMED \ __kmp_acquire_nested_user_lock_with_checks_timed #define RELEASE_LOCK __kmp_release_user_lock_with_checks #define RELEASE_NESTED_LOCK __kmp_release_nested_user_lock_with_checks #define TEST_LOCK __kmp_test_user_lock_with_checks #define TEST_NESTED_LOCK __kmp_test_nested_user_lock_with_checks #define DESTROY_LOCK __kmp_destroy_user_lock_with_checks #define DESTROY_NESTED_LOCK __kmp_destroy_nested_user_lock_with_checks // TODO: Make check abort messages use location info & pass it into // with_checks routines #if KMP_USE_DYNAMIC_LOCK // internal lock initializer static __forceinline void __kmp_init_lock_with_hint(ident_t *loc, void **lock, kmp_dyna_lockseq_t seq) { if (KMP_IS_D_LOCK(seq)) { KMP_INIT_D_LOCK(lock, seq); #if USE_ITT_BUILD __kmp_itt_lock_creating((kmp_user_lock_p)lock, NULL); #endif } else { KMP_INIT_I_LOCK(lock, seq); #if USE_ITT_BUILD kmp_indirect_lock_t *ilk = KMP_LOOKUP_I_LOCK(lock); __kmp_itt_lock_creating(ilk->lock, loc); #endif } } // internal nest lock initializer static __forceinline void __kmp_init_nest_lock_with_hint(ident_t *loc, void **lock, kmp_dyna_lockseq_t seq) { #if KMP_USE_TSX // Don't have nested lock implementation for speculative locks if (seq == lockseq_hle || seq == lockseq_rtm || seq == lockseq_adaptive) seq = __kmp_user_lock_seq; #endif switch (seq) { case lockseq_tas: seq = lockseq_nested_tas; break; #if KMP_USE_FUTEX case lockseq_futex: seq = lockseq_nested_futex; break; #endif case lockseq_ticket: seq = lockseq_nested_ticket; break; case lockseq_queuing: seq = lockseq_nested_queuing; break; case lockseq_drdpa: seq = lockseq_nested_drdpa; break; default: seq = lockseq_nested_queuing; } KMP_INIT_I_LOCK(lock, seq); #if USE_ITT_BUILD kmp_indirect_lock_t *ilk = KMP_LOOKUP_I_LOCK(lock); __kmp_itt_lock_creating(ilk->lock, loc); #endif } /* initialize the lock with a hint */ void __kmpc_init_lock_with_hint(ident_t *loc, kmp_int32 gtid, void **user_lock, uintptr_t hint) { KMP_DEBUG_ASSERT(__kmp_init_serial); if (__kmp_env_consistency_check && user_lock == NULL) { KMP_FATAL(LockIsUninitialized, "omp_init_lock_with_hint"); } __kmp_init_lock_with_hint(loc, user_lock, __kmp_map_hint_to_lock(hint)); #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.ompt_callback_lock_init) { ompt_callbacks.ompt_callback(ompt_callback_lock_init)( ompt_mutex_lock, (omp_lock_hint_t)hint, __ompt_get_mutex_impl_type(user_lock), (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } #endif } /* initialize the lock with a hint */ void __kmpc_init_nest_lock_with_hint(ident_t *loc, kmp_int32 gtid, void **user_lock, uintptr_t hint) { KMP_DEBUG_ASSERT(__kmp_init_serial); if (__kmp_env_consistency_check && user_lock == NULL) { KMP_FATAL(LockIsUninitialized, "omp_init_nest_lock_with_hint"); } __kmp_init_nest_lock_with_hint(loc, user_lock, __kmp_map_hint_to_lock(hint)); #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.ompt_callback_lock_init) { ompt_callbacks.ompt_callback(ompt_callback_lock_init)( ompt_mutex_nest_lock, (omp_lock_hint_t)hint, __ompt_get_mutex_impl_type(user_lock), (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } #endif } #endif // KMP_USE_DYNAMIC_LOCK /* initialize the lock */ void __kmpc_init_lock(ident_t *loc, kmp_int32 gtid, void **user_lock) { #if KMP_USE_DYNAMIC_LOCK KMP_DEBUG_ASSERT(__kmp_init_serial); if (__kmp_env_consistency_check && user_lock == NULL) { KMP_FATAL(LockIsUninitialized, "omp_init_lock"); } __kmp_init_lock_with_hint(loc, user_lock, __kmp_user_lock_seq); #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.ompt_callback_lock_init) { ompt_callbacks.ompt_callback(ompt_callback_lock_init)( ompt_mutex_lock, omp_lock_hint_none, __ompt_get_mutex_impl_type(user_lock), (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } #endif #else // KMP_USE_DYNAMIC_LOCK static char const *const func = "omp_init_lock"; kmp_user_lock_p lck; KMP_DEBUG_ASSERT(__kmp_init_serial); if (__kmp_env_consistency_check) { if (user_lock == NULL) { KMP_FATAL(LockIsUninitialized, func); } } KMP_CHECK_USER_LOCK_INIT(); if ((__kmp_user_lock_kind == lk_tas) && (sizeof(lck->tas.lk.poll) <= OMP_LOCK_T_SIZE)) { lck = (kmp_user_lock_p)user_lock; } #if KMP_USE_FUTEX else if ((__kmp_user_lock_kind == lk_futex) && (sizeof(lck->futex.lk.poll) <= OMP_LOCK_T_SIZE)) { lck = (kmp_user_lock_p)user_lock; } #endif else { lck = __kmp_user_lock_allocate(user_lock, gtid, 0); } INIT_LOCK(lck); __kmp_set_user_lock_location(lck, loc); #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.ompt_callback_lock_init) { ompt_callbacks.ompt_callback(ompt_callback_lock_init)( ompt_mutex_lock, omp_lock_hint_none, __ompt_get_mutex_impl_type(), (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } #endif #if USE_ITT_BUILD __kmp_itt_lock_creating(lck); #endif /* USE_ITT_BUILD */ #endif // KMP_USE_DYNAMIC_LOCK } // __kmpc_init_lock /* initialize the lock */ void __kmpc_init_nest_lock(ident_t *loc, kmp_int32 gtid, void **user_lock) { #if KMP_USE_DYNAMIC_LOCK KMP_DEBUG_ASSERT(__kmp_init_serial); if (__kmp_env_consistency_check && user_lock == NULL) { KMP_FATAL(LockIsUninitialized, "omp_init_nest_lock"); } __kmp_init_nest_lock_with_hint(loc, user_lock, __kmp_user_lock_seq); #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.ompt_callback_lock_init) { ompt_callbacks.ompt_callback(ompt_callback_lock_init)( ompt_mutex_nest_lock, omp_lock_hint_none, __ompt_get_mutex_impl_type(user_lock), (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } #endif #else // KMP_USE_DYNAMIC_LOCK static char const *const func = "omp_init_nest_lock"; kmp_user_lock_p lck; KMP_DEBUG_ASSERT(__kmp_init_serial); if (__kmp_env_consistency_check) { if (user_lock == NULL) { KMP_FATAL(LockIsUninitialized, func); } } KMP_CHECK_USER_LOCK_INIT(); if ((__kmp_user_lock_kind == lk_tas) && (sizeof(lck->tas.lk.poll) + sizeof(lck->tas.lk.depth_locked) <= OMP_NEST_LOCK_T_SIZE)) { lck = (kmp_user_lock_p)user_lock; } #if KMP_USE_FUTEX else if ((__kmp_user_lock_kind == lk_futex) && (sizeof(lck->futex.lk.poll) + sizeof(lck->futex.lk.depth_locked) <= OMP_NEST_LOCK_T_SIZE)) { lck = (kmp_user_lock_p)user_lock; } #endif else { lck = __kmp_user_lock_allocate(user_lock, gtid, 0); } INIT_NESTED_LOCK(lck); __kmp_set_user_lock_location(lck, loc); #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.ompt_callback_lock_init) { ompt_callbacks.ompt_callback(ompt_callback_lock_init)( ompt_mutex_nest_lock, omp_lock_hint_none, __ompt_get_mutex_impl_type(), (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } #endif #if USE_ITT_BUILD __kmp_itt_lock_creating(lck); #endif /* USE_ITT_BUILD */ #endif // KMP_USE_DYNAMIC_LOCK } // __kmpc_init_nest_lock void __kmpc_destroy_lock(ident_t *loc, kmp_int32 gtid, void **user_lock) { #if KMP_USE_DYNAMIC_LOCK #if USE_ITT_BUILD kmp_user_lock_p lck; if (KMP_EXTRACT_D_TAG(user_lock) == 0) { lck = ((kmp_indirect_lock_t *)KMP_LOOKUP_I_LOCK(user_lock))->lock; } else { lck = (kmp_user_lock_p)user_lock; } __kmp_itt_lock_destroyed(lck); #endif #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.ompt_callback_lock_destroy) { kmp_user_lock_p lck; if (KMP_EXTRACT_D_TAG(user_lock) == 0) { lck = ((kmp_indirect_lock_t *)KMP_LOOKUP_I_LOCK(user_lock))->lock; } else { lck = (kmp_user_lock_p)user_lock; } ompt_callbacks.ompt_callback(ompt_callback_lock_destroy)( ompt_mutex_lock, (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } #endif KMP_D_LOCK_FUNC(user_lock, destroy)((kmp_dyna_lock_t *)user_lock); #else kmp_user_lock_p lck; if ((__kmp_user_lock_kind == lk_tas) && (sizeof(lck->tas.lk.poll) <= OMP_LOCK_T_SIZE)) { lck = (kmp_user_lock_p)user_lock; } #if KMP_USE_FUTEX else if ((__kmp_user_lock_kind == lk_futex) && (sizeof(lck->futex.lk.poll) <= OMP_LOCK_T_SIZE)) { lck = (kmp_user_lock_p)user_lock; } #endif else { lck = __kmp_lookup_user_lock(user_lock, "omp_destroy_lock"); } #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.ompt_callback_lock_destroy) { ompt_callbacks.ompt_callback(ompt_callback_lock_destroy)( ompt_mutex_lock, (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } #endif #if USE_ITT_BUILD __kmp_itt_lock_destroyed(lck); #endif /* USE_ITT_BUILD */ DESTROY_LOCK(lck); if ((__kmp_user_lock_kind == lk_tas) && (sizeof(lck->tas.lk.poll) <= OMP_LOCK_T_SIZE)) { ; } #if KMP_USE_FUTEX else if ((__kmp_user_lock_kind == lk_futex) && (sizeof(lck->futex.lk.poll) <= OMP_LOCK_T_SIZE)) { ; } #endif else { __kmp_user_lock_free(user_lock, gtid, lck); } #endif // KMP_USE_DYNAMIC_LOCK } // __kmpc_destroy_lock /* destroy the lock */ void __kmpc_destroy_nest_lock(ident_t *loc, kmp_int32 gtid, void **user_lock) { #if KMP_USE_DYNAMIC_LOCK #if USE_ITT_BUILD kmp_indirect_lock_t *ilk = KMP_LOOKUP_I_LOCK(user_lock); __kmp_itt_lock_destroyed(ilk->lock); #endif #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.ompt_callback_lock_destroy) { ompt_callbacks.ompt_callback(ompt_callback_lock_destroy)( ompt_mutex_nest_lock, (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } #endif KMP_D_LOCK_FUNC(user_lock, destroy)((kmp_dyna_lock_t *)user_lock); #else // KMP_USE_DYNAMIC_LOCK kmp_user_lock_p lck; if ((__kmp_user_lock_kind == lk_tas) && (sizeof(lck->tas.lk.poll) + sizeof(lck->tas.lk.depth_locked) <= OMP_NEST_LOCK_T_SIZE)) { lck = (kmp_user_lock_p)user_lock; } #if KMP_USE_FUTEX else if ((__kmp_user_lock_kind == lk_futex) && (sizeof(lck->futex.lk.poll) + sizeof(lck->futex.lk.depth_locked) <= OMP_NEST_LOCK_T_SIZE)) { lck = (kmp_user_lock_p)user_lock; } #endif else { lck = __kmp_lookup_user_lock(user_lock, "omp_destroy_nest_lock"); } #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.ompt_callback_lock_destroy) { ompt_callbacks.ompt_callback(ompt_callback_lock_destroy)( ompt_mutex_nest_lock, (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } #endif #if USE_ITT_BUILD __kmp_itt_lock_destroyed(lck); #endif /* USE_ITT_BUILD */ DESTROY_NESTED_LOCK(lck); if ((__kmp_user_lock_kind == lk_tas) && (sizeof(lck->tas.lk.poll) + sizeof(lck->tas.lk.depth_locked) <= OMP_NEST_LOCK_T_SIZE)) { ; } #if KMP_USE_FUTEX else if ((__kmp_user_lock_kind == lk_futex) && (sizeof(lck->futex.lk.poll) + sizeof(lck->futex.lk.depth_locked) <= OMP_NEST_LOCK_T_SIZE)) { ; } #endif else { __kmp_user_lock_free(user_lock, gtid, lck); } #endif // KMP_USE_DYNAMIC_LOCK } // __kmpc_destroy_nest_lock void __kmpc_set_lock(ident_t *loc, kmp_int32 gtid, void **user_lock) { KMP_COUNT_BLOCK(OMP_set_lock); #if KMP_USE_DYNAMIC_LOCK int tag = KMP_EXTRACT_D_TAG(user_lock); #if USE_ITT_BUILD __kmp_itt_lock_acquiring( (kmp_user_lock_p) user_lock); // itt function will get to the right lock object. #endif #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.ompt_callback_mutex_acquire) { ompt_callbacks.ompt_callback(ompt_callback_mutex_acquire)( ompt_mutex_lock, omp_lock_hint_none, __ompt_get_mutex_impl_type(user_lock), (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } #endif #if KMP_USE_INLINED_TAS if (tag == locktag_tas && !__kmp_env_consistency_check) { KMP_ACQUIRE_TAS_LOCK(user_lock, gtid); } else #elif KMP_USE_INLINED_FUTEX if (tag == locktag_futex && !__kmp_env_consistency_check) { KMP_ACQUIRE_FUTEX_LOCK(user_lock, gtid); } else #endif { __kmp_direct_set[tag]((kmp_dyna_lock_t *)user_lock, gtid); } #if USE_ITT_BUILD __kmp_itt_lock_acquired((kmp_user_lock_p)user_lock); #endif #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.ompt_callback_mutex_acquired) { ompt_callbacks.ompt_callback(ompt_callback_mutex_acquired)( ompt_mutex_lock, (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } #endif #else // KMP_USE_DYNAMIC_LOCK kmp_user_lock_p lck; if ((__kmp_user_lock_kind == lk_tas) && (sizeof(lck->tas.lk.poll) <= OMP_LOCK_T_SIZE)) { lck = (kmp_user_lock_p)user_lock; } #if KMP_USE_FUTEX else if ((__kmp_user_lock_kind == lk_futex) && (sizeof(lck->futex.lk.poll) <= OMP_LOCK_T_SIZE)) { lck = (kmp_user_lock_p)user_lock; } #endif else { lck = __kmp_lookup_user_lock(user_lock, "omp_set_lock"); } #if USE_ITT_BUILD __kmp_itt_lock_acquiring(lck); #endif /* USE_ITT_BUILD */ #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.ompt_callback_mutex_acquire) { ompt_callbacks.ompt_callback(ompt_callback_mutex_acquire)( ompt_mutex_lock, omp_lock_hint_none, __ompt_get_mutex_impl_type(), (ompt_wait_id_t)(uintptr_t)lck, codeptr); } #endif ACQUIRE_LOCK(lck, gtid); #if USE_ITT_BUILD __kmp_itt_lock_acquired(lck); #endif /* USE_ITT_BUILD */ #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.ompt_callback_mutex_acquired) { ompt_callbacks.ompt_callback(ompt_callback_mutex_acquired)( ompt_mutex_lock, (ompt_wait_id_t)(uintptr_t)lck, codeptr); } #endif #endif // KMP_USE_DYNAMIC_LOCK } void __kmpc_set_nest_lock(ident_t *loc, kmp_int32 gtid, void **user_lock) { #if KMP_USE_DYNAMIC_LOCK #if USE_ITT_BUILD __kmp_itt_lock_acquiring((kmp_user_lock_p)user_lock); #endif #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.enabled) { if (ompt_enabled.ompt_callback_mutex_acquire) { ompt_callbacks.ompt_callback(ompt_callback_mutex_acquire)( ompt_mutex_nest_lock, omp_lock_hint_none, __ompt_get_mutex_impl_type(user_lock), (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } } #endif int acquire_status = KMP_D_LOCK_FUNC(user_lock, set)((kmp_dyna_lock_t *)user_lock, gtid); (void) acquire_status; #if USE_ITT_BUILD __kmp_itt_lock_acquired((kmp_user_lock_p)user_lock); #endif #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled) { if (acquire_status == KMP_LOCK_ACQUIRED_FIRST) { if (ompt_enabled.ompt_callback_mutex_acquired) { // lock_first ompt_callbacks.ompt_callback(ompt_callback_mutex_acquired)( ompt_mutex_nest_lock, (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } } else { if (ompt_enabled.ompt_callback_nest_lock) { // lock_next ompt_callbacks.ompt_callback(ompt_callback_nest_lock)( ompt_scope_begin, (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } } } #endif #else // KMP_USE_DYNAMIC_LOCK int acquire_status; kmp_user_lock_p lck; if ((__kmp_user_lock_kind == lk_tas) && (sizeof(lck->tas.lk.poll) + sizeof(lck->tas.lk.depth_locked) <= OMP_NEST_LOCK_T_SIZE)) { lck = (kmp_user_lock_p)user_lock; } #if KMP_USE_FUTEX else if ((__kmp_user_lock_kind == lk_futex) && (sizeof(lck->futex.lk.poll) + sizeof(lck->futex.lk.depth_locked) <= OMP_NEST_LOCK_T_SIZE)) { lck = (kmp_user_lock_p)user_lock; } #endif else { lck = __kmp_lookup_user_lock(user_lock, "omp_set_nest_lock"); } #if USE_ITT_BUILD __kmp_itt_lock_acquiring(lck); #endif /* USE_ITT_BUILD */ #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.enabled) { if (ompt_enabled.ompt_callback_mutex_acquire) { ompt_callbacks.ompt_callback(ompt_callback_mutex_acquire)( ompt_mutex_nest_lock, omp_lock_hint_none, __ompt_get_mutex_impl_type(), (ompt_wait_id_t)(uintptr_t)lck, codeptr); } } #endif ACQUIRE_NESTED_LOCK(lck, gtid, &acquire_status); #if USE_ITT_BUILD __kmp_itt_lock_acquired(lck); #endif /* USE_ITT_BUILD */ #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled) { if (acquire_status == KMP_LOCK_ACQUIRED_FIRST) { if (ompt_enabled.ompt_callback_mutex_acquired) { // lock_first ompt_callbacks.ompt_callback(ompt_callback_mutex_acquired)( ompt_mutex_nest_lock, (ompt_wait_id_t)(uintptr_t)lck, codeptr); } } else { if (ompt_enabled.ompt_callback_nest_lock) { // lock_next ompt_callbacks.ompt_callback(ompt_callback_nest_lock)( ompt_scope_begin, (ompt_wait_id_t)(uintptr_t)lck, codeptr); } } } #endif #endif // KMP_USE_DYNAMIC_LOCK } void __kmpc_unset_lock(ident_t *loc, kmp_int32 gtid, void **user_lock) { #if KMP_USE_DYNAMIC_LOCK int tag = KMP_EXTRACT_D_TAG(user_lock); #if USE_ITT_BUILD __kmp_itt_lock_releasing((kmp_user_lock_p)user_lock); #endif #if KMP_USE_INLINED_TAS if (tag == locktag_tas && !__kmp_env_consistency_check) { KMP_RELEASE_TAS_LOCK(user_lock, gtid); } else #elif KMP_USE_INLINED_FUTEX if (tag == locktag_futex && !__kmp_env_consistency_check) { KMP_RELEASE_FUTEX_LOCK(user_lock, gtid); } else #endif { __kmp_direct_unset[tag]((kmp_dyna_lock_t *)user_lock, gtid); } #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.ompt_callback_mutex_released) { ompt_callbacks.ompt_callback(ompt_callback_mutex_released)( ompt_mutex_lock, (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } #endif #else // KMP_USE_DYNAMIC_LOCK kmp_user_lock_p lck; /* Can't use serial interval since not block structured */ /* release the lock */ if ((__kmp_user_lock_kind == lk_tas) && (sizeof(lck->tas.lk.poll) <= OMP_LOCK_T_SIZE)) { #if KMP_OS_LINUX && \ (KMP_ARCH_X86 || KMP_ARCH_X86_64 || KMP_ARCH_ARM || KMP_ARCH_AARCH64) // "fast" path implemented to fix customer performance issue #if USE_ITT_BUILD __kmp_itt_lock_releasing((kmp_user_lock_p)user_lock); #endif /* USE_ITT_BUILD */ TCW_4(((kmp_user_lock_p)user_lock)->tas.lk.poll, 0); KMP_MB(); #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.ompt_callback_mutex_released) { ompt_callbacks.ompt_callback(ompt_callback_mutex_released)( ompt_mutex_lock, (ompt_wait_id_t)(uintptr_t)lck, codeptr); } #endif return; #else lck = (kmp_user_lock_p)user_lock; #endif } #if KMP_USE_FUTEX else if ((__kmp_user_lock_kind == lk_futex) && (sizeof(lck->futex.lk.poll) <= OMP_LOCK_T_SIZE)) { lck = (kmp_user_lock_p)user_lock; } #endif else { lck = __kmp_lookup_user_lock(user_lock, "omp_unset_lock"); } #if USE_ITT_BUILD __kmp_itt_lock_releasing(lck); #endif /* USE_ITT_BUILD */ RELEASE_LOCK(lck, gtid); #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.ompt_callback_mutex_released) { ompt_callbacks.ompt_callback(ompt_callback_mutex_released)( ompt_mutex_lock, (ompt_wait_id_t)(uintptr_t)lck, codeptr); } #endif #endif // KMP_USE_DYNAMIC_LOCK } /* release the lock */ void __kmpc_unset_nest_lock(ident_t *loc, kmp_int32 gtid, void **user_lock) { #if KMP_USE_DYNAMIC_LOCK #if USE_ITT_BUILD __kmp_itt_lock_releasing((kmp_user_lock_p)user_lock); #endif int release_status = KMP_D_LOCK_FUNC(user_lock, unset)((kmp_dyna_lock_t *)user_lock, gtid); (void) release_status; #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.enabled) { if (release_status == KMP_LOCK_RELEASED) { if (ompt_enabled.ompt_callback_mutex_released) { // release_lock_last ompt_callbacks.ompt_callback(ompt_callback_mutex_released)( ompt_mutex_nest_lock, (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } } else if (ompt_enabled.ompt_callback_nest_lock) { // release_lock_prev ompt_callbacks.ompt_callback(ompt_callback_nest_lock)( ompt_scope_end, (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } } #endif #else // KMP_USE_DYNAMIC_LOCK kmp_user_lock_p lck; /* Can't use serial interval since not block structured */ if ((__kmp_user_lock_kind == lk_tas) && (sizeof(lck->tas.lk.poll) + sizeof(lck->tas.lk.depth_locked) <= OMP_NEST_LOCK_T_SIZE)) { #if KMP_OS_LINUX && \ (KMP_ARCH_X86 || KMP_ARCH_X86_64 || KMP_ARCH_ARM || KMP_ARCH_AARCH64) // "fast" path implemented to fix customer performance issue kmp_tas_lock_t *tl = (kmp_tas_lock_t *)user_lock; #if USE_ITT_BUILD __kmp_itt_lock_releasing((kmp_user_lock_p)user_lock); #endif /* USE_ITT_BUILD */ #if OMPT_SUPPORT && OMPT_OPTIONAL int release_status = KMP_LOCK_STILL_HELD; #endif if (--(tl->lk.depth_locked) == 0) { TCW_4(tl->lk.poll, 0); #if OMPT_SUPPORT && OMPT_OPTIONAL release_status = KMP_LOCK_RELEASED; #endif } KMP_MB(); #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.enabled) { if (release_status == KMP_LOCK_RELEASED) { if (ompt_enabled.ompt_callback_mutex_released) { // release_lock_last ompt_callbacks.ompt_callback(ompt_callback_mutex_released)( ompt_mutex_nest_lock, (ompt_wait_id_t)(uintptr_t)lck, codeptr); } } else if (ompt_enabled.ompt_callback_nest_lock) { // release_lock_previous ompt_callbacks.ompt_callback(ompt_callback_nest_lock)( ompt_mutex_scope_end, (ompt_wait_id_t)(uintptr_t)lck, codeptr); } } #endif return; #else lck = (kmp_user_lock_p)user_lock; #endif } #if KMP_USE_FUTEX else if ((__kmp_user_lock_kind == lk_futex) && (sizeof(lck->futex.lk.poll) + sizeof(lck->futex.lk.depth_locked) <= OMP_NEST_LOCK_T_SIZE)) { lck = (kmp_user_lock_p)user_lock; } #endif else { lck = __kmp_lookup_user_lock(user_lock, "omp_unset_nest_lock"); } #if USE_ITT_BUILD __kmp_itt_lock_releasing(lck); #endif /* USE_ITT_BUILD */ int release_status; release_status = RELEASE_NESTED_LOCK(lck, gtid); #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.enabled) { if (release_status == KMP_LOCK_RELEASED) { if (ompt_enabled.ompt_callback_mutex_released) { // release_lock_last ompt_callbacks.ompt_callback(ompt_callback_mutex_released)( ompt_mutex_nest_lock, (ompt_wait_id_t)(uintptr_t)lck, codeptr); } } else if (ompt_enabled.ompt_callback_nest_lock) { // release_lock_previous ompt_callbacks.ompt_callback(ompt_callback_nest_lock)( ompt_mutex_scope_end, (ompt_wait_id_t)(uintptr_t)lck, codeptr); } } #endif #endif // KMP_USE_DYNAMIC_LOCK } /* try to acquire the lock */ int __kmpc_test_lock(ident_t *loc, kmp_int32 gtid, void **user_lock) { KMP_COUNT_BLOCK(OMP_test_lock); #if KMP_USE_DYNAMIC_LOCK int rc; int tag = KMP_EXTRACT_D_TAG(user_lock); #if USE_ITT_BUILD __kmp_itt_lock_acquiring((kmp_user_lock_p)user_lock); #endif #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.ompt_callback_mutex_acquire) { ompt_callbacks.ompt_callback(ompt_callback_mutex_acquire)( ompt_mutex_lock, omp_lock_hint_none, __ompt_get_mutex_impl_type(user_lock), (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } #endif #if KMP_USE_INLINED_TAS if (tag == locktag_tas && !__kmp_env_consistency_check) { KMP_TEST_TAS_LOCK(user_lock, gtid, rc); } else #elif KMP_USE_INLINED_FUTEX if (tag == locktag_futex && !__kmp_env_consistency_check) { KMP_TEST_FUTEX_LOCK(user_lock, gtid, rc); } else #endif { rc = __kmp_direct_test[tag]((kmp_dyna_lock_t *)user_lock, gtid); } if (rc) { #if USE_ITT_BUILD __kmp_itt_lock_acquired((kmp_user_lock_p)user_lock); #endif #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.ompt_callback_mutex_acquired) { ompt_callbacks.ompt_callback(ompt_callback_mutex_acquired)( ompt_mutex_lock, (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } #endif return FTN_TRUE; } else { #if USE_ITT_BUILD __kmp_itt_lock_cancelled((kmp_user_lock_p)user_lock); #endif return FTN_FALSE; } #else // KMP_USE_DYNAMIC_LOCK kmp_user_lock_p lck; int rc; if ((__kmp_user_lock_kind == lk_tas) && (sizeof(lck->tas.lk.poll) <= OMP_LOCK_T_SIZE)) { lck = (kmp_user_lock_p)user_lock; } #if KMP_USE_FUTEX else if ((__kmp_user_lock_kind == lk_futex) && (sizeof(lck->futex.lk.poll) <= OMP_LOCK_T_SIZE)) { lck = (kmp_user_lock_p)user_lock; } #endif else { lck = __kmp_lookup_user_lock(user_lock, "omp_test_lock"); } #if USE_ITT_BUILD __kmp_itt_lock_acquiring(lck); #endif /* USE_ITT_BUILD */ #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.ompt_callback_mutex_acquire) { ompt_callbacks.ompt_callback(ompt_callback_mutex_acquire)( ompt_mutex_lock, omp_lock_hint_none, __ompt_get_mutex_impl_type(), (ompt_wait_id_t)(uintptr_t)lck, codeptr); } #endif rc = TEST_LOCK(lck, gtid); #if USE_ITT_BUILD if (rc) { __kmp_itt_lock_acquired(lck); } else { __kmp_itt_lock_cancelled(lck); } #endif /* USE_ITT_BUILD */ #if OMPT_SUPPORT && OMPT_OPTIONAL if (rc && ompt_enabled.ompt_callback_mutex_acquired) { ompt_callbacks.ompt_callback(ompt_callback_mutex_acquired)( ompt_mutex_lock, (ompt_wait_id_t)(uintptr_t)lck, codeptr); } #endif return (rc ? FTN_TRUE : FTN_FALSE); /* Can't use serial interval since not block structured */ #endif // KMP_USE_DYNAMIC_LOCK } /* try to acquire the lock */ int __kmpc_test_nest_lock(ident_t *loc, kmp_int32 gtid, void **user_lock) { #if KMP_USE_DYNAMIC_LOCK int rc; #if USE_ITT_BUILD __kmp_itt_lock_acquiring((kmp_user_lock_p)user_lock); #endif #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.ompt_callback_mutex_acquire) { ompt_callbacks.ompt_callback(ompt_callback_mutex_acquire)( ompt_mutex_nest_lock, omp_lock_hint_none, __ompt_get_mutex_impl_type(user_lock), (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } #endif rc = KMP_D_LOCK_FUNC(user_lock, test)((kmp_dyna_lock_t *)user_lock, gtid); #if USE_ITT_BUILD if (rc) { __kmp_itt_lock_acquired((kmp_user_lock_p)user_lock); } else { __kmp_itt_lock_cancelled((kmp_user_lock_p)user_lock); } #endif #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled && rc) { if (rc == 1) { if (ompt_enabled.ompt_callback_mutex_acquired) { // lock_first ompt_callbacks.ompt_callback(ompt_callback_mutex_acquired)( ompt_mutex_nest_lock, (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } } else { if (ompt_enabled.ompt_callback_nest_lock) { // lock_next ompt_callbacks.ompt_callback(ompt_callback_nest_lock)( ompt_scope_begin, (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } } } #endif return rc; #else // KMP_USE_DYNAMIC_LOCK kmp_user_lock_p lck; int rc; if ((__kmp_user_lock_kind == lk_tas) && (sizeof(lck->tas.lk.poll) + sizeof(lck->tas.lk.depth_locked) <= OMP_NEST_LOCK_T_SIZE)) { lck = (kmp_user_lock_p)user_lock; } #if KMP_USE_FUTEX else if ((__kmp_user_lock_kind == lk_futex) && (sizeof(lck->futex.lk.poll) + sizeof(lck->futex.lk.depth_locked) <= OMP_NEST_LOCK_T_SIZE)) { lck = (kmp_user_lock_p)user_lock; } #endif else { lck = __kmp_lookup_user_lock(user_lock, "omp_test_nest_lock"); } #if USE_ITT_BUILD __kmp_itt_lock_acquiring(lck); #endif /* USE_ITT_BUILD */ #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.enabled) && ompt_enabled.ompt_callback_mutex_acquire) { ompt_callbacks.ompt_callback(ompt_callback_mutex_acquire)( ompt_mutex_nest_lock, omp_lock_hint_none, __ompt_get_mutex_impl_type(), (ompt_wait_id_t)(uintptr_t)lck, codeptr); } #endif rc = TEST_NESTED_LOCK(lck, gtid); #if USE_ITT_BUILD if (rc) { __kmp_itt_lock_acquired(lck); } else { __kmp_itt_lock_cancelled(lck); } #endif /* USE_ITT_BUILD */ #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled && rc) { if (rc == 1) { if (ompt_enabled.ompt_callback_mutex_acquired) { // lock_first ompt_callbacks.ompt_callback(ompt_callback_mutex_acquired)( ompt_mutex_nest_lock, (ompt_wait_id_t)(uintptr_t)lck, codeptr); } } else { if (ompt_enabled.ompt_callback_nest_lock) { // lock_next ompt_callbacks.ompt_callback(ompt_callback_nest_lock)( ompt_mutex_scope_begin, (ompt_wait_id_t)(uintptr_t)lck, codeptr); } } } #endif return rc; /* Can't use serial interval since not block structured */ #endif // KMP_USE_DYNAMIC_LOCK } // Interface to fast scalable reduce methods routines // keep the selected method in a thread local structure for cross-function // usage: will be used in __kmpc_end_reduce* functions; // another solution: to re-determine the method one more time in // __kmpc_end_reduce* functions (new prototype required then) // AT: which solution is better? #define __KMP_SET_REDUCTION_METHOD(gtid, rmethod) \ ((__kmp_threads[(gtid)]->th.th_local.packed_reduction_method) = (rmethod)) #define __KMP_GET_REDUCTION_METHOD(gtid) \ (__kmp_threads[(gtid)]->th.th_local.packed_reduction_method) // description of the packed_reduction_method variable: look at the macros in // kmp.h // used in a critical section reduce block static __forceinline void __kmp_enter_critical_section_reduce_block(ident_t *loc, kmp_int32 global_tid, kmp_critical_name *crit) { // this lock was visible to a customer and to the threading profile tool as a // serial overhead span (although it's used for an internal purpose only) // why was it visible in previous implementation? // should we keep it visible in new reduce block? kmp_user_lock_p lck; #if KMP_USE_DYNAMIC_LOCK kmp_dyna_lock_t *lk = (kmp_dyna_lock_t *)crit; // Check if it is initialized. if (*lk == 0) { if (KMP_IS_D_LOCK(__kmp_user_lock_seq)) { KMP_COMPARE_AND_STORE_ACQ32((volatile kmp_int32 *)crit, 0, KMP_GET_D_TAG(__kmp_user_lock_seq)); } else { __kmp_init_indirect_csptr(crit, loc, global_tid, KMP_GET_I_TAG(__kmp_user_lock_seq)); } } // Branch for accessing the actual lock object and set operation. This // branching is inevitable since this lock initialization does not follow the // normal dispatch path (lock table is not used). if (KMP_EXTRACT_D_TAG(lk) != 0) { lck = (kmp_user_lock_p)lk; KMP_DEBUG_ASSERT(lck != NULL); if (__kmp_env_consistency_check) { __kmp_push_sync(global_tid, ct_critical, loc, lck, __kmp_user_lock_seq); } KMP_D_LOCK_FUNC(lk, set)(lk, global_tid); } else { kmp_indirect_lock_t *ilk = *((kmp_indirect_lock_t **)lk); lck = ilk->lock; KMP_DEBUG_ASSERT(lck != NULL); if (__kmp_env_consistency_check) { __kmp_push_sync(global_tid, ct_critical, loc, lck, __kmp_user_lock_seq); } KMP_I_LOCK_FUNC(ilk, set)(lck, global_tid); } #else // KMP_USE_DYNAMIC_LOCK // We know that the fast reduction code is only emitted by Intel compilers // with 32 byte critical sections. If there isn't enough space, then we // have to use a pointer. if (__kmp_base_user_lock_size <= INTEL_CRITICAL_SIZE) { lck = (kmp_user_lock_p)crit; } else { lck = __kmp_get_critical_section_ptr(crit, loc, global_tid); } KMP_DEBUG_ASSERT(lck != NULL); if (__kmp_env_consistency_check) __kmp_push_sync(global_tid, ct_critical, loc, lck); __kmp_acquire_user_lock_with_checks(lck, global_tid); #endif // KMP_USE_DYNAMIC_LOCK } // used in a critical section reduce block static __forceinline void __kmp_end_critical_section_reduce_block(ident_t *loc, kmp_int32 global_tid, kmp_critical_name *crit) { kmp_user_lock_p lck; #if KMP_USE_DYNAMIC_LOCK if (KMP_IS_D_LOCK(__kmp_user_lock_seq)) { lck = (kmp_user_lock_p)crit; if (__kmp_env_consistency_check) __kmp_pop_sync(global_tid, ct_critical, loc); KMP_D_LOCK_FUNC(lck, unset)((kmp_dyna_lock_t *)lck, global_tid); } else { kmp_indirect_lock_t *ilk = (kmp_indirect_lock_t *)TCR_PTR(*((kmp_indirect_lock_t **)crit)); if (__kmp_env_consistency_check) __kmp_pop_sync(global_tid, ct_critical, loc); KMP_I_LOCK_FUNC(ilk, unset)(ilk->lock, global_tid); } #else // KMP_USE_DYNAMIC_LOCK // We know that the fast reduction code is only emitted by Intel compilers // with 32 byte critical sections. If there isn't enough space, then we have // to use a pointer. if (__kmp_base_user_lock_size > 32) { lck = *((kmp_user_lock_p *)crit); KMP_ASSERT(lck != NULL); } else { lck = (kmp_user_lock_p)crit; } if (__kmp_env_consistency_check) __kmp_pop_sync(global_tid, ct_critical, loc); __kmp_release_user_lock_with_checks(lck, global_tid); #endif // KMP_USE_DYNAMIC_LOCK } // __kmp_end_critical_section_reduce_block static __forceinline int __kmp_swap_teams_for_teams_reduction(kmp_info_t *th, kmp_team_t **team_p, int *task_state) { kmp_team_t *team; // Check if we are inside the teams construct? if (th->th.th_teams_microtask) { *team_p = team = th->th.th_team; if (team->t.t_level == th->th.th_teams_level) { // This is reduction at teams construct. KMP_DEBUG_ASSERT(!th->th.th_info.ds.ds_tid); // AC: check that tid == 0 // Let's swap teams temporarily for the reduction. th->th.th_info.ds.ds_tid = team->t.t_master_tid; th->th.th_team = team->t.t_parent; th->th.th_team_nproc = th->th.th_team->t.t_nproc; th->th.th_task_team = th->th.th_team->t.t_task_team[0]; *task_state = th->th.th_task_state; th->th.th_task_state = 0; return 1; } } return 0; } static __forceinline void __kmp_restore_swapped_teams(kmp_info_t *th, kmp_team_t *team, int task_state) { // Restore thread structure swapped in __kmp_swap_teams_for_teams_reduction. th->th.th_info.ds.ds_tid = 0; th->th.th_team = team; th->th.th_team_nproc = team->t.t_nproc; th->th.th_task_team = team->t.t_task_team[task_state]; th->th.th_task_state = task_state; } /* 2.a.i. Reduce Block without a terminating barrier */ /*! @ingroup SYNCHRONIZATION @param loc source location information @param global_tid global thread number @param num_vars number of items (variables) to be reduced @param reduce_size size of data in bytes to be reduced @param reduce_data pointer to data to be reduced @param reduce_func callback function providing reduction operation on two operands and returning result of reduction in lhs_data @param lck pointer to the unique lock data structure @result 1 for the master thread, 0 for all other team threads, 2 for all team threads if atomic reduction needed The nowait version is used for a reduce clause with the nowait argument. */ kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32 global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck) { KMP_COUNT_BLOCK(REDUCE_nowait); int retval = 0; PACKED_REDUCTION_METHOD_T packed_reduction_method; kmp_info_t *th; kmp_team_t *team; int teams_swapped = 0, task_state; KA_TRACE(10, ("__kmpc_reduce_nowait() enter: called T#%d\n", global_tid)); // why do we need this initialization here at all? // Reduction clause can not be used as a stand-alone directive. // do not call __kmp_serial_initialize(), it will be called by // __kmp_parallel_initialize() if needed // possible detection of false-positive race by the threadchecker ??? if (!TCR_4(__kmp_init_parallel)) __kmp_parallel_initialize(); __kmp_resume_if_soft_paused(); // check correctness of reduce block nesting #if KMP_USE_DYNAMIC_LOCK if (__kmp_env_consistency_check) __kmp_push_sync(global_tid, ct_reduce, loc, NULL, 0); #else if (__kmp_env_consistency_check) __kmp_push_sync(global_tid, ct_reduce, loc, NULL); #endif th = __kmp_thread_from_gtid(global_tid); teams_swapped = __kmp_swap_teams_for_teams_reduction(th, &team, &task_state); // packed_reduction_method value will be reused by __kmp_end_reduce* function, // the value should be kept in a variable // the variable should be either a construct-specific or thread-specific // property, not a team specific property // (a thread can reach the next reduce block on the next construct, reduce // method may differ on the next construct) // an ident_t "loc" parameter could be used as a construct-specific property // (what if loc == 0?) // (if both construct-specific and team-specific variables were shared, // then unness extra syncs should be needed) // a thread-specific variable is better regarding two issues above (next // construct and extra syncs) // a thread-specific "th_local.reduction_method" variable is used currently // each thread executes 'determine' and 'set' lines (no need to execute by one // thread, to avoid unness extra syncs) packed_reduction_method = __kmp_determine_reduction_method( loc, global_tid, num_vars, reduce_size, reduce_data, reduce_func, lck); __KMP_SET_REDUCTION_METHOD(global_tid, packed_reduction_method); OMPT_REDUCTION_DECL(th, global_tid); if (packed_reduction_method == critical_reduce_block) { OMPT_REDUCTION_BEGIN; __kmp_enter_critical_section_reduce_block(loc, global_tid, lck); retval = 1; } else if (packed_reduction_method == empty_reduce_block) { OMPT_REDUCTION_BEGIN; // usage: if team size == 1, no synchronization is required ( Intel // platforms only ) retval = 1; } else if (packed_reduction_method == atomic_reduce_block) { retval = 2; // all threads should do this pop here (because __kmpc_end_reduce_nowait() // won't be called by the code gen) // (it's not quite good, because the checking block has been closed by // this 'pop', // but atomic operation has not been executed yet, will be executed // slightly later, literally on next instruction) if (__kmp_env_consistency_check) __kmp_pop_sync(global_tid, ct_reduce, loc); } else if (TEST_REDUCTION_METHOD(packed_reduction_method, tree_reduce_block)) { // AT: performance issue: a real barrier here // AT: (if master goes slow, other threads are blocked here waiting for the // master to come and release them) // AT: (it's not what a customer might expect specifying NOWAIT clause) // AT: (specifying NOWAIT won't result in improvement of performance, it'll // be confusing to a customer) // AT: another implementation of *barrier_gather*nowait() (or some other design) // might go faster and be more in line with sense of NOWAIT // AT: TO DO: do epcc test and compare times // this barrier should be invisible to a customer and to the threading profile // tool (it's neither a terminating barrier nor customer's code, it's // used for an internal purpose) #if OMPT_SUPPORT // JP: can this barrier potentially leed to task scheduling? // JP: as long as there is a barrier in the implementation, OMPT should and // will provide the barrier events // so we set-up the necessary frame/return addresses. ompt_frame_t *ompt_frame; if (ompt_enabled.enabled) { __ompt_get_task_info_internal(0, NULL, NULL, &ompt_frame, NULL, NULL); if (ompt_frame->enter_frame.ptr == NULL) ompt_frame->enter_frame.ptr = OMPT_GET_FRAME_ADDRESS(0); OMPT_STORE_RETURN_ADDRESS(global_tid); } #endif #if USE_ITT_NOTIFY __kmp_threads[global_tid]->th.th_ident = loc; #endif retval = __kmp_barrier(UNPACK_REDUCTION_BARRIER(packed_reduction_method), global_tid, FALSE, reduce_size, reduce_data, reduce_func); retval = (retval != 0) ? (0) : (1); #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled) { ompt_frame->enter_frame = ompt_data_none; } #endif // all other workers except master should do this pop here // ( none of other workers will get to __kmpc_end_reduce_nowait() ) if (__kmp_env_consistency_check) { if (retval == 0) { __kmp_pop_sync(global_tid, ct_reduce, loc); } } } else { // should never reach this block KMP_ASSERT(0); // "unexpected method" } if (teams_swapped) { __kmp_restore_swapped_teams(th, team, task_state); } KA_TRACE( 10, ("__kmpc_reduce_nowait() exit: called T#%d: method %08x, returns %08x\n", global_tid, packed_reduction_method, retval)); return retval; } /*! @ingroup SYNCHRONIZATION @param loc source location information @param global_tid global thread id. @param lck pointer to the unique lock data structure Finish the execution of a reduce nowait. */ void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid, kmp_critical_name *lck) { PACKED_REDUCTION_METHOD_T packed_reduction_method; KA_TRACE(10, ("__kmpc_end_reduce_nowait() enter: called T#%d\n", global_tid)); packed_reduction_method = __KMP_GET_REDUCTION_METHOD(global_tid); OMPT_REDUCTION_DECL(__kmp_thread_from_gtid(global_tid), global_tid); if (packed_reduction_method == critical_reduce_block) { __kmp_end_critical_section_reduce_block(loc, global_tid, lck); OMPT_REDUCTION_END; } else if (packed_reduction_method == empty_reduce_block) { // usage: if team size == 1, no synchronization is required ( on Intel // platforms only ) OMPT_REDUCTION_END; } else if (packed_reduction_method == atomic_reduce_block) { // neither master nor other workers should get here // (code gen does not generate this call in case 2: atomic reduce block) // actually it's better to remove this elseif at all; // after removal this value will checked by the 'else' and will assert } else if (TEST_REDUCTION_METHOD(packed_reduction_method, tree_reduce_block)) { // only master gets here // OMPT: tree reduction is annotated in the barrier code } else { // should never reach this block KMP_ASSERT(0); // "unexpected method" } if (__kmp_env_consistency_check) __kmp_pop_sync(global_tid, ct_reduce, loc); KA_TRACE(10, ("__kmpc_end_reduce_nowait() exit: called T#%d: method %08x\n", global_tid, packed_reduction_method)); return; } /* 2.a.ii. Reduce Block with a terminating barrier */ /*! @ingroup SYNCHRONIZATION @param loc source location information @param global_tid global thread number @param num_vars number of items (variables) to be reduced @param reduce_size size of data in bytes to be reduced @param reduce_data pointer to data to be reduced @param reduce_func callback function providing reduction operation on two operands and returning result of reduction in lhs_data @param lck pointer to the unique lock data structure @result 1 for the master thread, 0 for all other team threads, 2 for all team threads if atomic reduction needed A blocking reduce that includes an implicit barrier. */ kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck) { KMP_COUNT_BLOCK(REDUCE_wait); int retval = 0; PACKED_REDUCTION_METHOD_T packed_reduction_method; kmp_info_t *th; kmp_team_t *team; int teams_swapped = 0, task_state; KA_TRACE(10, ("__kmpc_reduce() enter: called T#%d\n", global_tid)); // why do we need this initialization here at all? // Reduction clause can not be a stand-alone directive. // do not call __kmp_serial_initialize(), it will be called by // __kmp_parallel_initialize() if needed // possible detection of false-positive race by the threadchecker ??? if (!TCR_4(__kmp_init_parallel)) __kmp_parallel_initialize(); __kmp_resume_if_soft_paused(); // check correctness of reduce block nesting #if KMP_USE_DYNAMIC_LOCK if (__kmp_env_consistency_check) __kmp_push_sync(global_tid, ct_reduce, loc, NULL, 0); #else if (__kmp_env_consistency_check) __kmp_push_sync(global_tid, ct_reduce, loc, NULL); #endif th = __kmp_thread_from_gtid(global_tid); teams_swapped = __kmp_swap_teams_for_teams_reduction(th, &team, &task_state); packed_reduction_method = __kmp_determine_reduction_method( loc, global_tid, num_vars, reduce_size, reduce_data, reduce_func, lck); __KMP_SET_REDUCTION_METHOD(global_tid, packed_reduction_method); OMPT_REDUCTION_DECL(th, global_tid); if (packed_reduction_method == critical_reduce_block) { OMPT_REDUCTION_BEGIN; __kmp_enter_critical_section_reduce_block(loc, global_tid, lck); retval = 1; } else if (packed_reduction_method == empty_reduce_block) { OMPT_REDUCTION_BEGIN; // usage: if team size == 1, no synchronization is required ( Intel // platforms only ) retval = 1; } else if (packed_reduction_method == atomic_reduce_block) { retval = 2; } else if (TEST_REDUCTION_METHOD(packed_reduction_method, tree_reduce_block)) { // case tree_reduce_block: // this barrier should be visible to a customer and to the threading profile // tool (it's a terminating barrier on constructs if NOWAIT not specified) #if OMPT_SUPPORT ompt_frame_t *ompt_frame; if (ompt_enabled.enabled) { __ompt_get_task_info_internal(0, NULL, NULL, &ompt_frame, NULL, NULL); if (ompt_frame->enter_frame.ptr == NULL) ompt_frame->enter_frame.ptr = OMPT_GET_FRAME_ADDRESS(0); OMPT_STORE_RETURN_ADDRESS(global_tid); } #endif #if USE_ITT_NOTIFY __kmp_threads[global_tid]->th.th_ident = loc; // needed for correct notification of frames #endif retval = __kmp_barrier(UNPACK_REDUCTION_BARRIER(packed_reduction_method), global_tid, TRUE, reduce_size, reduce_data, reduce_func); retval = (retval != 0) ? (0) : (1); #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled) { ompt_frame->enter_frame = ompt_data_none; } #endif // all other workers except master should do this pop here // ( none of other workers except master will enter __kmpc_end_reduce() ) if (__kmp_env_consistency_check) { if (retval == 0) { // 0: all other workers; 1: master __kmp_pop_sync(global_tid, ct_reduce, loc); } } } else { // should never reach this block KMP_ASSERT(0); // "unexpected method" } if (teams_swapped) { __kmp_restore_swapped_teams(th, team, task_state); } KA_TRACE(10, ("__kmpc_reduce() exit: called T#%d: method %08x, returns %08x\n", global_tid, packed_reduction_method, retval)); return retval; } /*! @ingroup SYNCHRONIZATION @param loc source location information @param global_tid global thread id. @param lck pointer to the unique lock data structure Finish the execution of a blocking reduce. The lck pointer must be the same as that used in the corresponding start function. */ void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid, kmp_critical_name *lck) { PACKED_REDUCTION_METHOD_T packed_reduction_method; kmp_info_t *th; kmp_team_t *team; int teams_swapped = 0, task_state; KA_TRACE(10, ("__kmpc_end_reduce() enter: called T#%d\n", global_tid)); th = __kmp_thread_from_gtid(global_tid); teams_swapped = __kmp_swap_teams_for_teams_reduction(th, &team, &task_state); packed_reduction_method = __KMP_GET_REDUCTION_METHOD(global_tid); // this barrier should be visible to a customer and to the threading profile // tool (it's a terminating barrier on constructs if NOWAIT not specified) OMPT_REDUCTION_DECL(th, global_tid); if (packed_reduction_method == critical_reduce_block) { __kmp_end_critical_section_reduce_block(loc, global_tid, lck); OMPT_REDUCTION_END; // TODO: implicit barrier: should be exposed #if OMPT_SUPPORT ompt_frame_t *ompt_frame; if (ompt_enabled.enabled) { __ompt_get_task_info_internal(0, NULL, NULL, &ompt_frame, NULL, NULL); if (ompt_frame->enter_frame.ptr == NULL) ompt_frame->enter_frame.ptr = OMPT_GET_FRAME_ADDRESS(0); OMPT_STORE_RETURN_ADDRESS(global_tid); } #endif #if USE_ITT_NOTIFY __kmp_threads[global_tid]->th.th_ident = loc; #endif __kmp_barrier(bs_plain_barrier, global_tid, FALSE, 0, NULL, NULL); #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled) { ompt_frame->enter_frame = ompt_data_none; } #endif } else if (packed_reduction_method == empty_reduce_block) { OMPT_REDUCTION_END; // usage: if team size==1, no synchronization is required (Intel platforms only) // TODO: implicit barrier: should be exposed #if OMPT_SUPPORT ompt_frame_t *ompt_frame; if (ompt_enabled.enabled) { __ompt_get_task_info_internal(0, NULL, NULL, &ompt_frame, NULL, NULL); if (ompt_frame->enter_frame.ptr == NULL) ompt_frame->enter_frame.ptr = OMPT_GET_FRAME_ADDRESS(0); OMPT_STORE_RETURN_ADDRESS(global_tid); } #endif #if USE_ITT_NOTIFY __kmp_threads[global_tid]->th.th_ident = loc; #endif __kmp_barrier(bs_plain_barrier, global_tid, FALSE, 0, NULL, NULL); #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled) { ompt_frame->enter_frame = ompt_data_none; } #endif } else if (packed_reduction_method == atomic_reduce_block) { #if OMPT_SUPPORT ompt_frame_t *ompt_frame; if (ompt_enabled.enabled) { __ompt_get_task_info_internal(0, NULL, NULL, &ompt_frame, NULL, NULL); if (ompt_frame->enter_frame.ptr == NULL) ompt_frame->enter_frame.ptr = OMPT_GET_FRAME_ADDRESS(0); OMPT_STORE_RETURN_ADDRESS(global_tid); } #endif // TODO: implicit barrier: should be exposed #if USE_ITT_NOTIFY __kmp_threads[global_tid]->th.th_ident = loc; #endif __kmp_barrier(bs_plain_barrier, global_tid, FALSE, 0, NULL, NULL); #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled) { ompt_frame->enter_frame = ompt_data_none; } #endif } else if (TEST_REDUCTION_METHOD(packed_reduction_method, tree_reduce_block)) { // only master executes here (master releases all other workers) __kmp_end_split_barrier(UNPACK_REDUCTION_BARRIER(packed_reduction_method), global_tid); } else { // should never reach this block KMP_ASSERT(0); // "unexpected method" } if (teams_swapped) { __kmp_restore_swapped_teams(th, team, task_state); } if (__kmp_env_consistency_check) __kmp_pop_sync(global_tid, ct_reduce, loc); KA_TRACE(10, ("__kmpc_end_reduce() exit: called T#%d: method %08x\n", global_tid, packed_reduction_method)); return; } #undef __KMP_GET_REDUCTION_METHOD #undef __KMP_SET_REDUCTION_METHOD /* end of interface to fast scalable reduce routines */ kmp_uint64 __kmpc_get_taskid() { kmp_int32 gtid; kmp_info_t *thread; gtid = __kmp_get_gtid(); if (gtid < 0) { return 0; } thread = __kmp_thread_from_gtid(gtid); return thread->th.th_current_task->td_task_id; } // __kmpc_get_taskid kmp_uint64 __kmpc_get_parent_taskid() { kmp_int32 gtid; kmp_info_t *thread; kmp_taskdata_t *parent_task; gtid = __kmp_get_gtid(); if (gtid < 0) { return 0; } thread = __kmp_thread_from_gtid(gtid); parent_task = thread->th.th_current_task->td_parent; return (parent_task == NULL ? 0 : parent_task->td_task_id); } // __kmpc_get_parent_taskid /*! @ingroup WORK_SHARING @param loc source location information. @param gtid global thread number. @param num_dims number of associated doacross loops. @param dims info on loops bounds. Initialize doacross loop information. Expect compiler send us inclusive bounds, e.g. for(i=2;i<9;i+=2) lo=2, up=8, st=2. */ void __kmpc_doacross_init(ident_t *loc, int gtid, int num_dims, const struct kmp_dim *dims) { int j, idx; kmp_int64 last, trace_count; kmp_info_t *th = __kmp_threads[gtid]; kmp_team_t *team = th->th.th_team; kmp_uint32 *flags; kmp_disp_t *pr_buf = th->th.th_dispatch; dispatch_shared_info_t *sh_buf; KA_TRACE( 20, ("__kmpc_doacross_init() enter: called T#%d, num dims %d, active %d\n", gtid, num_dims, !team->t.t_serialized)); KMP_DEBUG_ASSERT(dims != NULL); KMP_DEBUG_ASSERT(num_dims > 0); if (team->t.t_serialized) { KA_TRACE(20, ("__kmpc_doacross_init() exit: serialized team\n")); return; // no dependencies if team is serialized } KMP_DEBUG_ASSERT(team->t.t_nproc > 1); idx = pr_buf->th_doacross_buf_idx++; // Increment index of shared buffer for // the next loop sh_buf = &team->t.t_disp_buffer[idx % __kmp_dispatch_num_buffers]; // Save bounds info into allocated private buffer KMP_DEBUG_ASSERT(pr_buf->th_doacross_info == NULL); pr_buf->th_doacross_info = (kmp_int64 *)__kmp_thread_malloc( th, sizeof(kmp_int64) * (4 * num_dims + 1)); KMP_DEBUG_ASSERT(pr_buf->th_doacross_info != NULL); pr_buf->th_doacross_info[0] = (kmp_int64)num_dims; // first element is number of dimensions // Save also address of num_done in order to access it later without knowing // the buffer index pr_buf->th_doacross_info[1] = (kmp_int64)&sh_buf->doacross_num_done; pr_buf->th_doacross_info[2] = dims[0].lo; pr_buf->th_doacross_info[3] = dims[0].up; pr_buf->th_doacross_info[4] = dims[0].st; last = 5; for (j = 1; j < num_dims; ++j) { kmp_int64 range_length; // To keep ranges of all dimensions but the first dims[0] if (dims[j].st == 1) { // most common case // AC: should we care of ranges bigger than LLONG_MAX? (not for now) range_length = dims[j].up - dims[j].lo + 1; } else { if (dims[j].st > 0) { KMP_DEBUG_ASSERT(dims[j].up > dims[j].lo); range_length = (kmp_uint64)(dims[j].up - dims[j].lo) / dims[j].st + 1; } else { // negative increment KMP_DEBUG_ASSERT(dims[j].lo > dims[j].up); range_length = (kmp_uint64)(dims[j].lo - dims[j].up) / (-dims[j].st) + 1; } } pr_buf->th_doacross_info[last++] = range_length; pr_buf->th_doacross_info[last++] = dims[j].lo; pr_buf->th_doacross_info[last++] = dims[j].up; pr_buf->th_doacross_info[last++] = dims[j].st; } // Compute total trip count. // Start with range of dims[0] which we don't need to keep in the buffer. if (dims[0].st == 1) { // most common case trace_count = dims[0].up - dims[0].lo + 1; } else if (dims[0].st > 0) { KMP_DEBUG_ASSERT(dims[0].up > dims[0].lo); trace_count = (kmp_uint64)(dims[0].up - dims[0].lo) / dims[0].st + 1; } else { // negative increment KMP_DEBUG_ASSERT(dims[0].lo > dims[0].up); trace_count = (kmp_uint64)(dims[0].lo - dims[0].up) / (-dims[0].st) + 1; } for (j = 1; j < num_dims; ++j) { trace_count *= pr_buf->th_doacross_info[4 * j + 1]; // use kept ranges } KMP_DEBUG_ASSERT(trace_count > 0); // Check if shared buffer is not occupied by other loop (idx - // __kmp_dispatch_num_buffers) if (idx != sh_buf->doacross_buf_idx) { // Shared buffer is occupied, wait for it to be free __kmp_wait_4((volatile kmp_uint32 *)&sh_buf->doacross_buf_idx, idx, __kmp_eq_4, NULL); } #if KMP_32_BIT_ARCH // Check if we are the first thread. After the CAS the first thread gets 0, // others get 1 if initialization is in progress, allocated pointer otherwise. // Treat pointer as volatile integer (value 0 or 1) until memory is allocated. flags = (kmp_uint32 *)KMP_COMPARE_AND_STORE_RET32( (volatile kmp_int32 *)&sh_buf->doacross_flags, NULL, 1); #else flags = (kmp_uint32 *)KMP_COMPARE_AND_STORE_RET64( (volatile kmp_int64 *)&sh_buf->doacross_flags, NULL, 1LL); #endif if (flags == NULL) { // we are the first thread, allocate the array of flags size_t size = trace_count / 8 + 8; // in bytes, use single bit per iteration flags = (kmp_uint32 *)__kmp_thread_calloc(th, size, 1); KMP_MB(); sh_buf->doacross_flags = flags; } else if (flags == (kmp_uint32 *)1) { #if KMP_32_BIT_ARCH // initialization is still in progress, need to wait while (*(volatile kmp_int32 *)&sh_buf->doacross_flags == 1) #else while (*(volatile kmp_int64 *)&sh_buf->doacross_flags == 1LL) #endif KMP_YIELD(TRUE); KMP_MB(); } else { KMP_MB(); } KMP_DEBUG_ASSERT(sh_buf->doacross_flags > (kmp_uint32 *)1); // check ptr value pr_buf->th_doacross_flags = sh_buf->doacross_flags; // save private copy in order to not // touch shared buffer on each iteration KA_TRACE(20, ("__kmpc_doacross_init() exit: T#%d\n", gtid)); } void __kmpc_doacross_wait(ident_t *loc, int gtid, const kmp_int64 *vec) { kmp_int32 shft, num_dims, i; kmp_uint32 flag; kmp_int64 iter_number; // iteration number of "collapsed" loop nest kmp_info_t *th = __kmp_threads[gtid]; kmp_team_t *team = th->th.th_team; kmp_disp_t *pr_buf; kmp_int64 lo, up, st; KA_TRACE(20, ("__kmpc_doacross_wait() enter: called T#%d\n", gtid)); if (team->t.t_serialized) { KA_TRACE(20, ("__kmpc_doacross_wait() exit: serialized team\n")); return; // no dependencies if team is serialized } // calculate sequential iteration number and check out-of-bounds condition pr_buf = th->th.th_dispatch; KMP_DEBUG_ASSERT(pr_buf->th_doacross_info != NULL); num_dims = pr_buf->th_doacross_info[0]; lo = pr_buf->th_doacross_info[2]; up = pr_buf->th_doacross_info[3]; st = pr_buf->th_doacross_info[4]; #if OMPT_SUPPORT && OMPT_OPTIONAL ompt_dependence_t deps[num_dims]; #endif if (st == 1) { // most common case if (vec[0] < lo || vec[0] > up) { KA_TRACE(20, ("__kmpc_doacross_wait() exit: T#%d iter %lld is out of " "bounds [%lld,%lld]\n", gtid, vec[0], lo, up)); return; } iter_number = vec[0] - lo; } else if (st > 0) { if (vec[0] < lo || vec[0] > up) { KA_TRACE(20, ("__kmpc_doacross_wait() exit: T#%d iter %lld is out of " "bounds [%lld,%lld]\n", gtid, vec[0], lo, up)); return; } iter_number = (kmp_uint64)(vec[0] - lo) / st; } else { // negative increment if (vec[0] > lo || vec[0] < up) { KA_TRACE(20, ("__kmpc_doacross_wait() exit: T#%d iter %lld is out of " "bounds [%lld,%lld]\n", gtid, vec[0], lo, up)); return; } iter_number = (kmp_uint64)(lo - vec[0]) / (-st); } #if OMPT_SUPPORT && OMPT_OPTIONAL deps[0].variable.value = iter_number; deps[0].dependence_type = ompt_dependence_type_sink; #endif for (i = 1; i < num_dims; ++i) { kmp_int64 iter, ln; kmp_int32 j = i * 4; ln = pr_buf->th_doacross_info[j + 1]; lo = pr_buf->th_doacross_info[j + 2]; up = pr_buf->th_doacross_info[j + 3]; st = pr_buf->th_doacross_info[j + 4]; if (st == 1) { if (vec[i] < lo || vec[i] > up) { KA_TRACE(20, ("__kmpc_doacross_wait() exit: T#%d iter %lld is out of " "bounds [%lld,%lld]\n", gtid, vec[i], lo, up)); return; } iter = vec[i] - lo; } else if (st > 0) { if (vec[i] < lo || vec[i] > up) { KA_TRACE(20, ("__kmpc_doacross_wait() exit: T#%d iter %lld is out of " "bounds [%lld,%lld]\n", gtid, vec[i], lo, up)); return; } iter = (kmp_uint64)(vec[i] - lo) / st; } else { // st < 0 if (vec[i] > lo || vec[i] < up) { KA_TRACE(20, ("__kmpc_doacross_wait() exit: T#%d iter %lld is out of " "bounds [%lld,%lld]\n", gtid, vec[i], lo, up)); return; } iter = (kmp_uint64)(lo - vec[i]) / (-st); } iter_number = iter + ln * iter_number; #if OMPT_SUPPORT && OMPT_OPTIONAL deps[i].variable.value = iter; deps[i].dependence_type = ompt_dependence_type_sink; #endif } shft = iter_number % 32; // use 32-bit granularity iter_number >>= 5; // divided by 32 flag = 1 << shft; while ((flag & pr_buf->th_doacross_flags[iter_number]) == 0) { KMP_YIELD(TRUE); } KMP_MB(); #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.ompt_callback_dependences) { ompt_callbacks.ompt_callback(ompt_callback_dependences)( &(OMPT_CUR_TASK_INFO(th)->task_data), deps, num_dims); } #endif KA_TRACE(20, ("__kmpc_doacross_wait() exit: T#%d wait for iter %lld completed\n", gtid, (iter_number << 5) + shft)); } void __kmpc_doacross_post(ident_t *loc, int gtid, const kmp_int64 *vec) { kmp_int32 shft, num_dims, i; kmp_uint32 flag; kmp_int64 iter_number; // iteration number of "collapsed" loop nest kmp_info_t *th = __kmp_threads[gtid]; kmp_team_t *team = th->th.th_team; kmp_disp_t *pr_buf; kmp_int64 lo, st; KA_TRACE(20, ("__kmpc_doacross_post() enter: called T#%d\n", gtid)); if (team->t.t_serialized) { KA_TRACE(20, ("__kmpc_doacross_post() exit: serialized team\n")); return; // no dependencies if team is serialized } // calculate sequential iteration number (same as in "wait" but no // out-of-bounds checks) pr_buf = th->th.th_dispatch; KMP_DEBUG_ASSERT(pr_buf->th_doacross_info != NULL); num_dims = pr_buf->th_doacross_info[0]; lo = pr_buf->th_doacross_info[2]; st = pr_buf->th_doacross_info[4]; #if OMPT_SUPPORT && OMPT_OPTIONAL ompt_dependence_t deps[num_dims]; #endif if (st == 1) { // most common case iter_number = vec[0] - lo; } else if (st > 0) { iter_number = (kmp_uint64)(vec[0] - lo) / st; } else { // negative increment iter_number = (kmp_uint64)(lo - vec[0]) / (-st); } #if OMPT_SUPPORT && OMPT_OPTIONAL deps[0].variable.value = iter_number; deps[0].dependence_type = ompt_dependence_type_source; #endif for (i = 1; i < num_dims; ++i) { kmp_int64 iter, ln; kmp_int32 j = i * 4; ln = pr_buf->th_doacross_info[j + 1]; lo = pr_buf->th_doacross_info[j + 2]; st = pr_buf->th_doacross_info[j + 4]; if (st == 1) { iter = vec[i] - lo; } else if (st > 0) { iter = (kmp_uint64)(vec[i] - lo) / st; } else { // st < 0 iter = (kmp_uint64)(lo - vec[i]) / (-st); } iter_number = iter + ln * iter_number; #if OMPT_SUPPORT && OMPT_OPTIONAL deps[i].variable.value = iter; deps[i].dependence_type = ompt_dependence_type_source; #endif } #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.ompt_callback_dependences) { ompt_callbacks.ompt_callback(ompt_callback_dependences)( &(OMPT_CUR_TASK_INFO(th)->task_data), deps, num_dims); } #endif shft = iter_number % 32; // use 32-bit granularity iter_number >>= 5; // divided by 32 flag = 1 << shft; KMP_MB(); if ((flag & pr_buf->th_doacross_flags[iter_number]) == 0) KMP_TEST_THEN_OR32(&pr_buf->th_doacross_flags[iter_number], flag); KA_TRACE(20, ("__kmpc_doacross_post() exit: T#%d iter %lld posted\n", gtid, (iter_number << 5) + shft)); } void __kmpc_doacross_fini(ident_t *loc, int gtid) { kmp_int32 num_done; kmp_info_t *th = __kmp_threads[gtid]; kmp_team_t *team = th->th.th_team; kmp_disp_t *pr_buf = th->th.th_dispatch; KA_TRACE(20, ("__kmpc_doacross_fini() enter: called T#%d\n", gtid)); if (team->t.t_serialized) { KA_TRACE(20, ("__kmpc_doacross_fini() exit: serialized team %p\n", team)); return; // nothing to do } num_done = KMP_TEST_THEN_INC32((kmp_int32 *)pr_buf->th_doacross_info[1]) + 1; if (num_done == th->th.th_team_nproc) { // we are the last thread, need to free shared resources int idx = pr_buf->th_doacross_buf_idx - 1; dispatch_shared_info_t *sh_buf = &team->t.t_disp_buffer[idx % __kmp_dispatch_num_buffers]; KMP_DEBUG_ASSERT(pr_buf->th_doacross_info[1] == (kmp_int64)&sh_buf->doacross_num_done); KMP_DEBUG_ASSERT(num_done == sh_buf->doacross_num_done); KMP_DEBUG_ASSERT(idx == sh_buf->doacross_buf_idx); __kmp_thread_free(th, CCAST(kmp_uint32 *, sh_buf->doacross_flags)); sh_buf->doacross_flags = NULL; sh_buf->doacross_num_done = 0; sh_buf->doacross_buf_idx += __kmp_dispatch_num_buffers; // free buffer for future re-use } // free private resources (need to keep buffer index forever) pr_buf->th_doacross_flags = NULL; __kmp_thread_free(th, (void *)pr_buf->th_doacross_info); pr_buf->th_doacross_info = NULL; KA_TRACE(20, ("__kmpc_doacross_fini() exit: T#%d\n", gtid)); } /* omp_alloc/omp_free only defined for C/C++, not for Fortran */ void *omp_alloc(size_t size, omp_allocator_handle_t allocator) { return __kmpc_alloc(__kmp_entry_gtid(), size, allocator); } void omp_free(void *ptr, omp_allocator_handle_t allocator) { __kmpc_free(__kmp_entry_gtid(), ptr, allocator); } int __kmpc_get_target_offload(void) { if (!__kmp_init_serial) { __kmp_serial_initialize(); } return __kmp_target_offload; } int __kmpc_pause_resource(kmp_pause_status_t level) { if (!__kmp_init_serial) { return 1; // Can't pause if runtime is not initialized } return __kmp_pause_resource(level); } Index: head/contrib/llvm-project/openmp/runtime/src/kmp_gsupport.cpp =================================================================== --- head/contrib/llvm-project/openmp/runtime/src/kmp_gsupport.cpp (revision 364731) +++ head/contrib/llvm-project/openmp/runtime/src/kmp_gsupport.cpp (revision 364732) @@ -1,2041 +1,2035 @@ /* * kmp_gsupport.cpp */ //===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "kmp.h" #include "kmp_atomic.h" #if OMPT_SUPPORT #include "ompt-specific.h" #endif #ifdef __cplusplus extern "C" { #endif // __cplusplus #define MKLOC(loc, routine) \ static ident_t loc = {0, KMP_IDENT_KMPC, 0, 0, ";unknown;unknown;0;0;;"}; #include "kmp_ftn_os.h" void KMP_EXPAND_NAME(KMP_API_NAME_GOMP_BARRIER)(void) { int gtid = __kmp_entry_gtid(); MKLOC(loc, "GOMP_barrier"); KA_TRACE(20, ("GOMP_barrier: T#%d\n", gtid)); #if OMPT_SUPPORT && OMPT_OPTIONAL ompt_frame_t *ompt_frame; if (ompt_enabled.enabled) { __ompt_get_task_info_internal(0, NULL, NULL, &ompt_frame, NULL, NULL); ompt_frame->enter_frame.ptr = OMPT_GET_FRAME_ADDRESS(0); OMPT_STORE_RETURN_ADDRESS(gtid); } #endif __kmpc_barrier(&loc, gtid); #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled) { ompt_frame->enter_frame = ompt_data_none; } #endif } // Mutual exclusion // The symbol that icc/ifort generates for unnamed for unnamed critical sections // - .gomp_critical_user_ - is defined using .comm in any objects reference it. // We can't reference it directly here in C code, as the symbol contains a ".". // // The RTL contains an assembly language definition of .gomp_critical_user_ // with another symbol __kmp_unnamed_critical_addr initialized with it's // address. extern kmp_critical_name *__kmp_unnamed_critical_addr; void KMP_EXPAND_NAME(KMP_API_NAME_GOMP_CRITICAL_START)(void) { int gtid = __kmp_entry_gtid(); MKLOC(loc, "GOMP_critical_start"); KA_TRACE(20, ("GOMP_critical_start: T#%d\n", gtid)); #if OMPT_SUPPORT && OMPT_OPTIONAL OMPT_STORE_RETURN_ADDRESS(gtid); #endif __kmpc_critical(&loc, gtid, __kmp_unnamed_critical_addr); } void KMP_EXPAND_NAME(KMP_API_NAME_GOMP_CRITICAL_END)(void) { int gtid = __kmp_get_gtid(); MKLOC(loc, "GOMP_critical_end"); KA_TRACE(20, ("GOMP_critical_end: T#%d\n", gtid)); #if OMPT_SUPPORT && OMPT_OPTIONAL OMPT_STORE_RETURN_ADDRESS(gtid); #endif __kmpc_end_critical(&loc, gtid, __kmp_unnamed_critical_addr); } void KMP_EXPAND_NAME(KMP_API_NAME_GOMP_CRITICAL_NAME_START)(void **pptr) { int gtid = __kmp_entry_gtid(); MKLOC(loc, "GOMP_critical_name_start"); KA_TRACE(20, ("GOMP_critical_name_start: T#%d\n", gtid)); __kmpc_critical(&loc, gtid, (kmp_critical_name *)pptr); } void KMP_EXPAND_NAME(KMP_API_NAME_GOMP_CRITICAL_NAME_END)(void **pptr) { int gtid = __kmp_get_gtid(); MKLOC(loc, "GOMP_critical_name_end"); KA_TRACE(20, ("GOMP_critical_name_end: T#%d\n", gtid)); __kmpc_end_critical(&loc, gtid, (kmp_critical_name *)pptr); } // The Gnu codegen tries to use locked operations to perform atomic updates // inline. If it can't, then it calls GOMP_atomic_start() before performing // the update and GOMP_atomic_end() afterward, regardless of the data type. void KMP_EXPAND_NAME(KMP_API_NAME_GOMP_ATOMIC_START)(void) { int gtid = __kmp_entry_gtid(); KA_TRACE(20, ("GOMP_atomic_start: T#%d\n", gtid)); #if OMPT_SUPPORT __ompt_thread_assign_wait_id(0); #endif __kmp_acquire_atomic_lock(&__kmp_atomic_lock, gtid); } void KMP_EXPAND_NAME(KMP_API_NAME_GOMP_ATOMIC_END)(void) { int gtid = __kmp_get_gtid(); KA_TRACE(20, ("GOMP_atomic_end: T#%d\n", gtid)); __kmp_release_atomic_lock(&__kmp_atomic_lock, gtid); } int KMP_EXPAND_NAME(KMP_API_NAME_GOMP_SINGLE_START)(void) { int gtid = __kmp_entry_gtid(); MKLOC(loc, "GOMP_single_start"); KA_TRACE(20, ("GOMP_single_start: T#%d\n", gtid)); if (!TCR_4(__kmp_init_parallel)) __kmp_parallel_initialize(); __kmp_resume_if_soft_paused(); // 3rd parameter == FALSE prevents kmp_enter_single from pushing a // workshare when USE_CHECKS is defined. We need to avoid the push, // as there is no corresponding GOMP_single_end() call. kmp_int32 rc = __kmp_enter_single(gtid, &loc, FALSE); #if OMPT_SUPPORT && OMPT_OPTIONAL kmp_info_t *this_thr = __kmp_threads[gtid]; kmp_team_t *team = this_thr->th.th_team; int tid = __kmp_tid_from_gtid(gtid); if (ompt_enabled.enabled) { if (rc) { if (ompt_enabled.ompt_callback_work) { ompt_callbacks.ompt_callback(ompt_callback_work)( ompt_work_single_executor, ompt_scope_begin, &(team->t.ompt_team_info.parallel_data), &(team->t.t_implicit_task_taskdata[tid].ompt_task_info.task_data), 1, OMPT_GET_RETURN_ADDRESS(0)); } } else { if (ompt_enabled.ompt_callback_work) { ompt_callbacks.ompt_callback(ompt_callback_work)( ompt_work_single_other, ompt_scope_begin, &(team->t.ompt_team_info.parallel_data), &(team->t.t_implicit_task_taskdata[tid].ompt_task_info.task_data), 1, OMPT_GET_RETURN_ADDRESS(0)); ompt_callbacks.ompt_callback(ompt_callback_work)( ompt_work_single_other, ompt_scope_end, &(team->t.ompt_team_info.parallel_data), &(team->t.t_implicit_task_taskdata[tid].ompt_task_info.task_data), 1, OMPT_GET_RETURN_ADDRESS(0)); } } } #endif return rc; } void *KMP_EXPAND_NAME(KMP_API_NAME_GOMP_SINGLE_COPY_START)(void) { void *retval; int gtid = __kmp_entry_gtid(); MKLOC(loc, "GOMP_single_copy_start"); KA_TRACE(20, ("GOMP_single_copy_start: T#%d\n", gtid)); if (!TCR_4(__kmp_init_parallel)) __kmp_parallel_initialize(); __kmp_resume_if_soft_paused(); // If this is the first thread to enter, return NULL. The generated code will // then call GOMP_single_copy_end() for this thread only, with the // copyprivate data pointer as an argument. if (__kmp_enter_single(gtid, &loc, FALSE)) return NULL; // Wait for the first thread to set the copyprivate data pointer, // and for all other threads to reach this point. #if OMPT_SUPPORT && OMPT_OPTIONAL ompt_frame_t *ompt_frame; if (ompt_enabled.enabled) { __ompt_get_task_info_internal(0, NULL, NULL, &ompt_frame, NULL, NULL); ompt_frame->enter_frame.ptr = OMPT_GET_FRAME_ADDRESS(0); OMPT_STORE_RETURN_ADDRESS(gtid); } #endif __kmp_barrier(bs_plain_barrier, gtid, FALSE, 0, NULL, NULL); // Retrieve the value of the copyprivate data point, and wait for all // threads to do likewise, then return. retval = __kmp_team_from_gtid(gtid)->t.t_copypriv_data; #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled) { OMPT_STORE_RETURN_ADDRESS(gtid); } #endif __kmp_barrier(bs_plain_barrier, gtid, FALSE, 0, NULL, NULL); #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled) { ompt_frame->enter_frame = ompt_data_none; } #endif return retval; } void KMP_EXPAND_NAME(KMP_API_NAME_GOMP_SINGLE_COPY_END)(void *data) { int gtid = __kmp_get_gtid(); KA_TRACE(20, ("GOMP_single_copy_end: T#%d\n", gtid)); // Set the copyprivate data pointer fo the team, then hit the barrier so that // the other threads will continue on and read it. Hit another barrier before // continuing, so that the know that the copyprivate data pointer has been // propagated to all threads before trying to reuse the t_copypriv_data field. __kmp_team_from_gtid(gtid)->t.t_copypriv_data = data; #if OMPT_SUPPORT && OMPT_OPTIONAL ompt_frame_t *ompt_frame; if (ompt_enabled.enabled) { __ompt_get_task_info_internal(0, NULL, NULL, &ompt_frame, NULL, NULL); ompt_frame->enter_frame.ptr = OMPT_GET_FRAME_ADDRESS(0); OMPT_STORE_RETURN_ADDRESS(gtid); } #endif __kmp_barrier(bs_plain_barrier, gtid, FALSE, 0, NULL, NULL); #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled) { OMPT_STORE_RETURN_ADDRESS(gtid); } #endif __kmp_barrier(bs_plain_barrier, gtid, FALSE, 0, NULL, NULL); #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled) { ompt_frame->enter_frame = ompt_data_none; } #endif } void KMP_EXPAND_NAME(KMP_API_NAME_GOMP_ORDERED_START)(void) { int gtid = __kmp_entry_gtid(); MKLOC(loc, "GOMP_ordered_start"); KA_TRACE(20, ("GOMP_ordered_start: T#%d\n", gtid)); #if OMPT_SUPPORT && OMPT_OPTIONAL OMPT_STORE_RETURN_ADDRESS(gtid); #endif __kmpc_ordered(&loc, gtid); } void KMP_EXPAND_NAME(KMP_API_NAME_GOMP_ORDERED_END)(void) { int gtid = __kmp_get_gtid(); MKLOC(loc, "GOMP_ordered_end"); KA_TRACE(20, ("GOMP_ordered_start: T#%d\n", gtid)); #if OMPT_SUPPORT && OMPT_OPTIONAL OMPT_STORE_RETURN_ADDRESS(gtid); #endif __kmpc_end_ordered(&loc, gtid); } // Dispatch macro defs // // They come in two flavors: 64-bit unsigned, and either 32-bit signed // (IA-32 architecture) or 64-bit signed (Intel(R) 64). #if KMP_ARCH_X86 || KMP_ARCH_ARM || KMP_ARCH_MIPS #define KMP_DISPATCH_INIT __kmp_aux_dispatch_init_4 #define KMP_DISPATCH_FINI_CHUNK __kmp_aux_dispatch_fini_chunk_4 #define KMP_DISPATCH_NEXT __kmpc_dispatch_next_4 #else #define KMP_DISPATCH_INIT __kmp_aux_dispatch_init_8 #define KMP_DISPATCH_FINI_CHUNK __kmp_aux_dispatch_fini_chunk_8 #define KMP_DISPATCH_NEXT __kmpc_dispatch_next_8 #endif /* KMP_ARCH_X86 */ #define KMP_DISPATCH_INIT_ULL __kmp_aux_dispatch_init_8u #define KMP_DISPATCH_FINI_CHUNK_ULL __kmp_aux_dispatch_fini_chunk_8u #define KMP_DISPATCH_NEXT_ULL __kmpc_dispatch_next_8u // The parallel construct #ifndef KMP_DEBUG static #endif /* KMP_DEBUG */ void __kmp_GOMP_microtask_wrapper(int *gtid, int *npr, void (*task)(void *), void *data) { #if OMPT_SUPPORT kmp_info_t *thr; ompt_frame_t *ompt_frame; ompt_state_t enclosing_state; if (ompt_enabled.enabled) { // get pointer to thread data structure thr = __kmp_threads[*gtid]; // save enclosing task state; set current state for task enclosing_state = thr->th.ompt_thread_info.state; thr->th.ompt_thread_info.state = ompt_state_work_parallel; // set task frame __ompt_get_task_info_internal(0, NULL, NULL, &ompt_frame, NULL, NULL); ompt_frame->exit_frame.ptr = OMPT_GET_FRAME_ADDRESS(0); } #endif task(data); #if OMPT_SUPPORT if (ompt_enabled.enabled) { // clear task frame ompt_frame->exit_frame = ompt_data_none; // restore enclosing state thr->th.ompt_thread_info.state = enclosing_state; } #endif } #ifndef KMP_DEBUG static #endif /* KMP_DEBUG */ void __kmp_GOMP_parallel_microtask_wrapper(int *gtid, int *npr, void (*task)(void *), void *data, unsigned num_threads, ident_t *loc, enum sched_type schedule, long start, long end, long incr, long chunk_size) { // Initialize the loop worksharing construct. KMP_DISPATCH_INIT(loc, *gtid, schedule, start, end, incr, chunk_size, schedule != kmp_sch_static); #if OMPT_SUPPORT kmp_info_t *thr; ompt_frame_t *ompt_frame; ompt_state_t enclosing_state; if (ompt_enabled.enabled) { thr = __kmp_threads[*gtid]; // save enclosing task state; set current state for task enclosing_state = thr->th.ompt_thread_info.state; thr->th.ompt_thread_info.state = ompt_state_work_parallel; // set task frame __ompt_get_task_info_internal(0, NULL, NULL, &ompt_frame, NULL, NULL); ompt_frame->exit_frame.ptr = OMPT_GET_FRAME_ADDRESS(0); } #endif // Now invoke the microtask. task(data); #if OMPT_SUPPORT if (ompt_enabled.enabled) { // clear task frame ompt_frame->exit_frame = ompt_data_none; // reset enclosing state thr->th.ompt_thread_info.state = enclosing_state; } #endif } #ifndef KMP_DEBUG static #endif /* KMP_DEBUG */ void __kmp_GOMP_fork_call(ident_t *loc, int gtid, void (*unwrapped_task)(void *), microtask_t wrapper, int argc, ...) { int rc; kmp_info_t *thr = __kmp_threads[gtid]; kmp_team_t *team = thr->th.th_team; int tid = __kmp_tid_from_gtid(gtid); va_list ap; va_start(ap, argc); rc = __kmp_fork_call(loc, gtid, fork_context_gnu, argc, wrapper, - __kmp_invoke_task_func, -#if (KMP_ARCH_X86_64 || KMP_ARCH_ARM || KMP_ARCH_AARCH64) && KMP_OS_LINUX - &ap -#else - ap -#endif - ); + __kmp_invoke_task_func, kmp_va_addr_of(ap)); va_end(ap); if (rc) { __kmp_run_before_invoked_task(gtid, tid, thr, team); } #if OMPT_SUPPORT int ompt_team_size; if (ompt_enabled.enabled) { ompt_team_info_t *team_info = __ompt_get_teaminfo(0, NULL); ompt_task_info_t *task_info = __ompt_get_task_info_object(0); // implicit task callback if (ompt_enabled.ompt_callback_implicit_task) { ompt_team_size = __kmp_team_from_gtid(gtid)->t.t_nproc; ompt_callbacks.ompt_callback(ompt_callback_implicit_task)( ompt_scope_begin, &(team_info->parallel_data), &(task_info->task_data), ompt_team_size, __kmp_tid_from_gtid(gtid), ompt_task_implicit); // TODO: Can this be ompt_task_initial? task_info->thread_num = __kmp_tid_from_gtid(gtid); } thr->th.ompt_thread_info.state = ompt_state_work_parallel; } #endif } static void __kmp_GOMP_serialized_parallel(ident_t *loc, kmp_int32 gtid, void (*task)(void *)) { #if OMPT_SUPPORT OMPT_STORE_RETURN_ADDRESS(gtid); #endif __kmp_serialized_parallel(loc, gtid); } void KMP_EXPAND_NAME(KMP_API_NAME_GOMP_PARALLEL_START)(void (*task)(void *), void *data, unsigned num_threads) { int gtid = __kmp_entry_gtid(); #if OMPT_SUPPORT ompt_frame_t *parent_frame, *frame; if (ompt_enabled.enabled) { __ompt_get_task_info_internal(0, NULL, NULL, &parent_frame, NULL, NULL); parent_frame->enter_frame.ptr = OMPT_GET_FRAME_ADDRESS(0); OMPT_STORE_RETURN_ADDRESS(gtid); } #endif MKLOC(loc, "GOMP_parallel_start"); KA_TRACE(20, ("GOMP_parallel_start: T#%d\n", gtid)); if (__kmpc_ok_to_fork(&loc) && (num_threads != 1)) { if (num_threads != 0) { __kmp_push_num_threads(&loc, gtid, num_threads); } __kmp_GOMP_fork_call(&loc, gtid, task, (microtask_t)__kmp_GOMP_microtask_wrapper, 2, task, data); } else { __kmp_GOMP_serialized_parallel(&loc, gtid, task); } #if OMPT_SUPPORT if (ompt_enabled.enabled) { __ompt_get_task_info_internal(0, NULL, NULL, &frame, NULL, NULL); frame->exit_frame.ptr = OMPT_GET_FRAME_ADDRESS(0); } #endif } void KMP_EXPAND_NAME(KMP_API_NAME_GOMP_PARALLEL_END)(void) { int gtid = __kmp_get_gtid(); kmp_info_t *thr; thr = __kmp_threads[gtid]; MKLOC(loc, "GOMP_parallel_end"); KA_TRACE(20, ("GOMP_parallel_end: T#%d\n", gtid)); if (!thr->th.th_team->t.t_serialized) { __kmp_run_after_invoked_task(gtid, __kmp_tid_from_gtid(gtid), thr, thr->th.th_team); #if OMPT_SUPPORT if (ompt_enabled.enabled) { // Implicit task is finished here, in the barrier we might schedule // deferred tasks, // these don't see the implicit task on the stack OMPT_CUR_TASK_INFO(thr)->frame.exit_frame = ompt_data_none; } #endif __kmp_join_call(&loc, gtid #if OMPT_SUPPORT , fork_context_gnu #endif ); } else { __kmpc_end_serialized_parallel(&loc, gtid); } } // Loop worksharing constructs // The Gnu codegen passes in an exclusive upper bound for the overall range, // but the libguide dispatch code expects an inclusive upper bound, hence the // "end - incr" 5th argument to KMP_DISPATCH_INIT (and the " ub - str" 11th // argument to __kmp_GOMP_fork_call). // // Conversely, KMP_DISPATCH_NEXT returns and inclusive upper bound in *p_ub, // but the Gnu codegen expects an exclusive upper bound, so the adjustment // "*p_ub += stride" compensates for the discrepancy. // // Correction: the gnu codegen always adjusts the upper bound by +-1, not the // stride value. We adjust the dispatch parameters accordingly (by +-1), but // we still adjust p_ub by the actual stride value. // // The "runtime" versions do not take a chunk_sz parameter. // // The profile lib cannot support construct checking of unordered loops that // are predetermined by the compiler to be statically scheduled, as the gcc // codegen will not always emit calls to GOMP_loop_static_next() to get the // next iteration. Instead, it emits inline code to call omp_get_thread_num() // num and calculate the iteration space using the result. It doesn't do this // with ordered static loop, so they can be checked. #if OMPT_SUPPORT #define IF_OMPT_SUPPORT(code) code #else #define IF_OMPT_SUPPORT(code) #endif #define LOOP_START(func, schedule) \ int func(long lb, long ub, long str, long chunk_sz, long *p_lb, \ long *p_ub) { \ int status; \ long stride; \ int gtid = __kmp_entry_gtid(); \ MKLOC(loc, KMP_STR(func)); \ KA_TRACE( \ 20, \ (KMP_STR( \ func) ": T#%d, lb 0x%lx, ub 0x%lx, str 0x%lx, chunk_sz 0x%lx\n", \ gtid, lb, ub, str, chunk_sz)); \ \ if ((str > 0) ? (lb < ub) : (lb > ub)) { \ IF_OMPT_SUPPORT(OMPT_STORE_RETURN_ADDRESS(gtid);) \ KMP_DISPATCH_INIT(&loc, gtid, (schedule), lb, \ (str > 0) ? (ub - 1) : (ub + 1), str, chunk_sz, \ (schedule) != kmp_sch_static); \ IF_OMPT_SUPPORT(OMPT_STORE_RETURN_ADDRESS(gtid);) \ status = KMP_DISPATCH_NEXT(&loc, gtid, NULL, (kmp_int *)p_lb, \ (kmp_int *)p_ub, (kmp_int *)&stride); \ if (status) { \ KMP_DEBUG_ASSERT(stride == str); \ *p_ub += (str > 0) ? 1 : -1; \ } \ } else { \ status = 0; \ } \ \ KA_TRACE( \ 20, \ (KMP_STR( \ func) " exit: T#%d, *p_lb 0x%lx, *p_ub 0x%lx, returning %d\n", \ gtid, *p_lb, *p_ub, status)); \ return status; \ } #define LOOP_RUNTIME_START(func, schedule) \ int func(long lb, long ub, long str, long *p_lb, long *p_ub) { \ int status; \ long stride; \ long chunk_sz = 0; \ int gtid = __kmp_entry_gtid(); \ MKLOC(loc, KMP_STR(func)); \ KA_TRACE( \ 20, \ (KMP_STR(func) ": T#%d, lb 0x%lx, ub 0x%lx, str 0x%lx, chunk_sz %d\n", \ gtid, lb, ub, str, chunk_sz)); \ \ if ((str > 0) ? (lb < ub) : (lb > ub)) { \ IF_OMPT_SUPPORT(OMPT_STORE_RETURN_ADDRESS(gtid);) \ KMP_DISPATCH_INIT(&loc, gtid, (schedule), lb, \ (str > 0) ? (ub - 1) : (ub + 1), str, chunk_sz, TRUE); \ IF_OMPT_SUPPORT(OMPT_STORE_RETURN_ADDRESS(gtid);) \ status = KMP_DISPATCH_NEXT(&loc, gtid, NULL, (kmp_int *)p_lb, \ (kmp_int *)p_ub, (kmp_int *)&stride); \ if (status) { \ KMP_DEBUG_ASSERT(stride == str); \ *p_ub += (str > 0) ? 1 : -1; \ } \ } else { \ status = 0; \ } \ \ KA_TRACE( \ 20, \ (KMP_STR( \ func) " exit: T#%d, *p_lb 0x%lx, *p_ub 0x%lx, returning %d\n", \ gtid, *p_lb, *p_ub, status)); \ return status; \ } #define KMP_DOACROSS_FINI(status, gtid) \ if (!status && __kmp_threads[gtid]->th.th_dispatch->th_doacross_flags) { \ __kmpc_doacross_fini(NULL, gtid); \ } #define LOOP_NEXT(func, fini_code) \ int func(long *p_lb, long *p_ub) { \ int status; \ long stride; \ int gtid = __kmp_get_gtid(); \ MKLOC(loc, KMP_STR(func)); \ KA_TRACE(20, (KMP_STR(func) ": T#%d\n", gtid)); \ \ IF_OMPT_SUPPORT(OMPT_STORE_RETURN_ADDRESS(gtid);) \ fini_code status = KMP_DISPATCH_NEXT(&loc, gtid, NULL, (kmp_int *)p_lb, \ (kmp_int *)p_ub, (kmp_int *)&stride); \ if (status) { \ *p_ub += (stride > 0) ? 1 : -1; \ } \ KMP_DOACROSS_FINI(status, gtid) \ \ KA_TRACE( \ 20, \ (KMP_STR(func) " exit: T#%d, *p_lb 0x%lx, *p_ub 0x%lx, stride 0x%lx, " \ "returning %d\n", \ gtid, *p_lb, *p_ub, stride, status)); \ return status; \ } LOOP_START(KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_STATIC_START), kmp_sch_static) LOOP_NEXT(KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_STATIC_NEXT), {}) LOOP_START(KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_DYNAMIC_START), kmp_sch_dynamic_chunked) LOOP_START(KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_NONMONOTONIC_DYNAMIC_START), kmp_sch_dynamic_chunked) LOOP_NEXT(KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_DYNAMIC_NEXT), {}) LOOP_NEXT(KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_NONMONOTONIC_DYNAMIC_NEXT), {}) LOOP_START(KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_GUIDED_START), kmp_sch_guided_chunked) LOOP_START(KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_NONMONOTONIC_GUIDED_START), kmp_sch_guided_chunked) LOOP_NEXT(KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_GUIDED_NEXT), {}) LOOP_NEXT(KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_NONMONOTONIC_GUIDED_NEXT), {}) LOOP_RUNTIME_START(KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_RUNTIME_START), kmp_sch_runtime) LOOP_NEXT(KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_RUNTIME_NEXT), {}) LOOP_RUNTIME_START( KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_MAYBE_NONMONOTONIC_RUNTIME_START), kmp_sch_runtime) LOOP_RUNTIME_START( KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_NONMONOTONIC_RUNTIME_START), kmp_sch_runtime) LOOP_NEXT( KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_MAYBE_NONMONOTONIC_RUNTIME_NEXT), {}) LOOP_NEXT(KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_NONMONOTONIC_RUNTIME_NEXT), {}) LOOP_START(KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_ORDERED_STATIC_START), kmp_ord_static) LOOP_NEXT(KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_ORDERED_STATIC_NEXT), { KMP_DISPATCH_FINI_CHUNK(&loc, gtid); }) LOOP_START(KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_ORDERED_DYNAMIC_START), kmp_ord_dynamic_chunked) LOOP_NEXT(KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_ORDERED_DYNAMIC_NEXT), { KMP_DISPATCH_FINI_CHUNK(&loc, gtid); }) LOOP_START(KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_ORDERED_GUIDED_START), kmp_ord_guided_chunked) LOOP_NEXT(KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_ORDERED_GUIDED_NEXT), { KMP_DISPATCH_FINI_CHUNK(&loc, gtid); }) LOOP_RUNTIME_START( KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_ORDERED_RUNTIME_START), kmp_ord_runtime) LOOP_NEXT(KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_ORDERED_RUNTIME_NEXT), { KMP_DISPATCH_FINI_CHUNK(&loc, gtid); }) #define LOOP_DOACROSS_START(func, schedule) \ bool func(unsigned ncounts, long *counts, long chunk_sz, long *p_lb, \ long *p_ub) { \ int status; \ long stride, lb, ub, str; \ int gtid = __kmp_entry_gtid(); \ struct kmp_dim *dims = \ (struct kmp_dim *)__kmp_allocate(sizeof(struct kmp_dim) * ncounts); \ MKLOC(loc, KMP_STR(func)); \ for (unsigned i = 0; i < ncounts; ++i) { \ dims[i].lo = 0; \ dims[i].up = counts[i] - 1; \ dims[i].st = 1; \ } \ __kmpc_doacross_init(&loc, gtid, (int)ncounts, dims); \ lb = 0; \ ub = counts[0]; \ str = 1; \ KA_TRACE(20, (KMP_STR(func) ": T#%d, ncounts %u, lb 0x%lx, ub 0x%lx, str " \ "0x%lx, chunk_sz " \ "0x%lx\n", \ gtid, ncounts, lb, ub, str, chunk_sz)); \ \ if ((str > 0) ? (lb < ub) : (lb > ub)) { \ KMP_DISPATCH_INIT(&loc, gtid, (schedule), lb, \ (str > 0) ? (ub - 1) : (ub + 1), str, chunk_sz, \ (schedule) != kmp_sch_static); \ status = KMP_DISPATCH_NEXT(&loc, gtid, NULL, (kmp_int *)p_lb, \ (kmp_int *)p_ub, (kmp_int *)&stride); \ if (status) { \ KMP_DEBUG_ASSERT(stride == str); \ *p_ub += (str > 0) ? 1 : -1; \ } \ } else { \ status = 0; \ } \ KMP_DOACROSS_FINI(status, gtid); \ \ KA_TRACE( \ 20, \ (KMP_STR( \ func) " exit: T#%d, *p_lb 0x%lx, *p_ub 0x%lx, returning %d\n", \ gtid, *p_lb, *p_ub, status)); \ __kmp_free(dims); \ return status; \ } #define LOOP_DOACROSS_RUNTIME_START(func, schedule) \ int func(unsigned ncounts, long *counts, long *p_lb, long *p_ub) { \ int status; \ long stride, lb, ub, str; \ long chunk_sz = 0; \ int gtid = __kmp_entry_gtid(); \ struct kmp_dim *dims = \ (struct kmp_dim *)__kmp_allocate(sizeof(struct kmp_dim) * ncounts); \ MKLOC(loc, KMP_STR(func)); \ for (unsigned i = 0; i < ncounts; ++i) { \ dims[i].lo = 0; \ dims[i].up = counts[i] - 1; \ dims[i].st = 1; \ } \ __kmpc_doacross_init(&loc, gtid, (int)ncounts, dims); \ lb = 0; \ ub = counts[0]; \ str = 1; \ KA_TRACE( \ 20, \ (KMP_STR(func) ": T#%d, lb 0x%lx, ub 0x%lx, str 0x%lx, chunk_sz %d\n", \ gtid, lb, ub, str, chunk_sz)); \ \ if ((str > 0) ? (lb < ub) : (lb > ub)) { \ KMP_DISPATCH_INIT(&loc, gtid, (schedule), lb, \ (str > 0) ? (ub - 1) : (ub + 1), str, chunk_sz, TRUE); \ status = KMP_DISPATCH_NEXT(&loc, gtid, NULL, (kmp_int *)p_lb, \ (kmp_int *)p_ub, (kmp_int *)&stride); \ if (status) { \ KMP_DEBUG_ASSERT(stride == str); \ *p_ub += (str > 0) ? 1 : -1; \ } \ } else { \ status = 0; \ } \ KMP_DOACROSS_FINI(status, gtid); \ \ KA_TRACE( \ 20, \ (KMP_STR( \ func) " exit: T#%d, *p_lb 0x%lx, *p_ub 0x%lx, returning %d\n", \ gtid, *p_lb, *p_ub, status)); \ __kmp_free(dims); \ return status; \ } LOOP_DOACROSS_START( KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_DOACROSS_STATIC_START), kmp_sch_static) LOOP_DOACROSS_START( KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_DOACROSS_DYNAMIC_START), kmp_sch_dynamic_chunked) LOOP_DOACROSS_START( KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_DOACROSS_GUIDED_START), kmp_sch_guided_chunked) LOOP_DOACROSS_RUNTIME_START( KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_DOACROSS_RUNTIME_START), kmp_sch_runtime) void KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_END)(void) { int gtid = __kmp_get_gtid(); KA_TRACE(20, ("GOMP_loop_end: T#%d\n", gtid)) #if OMPT_SUPPORT && OMPT_OPTIONAL ompt_frame_t *ompt_frame; if (ompt_enabled.enabled) { __ompt_get_task_info_internal(0, NULL, NULL, &ompt_frame, NULL, NULL); ompt_frame->enter_frame.ptr = OMPT_GET_FRAME_ADDRESS(0); OMPT_STORE_RETURN_ADDRESS(gtid); } #endif __kmp_barrier(bs_plain_barrier, gtid, FALSE, 0, NULL, NULL); #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled) { ompt_frame->enter_frame = ompt_data_none; } #endif KA_TRACE(20, ("GOMP_loop_end exit: T#%d\n", gtid)) } void KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_END_NOWAIT)(void) { KA_TRACE(20, ("GOMP_loop_end_nowait: T#%d\n", __kmp_get_gtid())) } // Unsigned long long loop worksharing constructs // // These are new with gcc 4.4 #define LOOP_START_ULL(func, schedule) \ int func(int up, unsigned long long lb, unsigned long long ub, \ unsigned long long str, unsigned long long chunk_sz, \ unsigned long long *p_lb, unsigned long long *p_ub) { \ int status; \ long long str2 = up ? ((long long)str) : -((long long)str); \ long long stride; \ int gtid = __kmp_entry_gtid(); \ MKLOC(loc, KMP_STR(func)); \ \ KA_TRACE(20, (KMP_STR(func) ": T#%d, up %d, lb 0x%llx, ub 0x%llx, str " \ "0x%llx, chunk_sz 0x%llx\n", \ gtid, up, lb, ub, str, chunk_sz)); \ \ if ((str > 0) ? (lb < ub) : (lb > ub)) { \ KMP_DISPATCH_INIT_ULL(&loc, gtid, (schedule), lb, \ (str2 > 0) ? (ub - 1) : (ub + 1), str2, chunk_sz, \ (schedule) != kmp_sch_static); \ status = \ KMP_DISPATCH_NEXT_ULL(&loc, gtid, NULL, (kmp_uint64 *)p_lb, \ (kmp_uint64 *)p_ub, (kmp_int64 *)&stride); \ if (status) { \ KMP_DEBUG_ASSERT(stride == str2); \ *p_ub += (str > 0) ? 1 : -1; \ } \ } else { \ status = 0; \ } \ \ KA_TRACE( \ 20, \ (KMP_STR( \ func) " exit: T#%d, *p_lb 0x%llx, *p_ub 0x%llx, returning %d\n", \ gtid, *p_lb, *p_ub, status)); \ return status; \ } #define LOOP_RUNTIME_START_ULL(func, schedule) \ int func(int up, unsigned long long lb, unsigned long long ub, \ unsigned long long str, unsigned long long *p_lb, \ unsigned long long *p_ub) { \ int status; \ long long str2 = up ? ((long long)str) : -((long long)str); \ unsigned long long stride; \ unsigned long long chunk_sz = 0; \ int gtid = __kmp_entry_gtid(); \ MKLOC(loc, KMP_STR(func)); \ \ KA_TRACE(20, (KMP_STR(func) ": T#%d, up %d, lb 0x%llx, ub 0x%llx, str " \ "0x%llx, chunk_sz 0x%llx\n", \ gtid, up, lb, ub, str, chunk_sz)); \ \ if ((str > 0) ? (lb < ub) : (lb > ub)) { \ KMP_DISPATCH_INIT_ULL(&loc, gtid, (schedule), lb, \ (str2 > 0) ? (ub - 1) : (ub + 1), str2, chunk_sz, \ TRUE); \ status = \ KMP_DISPATCH_NEXT_ULL(&loc, gtid, NULL, (kmp_uint64 *)p_lb, \ (kmp_uint64 *)p_ub, (kmp_int64 *)&stride); \ if (status) { \ KMP_DEBUG_ASSERT((long long)stride == str2); \ *p_ub += (str > 0) ? 1 : -1; \ } \ } else { \ status = 0; \ } \ \ KA_TRACE( \ 20, \ (KMP_STR( \ func) " exit: T#%d, *p_lb 0x%llx, *p_ub 0x%llx, returning %d\n", \ gtid, *p_lb, *p_ub, status)); \ return status; \ } #define LOOP_NEXT_ULL(func, fini_code) \ int func(unsigned long long *p_lb, unsigned long long *p_ub) { \ int status; \ long long stride; \ int gtid = __kmp_get_gtid(); \ MKLOC(loc, KMP_STR(func)); \ KA_TRACE(20, (KMP_STR(func) ": T#%d\n", gtid)); \ \ fini_code status = \ KMP_DISPATCH_NEXT_ULL(&loc, gtid, NULL, (kmp_uint64 *)p_lb, \ (kmp_uint64 *)p_ub, (kmp_int64 *)&stride); \ if (status) { \ *p_ub += (stride > 0) ? 1 : -1; \ } \ \ KA_TRACE( \ 20, \ (KMP_STR( \ func) " exit: T#%d, *p_lb 0x%llx, *p_ub 0x%llx, stride 0x%llx, " \ "returning %d\n", \ gtid, *p_lb, *p_ub, stride, status)); \ return status; \ } LOOP_START_ULL(KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_ULL_STATIC_START), kmp_sch_static) LOOP_NEXT_ULL(KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_ULL_STATIC_NEXT), {}) LOOP_START_ULL(KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_ULL_DYNAMIC_START), kmp_sch_dynamic_chunked) LOOP_NEXT_ULL(KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_ULL_DYNAMIC_NEXT), {}) LOOP_START_ULL(KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_ULL_GUIDED_START), kmp_sch_guided_chunked) LOOP_NEXT_ULL(KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_ULL_GUIDED_NEXT), {}) LOOP_START_ULL( KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_ULL_NONMONOTONIC_DYNAMIC_START), kmp_sch_dynamic_chunked) LOOP_NEXT_ULL( KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_ULL_NONMONOTONIC_DYNAMIC_NEXT), {}) LOOP_START_ULL( KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_ULL_NONMONOTONIC_GUIDED_START), kmp_sch_guided_chunked) LOOP_NEXT_ULL( KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_ULL_NONMONOTONIC_GUIDED_NEXT), {}) LOOP_RUNTIME_START_ULL( KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_ULL_RUNTIME_START), kmp_sch_runtime) LOOP_NEXT_ULL(KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_ULL_RUNTIME_NEXT), {}) LOOP_RUNTIME_START_ULL( KMP_EXPAND_NAME( KMP_API_NAME_GOMP_LOOP_ULL_MAYBE_NONMONOTONIC_RUNTIME_START), kmp_sch_runtime) LOOP_RUNTIME_START_ULL( KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_ULL_NONMONOTONIC_RUNTIME_START), kmp_sch_runtime) LOOP_NEXT_ULL( KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_ULL_MAYBE_NONMONOTONIC_RUNTIME_NEXT), {}) LOOP_NEXT_ULL( KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_ULL_NONMONOTONIC_RUNTIME_NEXT), {}) LOOP_START_ULL(KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_ULL_ORDERED_STATIC_START), kmp_ord_static) LOOP_NEXT_ULL(KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_ULL_ORDERED_STATIC_NEXT), { KMP_DISPATCH_FINI_CHUNK_ULL(&loc, gtid); }) LOOP_START_ULL( KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_ULL_ORDERED_DYNAMIC_START), kmp_ord_dynamic_chunked) LOOP_NEXT_ULL(KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_ULL_ORDERED_DYNAMIC_NEXT), { KMP_DISPATCH_FINI_CHUNK_ULL(&loc, gtid); }) LOOP_START_ULL(KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_ULL_ORDERED_GUIDED_START), kmp_ord_guided_chunked) LOOP_NEXT_ULL(KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_ULL_ORDERED_GUIDED_NEXT), { KMP_DISPATCH_FINI_CHUNK_ULL(&loc, gtid); }) LOOP_RUNTIME_START_ULL( KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_ULL_ORDERED_RUNTIME_START), kmp_ord_runtime) LOOP_NEXT_ULL(KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_ULL_ORDERED_RUNTIME_NEXT), { KMP_DISPATCH_FINI_CHUNK_ULL(&loc, gtid); }) #define LOOP_DOACROSS_START_ULL(func, schedule) \ int func(unsigned ncounts, unsigned long long *counts, \ unsigned long long chunk_sz, unsigned long long *p_lb, \ unsigned long long *p_ub) { \ int status; \ long long stride, str, lb, ub; \ int gtid = __kmp_entry_gtid(); \ struct kmp_dim *dims = \ (struct kmp_dim *)__kmp_allocate(sizeof(struct kmp_dim) * ncounts); \ MKLOC(loc, KMP_STR(func)); \ for (unsigned i = 0; i < ncounts; ++i) { \ dims[i].lo = 0; \ dims[i].up = counts[i] - 1; \ dims[i].st = 1; \ } \ __kmpc_doacross_init(&loc, gtid, (int)ncounts, dims); \ lb = 0; \ ub = counts[0]; \ str = 1; \ \ KA_TRACE(20, (KMP_STR(func) ": T#%d, lb 0x%llx, ub 0x%llx, str " \ "0x%llx, chunk_sz 0x%llx\n", \ gtid, lb, ub, str, chunk_sz)); \ \ if ((str > 0) ? (lb < ub) : (lb > ub)) { \ KMP_DISPATCH_INIT_ULL(&loc, gtid, (schedule), lb, \ (str > 0) ? (ub - 1) : (ub + 1), str, chunk_sz, \ (schedule) != kmp_sch_static); \ status = \ KMP_DISPATCH_NEXT_ULL(&loc, gtid, NULL, (kmp_uint64 *)p_lb, \ (kmp_uint64 *)p_ub, (kmp_int64 *)&stride); \ if (status) { \ KMP_DEBUG_ASSERT(stride == str); \ *p_ub += (str > 0) ? 1 : -1; \ } \ } else { \ status = 0; \ } \ KMP_DOACROSS_FINI(status, gtid); \ \ KA_TRACE( \ 20, \ (KMP_STR( \ func) " exit: T#%d, *p_lb 0x%llx, *p_ub 0x%llx, returning %d\n", \ gtid, *p_lb, *p_ub, status)); \ __kmp_free(dims); \ return status; \ } #define LOOP_DOACROSS_RUNTIME_START_ULL(func, schedule) \ int func(unsigned ncounts, unsigned long long *counts, \ unsigned long long *p_lb, unsigned long long *p_ub) { \ int status; \ unsigned long long stride, str, lb, ub; \ unsigned long long chunk_sz = 0; \ int gtid = __kmp_entry_gtid(); \ struct kmp_dim *dims = \ (struct kmp_dim *)__kmp_allocate(sizeof(struct kmp_dim) * ncounts); \ MKLOC(loc, KMP_STR(func)); \ for (unsigned i = 0; i < ncounts; ++i) { \ dims[i].lo = 0; \ dims[i].up = counts[i] - 1; \ dims[i].st = 1; \ } \ __kmpc_doacross_init(&loc, gtid, (int)ncounts, dims); \ lb = 0; \ ub = counts[0]; \ str = 1; \ KA_TRACE(20, (KMP_STR(func) ": T#%d, lb 0x%llx, ub 0x%llx, str " \ "0x%llx, chunk_sz 0x%llx\n", \ gtid, lb, ub, str, chunk_sz)); \ \ if ((str > 0) ? (lb < ub) : (lb > ub)) { \ KMP_DISPATCH_INIT_ULL(&loc, gtid, (schedule), lb, \ (str > 0) ? (ub - 1) : (ub + 1), str, chunk_sz, \ TRUE); \ status = \ KMP_DISPATCH_NEXT_ULL(&loc, gtid, NULL, (kmp_uint64 *)p_lb, \ (kmp_uint64 *)p_ub, (kmp_int64 *)&stride); \ if (status) { \ KMP_DEBUG_ASSERT(stride == str); \ *p_ub += (str > 0) ? 1 : -1; \ } \ } else { \ status = 0; \ } \ KMP_DOACROSS_FINI(status, gtid); \ \ KA_TRACE( \ 20, \ (KMP_STR( \ func) " exit: T#%d, *p_lb 0x%llx, *p_ub 0x%llx, returning %d\n", \ gtid, *p_lb, *p_ub, status)); \ __kmp_free(dims); \ return status; \ } LOOP_DOACROSS_START_ULL( KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_ULL_DOACROSS_STATIC_START), kmp_sch_static) LOOP_DOACROSS_START_ULL( KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_ULL_DOACROSS_DYNAMIC_START), kmp_sch_dynamic_chunked) LOOP_DOACROSS_START_ULL( KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_ULL_DOACROSS_GUIDED_START), kmp_sch_guided_chunked) LOOP_DOACROSS_RUNTIME_START_ULL( KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_ULL_DOACROSS_RUNTIME_START), kmp_sch_runtime) // Combined parallel / loop worksharing constructs // // There are no ull versions (yet). #define PARALLEL_LOOP_START(func, schedule, ompt_pre, ompt_post) \ void func(void (*task)(void *), void *data, unsigned num_threads, long lb, \ long ub, long str, long chunk_sz) { \ int gtid = __kmp_entry_gtid(); \ MKLOC(loc, KMP_STR(func)); \ KA_TRACE( \ 20, \ (KMP_STR( \ func) ": T#%d, lb 0x%lx, ub 0x%lx, str 0x%lx, chunk_sz 0x%lx\n", \ gtid, lb, ub, str, chunk_sz)); \ \ ompt_pre(); \ \ if (__kmpc_ok_to_fork(&loc) && (num_threads != 1)) { \ if (num_threads != 0) { \ __kmp_push_num_threads(&loc, gtid, num_threads); \ } \ __kmp_GOMP_fork_call(&loc, gtid, task, \ (microtask_t)__kmp_GOMP_parallel_microtask_wrapper, \ 9, task, data, num_threads, &loc, (schedule), lb, \ (str > 0) ? (ub - 1) : (ub + 1), str, chunk_sz); \ IF_OMPT_SUPPORT(OMPT_STORE_RETURN_ADDRESS(gtid)); \ } else { \ __kmp_GOMP_serialized_parallel(&loc, gtid, task); \ IF_OMPT_SUPPORT(OMPT_STORE_RETURN_ADDRESS(gtid)); \ } \ \ KMP_DISPATCH_INIT(&loc, gtid, (schedule), lb, \ (str > 0) ? (ub - 1) : (ub + 1), str, chunk_sz, \ (schedule) != kmp_sch_static); \ \ ompt_post(); \ \ KA_TRACE(20, (KMP_STR(func) " exit: T#%d\n", gtid)); \ } #if OMPT_SUPPORT && OMPT_OPTIONAL #define OMPT_LOOP_PRE() \ ompt_frame_t *parent_frame; \ if (ompt_enabled.enabled) { \ __ompt_get_task_info_internal(0, NULL, NULL, &parent_frame, NULL, NULL); \ parent_frame->enter_frame.ptr = OMPT_GET_FRAME_ADDRESS(0); \ OMPT_STORE_RETURN_ADDRESS(gtid); \ } #define OMPT_LOOP_POST() \ if (ompt_enabled.enabled) { \ parent_frame->enter_frame = ompt_data_none; \ } #else #define OMPT_LOOP_PRE() #define OMPT_LOOP_POST() #endif PARALLEL_LOOP_START( KMP_EXPAND_NAME(KMP_API_NAME_GOMP_PARALLEL_LOOP_STATIC_START), kmp_sch_static, OMPT_LOOP_PRE, OMPT_LOOP_POST) PARALLEL_LOOP_START( KMP_EXPAND_NAME(KMP_API_NAME_GOMP_PARALLEL_LOOP_DYNAMIC_START), kmp_sch_dynamic_chunked, OMPT_LOOP_PRE, OMPT_LOOP_POST) PARALLEL_LOOP_START( KMP_EXPAND_NAME(KMP_API_NAME_GOMP_PARALLEL_LOOP_GUIDED_START), kmp_sch_guided_chunked, OMPT_LOOP_PRE, OMPT_LOOP_POST) PARALLEL_LOOP_START( KMP_EXPAND_NAME(KMP_API_NAME_GOMP_PARALLEL_LOOP_RUNTIME_START), kmp_sch_runtime, OMPT_LOOP_PRE, OMPT_LOOP_POST) // Tasking constructs void KMP_EXPAND_NAME(KMP_API_NAME_GOMP_TASK)(void (*func)(void *), void *data, void (*copy_func)(void *, void *), long arg_size, long arg_align, bool if_cond, unsigned gomp_flags, void **depend) { MKLOC(loc, "GOMP_task"); int gtid = __kmp_entry_gtid(); kmp_int32 flags = 0; kmp_tasking_flags_t *input_flags = (kmp_tasking_flags_t *)&flags; KA_TRACE(20, ("GOMP_task: T#%d\n", gtid)); // The low-order bit is the "untied" flag if (!(gomp_flags & 1)) { input_flags->tiedness = 1; } // The second low-order bit is the "final" flag if (gomp_flags & 2) { input_flags->final = 1; } input_flags->native = 1; // __kmp_task_alloc() sets up all other flags if (!if_cond) { arg_size = 0; } kmp_task_t *task = __kmp_task_alloc( &loc, gtid, input_flags, sizeof(kmp_task_t), arg_size ? arg_size + arg_align - 1 : 0, (kmp_routine_entry_t)func); if (arg_size > 0) { if (arg_align > 0) { task->shareds = (void *)((((size_t)task->shareds) + arg_align - 1) / arg_align * arg_align); } // else error?? if (copy_func) { (*copy_func)(task->shareds, data); } else { KMP_MEMCPY(task->shareds, data, arg_size); } } #if OMPT_SUPPORT kmp_taskdata_t *current_task; if (ompt_enabled.enabled) { OMPT_STORE_RETURN_ADDRESS(gtid); current_task = __kmp_threads[gtid]->th.th_current_task; current_task->ompt_task_info.frame.enter_frame.ptr = OMPT_GET_FRAME_ADDRESS(0); } #endif if (if_cond) { if (gomp_flags & 8) { KMP_ASSERT(depend); const size_t ndeps = (kmp_intptr_t)depend[0]; const size_t nout = (kmp_intptr_t)depend[1]; kmp_depend_info_t dep_list[ndeps]; for (size_t i = 0U; i < ndeps; i++) { dep_list[i].base_addr = (kmp_intptr_t)depend[2U + i]; dep_list[i].len = 0U; dep_list[i].flags.in = 1; dep_list[i].flags.out = (i < nout); } __kmpc_omp_task_with_deps(&loc, gtid, task, ndeps, dep_list, 0, NULL); } else { __kmpc_omp_task(&loc, gtid, task); } } else { #if OMPT_SUPPORT ompt_thread_info_t oldInfo; kmp_info_t *thread; kmp_taskdata_t *taskdata; if (ompt_enabled.enabled) { // Store the threads states and restore them after the task thread = __kmp_threads[gtid]; taskdata = KMP_TASK_TO_TASKDATA(task); oldInfo = thread->th.ompt_thread_info; thread->th.ompt_thread_info.wait_id = 0; thread->th.ompt_thread_info.state = ompt_state_work_parallel; taskdata->ompt_task_info.frame.exit_frame.ptr = OMPT_GET_FRAME_ADDRESS(0); OMPT_STORE_RETURN_ADDRESS(gtid); } #endif __kmpc_omp_task_begin_if0(&loc, gtid, task); func(data); __kmpc_omp_task_complete_if0(&loc, gtid, task); #if OMPT_SUPPORT if (ompt_enabled.enabled) { thread->th.ompt_thread_info = oldInfo; taskdata->ompt_task_info.frame.exit_frame = ompt_data_none; } #endif } #if OMPT_SUPPORT if (ompt_enabled.enabled) { current_task->ompt_task_info.frame.enter_frame = ompt_data_none; } #endif KA_TRACE(20, ("GOMP_task exit: T#%d\n", gtid)); } void KMP_EXPAND_NAME(KMP_API_NAME_GOMP_TASKWAIT)(void) { MKLOC(loc, "GOMP_taskwait"); int gtid = __kmp_entry_gtid(); #if OMPT_SUPPORT if (ompt_enabled.enabled) OMPT_STORE_RETURN_ADDRESS(gtid); #endif KA_TRACE(20, ("GOMP_taskwait: T#%d\n", gtid)); __kmpc_omp_taskwait(&loc, gtid); KA_TRACE(20, ("GOMP_taskwait exit: T#%d\n", gtid)); } // Sections worksharing constructs // // For the sections construct, we initialize a dynamically scheduled loop // worksharing construct with lb 1 and stride 1, and use the iteration #'s // that its returns as sections ids. // // There are no special entry points for ordered sections, so we always use // the dynamically scheduled workshare, even if the sections aren't ordered. unsigned KMP_EXPAND_NAME(KMP_API_NAME_GOMP_SECTIONS_START)(unsigned count) { int status; kmp_int lb, ub, stride; int gtid = __kmp_entry_gtid(); MKLOC(loc, "GOMP_sections_start"); KA_TRACE(20, ("GOMP_sections_start: T#%d\n", gtid)); KMP_DISPATCH_INIT(&loc, gtid, kmp_nm_dynamic_chunked, 1, count, 1, 1, TRUE); status = KMP_DISPATCH_NEXT(&loc, gtid, NULL, &lb, &ub, &stride); if (status) { KMP_DEBUG_ASSERT(stride == 1); KMP_DEBUG_ASSERT(lb > 0); KMP_ASSERT(lb == ub); } else { lb = 0; } KA_TRACE(20, ("GOMP_sections_start exit: T#%d returning %u\n", gtid, (unsigned)lb)); return (unsigned)lb; } unsigned KMP_EXPAND_NAME(KMP_API_NAME_GOMP_SECTIONS_NEXT)(void) { int status; kmp_int lb, ub, stride; int gtid = __kmp_get_gtid(); MKLOC(loc, "GOMP_sections_next"); KA_TRACE(20, ("GOMP_sections_next: T#%d\n", gtid)); #if OMPT_SUPPORT OMPT_STORE_RETURN_ADDRESS(gtid); #endif status = KMP_DISPATCH_NEXT(&loc, gtid, NULL, &lb, &ub, &stride); if (status) { KMP_DEBUG_ASSERT(stride == 1); KMP_DEBUG_ASSERT(lb > 0); KMP_ASSERT(lb == ub); } else { lb = 0; } KA_TRACE( 20, ("GOMP_sections_next exit: T#%d returning %u\n", gtid, (unsigned)lb)); return (unsigned)lb; } void KMP_EXPAND_NAME(KMP_API_NAME_GOMP_PARALLEL_SECTIONS_START)( void (*task)(void *), void *data, unsigned num_threads, unsigned count) { int gtid = __kmp_entry_gtid(); #if OMPT_SUPPORT ompt_frame_t *parent_frame; if (ompt_enabled.enabled) { __ompt_get_task_info_internal(0, NULL, NULL, &parent_frame, NULL, NULL); parent_frame->enter_frame.ptr = OMPT_GET_FRAME_ADDRESS(0); OMPT_STORE_RETURN_ADDRESS(gtid); } #endif MKLOC(loc, "GOMP_parallel_sections_start"); KA_TRACE(20, ("GOMP_parallel_sections_start: T#%d\n", gtid)); if (__kmpc_ok_to_fork(&loc) && (num_threads != 1)) { if (num_threads != 0) { __kmp_push_num_threads(&loc, gtid, num_threads); } __kmp_GOMP_fork_call(&loc, gtid, task, (microtask_t)__kmp_GOMP_parallel_microtask_wrapper, 9, task, data, num_threads, &loc, kmp_nm_dynamic_chunked, (kmp_int)1, (kmp_int)count, (kmp_int)1, (kmp_int)1); } else { __kmp_GOMP_serialized_parallel(&loc, gtid, task); } #if OMPT_SUPPORT if (ompt_enabled.enabled) { parent_frame->enter_frame = ompt_data_none; } #endif KMP_DISPATCH_INIT(&loc, gtid, kmp_nm_dynamic_chunked, 1, count, 1, 1, TRUE); KA_TRACE(20, ("GOMP_parallel_sections_start exit: T#%d\n", gtid)); } void KMP_EXPAND_NAME(KMP_API_NAME_GOMP_SECTIONS_END)(void) { int gtid = __kmp_get_gtid(); KA_TRACE(20, ("GOMP_sections_end: T#%d\n", gtid)) #if OMPT_SUPPORT ompt_frame_t *ompt_frame; if (ompt_enabled.enabled) { __ompt_get_task_info_internal(0, NULL, NULL, &ompt_frame, NULL, NULL); ompt_frame->enter_frame.ptr = OMPT_GET_FRAME_ADDRESS(0); OMPT_STORE_RETURN_ADDRESS(gtid); } #endif __kmp_barrier(bs_plain_barrier, gtid, FALSE, 0, NULL, NULL); #if OMPT_SUPPORT if (ompt_enabled.enabled) { ompt_frame->enter_frame = ompt_data_none; } #endif KA_TRACE(20, ("GOMP_sections_end exit: T#%d\n", gtid)) } void KMP_EXPAND_NAME(KMP_API_NAME_GOMP_SECTIONS_END_NOWAIT)(void) { KA_TRACE(20, ("GOMP_sections_end_nowait: T#%d\n", __kmp_get_gtid())) } // libgomp has an empty function for GOMP_taskyield as of 2013-10-10 void KMP_EXPAND_NAME(KMP_API_NAME_GOMP_TASKYIELD)(void) { KA_TRACE(20, ("GOMP_taskyield: T#%d\n", __kmp_get_gtid())) return; } void KMP_EXPAND_NAME(KMP_API_NAME_GOMP_PARALLEL)(void (*task)(void *), void *data, unsigned num_threads, unsigned int flags) { int gtid = __kmp_entry_gtid(); MKLOC(loc, "GOMP_parallel"); KA_TRACE(20, ("GOMP_parallel: T#%d\n", gtid)); #if OMPT_SUPPORT ompt_task_info_t *parent_task_info, *task_info; if (ompt_enabled.enabled) { parent_task_info = __ompt_get_task_info_object(0); parent_task_info->frame.enter_frame.ptr = OMPT_GET_FRAME_ADDRESS(0); OMPT_STORE_RETURN_ADDRESS(gtid); } #endif if (__kmpc_ok_to_fork(&loc) && (num_threads != 1)) { if (num_threads != 0) { __kmp_push_num_threads(&loc, gtid, num_threads); } if (flags != 0) { __kmp_push_proc_bind(&loc, gtid, (kmp_proc_bind_t)flags); } __kmp_GOMP_fork_call(&loc, gtid, task, (microtask_t)__kmp_GOMP_microtask_wrapper, 2, task, data); } else { __kmp_GOMP_serialized_parallel(&loc, gtid, task); } #if OMPT_SUPPORT if (ompt_enabled.enabled) { task_info = __ompt_get_task_info_object(0); task_info->frame.exit_frame.ptr = OMPT_GET_FRAME_ADDRESS(0); } #endif task(data); #if OMPT_SUPPORT if (ompt_enabled.enabled) { OMPT_STORE_RETURN_ADDRESS(gtid); } #endif KMP_EXPAND_NAME(KMP_API_NAME_GOMP_PARALLEL_END)(); #if OMPT_SUPPORT if (ompt_enabled.enabled) { task_info->frame.exit_frame = ompt_data_none; parent_task_info->frame.enter_frame = ompt_data_none; } #endif } void KMP_EXPAND_NAME(KMP_API_NAME_GOMP_PARALLEL_SECTIONS)(void (*task)(void *), void *data, unsigned num_threads, unsigned count, unsigned flags) { int gtid = __kmp_entry_gtid(); MKLOC(loc, "GOMP_parallel_sections"); KA_TRACE(20, ("GOMP_parallel_sections: T#%d\n", gtid)); #if OMPT_SUPPORT OMPT_STORE_RETURN_ADDRESS(gtid); #endif if (__kmpc_ok_to_fork(&loc) && (num_threads != 1)) { if (num_threads != 0) { __kmp_push_num_threads(&loc, gtid, num_threads); } if (flags != 0) { __kmp_push_proc_bind(&loc, gtid, (kmp_proc_bind_t)flags); } __kmp_GOMP_fork_call(&loc, gtid, task, (microtask_t)__kmp_GOMP_parallel_microtask_wrapper, 9, task, data, num_threads, &loc, kmp_nm_dynamic_chunked, (kmp_int)1, (kmp_int)count, (kmp_int)1, (kmp_int)1); } else { __kmp_GOMP_serialized_parallel(&loc, gtid, task); } #if OMPT_SUPPORT OMPT_STORE_RETURN_ADDRESS(gtid); #endif KMP_DISPATCH_INIT(&loc, gtid, kmp_nm_dynamic_chunked, 1, count, 1, 1, TRUE); task(data); KMP_EXPAND_NAME(KMP_API_NAME_GOMP_PARALLEL_END)(); KA_TRACE(20, ("GOMP_parallel_sections exit: T#%d\n", gtid)); } #define PARALLEL_LOOP(func, schedule, ompt_pre, ompt_post) \ void func(void (*task)(void *), void *data, unsigned num_threads, long lb, \ long ub, long str, long chunk_sz, unsigned flags) { \ int gtid = __kmp_entry_gtid(); \ MKLOC(loc, KMP_STR(func)); \ KA_TRACE( \ 20, \ (KMP_STR( \ func) ": T#%d, lb 0x%lx, ub 0x%lx, str 0x%lx, chunk_sz 0x%lx\n", \ gtid, lb, ub, str, chunk_sz)); \ \ ompt_pre(); \ if (__kmpc_ok_to_fork(&loc) && (num_threads != 1)) { \ if (num_threads != 0) { \ __kmp_push_num_threads(&loc, gtid, num_threads); \ } \ if (flags != 0) { \ __kmp_push_proc_bind(&loc, gtid, (kmp_proc_bind_t)flags); \ } \ __kmp_GOMP_fork_call(&loc, gtid, task, \ (microtask_t)__kmp_GOMP_parallel_microtask_wrapper, \ 9, task, data, num_threads, &loc, (schedule), lb, \ (str > 0) ? (ub - 1) : (ub + 1), str, chunk_sz); \ } else { \ __kmp_GOMP_serialized_parallel(&loc, gtid, task); \ } \ \ IF_OMPT_SUPPORT(OMPT_STORE_RETURN_ADDRESS(gtid);) \ KMP_DISPATCH_INIT(&loc, gtid, (schedule), lb, \ (str > 0) ? (ub - 1) : (ub + 1), str, chunk_sz, \ (schedule) != kmp_sch_static); \ task(data); \ KMP_EXPAND_NAME(KMP_API_NAME_GOMP_PARALLEL_END)(); \ ompt_post(); \ \ KA_TRACE(20, (KMP_STR(func) " exit: T#%d\n", gtid)); \ } PARALLEL_LOOP(KMP_EXPAND_NAME(KMP_API_NAME_GOMP_PARALLEL_LOOP_STATIC), kmp_sch_static, OMPT_LOOP_PRE, OMPT_LOOP_POST) PARALLEL_LOOP(KMP_EXPAND_NAME(KMP_API_NAME_GOMP_PARALLEL_LOOP_DYNAMIC), kmp_sch_dynamic_chunked, OMPT_LOOP_PRE, OMPT_LOOP_POST) PARALLEL_LOOP( KMP_EXPAND_NAME(KMP_API_NAME_GOMP_PARALLEL_LOOP_NONMONOTONIC_GUIDED), kmp_sch_guided_chunked, OMPT_LOOP_PRE, OMPT_LOOP_POST) PARALLEL_LOOP( KMP_EXPAND_NAME(KMP_API_NAME_GOMP_PARALLEL_LOOP_NONMONOTONIC_DYNAMIC), kmp_sch_dynamic_chunked, OMPT_LOOP_PRE, OMPT_LOOP_POST) PARALLEL_LOOP(KMP_EXPAND_NAME(KMP_API_NAME_GOMP_PARALLEL_LOOP_GUIDED), kmp_sch_guided_chunked, OMPT_LOOP_PRE, OMPT_LOOP_POST) PARALLEL_LOOP(KMP_EXPAND_NAME(KMP_API_NAME_GOMP_PARALLEL_LOOP_RUNTIME), kmp_sch_runtime, OMPT_LOOP_PRE, OMPT_LOOP_POST) PARALLEL_LOOP( KMP_EXPAND_NAME(KMP_API_NAME_GOMP_PARALLEL_LOOP_MAYBE_NONMONOTONIC_RUNTIME), kmp_sch_runtime, OMPT_LOOP_PRE, OMPT_LOOP_POST) PARALLEL_LOOP( KMP_EXPAND_NAME(KMP_API_NAME_GOMP_PARALLEL_LOOP_NONMONOTONIC_RUNTIME), kmp_sch_runtime, OMPT_LOOP_PRE, OMPT_LOOP_POST) void KMP_EXPAND_NAME(KMP_API_NAME_GOMP_TASKGROUP_START)(void) { int gtid = __kmp_entry_gtid(); MKLOC(loc, "GOMP_taskgroup_start"); KA_TRACE(20, ("GOMP_taskgroup_start: T#%d\n", gtid)); #if OMPT_SUPPORT if (ompt_enabled.enabled) OMPT_STORE_RETURN_ADDRESS(gtid); #endif __kmpc_taskgroup(&loc, gtid); return; } void KMP_EXPAND_NAME(KMP_API_NAME_GOMP_TASKGROUP_END)(void) { int gtid = __kmp_get_gtid(); MKLOC(loc, "GOMP_taskgroup_end"); KA_TRACE(20, ("GOMP_taskgroup_end: T#%d\n", gtid)); #if OMPT_SUPPORT if (ompt_enabled.enabled) OMPT_STORE_RETURN_ADDRESS(gtid); #endif __kmpc_end_taskgroup(&loc, gtid); return; } static kmp_int32 __kmp_gomp_to_omp_cancellation_kind(int gomp_kind) { kmp_int32 cncl_kind = 0; switch (gomp_kind) { case 1: cncl_kind = cancel_parallel; break; case 2: cncl_kind = cancel_loop; break; case 4: cncl_kind = cancel_sections; break; case 8: cncl_kind = cancel_taskgroup; break; } return cncl_kind; } // Return true if cancellation should take place, false otherwise bool KMP_EXPAND_NAME(KMP_API_NAME_GOMP_CANCELLATION_POINT)(int which) { int gtid = __kmp_get_gtid(); MKLOC(loc, "GOMP_cancellation_point"); KA_TRACE(20, ("GOMP_cancellation_point: T#%d which:%d\n", gtid, which)); kmp_int32 cncl_kind = __kmp_gomp_to_omp_cancellation_kind(which); return __kmpc_cancellationpoint(&loc, gtid, cncl_kind); } // Return true if cancellation should take place, false otherwise bool KMP_EXPAND_NAME(KMP_API_NAME_GOMP_CANCEL)(int which, bool do_cancel) { int gtid = __kmp_get_gtid(); MKLOC(loc, "GOMP_cancel"); KA_TRACE(20, ("GOMP_cancel: T#%d which:%d do_cancel:%d\n", gtid, which, (int)do_cancel)); kmp_int32 cncl_kind = __kmp_gomp_to_omp_cancellation_kind(which); if (do_cancel == FALSE) { return __kmpc_cancellationpoint(&loc, gtid, cncl_kind); } else { return __kmpc_cancel(&loc, gtid, cncl_kind); } } // Return true if cancellation should take place, false otherwise bool KMP_EXPAND_NAME(KMP_API_NAME_GOMP_BARRIER_CANCEL)(void) { int gtid = __kmp_get_gtid(); KA_TRACE(20, ("GOMP_barrier_cancel: T#%d\n", gtid)); return __kmp_barrier_gomp_cancel(gtid); } // Return true if cancellation should take place, false otherwise bool KMP_EXPAND_NAME(KMP_API_NAME_GOMP_SECTIONS_END_CANCEL)(void) { int gtid = __kmp_get_gtid(); KA_TRACE(20, ("GOMP_sections_end_cancel: T#%d\n", gtid)); return __kmp_barrier_gomp_cancel(gtid); } // Return true if cancellation should take place, false otherwise bool KMP_EXPAND_NAME(KMP_API_NAME_GOMP_LOOP_END_CANCEL)(void) { int gtid = __kmp_get_gtid(); KA_TRACE(20, ("GOMP_loop_end_cancel: T#%d\n", gtid)); return __kmp_barrier_gomp_cancel(gtid); } // All target functions are empty as of 2014-05-29 void KMP_EXPAND_NAME(KMP_API_NAME_GOMP_TARGET)(int device, void (*fn)(void *), const void *openmp_target, size_t mapnum, void **hostaddrs, size_t *sizes, unsigned char *kinds) { return; } void KMP_EXPAND_NAME(KMP_API_NAME_GOMP_TARGET_DATA)( int device, const void *openmp_target, size_t mapnum, void **hostaddrs, size_t *sizes, unsigned char *kinds) { return; } void KMP_EXPAND_NAME(KMP_API_NAME_GOMP_TARGET_END_DATA)(void) { return; } void KMP_EXPAND_NAME(KMP_API_NAME_GOMP_TARGET_UPDATE)( int device, const void *openmp_target, size_t mapnum, void **hostaddrs, size_t *sizes, unsigned char *kinds) { return; } void KMP_EXPAND_NAME(KMP_API_NAME_GOMP_TEAMS)(unsigned int num_teams, unsigned int thread_limit) { return; } // Task duplication function which copies src to dest (both are // preallocated task structures) static void __kmp_gomp_task_dup(kmp_task_t *dest, kmp_task_t *src, kmp_int32 last_private) { kmp_taskdata_t *taskdata = KMP_TASK_TO_TASKDATA(src); if (taskdata->td_copy_func) { (taskdata->td_copy_func)(dest->shareds, src->shareds); } } #ifdef __cplusplus } // extern "C" #endif template void __GOMP_taskloop(void (*func)(void *), void *data, void (*copy_func)(void *, void *), long arg_size, long arg_align, unsigned gomp_flags, unsigned long num_tasks, int priority, T start, T end, T step) { typedef void (*p_task_dup_t)(kmp_task_t *, kmp_task_t *, kmp_int32); MKLOC(loc, "GOMP_taskloop"); int sched; T *loop_bounds; int gtid = __kmp_entry_gtid(); kmp_int32 flags = 0; int if_val = gomp_flags & (1u << 10); int nogroup = gomp_flags & (1u << 11); int up = gomp_flags & (1u << 8); p_task_dup_t task_dup = NULL; kmp_tasking_flags_t *input_flags = (kmp_tasking_flags_t *)&flags; #ifdef KMP_DEBUG { char *buff; buff = __kmp_str_format( "GOMP_taskloop: T#%%d: func:%%p data:%%p copy_func:%%p " "arg_size:%%ld arg_align:%%ld gomp_flags:0x%%x num_tasks:%%lu " "priority:%%d start:%%%s end:%%%s step:%%%s\n", traits_t::spec, traits_t::spec, traits_t::spec); KA_TRACE(20, (buff, gtid, func, data, copy_func, arg_size, arg_align, gomp_flags, num_tasks, priority, start, end, step)); __kmp_str_free(&buff); } #endif KMP_ASSERT((size_t)arg_size >= 2 * sizeof(T)); KMP_ASSERT(arg_align > 0); // The low-order bit is the "untied" flag if (!(gomp_flags & 1)) { input_flags->tiedness = 1; } // The second low-order bit is the "final" flag if (gomp_flags & 2) { input_flags->final = 1; } // Negative step flag if (!up) { // If step is flagged as negative, but isn't properly sign extended // Then manually sign extend it. Could be a short, int, char embedded // in a long. So cannot assume any cast. if (step > 0) { for (int i = sizeof(T) * CHAR_BIT - 1; i >= 0L; --i) { // break at the first 1 bit if (step & ((T)1 << i)) break; step |= ((T)1 << i); } } } input_flags->native = 1; // Figure out if none/grainsize/num_tasks clause specified if (num_tasks > 0) { if (gomp_flags & (1u << 9)) sched = 1; // grainsize specified else sched = 2; // num_tasks specified // neither grainsize nor num_tasks specified } else { sched = 0; } // __kmp_task_alloc() sets up all other flags kmp_task_t *task = __kmp_task_alloc(&loc, gtid, input_flags, sizeof(kmp_task_t), arg_size + arg_align - 1, (kmp_routine_entry_t)func); kmp_taskdata_t *taskdata = KMP_TASK_TO_TASKDATA(task); taskdata->td_copy_func = copy_func; taskdata->td_size_loop_bounds = sizeof(T); // re-align shareds if needed and setup firstprivate copy constructors // through the task_dup mechanism task->shareds = (void *)((((size_t)task->shareds) + arg_align - 1) / arg_align * arg_align); if (copy_func) { task_dup = __kmp_gomp_task_dup; } KMP_MEMCPY(task->shareds, data, arg_size); loop_bounds = (T *)task->shareds; loop_bounds[0] = start; loop_bounds[1] = end + (up ? -1 : 1); __kmpc_taskloop(&loc, gtid, task, if_val, (kmp_uint64 *)&(loop_bounds[0]), (kmp_uint64 *)&(loop_bounds[1]), (kmp_int64)step, nogroup, sched, (kmp_uint64)num_tasks, (void *)task_dup); } // 4 byte version of GOMP_doacross_post // This verison needs to create a temporary array which converts 4 byte // integers into 8 byte integers template void __kmp_GOMP_doacross_post(T *count); template <> void __kmp_GOMP_doacross_post(long *count) { int gtid = __kmp_entry_gtid(); kmp_info_t *th = __kmp_threads[gtid]; MKLOC(loc, "GOMP_doacross_post"); kmp_int64 num_dims = th->th.th_dispatch->th_doacross_info[0]; kmp_int64 *vec = (kmp_int64 *)__kmp_thread_malloc(th, sizeof(kmp_int64) * num_dims); for (kmp_int64 i = 0; i < num_dims; ++i) { vec[i] = (kmp_int64)count[i]; } __kmpc_doacross_post(&loc, gtid, vec); __kmp_thread_free(th, vec); } // 8 byte versions of GOMP_doacross_post // This version can just pass in the count array directly instead of creating // a temporary array template <> void __kmp_GOMP_doacross_post(long *count) { int gtid = __kmp_entry_gtid(); MKLOC(loc, "GOMP_doacross_post"); __kmpc_doacross_post(&loc, gtid, RCAST(kmp_int64 *, count)); } template void __kmp_GOMP_doacross_wait(T first, va_list args) { int gtid = __kmp_entry_gtid(); kmp_info_t *th = __kmp_threads[gtid]; MKLOC(loc, "GOMP_doacross_wait"); kmp_int64 num_dims = th->th.th_dispatch->th_doacross_info[0]; kmp_int64 *vec = (kmp_int64 *)__kmp_thread_malloc(th, sizeof(kmp_int64) * num_dims); vec[0] = (kmp_int64)first; for (kmp_int64 i = 1; i < num_dims; ++i) { T item = va_arg(args, T); vec[i] = (kmp_int64)item; } __kmpc_doacross_wait(&loc, gtid, vec); __kmp_thread_free(th, vec); return; } #ifdef __cplusplus extern "C" { #endif // __cplusplus void KMP_EXPAND_NAME(KMP_API_NAME_GOMP_TASKLOOP)( void (*func)(void *), void *data, void (*copy_func)(void *, void *), long arg_size, long arg_align, unsigned gomp_flags, unsigned long num_tasks, int priority, long start, long end, long step) { __GOMP_taskloop(func, data, copy_func, arg_size, arg_align, gomp_flags, num_tasks, priority, start, end, step); } void KMP_EXPAND_NAME(KMP_API_NAME_GOMP_TASKLOOP_ULL)( void (*func)(void *), void *data, void (*copy_func)(void *, void *), long arg_size, long arg_align, unsigned gomp_flags, unsigned long num_tasks, int priority, unsigned long long start, unsigned long long end, unsigned long long step) { __GOMP_taskloop(func, data, copy_func, arg_size, arg_align, gomp_flags, num_tasks, priority, start, end, step); } void KMP_EXPAND_NAME(KMP_API_NAME_GOMP_DOACROSS_POST)(long *count) { __kmp_GOMP_doacross_post(count); } void KMP_EXPAND_NAME(KMP_API_NAME_GOMP_DOACROSS_WAIT)(long first, ...) { va_list args; va_start(args, first); __kmp_GOMP_doacross_wait(first, args); va_end(args); } void KMP_EXPAND_NAME(KMP_API_NAME_GOMP_DOACROSS_ULL_POST)( unsigned long long *count) { int gtid = __kmp_entry_gtid(); MKLOC(loc, "GOMP_doacross_ull_post"); __kmpc_doacross_post(&loc, gtid, RCAST(kmp_int64 *, count)); } void KMP_EXPAND_NAME(KMP_API_NAME_GOMP_DOACROSS_ULL_WAIT)( unsigned long long first, ...) { va_list args; va_start(args, first); __kmp_GOMP_doacross_wait(first, args); va_end(args); } /* The following sections of code create aliases for the GOMP_* functions, then create versioned symbols using the assembler directive .symver. This is only pertinent for ELF .so library. The KMP_VERSION_SYMBOL macro is defined in kmp_os.h */ #ifdef KMP_USE_VERSION_SYMBOLS // GOMP_1.0 versioned symbols KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_ATOMIC_END, 10, "GOMP_1.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_ATOMIC_START, 10, "GOMP_1.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_BARRIER, 10, "GOMP_1.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_CRITICAL_END, 10, "GOMP_1.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_CRITICAL_NAME_END, 10, "GOMP_1.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_CRITICAL_NAME_START, 10, "GOMP_1.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_CRITICAL_START, 10, "GOMP_1.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_DYNAMIC_NEXT, 10, "GOMP_1.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_DYNAMIC_START, 10, "GOMP_1.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_END, 10, "GOMP_1.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_END_NOWAIT, 10, "GOMP_1.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_GUIDED_NEXT, 10, "GOMP_1.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_GUIDED_START, 10, "GOMP_1.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_ORDERED_DYNAMIC_NEXT, 10, "GOMP_1.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_ORDERED_DYNAMIC_START, 10, "GOMP_1.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_ORDERED_GUIDED_NEXT, 10, "GOMP_1.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_ORDERED_GUIDED_START, 10, "GOMP_1.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_ORDERED_RUNTIME_NEXT, 10, "GOMP_1.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_ORDERED_RUNTIME_START, 10, "GOMP_1.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_ORDERED_STATIC_NEXT, 10, "GOMP_1.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_ORDERED_STATIC_START, 10, "GOMP_1.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_RUNTIME_NEXT, 10, "GOMP_1.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_RUNTIME_START, 10, "GOMP_1.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_STATIC_NEXT, 10, "GOMP_1.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_STATIC_START, 10, "GOMP_1.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_ORDERED_END, 10, "GOMP_1.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_ORDERED_START, 10, "GOMP_1.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_PARALLEL_END, 10, "GOMP_1.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_PARALLEL_LOOP_DYNAMIC_START, 10, "GOMP_1.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_PARALLEL_LOOP_GUIDED_START, 10, "GOMP_1.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_PARALLEL_LOOP_RUNTIME_START, 10, "GOMP_1.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_PARALLEL_LOOP_STATIC_START, 10, "GOMP_1.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_PARALLEL_SECTIONS_START, 10, "GOMP_1.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_PARALLEL_START, 10, "GOMP_1.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_SECTIONS_END, 10, "GOMP_1.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_SECTIONS_END_NOWAIT, 10, "GOMP_1.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_SECTIONS_NEXT, 10, "GOMP_1.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_SECTIONS_START, 10, "GOMP_1.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_SINGLE_COPY_END, 10, "GOMP_1.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_SINGLE_COPY_START, 10, "GOMP_1.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_SINGLE_START, 10, "GOMP_1.0"); // GOMP_2.0 versioned symbols KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_TASK, 20, "GOMP_2.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_TASKWAIT, 20, "GOMP_2.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_ULL_DYNAMIC_NEXT, 20, "GOMP_2.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_ULL_DYNAMIC_START, 20, "GOMP_2.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_ULL_GUIDED_NEXT, 20, "GOMP_2.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_ULL_GUIDED_START, 20, "GOMP_2.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_ULL_ORDERED_DYNAMIC_NEXT, 20, "GOMP_2.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_ULL_ORDERED_DYNAMIC_START, 20, "GOMP_2.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_ULL_ORDERED_GUIDED_NEXT, 20, "GOMP_2.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_ULL_ORDERED_GUIDED_START, 20, "GOMP_2.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_ULL_ORDERED_RUNTIME_NEXT, 20, "GOMP_2.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_ULL_ORDERED_RUNTIME_START, 20, "GOMP_2.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_ULL_ORDERED_STATIC_NEXT, 20, "GOMP_2.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_ULL_ORDERED_STATIC_START, 20, "GOMP_2.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_ULL_RUNTIME_NEXT, 20, "GOMP_2.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_ULL_RUNTIME_START, 20, "GOMP_2.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_ULL_STATIC_NEXT, 20, "GOMP_2.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_ULL_STATIC_START, 20, "GOMP_2.0"); // GOMP_3.0 versioned symbols KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_TASKYIELD, 30, "GOMP_3.0"); // GOMP_4.0 versioned symbols KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_PARALLEL, 40, "GOMP_4.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_PARALLEL_SECTIONS, 40, "GOMP_4.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_PARALLEL_LOOP_DYNAMIC, 40, "GOMP_4.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_PARALLEL_LOOP_GUIDED, 40, "GOMP_4.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_PARALLEL_LOOP_RUNTIME, 40, "GOMP_4.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_PARALLEL_LOOP_STATIC, 40, "GOMP_4.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_TASKGROUP_START, 40, "GOMP_4.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_TASKGROUP_END, 40, "GOMP_4.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_BARRIER_CANCEL, 40, "GOMP_4.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_CANCEL, 40, "GOMP_4.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_CANCELLATION_POINT, 40, "GOMP_4.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_END_CANCEL, 40, "GOMP_4.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_SECTIONS_END_CANCEL, 40, "GOMP_4.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_TARGET, 40, "GOMP_4.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_TARGET_DATA, 40, "GOMP_4.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_TARGET_END_DATA, 40, "GOMP_4.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_TARGET_UPDATE, 40, "GOMP_4.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_TEAMS, 40, "GOMP_4.0"); // GOMP_4.5 versioned symbols KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_TASKLOOP, 45, "GOMP_4.5"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_TASKLOOP_ULL, 45, "GOMP_4.5"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_DOACROSS_POST, 45, "GOMP_4.5"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_DOACROSS_WAIT, 45, "GOMP_4.5"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_DOACROSS_STATIC_START, 45, "GOMP_4.5"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_DOACROSS_DYNAMIC_START, 45, "GOMP_4.5"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_DOACROSS_GUIDED_START, 45, "GOMP_4.5"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_DOACROSS_RUNTIME_START, 45, "GOMP_4.5"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_DOACROSS_ULL_POST, 45, "GOMP_4.5"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_DOACROSS_ULL_WAIT, 45, "GOMP_4.5"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_ULL_DOACROSS_STATIC_START, 45, "GOMP_4.5"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_ULL_DOACROSS_DYNAMIC_START, 45, "GOMP_4.5"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_ULL_DOACROSS_GUIDED_START, 45, "GOMP_4.5"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_ULL_DOACROSS_RUNTIME_START, 45, "GOMP_4.5"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_NONMONOTONIC_DYNAMIC_START, 45, "GOMP_4.5"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_NONMONOTONIC_DYNAMIC_NEXT, 45, "GOMP_4.5"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_NONMONOTONIC_GUIDED_START, 45, "GOMP_4.5"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_NONMONOTONIC_GUIDED_NEXT, 45, "GOMP_4.5"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_ULL_NONMONOTONIC_DYNAMIC_START, 45, "GOMP_4.5"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_ULL_NONMONOTONIC_DYNAMIC_NEXT, 45, "GOMP_4.5"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_ULL_NONMONOTONIC_GUIDED_START, 45, "GOMP_4.5"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_ULL_NONMONOTONIC_GUIDED_NEXT, 45, "GOMP_4.5"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_PARALLEL_LOOP_NONMONOTONIC_DYNAMIC, 45, "GOMP_4.5"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_PARALLEL_LOOP_NONMONOTONIC_GUIDED, 45, "GOMP_4.5"); // GOMP_5.0 versioned symbols KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_MAYBE_NONMONOTONIC_RUNTIME_NEXT, 50, "GOMP_5.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_MAYBE_NONMONOTONIC_RUNTIME_START, 50, "GOMP_5.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_NONMONOTONIC_RUNTIME_NEXT, 50, "GOMP_5.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_NONMONOTONIC_RUNTIME_START, 50, "GOMP_5.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_ULL_MAYBE_NONMONOTONIC_RUNTIME_NEXT, 50, "GOMP_5.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_ULL_MAYBE_NONMONOTONIC_RUNTIME_START, 50, "GOMP_5.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_ULL_NONMONOTONIC_RUNTIME_NEXT, 50, "GOMP_5.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_LOOP_ULL_NONMONOTONIC_RUNTIME_START, 50, "GOMP_5.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_PARALLEL_LOOP_NONMONOTONIC_RUNTIME, 50, "GOMP_5.0"); KMP_VERSION_SYMBOL(KMP_API_NAME_GOMP_PARALLEL_LOOP_MAYBE_NONMONOTONIC_RUNTIME, 50, "GOMP_5.0"); #endif // KMP_USE_VERSION_SYMBOLS #ifdef __cplusplus } // extern "C" #endif // __cplusplus Index: head/contrib/llvm-project/openmp/runtime/src/kmp_os.h =================================================================== --- head/contrib/llvm-project/openmp/runtime/src/kmp_os.h (revision 364731) +++ head/contrib/llvm-project/openmp/runtime/src/kmp_os.h (revision 364732) @@ -1,1047 +1,1059 @@ /* * kmp_os.h -- KPTS runtime header file. */ //===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #ifndef KMP_OS_H #define KMP_OS_H #include "kmp_config.h" #include #include #define KMP_FTN_PLAIN 1 #define KMP_FTN_APPEND 2 #define KMP_FTN_UPPER 3 /* #define KMP_FTN_PREPEND 4 #define KMP_FTN_UAPPEND 5 */ #define KMP_PTR_SKIP (sizeof(void *)) /* -------------------------- Compiler variations ------------------------ */ #define KMP_OFF 0 #define KMP_ON 1 #define KMP_MEM_CONS_VOLATILE 0 #define KMP_MEM_CONS_FENCE 1 #ifndef KMP_MEM_CONS_MODEL #define KMP_MEM_CONS_MODEL KMP_MEM_CONS_VOLATILE #endif #ifndef __has_cpp_attribute #define __has_cpp_attribute(x) 0 #endif #ifndef __has_attribute #define __has_attribute(x) 0 #endif /* ------------------------- Compiler recognition ---------------------- */ #define KMP_COMPILER_ICC 0 #define KMP_COMPILER_GCC 0 #define KMP_COMPILER_CLANG 0 #define KMP_COMPILER_MSVC 0 #if defined(__INTEL_COMPILER) #undef KMP_COMPILER_ICC #define KMP_COMPILER_ICC 1 #elif defined(__clang__) #undef KMP_COMPILER_CLANG #define KMP_COMPILER_CLANG 1 #elif defined(__GNUC__) #undef KMP_COMPILER_GCC #define KMP_COMPILER_GCC 1 #elif defined(_MSC_VER) #undef KMP_COMPILER_MSVC #define KMP_COMPILER_MSVC 1 #else #error Unknown compiler #endif #if (KMP_OS_LINUX || KMP_OS_WINDOWS || KMP_OS_FREEBSD) && !KMP_OS_CNK #define KMP_AFFINITY_SUPPORTED 1 #if KMP_OS_WINDOWS && KMP_ARCH_X86_64 #define KMP_GROUP_AFFINITY 1 #else #define KMP_GROUP_AFFINITY 0 #endif #else #define KMP_AFFINITY_SUPPORTED 0 #define KMP_GROUP_AFFINITY 0 #endif /* Check for quad-precision extension. */ #define KMP_HAVE_QUAD 0 #if KMP_ARCH_X86 || KMP_ARCH_X86_64 #if KMP_COMPILER_ICC /* _Quad is already defined for icc */ #undef KMP_HAVE_QUAD #define KMP_HAVE_QUAD 1 #elif KMP_COMPILER_CLANG /* Clang doesn't support a software-implemented 128-bit extended precision type yet */ typedef long double _Quad; #elif KMP_COMPILER_GCC /* GCC on NetBSD lacks __multc3/__divtc3 builtins needed for quad */ #if !KMP_OS_NETBSD typedef __float128 _Quad; #undef KMP_HAVE_QUAD #define KMP_HAVE_QUAD 1 #endif #elif KMP_COMPILER_MSVC typedef long double _Quad; #endif #else #if __LDBL_MAX_EXP__ >= 16384 && KMP_COMPILER_GCC typedef long double _Quad; #undef KMP_HAVE_QUAD #define KMP_HAVE_QUAD 1 #endif #endif /* KMP_ARCH_X86 || KMP_ARCH_X86_64 */ #define KMP_USE_X87CONTROL 0 #if KMP_OS_WINDOWS #define KMP_END_OF_LINE "\r\n" typedef char kmp_int8; typedef unsigned char kmp_uint8; typedef short kmp_int16; typedef unsigned short kmp_uint16; typedef int kmp_int32; typedef unsigned int kmp_uint32; #define KMP_INT32_SPEC "d" #define KMP_UINT32_SPEC "u" #ifndef KMP_STRUCT64 typedef __int64 kmp_int64; typedef unsigned __int64 kmp_uint64; #define KMP_INT64_SPEC "I64d" #define KMP_UINT64_SPEC "I64u" #else struct kmp_struct64 { kmp_int32 a, b; }; typedef struct kmp_struct64 kmp_int64; typedef struct kmp_struct64 kmp_uint64; /* Not sure what to use for KMP_[U]INT64_SPEC here */ #endif #if KMP_ARCH_X86 && KMP_MSVC_COMPAT #undef KMP_USE_X87CONTROL #define KMP_USE_X87CONTROL 1 #endif #if KMP_ARCH_X86_64 #define KMP_INTPTR 1 typedef __int64 kmp_intptr_t; typedef unsigned __int64 kmp_uintptr_t; #define KMP_INTPTR_SPEC "I64d" #define KMP_UINTPTR_SPEC "I64u" #endif #endif /* KMP_OS_WINDOWS */ #if KMP_OS_UNIX #define KMP_END_OF_LINE "\n" typedef char kmp_int8; typedef unsigned char kmp_uint8; typedef short kmp_int16; typedef unsigned short kmp_uint16; typedef int kmp_int32; typedef unsigned int kmp_uint32; typedef long long kmp_int64; typedef unsigned long long kmp_uint64; #define KMP_INT32_SPEC "d" #define KMP_UINT32_SPEC "u" #define KMP_INT64_SPEC "lld" #define KMP_UINT64_SPEC "llu" #endif /* KMP_OS_UNIX */ #if KMP_ARCH_X86 || KMP_ARCH_ARM || KMP_ARCH_MIPS #define KMP_SIZE_T_SPEC KMP_UINT32_SPEC #elif KMP_ARCH_X86_64 || KMP_ARCH_PPC64 || KMP_ARCH_AARCH64 || \ KMP_ARCH_MIPS64 || KMP_ARCH_RISCV64 #define KMP_SIZE_T_SPEC KMP_UINT64_SPEC #else #error "Can't determine size_t printf format specifier." #endif #if KMP_ARCH_X86 #define KMP_SIZE_T_MAX (0xFFFFFFFF) #else #define KMP_SIZE_T_MAX (0xFFFFFFFFFFFFFFFF) #endif typedef size_t kmp_size_t; typedef float kmp_real32; typedef double kmp_real64; #ifndef KMP_INTPTR #define KMP_INTPTR 1 typedef long kmp_intptr_t; typedef unsigned long kmp_uintptr_t; #define KMP_INTPTR_SPEC "ld" #define KMP_UINTPTR_SPEC "lu" #endif #ifdef BUILD_I8 typedef kmp_int64 kmp_int; typedef kmp_uint64 kmp_uint; #else typedef kmp_int32 kmp_int; typedef kmp_uint32 kmp_uint; #endif /* BUILD_I8 */ #define KMP_INT_MAX ((kmp_int32)0x7FFFFFFF) #define KMP_INT_MIN ((kmp_int32)0x80000000) +// stdarg handling +#if (KMP_ARCH_ARM || KMP_ARCH_X86_64 || KMP_ARCH_AARCH64) && \ + (KMP_OS_FREEBSD || KMP_OS_LINUX) +typedef va_list *kmp_va_list; +#define kmp_va_deref(ap) (*(ap)) +#define kmp_va_addr_of(ap) (&(ap)) +#else +typedef va_list kmp_va_list; +#define kmp_va_deref(ap) (ap) +#define kmp_va_addr_of(ap) (ap) +#endif + #ifdef __cplusplus // macros to cast out qualifiers and to re-interpret types #define CCAST(type, var) const_cast(var) #define RCAST(type, var) reinterpret_cast(var) //------------------------------------------------------------------------- // template for debug prints specification ( d, u, lld, llu ), and to obtain // signed/unsigned flavors of a type template struct traits_t {}; // int template <> struct traits_t { typedef signed int signed_t; typedef unsigned int unsigned_t; typedef double floating_t; static char const *spec; static const signed_t max_value = 0x7fffffff; static const signed_t min_value = 0x80000000; static const int type_size = sizeof(signed_t); }; // unsigned int template <> struct traits_t { typedef signed int signed_t; typedef unsigned int unsigned_t; typedef double floating_t; static char const *spec; static const unsigned_t max_value = 0xffffffff; static const unsigned_t min_value = 0x00000000; static const int type_size = sizeof(unsigned_t); }; // long template <> struct traits_t { typedef signed long signed_t; typedef unsigned long unsigned_t; typedef long double floating_t; static char const *spec; static const int type_size = sizeof(signed_t); }; // long long template <> struct traits_t { typedef signed long long signed_t; typedef unsigned long long unsigned_t; typedef long double floating_t; static char const *spec; static const signed_t max_value = 0x7fffffffffffffffLL; static const signed_t min_value = 0x8000000000000000LL; static const int type_size = sizeof(signed_t); }; // unsigned long long template <> struct traits_t { typedef signed long long signed_t; typedef unsigned long long unsigned_t; typedef long double floating_t; static char const *spec; static const unsigned_t max_value = 0xffffffffffffffffLL; static const unsigned_t min_value = 0x0000000000000000LL; static const int type_size = sizeof(unsigned_t); }; //------------------------------------------------------------------------- #else #define CCAST(type, var) (type)(var) #define RCAST(type, var) (type)(var) #endif // __cplusplus #define KMP_EXPORT extern /* export declaration in guide libraries */ #if __GNUC__ >= 4 && !defined(__MINGW32__) #define __forceinline __inline #endif #if KMP_OS_WINDOWS #include static inline int KMP_GET_PAGE_SIZE(void) { SYSTEM_INFO si; GetSystemInfo(&si); return si.dwPageSize; } #else #define KMP_GET_PAGE_SIZE() getpagesize() #endif #define PAGE_ALIGNED(_addr) \ (!((size_t)_addr & (size_t)(KMP_GET_PAGE_SIZE() - 1))) #define ALIGN_TO_PAGE(x) \ (void *)(((size_t)(x)) & ~((size_t)(KMP_GET_PAGE_SIZE() - 1))) /* ---------- Support for cache alignment, padding, etc. ----------------*/ #ifdef __cplusplus extern "C" { #endif // __cplusplus #define INTERNODE_CACHE_LINE 4096 /* for multi-node systems */ /* Define the default size of the cache line */ #ifndef CACHE_LINE #define CACHE_LINE 128 /* cache line size in bytes */ #else #if (CACHE_LINE < 64) && !defined(KMP_OS_DARWIN) // 2006-02-13: This produces too many warnings on OS X*. Disable for now #warning CACHE_LINE is too small. #endif #endif /* CACHE_LINE */ #define KMP_CACHE_PREFETCH(ADDR) /* nothing */ // Define attribute that indicates that the fall through from the previous // case label is intentional and should not be diagnosed by a compiler // Code from libcxx/include/__config // Use a function like macro to imply that it must be followed by a semicolon #if __cplusplus > 201402L && __has_cpp_attribute(fallthrough) # define KMP_FALLTHROUGH() [[fallthrough]] #elif __has_cpp_attribute(clang::fallthrough) # define KMP_FALLTHROUGH() [[clang::fallthrough]] #elif __has_attribute(fallthrough) || __GNUC__ >= 7 # define KMP_FALLTHROUGH() __attribute__((__fallthrough__)) #else # define KMP_FALLTHROUGH() ((void)0) #endif // Define attribute that indicates a function does not return #if __cplusplus >= 201103L #define KMP_NORETURN [[noreturn]] #elif KMP_OS_WINDOWS #define KMP_NORETURN __declspec(noreturn) #else #define KMP_NORETURN __attribute__((noreturn)) #endif #if KMP_OS_WINDOWS && KMP_MSVC_COMPAT #define KMP_ALIGN(bytes) __declspec(align(bytes)) #define KMP_THREAD_LOCAL __declspec(thread) #define KMP_ALIAS /* Nothing */ #else #define KMP_ALIGN(bytes) __attribute__((aligned(bytes))) #define KMP_THREAD_LOCAL __thread #define KMP_ALIAS(alias_of) __attribute__((alias(alias_of))) #endif #if KMP_HAVE_WEAK_ATTRIBUTE && !KMP_DYNAMIC_LIB #define KMP_WEAK_ATTRIBUTE_EXTERNAL __attribute__((weak)) #else #define KMP_WEAK_ATTRIBUTE_EXTERNAL /* Nothing */ #endif #if KMP_HAVE_WEAK_ATTRIBUTE #define KMP_WEAK_ATTRIBUTE_INTERNAL __attribute__((weak)) #else #define KMP_WEAK_ATTRIBUTE_INTERNAL /* Nothing */ #endif // Define KMP_VERSION_SYMBOL and KMP_EXPAND_NAME #ifndef KMP_STR #define KMP_STR(x) _KMP_STR(x) #define _KMP_STR(x) #x #endif #ifdef KMP_USE_VERSION_SYMBOLS // If using versioned symbols, KMP_EXPAND_NAME prepends // __kmp_api_ to the real API name #define KMP_EXPAND_NAME(api_name) _KMP_EXPAND_NAME(api_name) #define _KMP_EXPAND_NAME(api_name) __kmp_api_##api_name #define KMP_VERSION_SYMBOL(api_name, ver_num, ver_str) \ _KMP_VERSION_SYMBOL(api_name, ver_num, ver_str, "VERSION") #define _KMP_VERSION_SYMBOL(api_name, ver_num, ver_str, default_ver) \ __typeof__(__kmp_api_##api_name) __kmp_api_##api_name##_##ver_num##_alias \ __attribute__((alias(KMP_STR(__kmp_api_##api_name)))); \ __asm__( \ ".symver " KMP_STR(__kmp_api_##api_name##_##ver_num##_alias) "," KMP_STR( \ api_name) "@" ver_str "\n\t"); \ __asm__(".symver " KMP_STR(__kmp_api_##api_name) "," KMP_STR( \ api_name) "@@" default_ver "\n\t") #else // KMP_USE_VERSION_SYMBOLS #define KMP_EXPAND_NAME(api_name) api_name #define KMP_VERSION_SYMBOL(api_name, ver_num, ver_str) /* Nothing */ #endif // KMP_USE_VERSION_SYMBOLS /* Temporary note: if performance testing of this passes, we can remove all references to KMP_DO_ALIGN and replace with KMP_ALIGN. */ #define KMP_DO_ALIGN(bytes) KMP_ALIGN(bytes) #define KMP_ALIGN_CACHE KMP_ALIGN(CACHE_LINE) #define KMP_ALIGN_CACHE_INTERNODE KMP_ALIGN(INTERNODE_CACHE_LINE) /* General purpose fence types for memory operations */ enum kmp_mem_fence_type { kmp_no_fence, /* No memory fence */ kmp_acquire_fence, /* Acquire (read) memory fence */ kmp_release_fence, /* Release (write) memory fence */ kmp_full_fence /* Full (read+write) memory fence */ }; // Synchronization primitives #if KMP_ASM_INTRINS && KMP_OS_WINDOWS #if KMP_MSVC_COMPAT && !KMP_COMPILER_CLANG #pragma intrinsic(InterlockedExchangeAdd) #pragma intrinsic(InterlockedCompareExchange) #pragma intrinsic(InterlockedExchange) #pragma intrinsic(InterlockedExchange64) #endif // Using InterlockedIncrement / InterlockedDecrement causes a library loading // ordering problem, so we use InterlockedExchangeAdd instead. #define KMP_TEST_THEN_INC32(p) InterlockedExchangeAdd((volatile long *)(p), 1) #define KMP_TEST_THEN_INC_ACQ32(p) \ InterlockedExchangeAdd((volatile long *)(p), 1) #define KMP_TEST_THEN_ADD4_32(p) InterlockedExchangeAdd((volatile long *)(p), 4) #define KMP_TEST_THEN_ADD4_ACQ32(p) \ InterlockedExchangeAdd((volatile long *)(p), 4) #define KMP_TEST_THEN_DEC32(p) InterlockedExchangeAdd((volatile long *)(p), -1) #define KMP_TEST_THEN_DEC_ACQ32(p) \ InterlockedExchangeAdd((volatile long *)(p), -1) #define KMP_TEST_THEN_ADD32(p, v) \ InterlockedExchangeAdd((volatile long *)(p), (v)) #define KMP_COMPARE_AND_STORE_RET32(p, cv, sv) \ InterlockedCompareExchange((volatile long *)(p), (long)(sv), (long)(cv)) #define KMP_XCHG_FIXED32(p, v) \ InterlockedExchange((volatile long *)(p), (long)(v)) #define KMP_XCHG_FIXED64(p, v) \ InterlockedExchange64((volatile kmp_int64 *)(p), (kmp_int64)(v)) inline kmp_real32 KMP_XCHG_REAL32(volatile kmp_real32 *p, kmp_real32 v) { kmp_int32 tmp = InterlockedExchange((volatile long *)p, *(long *)&v); return *(kmp_real32 *)&tmp; } // Routines that we still need to implement in assembly. extern kmp_int8 __kmp_test_then_add8(volatile kmp_int8 *p, kmp_int8 v); extern kmp_int8 __kmp_test_then_or8(volatile kmp_int8 *p, kmp_int8 v); extern kmp_int8 __kmp_test_then_and8(volatile kmp_int8 *p, kmp_int8 v); extern kmp_int32 __kmp_test_then_add32(volatile kmp_int32 *p, kmp_int32 v); extern kmp_uint32 __kmp_test_then_or32(volatile kmp_uint32 *p, kmp_uint32 v); extern kmp_uint32 __kmp_test_then_and32(volatile kmp_uint32 *p, kmp_uint32 v); extern kmp_int64 __kmp_test_then_add64(volatile kmp_int64 *p, kmp_int64 v); extern kmp_uint64 __kmp_test_then_or64(volatile kmp_uint64 *p, kmp_uint64 v); extern kmp_uint64 __kmp_test_then_and64(volatile kmp_uint64 *p, kmp_uint64 v); extern kmp_int8 __kmp_compare_and_store8(volatile kmp_int8 *p, kmp_int8 cv, kmp_int8 sv); extern kmp_int16 __kmp_compare_and_store16(volatile kmp_int16 *p, kmp_int16 cv, kmp_int16 sv); extern kmp_int32 __kmp_compare_and_store32(volatile kmp_int32 *p, kmp_int32 cv, kmp_int32 sv); extern kmp_int32 __kmp_compare_and_store64(volatile kmp_int64 *p, kmp_int64 cv, kmp_int64 sv); extern kmp_int8 __kmp_compare_and_store_ret8(volatile kmp_int8 *p, kmp_int8 cv, kmp_int8 sv); extern kmp_int16 __kmp_compare_and_store_ret16(volatile kmp_int16 *p, kmp_int16 cv, kmp_int16 sv); extern kmp_int32 __kmp_compare_and_store_ret32(volatile kmp_int32 *p, kmp_int32 cv, kmp_int32 sv); extern kmp_int64 __kmp_compare_and_store_ret64(volatile kmp_int64 *p, kmp_int64 cv, kmp_int64 sv); extern kmp_int8 __kmp_xchg_fixed8(volatile kmp_int8 *p, kmp_int8 v); extern kmp_int16 __kmp_xchg_fixed16(volatile kmp_int16 *p, kmp_int16 v); extern kmp_int32 __kmp_xchg_fixed32(volatile kmp_int32 *p, kmp_int32 v); extern kmp_int64 __kmp_xchg_fixed64(volatile kmp_int64 *p, kmp_int64 v); extern kmp_real32 __kmp_xchg_real32(volatile kmp_real32 *p, kmp_real32 v); extern kmp_real64 __kmp_xchg_real64(volatile kmp_real64 *p, kmp_real64 v); //#define KMP_TEST_THEN_INC32(p) __kmp_test_then_add32((p), 1) //#define KMP_TEST_THEN_INC_ACQ32(p) __kmp_test_then_add32((p), 1) #define KMP_TEST_THEN_INC64(p) __kmp_test_then_add64((p), 1LL) #define KMP_TEST_THEN_INC_ACQ64(p) __kmp_test_then_add64((p), 1LL) //#define KMP_TEST_THEN_ADD4_32(p) __kmp_test_then_add32((p), 4) //#define KMP_TEST_THEN_ADD4_ACQ32(p) __kmp_test_then_add32((p), 4) #define KMP_TEST_THEN_ADD4_64(p) __kmp_test_then_add64((p), 4LL) #define KMP_TEST_THEN_ADD4_ACQ64(p) __kmp_test_then_add64((p), 4LL) //#define KMP_TEST_THEN_DEC32(p) __kmp_test_then_add32((p), -1) //#define KMP_TEST_THEN_DEC_ACQ32(p) __kmp_test_then_add32((p), -1) #define KMP_TEST_THEN_DEC64(p) __kmp_test_then_add64((p), -1LL) #define KMP_TEST_THEN_DEC_ACQ64(p) __kmp_test_then_add64((p), -1LL) //#define KMP_TEST_THEN_ADD32(p, v) __kmp_test_then_add32((p), (v)) #define KMP_TEST_THEN_ADD8(p, v) __kmp_test_then_add8((p), (v)) #define KMP_TEST_THEN_ADD64(p, v) __kmp_test_then_add64((p), (v)) #define KMP_TEST_THEN_OR8(p, v) __kmp_test_then_or8((p), (v)) #define KMP_TEST_THEN_AND8(p, v) __kmp_test_then_and8((p), (v)) #define KMP_TEST_THEN_OR32(p, v) __kmp_test_then_or32((p), (v)) #define KMP_TEST_THEN_AND32(p, v) __kmp_test_then_and32((p), (v)) #define KMP_TEST_THEN_OR64(p, v) __kmp_test_then_or64((p), (v)) #define KMP_TEST_THEN_AND64(p, v) __kmp_test_then_and64((p), (v)) #define KMP_COMPARE_AND_STORE_ACQ8(p, cv, sv) \ __kmp_compare_and_store8((p), (cv), (sv)) #define KMP_COMPARE_AND_STORE_REL8(p, cv, sv) \ __kmp_compare_and_store8((p), (cv), (sv)) #define KMP_COMPARE_AND_STORE_ACQ16(p, cv, sv) \ __kmp_compare_and_store16((p), (cv), (sv)) #define KMP_COMPARE_AND_STORE_REL16(p, cv, sv) \ __kmp_compare_and_store16((p), (cv), (sv)) #define KMP_COMPARE_AND_STORE_ACQ32(p, cv, sv) \ __kmp_compare_and_store32((volatile kmp_int32 *)(p), (kmp_int32)(cv), \ (kmp_int32)(sv)) #define KMP_COMPARE_AND_STORE_REL32(p, cv, sv) \ __kmp_compare_and_store32((volatile kmp_int32 *)(p), (kmp_int32)(cv), \ (kmp_int32)(sv)) #define KMP_COMPARE_AND_STORE_ACQ64(p, cv, sv) \ __kmp_compare_and_store64((volatile kmp_int64 *)(p), (kmp_int64)(cv), \ (kmp_int64)(sv)) #define KMP_COMPARE_AND_STORE_REL64(p, cv, sv) \ __kmp_compare_and_store64((volatile kmp_int64 *)(p), (kmp_int64)(cv), \ (kmp_int64)(sv)) #if KMP_ARCH_X86 #define KMP_COMPARE_AND_STORE_PTR(p, cv, sv) \ __kmp_compare_and_store32((volatile kmp_int32 *)(p), (kmp_int32)(cv), \ (kmp_int32)(sv)) #else /* 64 bit pointers */ #define KMP_COMPARE_AND_STORE_PTR(p, cv, sv) \ __kmp_compare_and_store64((volatile kmp_int64 *)(p), (kmp_int64)(cv), \ (kmp_int64)(sv)) #endif /* KMP_ARCH_X86 */ #define KMP_COMPARE_AND_STORE_RET8(p, cv, sv) \ __kmp_compare_and_store_ret8((p), (cv), (sv)) #define KMP_COMPARE_AND_STORE_RET16(p, cv, sv) \ __kmp_compare_and_store_ret16((p), (cv), (sv)) #define KMP_COMPARE_AND_STORE_RET64(p, cv, sv) \ __kmp_compare_and_store_ret64((volatile kmp_int64 *)(p), (kmp_int64)(cv), \ (kmp_int64)(sv)) #define KMP_XCHG_FIXED8(p, v) \ __kmp_xchg_fixed8((volatile kmp_int8 *)(p), (kmp_int8)(v)); #define KMP_XCHG_FIXED16(p, v) __kmp_xchg_fixed16((p), (v)); //#define KMP_XCHG_FIXED32(p, v) __kmp_xchg_fixed32((p), (v)); //#define KMP_XCHG_FIXED64(p, v) __kmp_xchg_fixed64((p), (v)); //#define KMP_XCHG_REAL32(p, v) __kmp_xchg_real32((p), (v)); #define KMP_XCHG_REAL64(p, v) __kmp_xchg_real64((p), (v)); #elif (KMP_ASM_INTRINS && KMP_OS_UNIX) || !(KMP_ARCH_X86 || KMP_ARCH_X86_64) /* cast p to correct type so that proper intrinsic will be used */ #define KMP_TEST_THEN_INC32(p) \ __sync_fetch_and_add((volatile kmp_int32 *)(p), 1) #define KMP_TEST_THEN_INC_ACQ32(p) \ __sync_fetch_and_add((volatile kmp_int32 *)(p), 1) #if KMP_ARCH_MIPS #define KMP_TEST_THEN_INC64(p) \ __atomic_fetch_add((volatile kmp_int64 *)(p), 1LL, __ATOMIC_SEQ_CST) #define KMP_TEST_THEN_INC_ACQ64(p) \ __atomic_fetch_add((volatile kmp_int64 *)(p), 1LL, __ATOMIC_SEQ_CST) #else #define KMP_TEST_THEN_INC64(p) \ __sync_fetch_and_add((volatile kmp_int64 *)(p), 1LL) #define KMP_TEST_THEN_INC_ACQ64(p) \ __sync_fetch_and_add((volatile kmp_int64 *)(p), 1LL) #endif #define KMP_TEST_THEN_ADD4_32(p) \ __sync_fetch_and_add((volatile kmp_int32 *)(p), 4) #define KMP_TEST_THEN_ADD4_ACQ32(p) \ __sync_fetch_and_add((volatile kmp_int32 *)(p), 4) #if KMP_ARCH_MIPS #define KMP_TEST_THEN_ADD4_64(p) \ __atomic_fetch_add((volatile kmp_int64 *)(p), 4LL, __ATOMIC_SEQ_CST) #define KMP_TEST_THEN_ADD4_ACQ64(p) \ __atomic_fetch_add((volatile kmp_int64 *)(p), 4LL, __ATOMIC_SEQ_CST) #define KMP_TEST_THEN_DEC64(p) \ __atomic_fetch_sub((volatile kmp_int64 *)(p), 1LL, __ATOMIC_SEQ_CST) #define KMP_TEST_THEN_DEC_ACQ64(p) \ __atomic_fetch_sub((volatile kmp_int64 *)(p), 1LL, __ATOMIC_SEQ_CST) #else #define KMP_TEST_THEN_ADD4_64(p) \ __sync_fetch_and_add((volatile kmp_int64 *)(p), 4LL) #define KMP_TEST_THEN_ADD4_ACQ64(p) \ __sync_fetch_and_add((volatile kmp_int64 *)(p), 4LL) #define KMP_TEST_THEN_DEC64(p) \ __sync_fetch_and_sub((volatile kmp_int64 *)(p), 1LL) #define KMP_TEST_THEN_DEC_ACQ64(p) \ __sync_fetch_and_sub((volatile kmp_int64 *)(p), 1LL) #endif #define KMP_TEST_THEN_DEC32(p) \ __sync_fetch_and_sub((volatile kmp_int32 *)(p), 1) #define KMP_TEST_THEN_DEC_ACQ32(p) \ __sync_fetch_and_sub((volatile kmp_int32 *)(p), 1) #define KMP_TEST_THEN_ADD8(p, v) \ __sync_fetch_and_add((volatile kmp_int8 *)(p), (kmp_int8)(v)) #define KMP_TEST_THEN_ADD32(p, v) \ __sync_fetch_and_add((volatile kmp_int32 *)(p), (kmp_int32)(v)) #if KMP_ARCH_MIPS #define KMP_TEST_THEN_ADD64(p, v) \ __atomic_fetch_add((volatile kmp_uint64 *)(p), (kmp_uint64)(v), \ __ATOMIC_SEQ_CST) #else #define KMP_TEST_THEN_ADD64(p, v) \ __sync_fetch_and_add((volatile kmp_int64 *)(p), (kmp_int64)(v)) #endif #define KMP_TEST_THEN_OR8(p, v) \ __sync_fetch_and_or((volatile kmp_int8 *)(p), (kmp_int8)(v)) #define KMP_TEST_THEN_AND8(p, v) \ __sync_fetch_and_and((volatile kmp_int8 *)(p), (kmp_int8)(v)) #define KMP_TEST_THEN_OR32(p, v) \ __sync_fetch_and_or((volatile kmp_uint32 *)(p), (kmp_uint32)(v)) #define KMP_TEST_THEN_AND32(p, v) \ __sync_fetch_and_and((volatile kmp_uint32 *)(p), (kmp_uint32)(v)) #if KMP_ARCH_MIPS #define KMP_TEST_THEN_OR64(p, v) \ __atomic_fetch_or((volatile kmp_uint64 *)(p), (kmp_uint64)(v), \ __ATOMIC_SEQ_CST) #define KMP_TEST_THEN_AND64(p, v) \ __atomic_fetch_and((volatile kmp_uint64 *)(p), (kmp_uint64)(v), \ __ATOMIC_SEQ_CST) #else #define KMP_TEST_THEN_OR64(p, v) \ __sync_fetch_and_or((volatile kmp_uint64 *)(p), (kmp_uint64)(v)) #define KMP_TEST_THEN_AND64(p, v) \ __sync_fetch_and_and((volatile kmp_uint64 *)(p), (kmp_uint64)(v)) #endif #define KMP_COMPARE_AND_STORE_ACQ8(p, cv, sv) \ __sync_bool_compare_and_swap((volatile kmp_uint8 *)(p), (kmp_uint8)(cv), \ (kmp_uint8)(sv)) #define KMP_COMPARE_AND_STORE_REL8(p, cv, sv) \ __sync_bool_compare_and_swap((volatile kmp_uint8 *)(p), (kmp_uint8)(cv), \ (kmp_uint8)(sv)) #define KMP_COMPARE_AND_STORE_ACQ16(p, cv, sv) \ __sync_bool_compare_and_swap((volatile kmp_uint16 *)(p), (kmp_uint16)(cv), \ (kmp_uint16)(sv)) #define KMP_COMPARE_AND_STORE_REL16(p, cv, sv) \ __sync_bool_compare_and_swap((volatile kmp_uint16 *)(p), (kmp_uint16)(cv), \ (kmp_uint16)(sv)) #define KMP_COMPARE_AND_STORE_ACQ32(p, cv, sv) \ __sync_bool_compare_and_swap((volatile kmp_uint32 *)(p), (kmp_uint32)(cv), \ (kmp_uint32)(sv)) #define KMP_COMPARE_AND_STORE_REL32(p, cv, sv) \ __sync_bool_compare_and_swap((volatile kmp_uint32 *)(p), (kmp_uint32)(cv), \ (kmp_uint32)(sv)) #define KMP_COMPARE_AND_STORE_PTR(p, cv, sv) \ __sync_bool_compare_and_swap((void *volatile *)(p), (void *)(cv), \ (void *)(sv)) #define KMP_COMPARE_AND_STORE_RET8(p, cv, sv) \ __sync_val_compare_and_swap((volatile kmp_uint8 *)(p), (kmp_uint8)(cv), \ (kmp_uint8)(sv)) #define KMP_COMPARE_AND_STORE_RET16(p, cv, sv) \ __sync_val_compare_and_swap((volatile kmp_uint16 *)(p), (kmp_uint16)(cv), \ (kmp_uint16)(sv)) #define KMP_COMPARE_AND_STORE_RET32(p, cv, sv) \ __sync_val_compare_and_swap((volatile kmp_uint32 *)(p), (kmp_uint32)(cv), \ (kmp_uint32)(sv)) #if KMP_ARCH_MIPS static inline bool mips_sync_bool_compare_and_swap( volatile kmp_uint64 *p, kmp_uint64 cv, kmp_uint64 sv) { return __atomic_compare_exchange(p, &cv, &sv, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); } static inline bool mips_sync_val_compare_and_swap( volatile kmp_uint64 *p, kmp_uint64 cv, kmp_uint64 sv) { __atomic_compare_exchange(p, &cv, &sv, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); return cv; } #define KMP_COMPARE_AND_STORE_ACQ64(p, cv, sv) \ mips_sync_bool_compare_and_swap((volatile kmp_uint64 *)(p), (kmp_uint64)(cv),\ (kmp_uint64)(sv)) #define KMP_COMPARE_AND_STORE_REL64(p, cv, sv) \ mips_sync_bool_compare_and_swap((volatile kmp_uint64 *)(p), (kmp_uint64)(cv),\ (kmp_uint64)(sv)) #define KMP_COMPARE_AND_STORE_RET64(p, cv, sv) \ mips_sync_val_compare_and_swap((volatile kmp_uint64 *)(p), (kmp_uint64)(cv), \ (kmp_uint64)(sv)) #else #define KMP_COMPARE_AND_STORE_ACQ64(p, cv, sv) \ __sync_bool_compare_and_swap((volatile kmp_uint64 *)(p), (kmp_uint64)(cv), \ (kmp_uint64)(sv)) #define KMP_COMPARE_AND_STORE_REL64(p, cv, sv) \ __sync_bool_compare_and_swap((volatile kmp_uint64 *)(p), (kmp_uint64)(cv), \ (kmp_uint64)(sv)) #define KMP_COMPARE_AND_STORE_RET64(p, cv, sv) \ __sync_val_compare_and_swap((volatile kmp_uint64 *)(p), (kmp_uint64)(cv), \ (kmp_uint64)(sv)) #endif #define KMP_XCHG_FIXED8(p, v) \ __sync_lock_test_and_set((volatile kmp_uint8 *)(p), (kmp_uint8)(v)) #define KMP_XCHG_FIXED16(p, v) \ __sync_lock_test_and_set((volatile kmp_uint16 *)(p), (kmp_uint16)(v)) #define KMP_XCHG_FIXED32(p, v) \ __sync_lock_test_and_set((volatile kmp_uint32 *)(p), (kmp_uint32)(v)) #define KMP_XCHG_FIXED64(p, v) \ __sync_lock_test_and_set((volatile kmp_uint64 *)(p), (kmp_uint64)(v)) inline kmp_real32 KMP_XCHG_REAL32(volatile kmp_real32 *p, kmp_real32 v) { kmp_int32 tmp = __sync_lock_test_and_set((volatile kmp_uint32 *)(p), *(kmp_uint32 *)&v); return *(kmp_real32 *)&tmp; } inline kmp_real64 KMP_XCHG_REAL64(volatile kmp_real64 *p, kmp_real64 v) { kmp_int64 tmp = __sync_lock_test_and_set((volatile kmp_uint64 *)(p), *(kmp_uint64 *)&v); return *(kmp_real64 *)&tmp; } #else extern kmp_int8 __kmp_test_then_add8(volatile kmp_int8 *p, kmp_int8 v); extern kmp_int8 __kmp_test_then_or8(volatile kmp_int8 *p, kmp_int8 v); extern kmp_int8 __kmp_test_then_and8(volatile kmp_int8 *p, kmp_int8 v); extern kmp_int32 __kmp_test_then_add32(volatile kmp_int32 *p, kmp_int32 v); extern kmp_uint32 __kmp_test_then_or32(volatile kmp_uint32 *p, kmp_uint32 v); extern kmp_uint32 __kmp_test_then_and32(volatile kmp_uint32 *p, kmp_uint32 v); extern kmp_int64 __kmp_test_then_add64(volatile kmp_int64 *p, kmp_int64 v); extern kmp_uint64 __kmp_test_then_or64(volatile kmp_uint64 *p, kmp_uint64 v); extern kmp_uint64 __kmp_test_then_and64(volatile kmp_uint64 *p, kmp_uint64 v); extern kmp_int8 __kmp_compare_and_store8(volatile kmp_int8 *p, kmp_int8 cv, kmp_int8 sv); extern kmp_int16 __kmp_compare_and_store16(volatile kmp_int16 *p, kmp_int16 cv, kmp_int16 sv); extern kmp_int32 __kmp_compare_and_store32(volatile kmp_int32 *p, kmp_int32 cv, kmp_int32 sv); extern kmp_int32 __kmp_compare_and_store64(volatile kmp_int64 *p, kmp_int64 cv, kmp_int64 sv); extern kmp_int8 __kmp_compare_and_store_ret8(volatile kmp_int8 *p, kmp_int8 cv, kmp_int8 sv); extern kmp_int16 __kmp_compare_and_store_ret16(volatile kmp_int16 *p, kmp_int16 cv, kmp_int16 sv); extern kmp_int32 __kmp_compare_and_store_ret32(volatile kmp_int32 *p, kmp_int32 cv, kmp_int32 sv); extern kmp_int64 __kmp_compare_and_store_ret64(volatile kmp_int64 *p, kmp_int64 cv, kmp_int64 sv); extern kmp_int8 __kmp_xchg_fixed8(volatile kmp_int8 *p, kmp_int8 v); extern kmp_int16 __kmp_xchg_fixed16(volatile kmp_int16 *p, kmp_int16 v); extern kmp_int32 __kmp_xchg_fixed32(volatile kmp_int32 *p, kmp_int32 v); extern kmp_int64 __kmp_xchg_fixed64(volatile kmp_int64 *p, kmp_int64 v); extern kmp_real32 __kmp_xchg_real32(volatile kmp_real32 *p, kmp_real32 v); extern kmp_real64 __kmp_xchg_real64(volatile kmp_real64 *p, kmp_real64 v); #define KMP_TEST_THEN_INC32(p) \ __kmp_test_then_add32((volatile kmp_int32 *)(p), 1) #define KMP_TEST_THEN_INC_ACQ32(p) \ __kmp_test_then_add32((volatile kmp_int32 *)(p), 1) #define KMP_TEST_THEN_INC64(p) \ __kmp_test_then_add64((volatile kmp_int64 *)(p), 1LL) #define KMP_TEST_THEN_INC_ACQ64(p) \ __kmp_test_then_add64((volatile kmp_int64 *)(p), 1LL) #define KMP_TEST_THEN_ADD4_32(p) \ __kmp_test_then_add32((volatile kmp_int32 *)(p), 4) #define KMP_TEST_THEN_ADD4_ACQ32(p) \ __kmp_test_then_add32((volatile kmp_int32 *)(p), 4) #define KMP_TEST_THEN_ADD4_64(p) \ __kmp_test_then_add64((volatile kmp_int64 *)(p), 4LL) #define KMP_TEST_THEN_ADD4_ACQ64(p) \ __kmp_test_then_add64((volatile kmp_int64 *)(p), 4LL) #define KMP_TEST_THEN_DEC32(p) \ __kmp_test_then_add32((volatile kmp_int32 *)(p), -1) #define KMP_TEST_THEN_DEC_ACQ32(p) \ __kmp_test_then_add32((volatile kmp_int32 *)(p), -1) #define KMP_TEST_THEN_DEC64(p) \ __kmp_test_then_add64((volatile kmp_int64 *)(p), -1LL) #define KMP_TEST_THEN_DEC_ACQ64(p) \ __kmp_test_then_add64((volatile kmp_int64 *)(p), -1LL) #define KMP_TEST_THEN_ADD8(p, v) \ __kmp_test_then_add8((volatile kmp_int8 *)(p), (kmp_int8)(v)) #define KMP_TEST_THEN_ADD32(p, v) \ __kmp_test_then_add32((volatile kmp_int32 *)(p), (kmp_int32)(v)) #define KMP_TEST_THEN_ADD64(p, v) \ __kmp_test_then_add64((volatile kmp_int64 *)(p), (kmp_int64)(v)) #define KMP_TEST_THEN_OR8(p, v) \ __kmp_test_then_or8((volatile kmp_int8 *)(p), (kmp_int8)(v)) #define KMP_TEST_THEN_AND8(p, v) \ __kmp_test_then_and8((volatile kmp_int8 *)(p), (kmp_int8)(v)) #define KMP_TEST_THEN_OR32(p, v) \ __kmp_test_then_or32((volatile kmp_uint32 *)(p), (kmp_uint32)(v)) #define KMP_TEST_THEN_AND32(p, v) \ __kmp_test_then_and32((volatile kmp_uint32 *)(p), (kmp_uint32)(v)) #define KMP_TEST_THEN_OR64(p, v) \ __kmp_test_then_or64((volatile kmp_uint64 *)(p), (kmp_uint64)(v)) #define KMP_TEST_THEN_AND64(p, v) \ __kmp_test_then_and64((volatile kmp_uint64 *)(p), (kmp_uint64)(v)) #define KMP_COMPARE_AND_STORE_ACQ8(p, cv, sv) \ __kmp_compare_and_store8((volatile kmp_int8 *)(p), (kmp_int8)(cv), \ (kmp_int8)(sv)) #define KMP_COMPARE_AND_STORE_REL8(p, cv, sv) \ __kmp_compare_and_store8((volatile kmp_int8 *)(p), (kmp_int8)(cv), \ (kmp_int8)(sv)) #define KMP_COMPARE_AND_STORE_ACQ16(p, cv, sv) \ __kmp_compare_and_store16((volatile kmp_int16 *)(p), (kmp_int16)(cv), \ (kmp_int16)(sv)) #define KMP_COMPARE_AND_STORE_REL16(p, cv, sv) \ __kmp_compare_and_store16((volatile kmp_int16 *)(p), (kmp_int16)(cv), \ (kmp_int16)(sv)) #define KMP_COMPARE_AND_STORE_ACQ32(p, cv, sv) \ __kmp_compare_and_store32((volatile kmp_int32 *)(p), (kmp_int32)(cv), \ (kmp_int32)(sv)) #define KMP_COMPARE_AND_STORE_REL32(p, cv, sv) \ __kmp_compare_and_store32((volatile kmp_int32 *)(p), (kmp_int32)(cv), \ (kmp_int32)(sv)) #define KMP_COMPARE_AND_STORE_ACQ64(p, cv, sv) \ __kmp_compare_and_store64((volatile kmp_int64 *)(p), (kmp_int64)(cv), \ (kmp_int64)(sv)) #define KMP_COMPARE_AND_STORE_REL64(p, cv, sv) \ __kmp_compare_and_store64((volatile kmp_int64 *)(p), (kmp_int64)(cv), \ (kmp_int64)(sv)) #if KMP_ARCH_X86 #define KMP_COMPARE_AND_STORE_PTR(p, cv, sv) \ __kmp_compare_and_store32((volatile kmp_int32 *)(p), (kmp_int32)(cv), \ (kmp_int32)(sv)) #else /* 64 bit pointers */ #define KMP_COMPARE_AND_STORE_PTR(p, cv, sv) \ __kmp_compare_and_store64((volatile kmp_int64 *)(p), (kmp_int64)(cv), \ (kmp_int64)(sv)) #endif /* KMP_ARCH_X86 */ #define KMP_COMPARE_AND_STORE_RET8(p, cv, sv) \ __kmp_compare_and_store_ret8((p), (cv), (sv)) #define KMP_COMPARE_AND_STORE_RET16(p, cv, sv) \ __kmp_compare_and_store_ret16((p), (cv), (sv)) #define KMP_COMPARE_AND_STORE_RET32(p, cv, sv) \ __kmp_compare_and_store_ret32((volatile kmp_int32 *)(p), (kmp_int32)(cv), \ (kmp_int32)(sv)) #define KMP_COMPARE_AND_STORE_RET64(p, cv, sv) \ __kmp_compare_and_store_ret64((volatile kmp_int64 *)(p), (kmp_int64)(cv), \ (kmp_int64)(sv)) #define KMP_XCHG_FIXED8(p, v) \ __kmp_xchg_fixed8((volatile kmp_int8 *)(p), (kmp_int8)(v)); #define KMP_XCHG_FIXED16(p, v) __kmp_xchg_fixed16((p), (v)); #define KMP_XCHG_FIXED32(p, v) __kmp_xchg_fixed32((p), (v)); #define KMP_XCHG_FIXED64(p, v) __kmp_xchg_fixed64((p), (v)); #define KMP_XCHG_REAL32(p, v) __kmp_xchg_real32((p), (v)); #define KMP_XCHG_REAL64(p, v) __kmp_xchg_real64((p), (v)); #endif /* KMP_ASM_INTRINS */ /* ------------- relaxed consistency memory model stuff ------------------ */ #if KMP_OS_WINDOWS #ifdef __ABSOFT_WIN #define KMP_MB() asm("nop") #define KMP_IMB() asm("nop") #else #define KMP_MB() /* _asm{ nop } */ #define KMP_IMB() /* _asm{ nop } */ #endif #endif /* KMP_OS_WINDOWS */ #if KMP_ARCH_PPC64 || KMP_ARCH_ARM || KMP_ARCH_AARCH64 || KMP_ARCH_MIPS || \ KMP_ARCH_MIPS64 || KMP_ARCH_RISCV64 #define KMP_MB() __sync_synchronize() #endif #ifndef KMP_MB #define KMP_MB() /* nothing to do */ #endif #ifndef KMP_IMB #define KMP_IMB() /* nothing to do */ #endif #ifndef KMP_ST_REL32 #define KMP_ST_REL32(A, D) (*(A) = (D)) #endif #ifndef KMP_ST_REL64 #define KMP_ST_REL64(A, D) (*(A) = (D)) #endif #ifndef KMP_LD_ACQ32 #define KMP_LD_ACQ32(A) (*(A)) #endif #ifndef KMP_LD_ACQ64 #define KMP_LD_ACQ64(A) (*(A)) #endif /* ------------------------------------------------------------------------ */ // FIXME - maybe this should this be // // #define TCR_4(a) (*(volatile kmp_int32 *)(&a)) // #define TCW_4(a,b) (a) = (*(volatile kmp_int32 *)&(b)) // // #define TCR_8(a) (*(volatile kmp_int64 *)(a)) // #define TCW_8(a,b) (a) = (*(volatile kmp_int64 *)(&b)) // // I'm fairly certain this is the correct thing to do, but I'm afraid // of performance regressions. #define TCR_1(a) (a) #define TCW_1(a, b) (a) = (b) #define TCR_4(a) (a) #define TCW_4(a, b) (a) = (b) #define TCI_4(a) (++(a)) #define TCD_4(a) (--(a)) #define TCR_8(a) (a) #define TCW_8(a, b) (a) = (b) #define TCI_8(a) (++(a)) #define TCD_8(a) (--(a)) #define TCR_SYNC_4(a) (a) #define TCW_SYNC_4(a, b) (a) = (b) #define TCX_SYNC_4(a, b, c) \ KMP_COMPARE_AND_STORE_REL32((volatile kmp_int32 *)(volatile void *)&(a), \ (kmp_int32)(b), (kmp_int32)(c)) #define TCR_SYNC_8(a) (a) #define TCW_SYNC_8(a, b) (a) = (b) #define TCX_SYNC_8(a, b, c) \ KMP_COMPARE_AND_STORE_REL64((volatile kmp_int64 *)(volatile void *)&(a), \ (kmp_int64)(b), (kmp_int64)(c)) #if KMP_ARCH_X86 || KMP_ARCH_MIPS // What about ARM? #define TCR_PTR(a) ((void *)TCR_4(a)) #define TCW_PTR(a, b) TCW_4((a), (b)) #define TCR_SYNC_PTR(a) ((void *)TCR_SYNC_4(a)) #define TCW_SYNC_PTR(a, b) TCW_SYNC_4((a), (b)) #define TCX_SYNC_PTR(a, b, c) ((void *)TCX_SYNC_4((a), (b), (c))) #else /* 64 bit pointers */ #define TCR_PTR(a) ((void *)TCR_8(a)) #define TCW_PTR(a, b) TCW_8((a), (b)) #define TCR_SYNC_PTR(a) ((void *)TCR_SYNC_8(a)) #define TCW_SYNC_PTR(a, b) TCW_SYNC_8((a), (b)) #define TCX_SYNC_PTR(a, b, c) ((void *)TCX_SYNC_8((a), (b), (c))) #endif /* KMP_ARCH_X86 */ /* If these FTN_{TRUE,FALSE} values change, may need to change several places where they are used to check that language is Fortran, not C. */ #ifndef FTN_TRUE #define FTN_TRUE TRUE #endif #ifndef FTN_FALSE #define FTN_FALSE FALSE #endif typedef void (*microtask_t)(int *gtid, int *npr, ...); #ifdef USE_VOLATILE_CAST #define VOLATILE_CAST(x) (volatile x) #else #define VOLATILE_CAST(x) (x) #endif #define KMP_WAIT __kmp_wait_4 #define KMP_WAIT_PTR __kmp_wait_4_ptr #define KMP_EQ __kmp_eq_4 #define KMP_NEQ __kmp_neq_4 #define KMP_LT __kmp_lt_4 #define KMP_GE __kmp_ge_4 #define KMP_LE __kmp_le_4 /* Workaround for Intel(R) 64 code gen bug when taking address of static array * (Intel(R) 64 Tracker #138) */ #if (KMP_ARCH_X86_64 || KMP_ARCH_PPC64) && KMP_OS_LINUX #define STATIC_EFI2_WORKAROUND #else #define STATIC_EFI2_WORKAROUND static #endif // Support of BGET usage #ifndef KMP_USE_BGET #define KMP_USE_BGET 1 #endif // Switches for OSS builds #ifndef USE_CMPXCHG_FIX #define USE_CMPXCHG_FIX 1 #endif // Enable dynamic user lock #define KMP_USE_DYNAMIC_LOCK 1 // Enable Intel(R) Transactional Synchronization Extensions (Intel(R) TSX) if // dynamic user lock is turned on #if KMP_USE_DYNAMIC_LOCK // Visual studio can't handle the asm sections in this code #define KMP_USE_TSX (KMP_ARCH_X86 || KMP_ARCH_X86_64) && !KMP_COMPILER_MSVC #ifdef KMP_USE_ADAPTIVE_LOCKS #undef KMP_USE_ADAPTIVE_LOCKS #endif #define KMP_USE_ADAPTIVE_LOCKS KMP_USE_TSX #endif // Enable tick time conversion of ticks to seconds #if KMP_STATS_ENABLED #define KMP_HAVE_TICK_TIME \ (KMP_OS_LINUX && (KMP_MIC || KMP_ARCH_X86 || KMP_ARCH_X86_64)) #endif // Warning levels enum kmp_warnings_level { kmp_warnings_off = 0, /* No warnings */ kmp_warnings_low, /* Minimal warnings (default) */ kmp_warnings_explicit = 6, /* Explicitly set to ON - more warnings */ kmp_warnings_verbose /* reserved */ }; #ifdef __cplusplus } // extern "C" #endif // __cplusplus // Macros for C++11 atomic functions #define KMP_ATOMIC_LD(p, order) (p)->load(std::memory_order_##order) #define KMP_ATOMIC_OP(op, p, v, order) (p)->op(v, std::memory_order_##order) // For non-default load/store #define KMP_ATOMIC_LD_ACQ(p) KMP_ATOMIC_LD(p, acquire) #define KMP_ATOMIC_LD_RLX(p) KMP_ATOMIC_LD(p, relaxed) #define KMP_ATOMIC_ST_REL(p, v) KMP_ATOMIC_OP(store, p, v, release) #define KMP_ATOMIC_ST_RLX(p, v) KMP_ATOMIC_OP(store, p, v, relaxed) // For non-default fetch_ #define KMP_ATOMIC_ADD(p, v) KMP_ATOMIC_OP(fetch_add, p, v, acq_rel) #define KMP_ATOMIC_SUB(p, v) KMP_ATOMIC_OP(fetch_sub, p, v, acq_rel) #define KMP_ATOMIC_AND(p, v) KMP_ATOMIC_OP(fetch_and, p, v, acq_rel) #define KMP_ATOMIC_OR(p, v) KMP_ATOMIC_OP(fetch_or, p, v, acq_rel) #define KMP_ATOMIC_INC(p) KMP_ATOMIC_OP(fetch_add, p, 1, acq_rel) #define KMP_ATOMIC_DEC(p) KMP_ATOMIC_OP(fetch_sub, p, 1, acq_rel) #define KMP_ATOMIC_ADD_RLX(p, v) KMP_ATOMIC_OP(fetch_add, p, v, relaxed) #define KMP_ATOMIC_INC_RLX(p) KMP_ATOMIC_OP(fetch_add, p, 1, relaxed) // Callers of the following functions cannot see the side effect on "expected". template bool __kmp_atomic_compare_store(std::atomic *p, T expected, T desired) { return p->compare_exchange_strong( expected, desired, std::memory_order_acq_rel, std::memory_order_relaxed); } template bool __kmp_atomic_compare_store_acq(std::atomic *p, T expected, T desired) { return p->compare_exchange_strong( expected, desired, std::memory_order_acquire, std::memory_order_relaxed); } template bool __kmp_atomic_compare_store_rel(std::atomic *p, T expected, T desired) { return p->compare_exchange_strong( expected, desired, std::memory_order_release, std::memory_order_relaxed); } #endif /* KMP_OS_H */ // Safe C API #include "kmp_safe_c_api.h" Index: head/contrib/llvm-project/openmp/runtime/src/kmp_runtime.cpp =================================================================== --- head/contrib/llvm-project/openmp/runtime/src/kmp_runtime.cpp (revision 364731) +++ head/contrib/llvm-project/openmp/runtime/src/kmp_runtime.cpp (revision 364732) @@ -1,8307 +1,8281 @@ /* * kmp_runtime.cpp -- KPTS runtime support library */ //===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "kmp.h" #include "kmp_affinity.h" #include "kmp_atomic.h" #include "kmp_environment.h" #include "kmp_error.h" #include "kmp_i18n.h" #include "kmp_io.h" #include "kmp_itt.h" #include "kmp_settings.h" #include "kmp_stats.h" #include "kmp_str.h" #include "kmp_wait_release.h" #include "kmp_wrapper_getpid.h" #include "kmp_dispatch.h" #if KMP_USE_HIER_SCHED #include "kmp_dispatch_hier.h" #endif #if OMPT_SUPPORT #include "ompt-specific.h" #endif /* these are temporary issues to be dealt with */ #define KMP_USE_PRCTL 0 #if KMP_OS_WINDOWS #include #endif #include "tsan_annotations.h" #if defined(KMP_GOMP_COMPAT) char const __kmp_version_alt_comp[] = KMP_VERSION_PREFIX "alternative compiler support: yes"; #endif /* defined(KMP_GOMP_COMPAT) */ char const __kmp_version_omp_api[] = KMP_VERSION_PREFIX "API version: 5.0 (201611)"; #ifdef KMP_DEBUG char const __kmp_version_lock[] = KMP_VERSION_PREFIX "lock type: run time selectable"; #endif /* KMP_DEBUG */ #define KMP_MIN(x, y) ((x) < (y) ? (x) : (y)) /* ------------------------------------------------------------------------ */ #if KMP_USE_MONITOR kmp_info_t __kmp_monitor; #endif /* Forward declarations */ void __kmp_cleanup(void); static void __kmp_initialize_info(kmp_info_t *, kmp_team_t *, int tid, int gtid); static void __kmp_initialize_team(kmp_team_t *team, int new_nproc, kmp_internal_control_t *new_icvs, ident_t *loc); #if KMP_AFFINITY_SUPPORTED static void __kmp_partition_places(kmp_team_t *team, int update_master_only = 0); #endif static void __kmp_do_serial_initialize(void); void __kmp_fork_barrier(int gtid, int tid); void __kmp_join_barrier(int gtid); void __kmp_setup_icv_copy(kmp_team_t *team, int new_nproc, kmp_internal_control_t *new_icvs, ident_t *loc); #ifdef USE_LOAD_BALANCE static int __kmp_load_balance_nproc(kmp_root_t *root, int set_nproc); #endif static int __kmp_expand_threads(int nNeed); #if KMP_OS_WINDOWS static int __kmp_unregister_root_other_thread(int gtid); #endif static void __kmp_unregister_library(void); // called by __kmp_internal_end() static void __kmp_reap_thread(kmp_info_t *thread, int is_root); kmp_info_t *__kmp_thread_pool_insert_pt = NULL; /* Calculate the identifier of the current thread */ /* fast (and somewhat portable) way to get unique identifier of executing thread. Returns KMP_GTID_DNE if we haven't been assigned a gtid. */ int __kmp_get_global_thread_id() { int i; kmp_info_t **other_threads; size_t stack_data; char *stack_addr; size_t stack_size; char *stack_base; KA_TRACE( 1000, ("*** __kmp_get_global_thread_id: entering, nproc=%d all_nproc=%d\n", __kmp_nth, __kmp_all_nth)); /* JPH - to handle the case where __kmpc_end(0) is called immediately prior to a parallel region, made it return KMP_GTID_DNE to force serial_initialize by caller. Had to handle KMP_GTID_DNE at all call-sites, or else guarantee __kmp_init_gtid for this to work. */ if (!TCR_4(__kmp_init_gtid)) return KMP_GTID_DNE; #ifdef KMP_TDATA_GTID if (TCR_4(__kmp_gtid_mode) >= 3) { KA_TRACE(1000, ("*** __kmp_get_global_thread_id: using TDATA\n")); return __kmp_gtid; } #endif if (TCR_4(__kmp_gtid_mode) >= 2) { KA_TRACE(1000, ("*** __kmp_get_global_thread_id: using keyed TLS\n")); return __kmp_gtid_get_specific(); } KA_TRACE(1000, ("*** __kmp_get_global_thread_id: using internal alg.\n")); stack_addr = (char *)&stack_data; other_threads = __kmp_threads; /* ATT: The code below is a source of potential bugs due to unsynchronized access to __kmp_threads array. For example: 1. Current thread loads other_threads[i] to thr and checks it, it is non-NULL. 2. Current thread is suspended by OS. 3. Another thread unregisters and finishes (debug versions of free() may fill memory with something like 0xEF). 4. Current thread is resumed. 5. Current thread reads junk from *thr. TODO: Fix it. --ln */ for (i = 0; i < __kmp_threads_capacity; i++) { kmp_info_t *thr = (kmp_info_t *)TCR_SYNC_PTR(other_threads[i]); if (!thr) continue; stack_size = (size_t)TCR_PTR(thr->th.th_info.ds.ds_stacksize); stack_base = (char *)TCR_PTR(thr->th.th_info.ds.ds_stackbase); /* stack grows down -- search through all of the active threads */ if (stack_addr <= stack_base) { size_t stack_diff = stack_base - stack_addr; if (stack_diff <= stack_size) { /* The only way we can be closer than the allocated */ /* stack size is if we are running on this thread. */ KMP_DEBUG_ASSERT(__kmp_gtid_get_specific() == i); return i; } } } /* get specific to try and determine our gtid */ KA_TRACE(1000, ("*** __kmp_get_global_thread_id: internal alg. failed to find " "thread, using TLS\n")); i = __kmp_gtid_get_specific(); /*fprintf( stderr, "=== %d\n", i ); */ /* GROO */ /* if we havn't been assigned a gtid, then return code */ if (i < 0) return i; /* dynamically updated stack window for uber threads to avoid get_specific call */ if (!TCR_4(other_threads[i]->th.th_info.ds.ds_stackgrow)) { KMP_FATAL(StackOverflow, i); } stack_base = (char *)other_threads[i]->th.th_info.ds.ds_stackbase; if (stack_addr > stack_base) { TCW_PTR(other_threads[i]->th.th_info.ds.ds_stackbase, stack_addr); TCW_PTR(other_threads[i]->th.th_info.ds.ds_stacksize, other_threads[i]->th.th_info.ds.ds_stacksize + stack_addr - stack_base); } else { TCW_PTR(other_threads[i]->th.th_info.ds.ds_stacksize, stack_base - stack_addr); } /* Reprint stack bounds for ubermaster since they have been refined */ if (__kmp_storage_map) { char *stack_end = (char *)other_threads[i]->th.th_info.ds.ds_stackbase; char *stack_beg = stack_end - other_threads[i]->th.th_info.ds.ds_stacksize; __kmp_print_storage_map_gtid(i, stack_beg, stack_end, other_threads[i]->th.th_info.ds.ds_stacksize, "th_%d stack (refinement)", i); } return i; } int __kmp_get_global_thread_id_reg() { int gtid; if (!__kmp_init_serial) { gtid = KMP_GTID_DNE; } else #ifdef KMP_TDATA_GTID if (TCR_4(__kmp_gtid_mode) >= 3) { KA_TRACE(1000, ("*** __kmp_get_global_thread_id_reg: using TDATA\n")); gtid = __kmp_gtid; } else #endif if (TCR_4(__kmp_gtid_mode) >= 2) { KA_TRACE(1000, ("*** __kmp_get_global_thread_id_reg: using keyed TLS\n")); gtid = __kmp_gtid_get_specific(); } else { KA_TRACE(1000, ("*** __kmp_get_global_thread_id_reg: using internal alg.\n")); gtid = __kmp_get_global_thread_id(); } /* we must be a new uber master sibling thread */ if (gtid == KMP_GTID_DNE) { KA_TRACE(10, ("__kmp_get_global_thread_id_reg: Encountered new root thread. " "Registering a new gtid.\n")); __kmp_acquire_bootstrap_lock(&__kmp_initz_lock); if (!__kmp_init_serial) { __kmp_do_serial_initialize(); gtid = __kmp_gtid_get_specific(); } else { gtid = __kmp_register_root(FALSE); } __kmp_release_bootstrap_lock(&__kmp_initz_lock); /*__kmp_printf( "+++ %d\n", gtid ); */ /* GROO */ } KMP_DEBUG_ASSERT(gtid >= 0); return gtid; } /* caller must hold forkjoin_lock */ void __kmp_check_stack_overlap(kmp_info_t *th) { int f; char *stack_beg = NULL; char *stack_end = NULL; int gtid; KA_TRACE(10, ("__kmp_check_stack_overlap: called\n")); if (__kmp_storage_map) { stack_end = (char *)th->th.th_info.ds.ds_stackbase; stack_beg = stack_end - th->th.th_info.ds.ds_stacksize; gtid = __kmp_gtid_from_thread(th); if (gtid == KMP_GTID_MONITOR) { __kmp_print_storage_map_gtid( gtid, stack_beg, stack_end, th->th.th_info.ds.ds_stacksize, "th_%s stack (%s)", "mon", (th->th.th_info.ds.ds_stackgrow) ? "initial" : "actual"); } else { __kmp_print_storage_map_gtid( gtid, stack_beg, stack_end, th->th.th_info.ds.ds_stacksize, "th_%d stack (%s)", gtid, (th->th.th_info.ds.ds_stackgrow) ? "initial" : "actual"); } } /* No point in checking ubermaster threads since they use refinement and * cannot overlap */ gtid = __kmp_gtid_from_thread(th); if (__kmp_env_checks == TRUE && !KMP_UBER_GTID(gtid)) { KA_TRACE(10, ("__kmp_check_stack_overlap: performing extensive checking\n")); if (stack_beg == NULL) { stack_end = (char *)th->th.th_info.ds.ds_stackbase; stack_beg = stack_end - th->th.th_info.ds.ds_stacksize; } for (f = 0; f < __kmp_threads_capacity; f++) { kmp_info_t *f_th = (kmp_info_t *)TCR_SYNC_PTR(__kmp_threads[f]); if (f_th && f_th != th) { char *other_stack_end = (char *)TCR_PTR(f_th->th.th_info.ds.ds_stackbase); char *other_stack_beg = other_stack_end - (size_t)TCR_PTR(f_th->th.th_info.ds.ds_stacksize); if ((stack_beg > other_stack_beg && stack_beg < other_stack_end) || (stack_end > other_stack_beg && stack_end < other_stack_end)) { /* Print the other stack values before the abort */ if (__kmp_storage_map) __kmp_print_storage_map_gtid( -1, other_stack_beg, other_stack_end, (size_t)TCR_PTR(f_th->th.th_info.ds.ds_stacksize), "th_%d stack (overlapped)", __kmp_gtid_from_thread(f_th)); __kmp_fatal(KMP_MSG(StackOverlap), KMP_HNT(ChangeStackLimit), __kmp_msg_null); } } } } KA_TRACE(10, ("__kmp_check_stack_overlap: returning\n")); } /* ------------------------------------------------------------------------ */ void __kmp_infinite_loop(void) { static int done = FALSE; while (!done) { KMP_YIELD(TRUE); } } #define MAX_MESSAGE 512 void __kmp_print_storage_map_gtid(int gtid, void *p1, void *p2, size_t size, char const *format, ...) { char buffer[MAX_MESSAGE]; va_list ap; va_start(ap, format); KMP_SNPRINTF(buffer, sizeof(buffer), "OMP storage map: %p %p%8lu %s\n", p1, p2, (unsigned long)size, format); __kmp_acquire_bootstrap_lock(&__kmp_stdio_lock); __kmp_vprintf(kmp_err, buffer, ap); #if KMP_PRINT_DATA_PLACEMENT int node; if (gtid >= 0) { if (p1 <= p2 && (char *)p2 - (char *)p1 == size) { if (__kmp_storage_map_verbose) { node = __kmp_get_host_node(p1); if (node < 0) /* doesn't work, so don't try this next time */ __kmp_storage_map_verbose = FALSE; else { char *last; int lastNode; int localProc = __kmp_get_cpu_from_gtid(gtid); const int page_size = KMP_GET_PAGE_SIZE(); p1 = (void *)((size_t)p1 & ~((size_t)page_size - 1)); p2 = (void *)(((size_t)p2 - 1) & ~((size_t)page_size - 1)); if (localProc >= 0) __kmp_printf_no_lock(" GTID %d localNode %d\n", gtid, localProc >> 1); else __kmp_printf_no_lock(" GTID %d\n", gtid); #if KMP_USE_PRCTL /* The more elaborate format is disabled for now because of the prctl * hanging bug. */ do { last = p1; lastNode = node; /* This loop collates adjacent pages with the same host node. */ do { (char *)p1 += page_size; } while (p1 <= p2 && (node = __kmp_get_host_node(p1)) == lastNode); __kmp_printf_no_lock(" %p-%p memNode %d\n", last, (char *)p1 - 1, lastNode); } while (p1 <= p2); #else __kmp_printf_no_lock(" %p-%p memNode %d\n", p1, (char *)p1 + (page_size - 1), __kmp_get_host_node(p1)); if (p1 < p2) { __kmp_printf_no_lock(" %p-%p memNode %d\n", p2, (char *)p2 + (page_size - 1), __kmp_get_host_node(p2)); } #endif } } } else __kmp_printf_no_lock(" %s\n", KMP_I18N_STR(StorageMapWarning)); } #endif /* KMP_PRINT_DATA_PLACEMENT */ __kmp_release_bootstrap_lock(&__kmp_stdio_lock); } void __kmp_warn(char const *format, ...) { char buffer[MAX_MESSAGE]; va_list ap; if (__kmp_generate_warnings == kmp_warnings_off) { return; } va_start(ap, format); KMP_SNPRINTF(buffer, sizeof(buffer), "OMP warning: %s\n", format); __kmp_acquire_bootstrap_lock(&__kmp_stdio_lock); __kmp_vprintf(kmp_err, buffer, ap); __kmp_release_bootstrap_lock(&__kmp_stdio_lock); va_end(ap); } void __kmp_abort_process() { // Later threads may stall here, but that's ok because abort() will kill them. __kmp_acquire_bootstrap_lock(&__kmp_exit_lock); if (__kmp_debug_buf) { __kmp_dump_debug_buffer(); } if (KMP_OS_WINDOWS) { // Let other threads know of abnormal termination and prevent deadlock // if abort happened during library initialization or shutdown __kmp_global.g.g_abort = SIGABRT; /* On Windows* OS by default abort() causes pop-up error box, which stalls nightly testing. Unfortunately, we cannot reliably suppress pop-up error boxes. _set_abort_behavior() works well, but this function is not available in VS7 (this is not problem for DLL, but it is a problem for static OpenMP RTL). SetErrorMode (and so, timelimit utility) does not help, at least in some versions of MS C RTL. It seems following sequence is the only way to simulate abort() and avoid pop-up error box. */ raise(SIGABRT); _exit(3); // Just in case, if signal ignored, exit anyway. } else { abort(); } __kmp_infinite_loop(); __kmp_release_bootstrap_lock(&__kmp_exit_lock); } // __kmp_abort_process void __kmp_abort_thread(void) { // TODO: Eliminate g_abort global variable and this function. // In case of abort just call abort(), it will kill all the threads. __kmp_infinite_loop(); } // __kmp_abort_thread /* Print out the storage map for the major kmp_info_t thread data structures that are allocated together. */ static void __kmp_print_thread_storage_map(kmp_info_t *thr, int gtid) { __kmp_print_storage_map_gtid(gtid, thr, thr + 1, sizeof(kmp_info_t), "th_%d", gtid); __kmp_print_storage_map_gtid(gtid, &thr->th.th_info, &thr->th.th_team, sizeof(kmp_desc_t), "th_%d.th_info", gtid); __kmp_print_storage_map_gtid(gtid, &thr->th.th_local, &thr->th.th_pri_head, sizeof(kmp_local_t), "th_%d.th_local", gtid); __kmp_print_storage_map_gtid( gtid, &thr->th.th_bar[0], &thr->th.th_bar[bs_last_barrier], sizeof(kmp_balign_t) * bs_last_barrier, "th_%d.th_bar", gtid); __kmp_print_storage_map_gtid(gtid, &thr->th.th_bar[bs_plain_barrier], &thr->th.th_bar[bs_plain_barrier + 1], sizeof(kmp_balign_t), "th_%d.th_bar[plain]", gtid); __kmp_print_storage_map_gtid(gtid, &thr->th.th_bar[bs_forkjoin_barrier], &thr->th.th_bar[bs_forkjoin_barrier + 1], sizeof(kmp_balign_t), "th_%d.th_bar[forkjoin]", gtid); #if KMP_FAST_REDUCTION_BARRIER __kmp_print_storage_map_gtid(gtid, &thr->th.th_bar[bs_reduction_barrier], &thr->th.th_bar[bs_reduction_barrier + 1], sizeof(kmp_balign_t), "th_%d.th_bar[reduction]", gtid); #endif // KMP_FAST_REDUCTION_BARRIER } /* Print out the storage map for the major kmp_team_t team data structures that are allocated together. */ static void __kmp_print_team_storage_map(const char *header, kmp_team_t *team, int team_id, int num_thr) { int num_disp_buff = team->t.t_max_nproc > 1 ? __kmp_dispatch_num_buffers : 2; __kmp_print_storage_map_gtid(-1, team, team + 1, sizeof(kmp_team_t), "%s_%d", header, team_id); __kmp_print_storage_map_gtid(-1, &team->t.t_bar[0], &team->t.t_bar[bs_last_barrier], sizeof(kmp_balign_team_t) * bs_last_barrier, "%s_%d.t_bar", header, team_id); __kmp_print_storage_map_gtid(-1, &team->t.t_bar[bs_plain_barrier], &team->t.t_bar[bs_plain_barrier + 1], sizeof(kmp_balign_team_t), "%s_%d.t_bar[plain]", header, team_id); __kmp_print_storage_map_gtid(-1, &team->t.t_bar[bs_forkjoin_barrier], &team->t.t_bar[bs_forkjoin_barrier + 1], sizeof(kmp_balign_team_t), "%s_%d.t_bar[forkjoin]", header, team_id); #if KMP_FAST_REDUCTION_BARRIER __kmp_print_storage_map_gtid(-1, &team->t.t_bar[bs_reduction_barrier], &team->t.t_bar[bs_reduction_barrier + 1], sizeof(kmp_balign_team_t), "%s_%d.t_bar[reduction]", header, team_id); #endif // KMP_FAST_REDUCTION_BARRIER __kmp_print_storage_map_gtid( -1, &team->t.t_dispatch[0], &team->t.t_dispatch[num_thr], sizeof(kmp_disp_t) * num_thr, "%s_%d.t_dispatch", header, team_id); __kmp_print_storage_map_gtid( -1, &team->t.t_threads[0], &team->t.t_threads[num_thr], sizeof(kmp_info_t *) * num_thr, "%s_%d.t_threads", header, team_id); __kmp_print_storage_map_gtid(-1, &team->t.t_disp_buffer[0], &team->t.t_disp_buffer[num_disp_buff], sizeof(dispatch_shared_info_t) * num_disp_buff, "%s_%d.t_disp_buffer", header, team_id); } static void __kmp_init_allocator() { __kmp_init_memkind(); } static void __kmp_fini_allocator() { __kmp_fini_memkind(); } /* ------------------------------------------------------------------------ */ #if KMP_DYNAMIC_LIB #if KMP_OS_WINDOWS static void __kmp_reset_lock(kmp_bootstrap_lock_t *lck) { // TODO: Change to __kmp_break_bootstrap_lock(). __kmp_init_bootstrap_lock(lck); // make the lock released } static void __kmp_reset_locks_on_process_detach(int gtid_req) { int i; int thread_count; // PROCESS_DETACH is expected to be called by a thread that executes // ProcessExit() or FreeLibrary(). OS terminates other threads (except the one // calling ProcessExit or FreeLibrary). So, it might be safe to access the // __kmp_threads[] without taking the forkjoin_lock. However, in fact, some // threads can be still alive here, although being about to be terminated. The // threads in the array with ds_thread==0 are most suspicious. Actually, it // can be not safe to access the __kmp_threads[]. // TODO: does it make sense to check __kmp_roots[] ? // Let's check that there are no other alive threads registered with the OMP // lib. while (1) { thread_count = 0; for (i = 0; i < __kmp_threads_capacity; ++i) { if (!__kmp_threads) continue; kmp_info_t *th = __kmp_threads[i]; if (th == NULL) continue; int gtid = th->th.th_info.ds.ds_gtid; if (gtid == gtid_req) continue; if (gtid < 0) continue; DWORD exit_val; int alive = __kmp_is_thread_alive(th, &exit_val); if (alive) { ++thread_count; } } if (thread_count == 0) break; // success } // Assume that I'm alone. Now it might be safe to check and reset locks. // __kmp_forkjoin_lock and __kmp_stdio_lock are expected to be reset. __kmp_reset_lock(&__kmp_forkjoin_lock); #ifdef KMP_DEBUG __kmp_reset_lock(&__kmp_stdio_lock); #endif // KMP_DEBUG } BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID lpReserved) { //__kmp_acquire_bootstrap_lock( &__kmp_initz_lock ); switch (fdwReason) { case DLL_PROCESS_ATTACH: KA_TRACE(10, ("DllMain: PROCESS_ATTACH\n")); return TRUE; case DLL_PROCESS_DETACH: KA_TRACE(10, ("DllMain: PROCESS_DETACH T#%d\n", __kmp_gtid_get_specific())); if (lpReserved != NULL) { // lpReserved is used for telling the difference: // lpReserved == NULL when FreeLibrary() was called, // lpReserved != NULL when the process terminates. // When FreeLibrary() is called, worker threads remain alive. So they will // release the forkjoin lock by themselves. When the process terminates, // worker threads disappear triggering the problem of unreleased forkjoin // lock as described below. // A worker thread can take the forkjoin lock. The problem comes up if // that worker thread becomes dead before it releases the forkjoin lock. // The forkjoin lock remains taken, while the thread executing // DllMain()->PROCESS_DETACH->__kmp_internal_end_library() below will try // to take the forkjoin lock and will always fail, so that the application // will never finish [normally]. This scenario is possible if // __kmpc_end() has not been executed. It looks like it's not a corner // case, but common cases: // - the main function was compiled by an alternative compiler; // - the main function was compiled by icl but without /Qopenmp // (application with plugins); // - application terminates by calling C exit(), Fortran CALL EXIT() or // Fortran STOP. // - alive foreign thread prevented __kmpc_end from doing cleanup. // // This is a hack to work around the problem. // TODO: !!! figure out something better. __kmp_reset_locks_on_process_detach(__kmp_gtid_get_specific()); } __kmp_internal_end_library(__kmp_gtid_get_specific()); return TRUE; case DLL_THREAD_ATTACH: KA_TRACE(10, ("DllMain: THREAD_ATTACH\n")); /* if we want to register new siblings all the time here call * __kmp_get_gtid(); */ return TRUE; case DLL_THREAD_DETACH: KA_TRACE(10, ("DllMain: THREAD_DETACH T#%d\n", __kmp_gtid_get_specific())); __kmp_internal_end_thread(__kmp_gtid_get_specific()); return TRUE; } return TRUE; } #endif /* KMP_OS_WINDOWS */ #endif /* KMP_DYNAMIC_LIB */ /* __kmp_parallel_deo -- Wait until it's our turn. */ void __kmp_parallel_deo(int *gtid_ref, int *cid_ref, ident_t *loc_ref) { int gtid = *gtid_ref; #ifdef BUILD_PARALLEL_ORDERED kmp_team_t *team = __kmp_team_from_gtid(gtid); #endif /* BUILD_PARALLEL_ORDERED */ if (__kmp_env_consistency_check) { if (__kmp_threads[gtid]->th.th_root->r.r_active) #if KMP_USE_DYNAMIC_LOCK __kmp_push_sync(gtid, ct_ordered_in_parallel, loc_ref, NULL, 0); #else __kmp_push_sync(gtid, ct_ordered_in_parallel, loc_ref, NULL); #endif } #ifdef BUILD_PARALLEL_ORDERED if (!team->t.t_serialized) { KMP_MB(); KMP_WAIT(&team->t.t_ordered.dt.t_value, __kmp_tid_from_gtid(gtid), KMP_EQ, NULL); KMP_MB(); } #endif /* BUILD_PARALLEL_ORDERED */ } /* __kmp_parallel_dxo -- Signal the next task. */ void __kmp_parallel_dxo(int *gtid_ref, int *cid_ref, ident_t *loc_ref) { int gtid = *gtid_ref; #ifdef BUILD_PARALLEL_ORDERED int tid = __kmp_tid_from_gtid(gtid); kmp_team_t *team = __kmp_team_from_gtid(gtid); #endif /* BUILD_PARALLEL_ORDERED */ if (__kmp_env_consistency_check) { if (__kmp_threads[gtid]->th.th_root->r.r_active) __kmp_pop_sync(gtid, ct_ordered_in_parallel, loc_ref); } #ifdef BUILD_PARALLEL_ORDERED if (!team->t.t_serialized) { KMP_MB(); /* Flush all pending memory write invalidates. */ /* use the tid of the next thread in this team */ /* TODO replace with general release procedure */ team->t.t_ordered.dt.t_value = ((tid + 1) % team->t.t_nproc); KMP_MB(); /* Flush all pending memory write invalidates. */ } #endif /* BUILD_PARALLEL_ORDERED */ } /* ------------------------------------------------------------------------ */ /* The BARRIER for a SINGLE process section is always explicit */ int __kmp_enter_single(int gtid, ident_t *id_ref, int push_ws) { int status; kmp_info_t *th; kmp_team_t *team; if (!TCR_4(__kmp_init_parallel)) __kmp_parallel_initialize(); __kmp_resume_if_soft_paused(); th = __kmp_threads[gtid]; team = th->th.th_team; status = 0; th->th.th_ident = id_ref; if (team->t.t_serialized) { status = 1; } else { kmp_int32 old_this = th->th.th_local.this_construct; ++th->th.th_local.this_construct; /* try to set team count to thread count--success means thread got the single block */ /* TODO: Should this be acquire or release? */ if (team->t.t_construct == old_this) { status = __kmp_atomic_compare_store_acq(&team->t.t_construct, old_this, th->th.th_local.this_construct); } #if USE_ITT_BUILD if (__itt_metadata_add_ptr && __kmp_forkjoin_frames_mode == 3 && KMP_MASTER_GTID(gtid) && th->th.th_teams_microtask == NULL && team->t.t_active_level == 1) { // Only report metadata by master of active team at level 1 __kmp_itt_metadata_single(id_ref); } #endif /* USE_ITT_BUILD */ } if (__kmp_env_consistency_check) { if (status && push_ws) { __kmp_push_workshare(gtid, ct_psingle, id_ref); } else { __kmp_check_workshare(gtid, ct_psingle, id_ref); } } #if USE_ITT_BUILD if (status) { __kmp_itt_single_start(gtid); } #endif /* USE_ITT_BUILD */ return status; } void __kmp_exit_single(int gtid) { #if USE_ITT_BUILD __kmp_itt_single_end(gtid); #endif /* USE_ITT_BUILD */ if (__kmp_env_consistency_check) __kmp_pop_workshare(gtid, ct_psingle, NULL); } /* determine if we can go parallel or must use a serialized parallel region and * how many threads we can use * set_nproc is the number of threads requested for the team * returns 0 if we should serialize or only use one thread, * otherwise the number of threads to use * The forkjoin lock is held by the caller. */ static int __kmp_reserve_threads(kmp_root_t *root, kmp_team_t *parent_team, int master_tid, int set_nthreads, int enter_teams) { int capacity; int new_nthreads; KMP_DEBUG_ASSERT(__kmp_init_serial); KMP_DEBUG_ASSERT(root && parent_team); kmp_info_t *this_thr = parent_team->t.t_threads[master_tid]; // If dyn-var is set, dynamically adjust the number of desired threads, // according to the method specified by dynamic_mode. new_nthreads = set_nthreads; if (!get__dynamic_2(parent_team, master_tid)) { ; } #ifdef USE_LOAD_BALANCE else if (__kmp_global.g.g_dynamic_mode == dynamic_load_balance) { new_nthreads = __kmp_load_balance_nproc(root, set_nthreads); if (new_nthreads == 1) { KC_TRACE(10, ("__kmp_reserve_threads: T#%d load balance reduced " "reservation to 1 thread\n", master_tid)); return 1; } if (new_nthreads < set_nthreads) { KC_TRACE(10, ("__kmp_reserve_threads: T#%d load balance reduced " "reservation to %d threads\n", master_tid, new_nthreads)); } } #endif /* USE_LOAD_BALANCE */ else if (__kmp_global.g.g_dynamic_mode == dynamic_thread_limit) { new_nthreads = __kmp_avail_proc - __kmp_nth + (root->r.r_active ? 1 : root->r.r_hot_team->t.t_nproc); if (new_nthreads <= 1) { KC_TRACE(10, ("__kmp_reserve_threads: T#%d thread limit reduced " "reservation to 1 thread\n", master_tid)); return 1; } if (new_nthreads < set_nthreads) { KC_TRACE(10, ("__kmp_reserve_threads: T#%d thread limit reduced " "reservation to %d threads\n", master_tid, new_nthreads)); } else { new_nthreads = set_nthreads; } } else if (__kmp_global.g.g_dynamic_mode == dynamic_random) { if (set_nthreads > 2) { new_nthreads = __kmp_get_random(parent_team->t.t_threads[master_tid]); new_nthreads = (new_nthreads % set_nthreads) + 1; if (new_nthreads == 1) { KC_TRACE(10, ("__kmp_reserve_threads: T#%d dynamic random reduced " "reservation to 1 thread\n", master_tid)); return 1; } if (new_nthreads < set_nthreads) { KC_TRACE(10, ("__kmp_reserve_threads: T#%d dynamic random reduced " "reservation to %d threads\n", master_tid, new_nthreads)); } } } else { KMP_ASSERT(0); } // Respect KMP_ALL_THREADS/KMP_DEVICE_THREAD_LIMIT. if (__kmp_nth + new_nthreads - (root->r.r_active ? 1 : root->r.r_hot_team->t.t_nproc) > __kmp_max_nth) { int tl_nthreads = __kmp_max_nth - __kmp_nth + (root->r.r_active ? 1 : root->r.r_hot_team->t.t_nproc); if (tl_nthreads <= 0) { tl_nthreads = 1; } // If dyn-var is false, emit a 1-time warning. if (!get__dynamic_2(parent_team, master_tid) && (!__kmp_reserve_warn)) { __kmp_reserve_warn = 1; __kmp_msg(kmp_ms_warning, KMP_MSG(CantFormThrTeam, set_nthreads, tl_nthreads), KMP_HNT(Unset_ALL_THREADS), __kmp_msg_null); } if (tl_nthreads == 1) { KC_TRACE(10, ("__kmp_reserve_threads: T#%d KMP_DEVICE_THREAD_LIMIT " "reduced reservation to 1 thread\n", master_tid)); return 1; } KC_TRACE(10, ("__kmp_reserve_threads: T#%d KMP_DEVICE_THREAD_LIMIT reduced " "reservation to %d threads\n", master_tid, tl_nthreads)); new_nthreads = tl_nthreads; } // Respect OMP_THREAD_LIMIT int cg_nthreads = this_thr->th.th_cg_roots->cg_nthreads; int max_cg_threads = this_thr->th.th_cg_roots->cg_thread_limit; if (cg_nthreads + new_nthreads - (root->r.r_active ? 1 : root->r.r_hot_team->t.t_nproc) > max_cg_threads) { int tl_nthreads = max_cg_threads - cg_nthreads + (root->r.r_active ? 1 : root->r.r_hot_team->t.t_nproc); if (tl_nthreads <= 0) { tl_nthreads = 1; } // If dyn-var is false, emit a 1-time warning. if (!get__dynamic_2(parent_team, master_tid) && (!__kmp_reserve_warn)) { __kmp_reserve_warn = 1; __kmp_msg(kmp_ms_warning, KMP_MSG(CantFormThrTeam, set_nthreads, tl_nthreads), KMP_HNT(Unset_ALL_THREADS), __kmp_msg_null); } if (tl_nthreads == 1) { KC_TRACE(10, ("__kmp_reserve_threads: T#%d OMP_THREAD_LIMIT " "reduced reservation to 1 thread\n", master_tid)); return 1; } KC_TRACE(10, ("__kmp_reserve_threads: T#%d OMP_THREAD_LIMIT reduced " "reservation to %d threads\n", master_tid, tl_nthreads)); new_nthreads = tl_nthreads; } // Check if the threads array is large enough, or needs expanding. // See comment in __kmp_register_root() about the adjustment if // __kmp_threads[0] == NULL. capacity = __kmp_threads_capacity; if (TCR_PTR(__kmp_threads[0]) == NULL) { --capacity; } if (__kmp_nth + new_nthreads - (root->r.r_active ? 1 : root->r.r_hot_team->t.t_nproc) > capacity) { // Expand the threads array. int slotsRequired = __kmp_nth + new_nthreads - (root->r.r_active ? 1 : root->r.r_hot_team->t.t_nproc) - capacity; int slotsAdded = __kmp_expand_threads(slotsRequired); if (slotsAdded < slotsRequired) { // The threads array was not expanded enough. new_nthreads -= (slotsRequired - slotsAdded); KMP_ASSERT(new_nthreads >= 1); // If dyn-var is false, emit a 1-time warning. if (!get__dynamic_2(parent_team, master_tid) && (!__kmp_reserve_warn)) { __kmp_reserve_warn = 1; if (__kmp_tp_cached) { __kmp_msg(kmp_ms_warning, KMP_MSG(CantFormThrTeam, set_nthreads, new_nthreads), KMP_HNT(Set_ALL_THREADPRIVATE, __kmp_tp_capacity), KMP_HNT(PossibleSystemLimitOnThreads), __kmp_msg_null); } else { __kmp_msg(kmp_ms_warning, KMP_MSG(CantFormThrTeam, set_nthreads, new_nthreads), KMP_HNT(SystemLimitOnThreads), __kmp_msg_null); } } } } #ifdef KMP_DEBUG if (new_nthreads == 1) { KC_TRACE(10, ("__kmp_reserve_threads: T#%d serializing team after reclaiming " "dead roots and rechecking; requested %d threads\n", __kmp_get_gtid(), set_nthreads)); } else { KC_TRACE(10, ("__kmp_reserve_threads: T#%d allocating %d threads; requested" " %d threads\n", __kmp_get_gtid(), new_nthreads, set_nthreads)); } #endif // KMP_DEBUG return new_nthreads; } /* Allocate threads from the thread pool and assign them to the new team. We are assured that there are enough threads available, because we checked on that earlier within critical section forkjoin */ static void __kmp_fork_team_threads(kmp_root_t *root, kmp_team_t *team, kmp_info_t *master_th, int master_gtid) { int i; int use_hot_team; KA_TRACE(10, ("__kmp_fork_team_threads: new_nprocs = %d\n", team->t.t_nproc)); KMP_DEBUG_ASSERT(master_gtid == __kmp_get_gtid()); KMP_MB(); /* first, let's setup the master thread */ master_th->th.th_info.ds.ds_tid = 0; master_th->th.th_team = team; master_th->th.th_team_nproc = team->t.t_nproc; master_th->th.th_team_master = master_th; master_th->th.th_team_serialized = FALSE; master_th->th.th_dispatch = &team->t.t_dispatch[0]; /* make sure we are not the optimized hot team */ #if KMP_NESTED_HOT_TEAMS use_hot_team = 0; kmp_hot_team_ptr_t *hot_teams = master_th->th.th_hot_teams; if (hot_teams) { // hot teams array is not allocated if // KMP_HOT_TEAMS_MAX_LEVEL=0 int level = team->t.t_active_level - 1; // index in array of hot teams if (master_th->th.th_teams_microtask) { // are we inside the teams? if (master_th->th.th_teams_size.nteams > 1) { ++level; // level was not increased in teams construct for // team_of_masters } if (team->t.t_pkfn != (microtask_t)__kmp_teams_master && master_th->th.th_teams_level == team->t.t_level) { ++level; // level was not increased in teams construct for // team_of_workers before the parallel } // team->t.t_level will be increased inside parallel } if (level < __kmp_hot_teams_max_level) { if (hot_teams[level].hot_team) { // hot team has already been allocated for given level KMP_DEBUG_ASSERT(hot_teams[level].hot_team == team); use_hot_team = 1; // the team is ready to use } else { use_hot_team = 0; // AC: threads are not allocated yet hot_teams[level].hot_team = team; // remember new hot team hot_teams[level].hot_team_nth = team->t.t_nproc; } } else { use_hot_team = 0; } } #else use_hot_team = team == root->r.r_hot_team; #endif if (!use_hot_team) { /* install the master thread */ team->t.t_threads[0] = master_th; __kmp_initialize_info(master_th, team, 0, master_gtid); /* now, install the worker threads */ for (i = 1; i < team->t.t_nproc; i++) { /* fork or reallocate a new thread and install it in team */ kmp_info_t *thr = __kmp_allocate_thread(root, team, i); team->t.t_threads[i] = thr; KMP_DEBUG_ASSERT(thr); KMP_DEBUG_ASSERT(thr->th.th_team == team); /* align team and thread arrived states */ KA_TRACE(20, ("__kmp_fork_team_threads: T#%d(%d:%d) init arrived " "T#%d(%d:%d) join =%llu, plain=%llu\n", __kmp_gtid_from_tid(0, team), team->t.t_id, 0, __kmp_gtid_from_tid(i, team), team->t.t_id, i, team->t.t_bar[bs_forkjoin_barrier].b_arrived, team->t.t_bar[bs_plain_barrier].b_arrived)); thr->th.th_teams_microtask = master_th->th.th_teams_microtask; thr->th.th_teams_level = master_th->th.th_teams_level; thr->th.th_teams_size = master_th->th.th_teams_size; { // Initialize threads' barrier data. int b; kmp_balign_t *balign = team->t.t_threads[i]->th.th_bar; for (b = 0; b < bs_last_barrier; ++b) { balign[b].bb.b_arrived = team->t.t_bar[b].b_arrived; KMP_DEBUG_ASSERT(balign[b].bb.wait_flag != KMP_BARRIER_PARENT_FLAG); #if USE_DEBUGGER balign[b].bb.b_worker_arrived = team->t.t_bar[b].b_team_arrived; #endif } } } #if KMP_AFFINITY_SUPPORTED __kmp_partition_places(team); #endif } if (__kmp_display_affinity && team->t.t_display_affinity != 1) { for (i = 0; i < team->t.t_nproc; i++) { kmp_info_t *thr = team->t.t_threads[i]; if (thr->th.th_prev_num_threads != team->t.t_nproc || thr->th.th_prev_level != team->t.t_level) { team->t.t_display_affinity = 1; break; } } } KMP_MB(); } #if KMP_ARCH_X86 || KMP_ARCH_X86_64 // Propagate any changes to the floating point control registers out to the team // We try to avoid unnecessary writes to the relevant cache line in the team // structure, so we don't make changes unless they are needed. inline static void propagateFPControl(kmp_team_t *team) { if (__kmp_inherit_fp_control) { kmp_int16 x87_fpu_control_word; kmp_uint32 mxcsr; // Get master values of FPU control flags (both X87 and vector) __kmp_store_x87_fpu_control_word(&x87_fpu_control_word); __kmp_store_mxcsr(&mxcsr); mxcsr &= KMP_X86_MXCSR_MASK; // There is no point looking at t_fp_control_saved here. // If it is TRUE, we still have to update the values if they are different // from those we now have. If it is FALSE we didn't save anything yet, but // our objective is the same. We have to ensure that the values in the team // are the same as those we have. // So, this code achieves what we need whether or not t_fp_control_saved is // true. By checking whether the value needs updating we avoid unnecessary // writes that would put the cache-line into a written state, causing all // threads in the team to have to read it again. KMP_CHECK_UPDATE(team->t.t_x87_fpu_control_word, x87_fpu_control_word); KMP_CHECK_UPDATE(team->t.t_mxcsr, mxcsr); // Although we don't use this value, other code in the runtime wants to know // whether it should restore them. So we must ensure it is correct. KMP_CHECK_UPDATE(team->t.t_fp_control_saved, TRUE); } else { // Similarly here. Don't write to this cache-line in the team structure // unless we have to. KMP_CHECK_UPDATE(team->t.t_fp_control_saved, FALSE); } } // Do the opposite, setting the hardware registers to the updated values from // the team. inline static void updateHWFPControl(kmp_team_t *team) { if (__kmp_inherit_fp_control && team->t.t_fp_control_saved) { // Only reset the fp control regs if they have been changed in the team. // the parallel region that we are exiting. kmp_int16 x87_fpu_control_word; kmp_uint32 mxcsr; __kmp_store_x87_fpu_control_word(&x87_fpu_control_word); __kmp_store_mxcsr(&mxcsr); mxcsr &= KMP_X86_MXCSR_MASK; if (team->t.t_x87_fpu_control_word != x87_fpu_control_word) { __kmp_clear_x87_fpu_status_word(); __kmp_load_x87_fpu_control_word(&team->t.t_x87_fpu_control_word); } if (team->t.t_mxcsr != mxcsr) { __kmp_load_mxcsr(&team->t.t_mxcsr); } } } #else #define propagateFPControl(x) ((void)0) #define updateHWFPControl(x) ((void)0) #endif /* KMP_ARCH_X86 || KMP_ARCH_X86_64 */ static void __kmp_alloc_argv_entries(int argc, kmp_team_t *team, int realloc); // forward declaration /* Run a parallel region that has been serialized, so runs only in a team of the single master thread. */ void __kmp_serialized_parallel(ident_t *loc, kmp_int32 global_tid) { kmp_info_t *this_thr; kmp_team_t *serial_team; KC_TRACE(10, ("__kmpc_serialized_parallel: called by T#%d\n", global_tid)); /* Skip all this code for autopar serialized loops since it results in unacceptable overhead */ if (loc != NULL && (loc->flags & KMP_IDENT_AUTOPAR)) return; if (!TCR_4(__kmp_init_parallel)) __kmp_parallel_initialize(); __kmp_resume_if_soft_paused(); this_thr = __kmp_threads[global_tid]; serial_team = this_thr->th.th_serial_team; /* utilize the serialized team held by this thread */ KMP_DEBUG_ASSERT(serial_team); KMP_MB(); if (__kmp_tasking_mode != tskm_immediate_exec) { KMP_DEBUG_ASSERT( this_thr->th.th_task_team == this_thr->th.th_team->t.t_task_team[this_thr->th.th_task_state]); KMP_DEBUG_ASSERT(serial_team->t.t_task_team[this_thr->th.th_task_state] == NULL); KA_TRACE(20, ("__kmpc_serialized_parallel: T#%d pushing task_team %p / " "team %p, new task_team = NULL\n", global_tid, this_thr->th.th_task_team, this_thr->th.th_team)); this_thr->th.th_task_team = NULL; } kmp_proc_bind_t proc_bind = this_thr->th.th_set_proc_bind; if (this_thr->th.th_current_task->td_icvs.proc_bind == proc_bind_false) { proc_bind = proc_bind_false; } else if (proc_bind == proc_bind_default) { // No proc_bind clause was specified, so use the current value // of proc-bind-var for this parallel region. proc_bind = this_thr->th.th_current_task->td_icvs.proc_bind; } // Reset for next parallel region this_thr->th.th_set_proc_bind = proc_bind_default; #if OMPT_SUPPORT ompt_data_t ompt_parallel_data = ompt_data_none; ompt_data_t *implicit_task_data; void *codeptr = OMPT_LOAD_RETURN_ADDRESS(global_tid); if (ompt_enabled.enabled && this_thr->th.ompt_thread_info.state != ompt_state_overhead) { ompt_task_info_t *parent_task_info; parent_task_info = OMPT_CUR_TASK_INFO(this_thr); parent_task_info->frame.enter_frame.ptr = OMPT_GET_FRAME_ADDRESS(0); if (ompt_enabled.ompt_callback_parallel_begin) { int team_size = 1; ompt_callbacks.ompt_callback(ompt_callback_parallel_begin)( &(parent_task_info->task_data), &(parent_task_info->frame), &ompt_parallel_data, team_size, ompt_parallel_invoker_program | ompt_parallel_team, codeptr); } } #endif // OMPT_SUPPORT if (this_thr->th.th_team != serial_team) { // Nested level will be an index in the nested nthreads array int level = this_thr->th.th_team->t.t_level; if (serial_team->t.t_serialized) { /* this serial team was already used TODO increase performance by making this locks more specific */ kmp_team_t *new_team; __kmp_acquire_bootstrap_lock(&__kmp_forkjoin_lock); new_team = __kmp_allocate_team(this_thr->th.th_root, 1, 1, #if OMPT_SUPPORT ompt_parallel_data, #endif proc_bind, &this_thr->th.th_current_task->td_icvs, 0 USE_NESTED_HOT_ARG(NULL)); __kmp_release_bootstrap_lock(&__kmp_forkjoin_lock); KMP_ASSERT(new_team); /* setup new serialized team and install it */ new_team->t.t_threads[0] = this_thr; new_team->t.t_parent = this_thr->th.th_team; serial_team = new_team; this_thr->th.th_serial_team = serial_team; KF_TRACE( 10, ("__kmpc_serialized_parallel: T#%d allocated new serial team %p\n", global_tid, serial_team)); /* TODO the above breaks the requirement that if we run out of resources, then we can still guarantee that serialized teams are ok, since we may need to allocate a new one */ } else { KF_TRACE( 10, ("__kmpc_serialized_parallel: T#%d reusing cached serial team %p\n", global_tid, serial_team)); } /* we have to initialize this serial team */ KMP_DEBUG_ASSERT(serial_team->t.t_threads); KMP_DEBUG_ASSERT(serial_team->t.t_threads[0] == this_thr); KMP_DEBUG_ASSERT(this_thr->th.th_team != serial_team); serial_team->t.t_ident = loc; serial_team->t.t_serialized = 1; serial_team->t.t_nproc = 1; serial_team->t.t_parent = this_thr->th.th_team; serial_team->t.t_sched.sched = this_thr->th.th_team->t.t_sched.sched; this_thr->th.th_team = serial_team; serial_team->t.t_master_tid = this_thr->th.th_info.ds.ds_tid; KF_TRACE(10, ("__kmpc_serialized_parallel: T#d curtask=%p\n", global_tid, this_thr->th.th_current_task)); KMP_ASSERT(this_thr->th.th_current_task->td_flags.executing == 1); this_thr->th.th_current_task->td_flags.executing = 0; __kmp_push_current_task_to_thread(this_thr, serial_team, 0); /* TODO: GEH: do ICVs work for nested serialized teams? Don't we need an implicit task for each serialized task represented by team->t.t_serialized? */ copy_icvs(&this_thr->th.th_current_task->td_icvs, &this_thr->th.th_current_task->td_parent->td_icvs); // Thread value exists in the nested nthreads array for the next nested // level if (__kmp_nested_nth.used && (level + 1 < __kmp_nested_nth.used)) { this_thr->th.th_current_task->td_icvs.nproc = __kmp_nested_nth.nth[level + 1]; } if (__kmp_nested_proc_bind.used && (level + 1 < __kmp_nested_proc_bind.used)) { this_thr->th.th_current_task->td_icvs.proc_bind = __kmp_nested_proc_bind.bind_types[level + 1]; } #if USE_DEBUGGER serial_team->t.t_pkfn = (microtask_t)(~0); // For the debugger. #endif this_thr->th.th_info.ds.ds_tid = 0; /* set thread cache values */ this_thr->th.th_team_nproc = 1; this_thr->th.th_team_master = this_thr; this_thr->th.th_team_serialized = 1; serial_team->t.t_level = serial_team->t.t_parent->t.t_level + 1; serial_team->t.t_active_level = serial_team->t.t_parent->t.t_active_level; serial_team->t.t_def_allocator = this_thr->th.th_def_allocator; // save propagateFPControl(serial_team); /* check if we need to allocate dispatch buffers stack */ KMP_DEBUG_ASSERT(serial_team->t.t_dispatch); if (!serial_team->t.t_dispatch->th_disp_buffer) { serial_team->t.t_dispatch->th_disp_buffer = (dispatch_private_info_t *)__kmp_allocate( sizeof(dispatch_private_info_t)); } this_thr->th.th_dispatch = serial_team->t.t_dispatch; KMP_MB(); } else { /* this serialized team is already being used, * that's fine, just add another nested level */ KMP_DEBUG_ASSERT(this_thr->th.th_team == serial_team); KMP_DEBUG_ASSERT(serial_team->t.t_threads); KMP_DEBUG_ASSERT(serial_team->t.t_threads[0] == this_thr); ++serial_team->t.t_serialized; this_thr->th.th_team_serialized = serial_team->t.t_serialized; // Nested level will be an index in the nested nthreads array int level = this_thr->th.th_team->t.t_level; // Thread value exists in the nested nthreads array for the next nested // level if (__kmp_nested_nth.used && (level + 1 < __kmp_nested_nth.used)) { this_thr->th.th_current_task->td_icvs.nproc = __kmp_nested_nth.nth[level + 1]; } serial_team->t.t_level++; KF_TRACE(10, ("__kmpc_serialized_parallel: T#%d increasing nesting level " "of serial team %p to %d\n", global_tid, serial_team, serial_team->t.t_level)); /* allocate/push dispatch buffers stack */ KMP_DEBUG_ASSERT(serial_team->t.t_dispatch); { dispatch_private_info_t *disp_buffer = (dispatch_private_info_t *)__kmp_allocate( sizeof(dispatch_private_info_t)); disp_buffer->next = serial_team->t.t_dispatch->th_disp_buffer; serial_team->t.t_dispatch->th_disp_buffer = disp_buffer; } this_thr->th.th_dispatch = serial_team->t.t_dispatch; KMP_MB(); } KMP_CHECK_UPDATE(serial_team->t.t_cancel_request, cancel_noreq); // Perform the display affinity functionality for // serialized parallel regions if (__kmp_display_affinity) { if (this_thr->th.th_prev_level != serial_team->t.t_level || this_thr->th.th_prev_num_threads != 1) { // NULL means use the affinity-format-var ICV __kmp_aux_display_affinity(global_tid, NULL); this_thr->th.th_prev_level = serial_team->t.t_level; this_thr->th.th_prev_num_threads = 1; } } if (__kmp_env_consistency_check) __kmp_push_parallel(global_tid, NULL); #if OMPT_SUPPORT serial_team->t.ompt_team_info.master_return_address = codeptr; if (ompt_enabled.enabled && this_thr->th.ompt_thread_info.state != ompt_state_overhead) { OMPT_CUR_TASK_INFO(this_thr)->frame.exit_frame.ptr = OMPT_GET_FRAME_ADDRESS(0); ompt_lw_taskteam_t lw_taskteam; __ompt_lw_taskteam_init(&lw_taskteam, this_thr, global_tid, &ompt_parallel_data, codeptr); __ompt_lw_taskteam_link(&lw_taskteam, this_thr, 1); // don't use lw_taskteam after linking. content was swaped /* OMPT implicit task begin */ implicit_task_data = OMPT_CUR_TASK_DATA(this_thr); if (ompt_enabled.ompt_callback_implicit_task) { ompt_callbacks.ompt_callback(ompt_callback_implicit_task)( ompt_scope_begin, OMPT_CUR_TEAM_DATA(this_thr), OMPT_CUR_TASK_DATA(this_thr), 1, __kmp_tid_from_gtid(global_tid), ompt_task_implicit); // TODO: Can this be ompt_task_initial? OMPT_CUR_TASK_INFO(this_thr) ->thread_num = __kmp_tid_from_gtid(global_tid); } /* OMPT state */ this_thr->th.ompt_thread_info.state = ompt_state_work_parallel; OMPT_CUR_TASK_INFO(this_thr)->frame.exit_frame.ptr = OMPT_GET_FRAME_ADDRESS(0); } #endif } /* most of the work for a fork */ /* return true if we really went parallel, false if serialized */ int __kmp_fork_call(ident_t *loc, int gtid, enum fork_context_e call_context, // Intel, GNU, ... kmp_int32 argc, microtask_t microtask, launch_t invoker, -/* TODO: revert workaround for Intel(R) 64 tracker #96 */ -#if (KMP_ARCH_X86_64 || KMP_ARCH_ARM || KMP_ARCH_AARCH64) && KMP_OS_LINUX - va_list *ap -#else - va_list ap -#endif - ) { + kmp_va_list ap) { void **argv; int i; int master_tid; int master_this_cons; kmp_team_t *team; kmp_team_t *parent_team; kmp_info_t *master_th; kmp_root_t *root; int nthreads; int master_active; int master_set_numthreads; int level; int active_level; int teams_level; #if KMP_NESTED_HOT_TEAMS kmp_hot_team_ptr_t **p_hot_teams; #endif { // KMP_TIME_BLOCK KMP_TIME_DEVELOPER_PARTITIONED_BLOCK(KMP_fork_call); KMP_COUNT_VALUE(OMP_PARALLEL_args, argc); KA_TRACE(20, ("__kmp_fork_call: enter T#%d\n", gtid)); if (__kmp_stkpadding > 0 && __kmp_root[gtid] != NULL) { /* Some systems prefer the stack for the root thread(s) to start with */ /* some gap from the parent stack to prevent false sharing. */ void *dummy = KMP_ALLOCA(__kmp_stkpadding); /* These 2 lines below are so this does not get optimized out */ if (__kmp_stkpadding > KMP_MAX_STKPADDING) __kmp_stkpadding += (short)((kmp_int64)dummy); } /* initialize if needed */ KMP_DEBUG_ASSERT( __kmp_init_serial); // AC: potentially unsafe, not in sync with shutdown if (!TCR_4(__kmp_init_parallel)) __kmp_parallel_initialize(); __kmp_resume_if_soft_paused(); /* setup current data */ master_th = __kmp_threads[gtid]; // AC: potentially unsafe, not in sync with // shutdown parent_team = master_th->th.th_team; master_tid = master_th->th.th_info.ds.ds_tid; master_this_cons = master_th->th.th_local.this_construct; root = master_th->th.th_root; master_active = root->r.r_active; master_set_numthreads = master_th->th.th_set_nproc; #if OMPT_SUPPORT ompt_data_t ompt_parallel_data = ompt_data_none; ompt_data_t *parent_task_data; ompt_frame_t *ompt_frame; ompt_data_t *implicit_task_data; void *return_address = NULL; if (ompt_enabled.enabled) { __ompt_get_task_info_internal(0, NULL, &parent_task_data, &ompt_frame, NULL, NULL); return_address = OMPT_LOAD_RETURN_ADDRESS(gtid); } #endif // Nested level will be an index in the nested nthreads array level = parent_team->t.t_level; // used to launch non-serial teams even if nested is not allowed active_level = parent_team->t.t_active_level; // needed to check nesting inside the teams teams_level = master_th->th.th_teams_level; #if KMP_NESTED_HOT_TEAMS p_hot_teams = &master_th->th.th_hot_teams; if (*p_hot_teams == NULL && __kmp_hot_teams_max_level > 0) { *p_hot_teams = (kmp_hot_team_ptr_t *)__kmp_allocate( sizeof(kmp_hot_team_ptr_t) * __kmp_hot_teams_max_level); (*p_hot_teams)[0].hot_team = root->r.r_hot_team; // it is either actual or not needed (when active_level > 0) (*p_hot_teams)[0].hot_team_nth = 1; } #endif #if OMPT_SUPPORT if (ompt_enabled.enabled) { if (ompt_enabled.ompt_callback_parallel_begin) { int team_size = master_set_numthreads ? master_set_numthreads : get__nproc_2(parent_team, master_tid); int flags = OMPT_INVOKER(call_context) | ((microtask == (microtask_t)__kmp_teams_master) ? ompt_parallel_league : ompt_parallel_team); ompt_callbacks.ompt_callback(ompt_callback_parallel_begin)( parent_task_data, ompt_frame, &ompt_parallel_data, team_size, flags, return_address); } master_th->th.ompt_thread_info.state = ompt_state_overhead; } #endif master_th->th.th_ident = loc; if (master_th->th.th_teams_microtask && ap && microtask != (microtask_t)__kmp_teams_master && level == teams_level) { // AC: This is start of parallel that is nested inside teams construct. // The team is actual (hot), all workers are ready at the fork barrier. // No lock needed to initialize the team a bit, then free workers. parent_team->t.t_ident = loc; __kmp_alloc_argv_entries(argc, parent_team, TRUE); parent_team->t.t_argc = argc; argv = (void **)parent_team->t.t_argv; for (i = argc - 1; i >= 0; --i) -/* TODO: revert workaround for Intel(R) 64 tracker #96 */ -#if (KMP_ARCH_X86_64 || KMP_ARCH_ARM || KMP_ARCH_AARCH64) && KMP_OS_LINUX - *argv++ = va_arg(*ap, void *); -#else - *argv++ = va_arg(ap, void *); -#endif + *argv++ = va_arg(kmp_va_deref(ap), void *); // Increment our nested depth levels, but not increase the serialization if (parent_team == master_th->th.th_serial_team) { // AC: we are in serialized parallel __kmpc_serialized_parallel(loc, gtid); KMP_DEBUG_ASSERT(parent_team->t.t_serialized > 1); #if OMPT_SUPPORT void *dummy; void **exit_frame_p; ompt_lw_taskteam_t lw_taskteam; if (ompt_enabled.enabled) { __ompt_lw_taskteam_init(&lw_taskteam, master_th, gtid, &ompt_parallel_data, return_address); exit_frame_p = &(lw_taskteam.ompt_task_info.frame.exit_frame.ptr); __ompt_lw_taskteam_link(&lw_taskteam, master_th, 0); // don't use lw_taskteam after linking. content was swaped /* OMPT implicit task begin */ implicit_task_data = OMPT_CUR_TASK_DATA(master_th); if (ompt_enabled.ompt_callback_implicit_task) { OMPT_CUR_TASK_INFO(master_th) ->thread_num = __kmp_tid_from_gtid(gtid); ompt_callbacks.ompt_callback(ompt_callback_implicit_task)( ompt_scope_begin, OMPT_CUR_TEAM_DATA(master_th), implicit_task_data, 1, OMPT_CUR_TASK_INFO(master_th)->thread_num, ompt_task_implicit); } /* OMPT state */ master_th->th.ompt_thread_info.state = ompt_state_work_parallel; } else { exit_frame_p = &dummy; } #endif // AC: need to decrement t_serialized for enquiry functions to work // correctly, will restore at join time parent_team->t.t_serialized--; { KMP_TIME_PARTITIONED_BLOCK(OMP_parallel); KMP_SET_THREAD_STATE_BLOCK(IMPLICIT_TASK); __kmp_invoke_microtask(microtask, gtid, 0, argc, parent_team->t.t_argv #if OMPT_SUPPORT , exit_frame_p #endif ); } #if OMPT_SUPPORT if (ompt_enabled.enabled) { *exit_frame_p = NULL; OMPT_CUR_TASK_INFO(master_th)->frame.exit_frame = ompt_data_none; if (ompt_enabled.ompt_callback_implicit_task) { ompt_callbacks.ompt_callback(ompt_callback_implicit_task)( ompt_scope_end, NULL, implicit_task_data, 1, OMPT_CUR_TASK_INFO(master_th)->thread_num, ompt_task_implicit); } ompt_parallel_data = *OMPT_CUR_TEAM_DATA(master_th); __ompt_lw_taskteam_unlink(master_th); if (ompt_enabled.ompt_callback_parallel_end) { ompt_callbacks.ompt_callback(ompt_callback_parallel_end)( &ompt_parallel_data, OMPT_CUR_TASK_DATA(master_th), OMPT_INVOKER(call_context) | ompt_parallel_team, return_address); } master_th->th.ompt_thread_info.state = ompt_state_overhead; } #endif return TRUE; } parent_team->t.t_pkfn = microtask; parent_team->t.t_invoke = invoker; KMP_ATOMIC_INC(&root->r.r_in_parallel); parent_team->t.t_active_level++; parent_team->t.t_level++; parent_team->t.t_def_allocator = master_th->th.th_def_allocator; // save #if OMPT_SUPPORT if (ompt_enabled.enabled) { ompt_lw_taskteam_t lw_taskteam; __ompt_lw_taskteam_init(&lw_taskteam, master_th, gtid, &ompt_parallel_data, return_address); __ompt_lw_taskteam_link(&lw_taskteam, master_th, 1, true); } #endif /* Change number of threads in the team if requested */ if (master_set_numthreads) { // The parallel has num_threads clause if (master_set_numthreads < master_th->th.th_teams_size.nth) { // AC: only can reduce number of threads dynamically, can't increase kmp_info_t **other_threads = parent_team->t.t_threads; parent_team->t.t_nproc = master_set_numthreads; for (i = 0; i < master_set_numthreads; ++i) { other_threads[i]->th.th_team_nproc = master_set_numthreads; } // Keep extra threads hot in the team for possible next parallels } master_th->th.th_set_nproc = 0; } #if USE_DEBUGGER if (__kmp_debugging) { // Let debugger override number of threads. int nth = __kmp_omp_num_threads(loc); if (nth > 0) { // 0 means debugger doesn't want to change num threads master_set_numthreads = nth; } } #endif KF_TRACE(10, ("__kmp_fork_call: before internal fork: root=%p, team=%p, " "master_th=%p, gtid=%d\n", root, parent_team, master_th, gtid)); __kmp_internal_fork(loc, gtid, parent_team); KF_TRACE(10, ("__kmp_fork_call: after internal fork: root=%p, team=%p, " "master_th=%p, gtid=%d\n", root, parent_team, master_th, gtid)); /* Invoke microtask for MASTER thread */ KA_TRACE(20, ("__kmp_fork_call: T#%d(%d:0) invoke microtask = %p\n", gtid, parent_team->t.t_id, parent_team->t.t_pkfn)); if (!parent_team->t.t_invoke(gtid)) { KMP_ASSERT2(0, "cannot invoke microtask for MASTER thread"); } KA_TRACE(20, ("__kmp_fork_call: T#%d(%d:0) done microtask = %p\n", gtid, parent_team->t.t_id, parent_team->t.t_pkfn)); KMP_MB(); /* Flush all pending memory write invalidates. */ KA_TRACE(20, ("__kmp_fork_call: parallel exit T#%d\n", gtid)); return TRUE; } // Parallel closely nested in teams construct #if KMP_DEBUG if (__kmp_tasking_mode != tskm_immediate_exec) { KMP_DEBUG_ASSERT(master_th->th.th_task_team == parent_team->t.t_task_team[master_th->th.th_task_state]); } #endif if (parent_team->t.t_active_level >= master_th->th.th_current_task->td_icvs.max_active_levels) { nthreads = 1; } else { int enter_teams = ((ap == NULL && active_level == 0) || (ap && teams_level > 0 && teams_level == level)); nthreads = master_set_numthreads ? master_set_numthreads : get__nproc_2( parent_team, master_tid); // TODO: get nproc directly from current task // Check if we need to take forkjoin lock? (no need for serialized // parallel out of teams construct). This code moved here from // __kmp_reserve_threads() to speedup nested serialized parallels. if (nthreads > 1) { if ((get__max_active_levels(master_th) == 1 && (root->r.r_in_parallel && !enter_teams)) || (__kmp_library == library_serial)) { KC_TRACE(10, ("__kmp_fork_call: T#%d serializing team; requested %d" " threads\n", gtid, nthreads)); nthreads = 1; } } if (nthreads > 1) { /* determine how many new threads we can use */ __kmp_acquire_bootstrap_lock(&__kmp_forkjoin_lock); /* AC: If we execute teams from parallel region (on host), then teams should be created but each can only have 1 thread if nesting is disabled. If teams called from serial region, then teams and their threads should be created regardless of the nesting setting. */ nthreads = __kmp_reserve_threads(root, parent_team, master_tid, nthreads, enter_teams); if (nthreads == 1) { // Free lock for single thread execution here; for multi-thread // execution it will be freed later after team of threads created // and initialized __kmp_release_bootstrap_lock(&__kmp_forkjoin_lock); } } } KMP_DEBUG_ASSERT(nthreads > 0); // If we temporarily changed the set number of threads then restore it now master_th->th.th_set_nproc = 0; /* create a serialized parallel region? */ if (nthreads == 1) { /* josh todo: hypothetical question: what do we do for OS X*? */ #if KMP_OS_LINUX && \ (KMP_ARCH_X86 || KMP_ARCH_X86_64 || KMP_ARCH_ARM || KMP_ARCH_AARCH64) void *args[argc]; #else void **args = (void **)KMP_ALLOCA(argc * sizeof(void *)); #endif /* KMP_OS_LINUX && ( KMP_ARCH_X86 || KMP_ARCH_X86_64 || KMP_ARCH_ARM || \ KMP_ARCH_AARCH64) */ KA_TRACE(20, ("__kmp_fork_call: T#%d serializing parallel region\n", gtid)); __kmpc_serialized_parallel(loc, gtid); if (call_context == fork_context_intel) { /* TODO this sucks, use the compiler itself to pass args! :) */ master_th->th.th_serial_team->t.t_ident = loc; if (!ap) { // revert change made in __kmpc_serialized_parallel() master_th->th.th_serial_team->t.t_level--; // Get args from parent team for teams construct #if OMPT_SUPPORT void *dummy; void **exit_frame_p; ompt_task_info_t *task_info; ompt_lw_taskteam_t lw_taskteam; if (ompt_enabled.enabled) { __ompt_lw_taskteam_init(&lw_taskteam, master_th, gtid, &ompt_parallel_data, return_address); __ompt_lw_taskteam_link(&lw_taskteam, master_th, 0); // don't use lw_taskteam after linking. content was swaped task_info = OMPT_CUR_TASK_INFO(master_th); exit_frame_p = &(task_info->frame.exit_frame.ptr); if (ompt_enabled.ompt_callback_implicit_task) { OMPT_CUR_TASK_INFO(master_th) ->thread_num = __kmp_tid_from_gtid(gtid); ompt_callbacks.ompt_callback(ompt_callback_implicit_task)( ompt_scope_begin, OMPT_CUR_TEAM_DATA(master_th), &(task_info->task_data), 1, OMPT_CUR_TASK_INFO(master_th)->thread_num, ompt_task_implicit); } /* OMPT state */ master_th->th.ompt_thread_info.state = ompt_state_work_parallel; } else { exit_frame_p = &dummy; } #endif { KMP_TIME_PARTITIONED_BLOCK(OMP_parallel); KMP_SET_THREAD_STATE_BLOCK(IMPLICIT_TASK); __kmp_invoke_microtask(microtask, gtid, 0, argc, parent_team->t.t_argv #if OMPT_SUPPORT , exit_frame_p #endif ); } #if OMPT_SUPPORT if (ompt_enabled.enabled) { *exit_frame_p = NULL; if (ompt_enabled.ompt_callback_implicit_task) { ompt_callbacks.ompt_callback(ompt_callback_implicit_task)( ompt_scope_end, NULL, &(task_info->task_data), 1, OMPT_CUR_TASK_INFO(master_th)->thread_num, ompt_task_implicit); } ompt_parallel_data = *OMPT_CUR_TEAM_DATA(master_th); __ompt_lw_taskteam_unlink(master_th); if (ompt_enabled.ompt_callback_parallel_end) { ompt_callbacks.ompt_callback(ompt_callback_parallel_end)( &ompt_parallel_data, parent_task_data, OMPT_INVOKER(call_context) | ompt_parallel_team, return_address); } master_th->th.ompt_thread_info.state = ompt_state_overhead; } #endif } else if (microtask == (microtask_t)__kmp_teams_master) { KMP_DEBUG_ASSERT(master_th->th.th_team == master_th->th.th_serial_team); team = master_th->th.th_team; // team->t.t_pkfn = microtask; team->t.t_invoke = invoker; __kmp_alloc_argv_entries(argc, team, TRUE); team->t.t_argc = argc; argv = (void **)team->t.t_argv; if (ap) { for (i = argc - 1; i >= 0; --i) -// TODO: revert workaround for Intel(R) 64 tracker #96 -#if (KMP_ARCH_X86_64 || KMP_ARCH_ARM || KMP_ARCH_AARCH64) && KMP_OS_LINUX - *argv++ = va_arg(*ap, void *); -#else - *argv++ = va_arg(ap, void *); -#endif + *argv++ = va_arg(kmp_va_deref(ap), void *); } else { for (i = 0; i < argc; ++i) // Get args from parent team for teams construct argv[i] = parent_team->t.t_argv[i]; } // AC: revert change made in __kmpc_serialized_parallel() // because initial code in teams should have level=0 team->t.t_level--; // AC: call special invoker for outer "parallel" of teams construct invoker(gtid); #if OMPT_SUPPORT if (ompt_enabled.enabled) { ompt_task_info_t *task_info = OMPT_CUR_TASK_INFO(master_th); if (ompt_enabled.ompt_callback_implicit_task) { ompt_callbacks.ompt_callback(ompt_callback_implicit_task)( ompt_scope_end, NULL, &(task_info->task_data), 0, OMPT_CUR_TASK_INFO(master_th)->thread_num, ompt_task_initial); } if (ompt_enabled.ompt_callback_parallel_end) { ompt_callbacks.ompt_callback(ompt_callback_parallel_end)( &ompt_parallel_data, parent_task_data, OMPT_INVOKER(call_context) | ompt_parallel_league, return_address); } master_th->th.ompt_thread_info.state = ompt_state_overhead; } #endif } else { argv = args; for (i = argc - 1; i >= 0; --i) -// TODO: revert workaround for Intel(R) 64 tracker #96 -#if (KMP_ARCH_X86_64 || KMP_ARCH_ARM || KMP_ARCH_AARCH64) && KMP_OS_LINUX - *argv++ = va_arg(*ap, void *); -#else - *argv++ = va_arg(ap, void *); -#endif + *argv++ = va_arg(kmp_va_deref(ap), void *); KMP_MB(); #if OMPT_SUPPORT void *dummy; void **exit_frame_p; ompt_task_info_t *task_info; ompt_lw_taskteam_t lw_taskteam; if (ompt_enabled.enabled) { __ompt_lw_taskteam_init(&lw_taskteam, master_th, gtid, &ompt_parallel_data, return_address); __ompt_lw_taskteam_link(&lw_taskteam, master_th, 0); // don't use lw_taskteam after linking. content was swaped task_info = OMPT_CUR_TASK_INFO(master_th); exit_frame_p = &(task_info->frame.exit_frame.ptr); /* OMPT implicit task begin */ implicit_task_data = OMPT_CUR_TASK_DATA(master_th); if (ompt_enabled.ompt_callback_implicit_task) { ompt_callbacks.ompt_callback(ompt_callback_implicit_task)( ompt_scope_begin, OMPT_CUR_TEAM_DATA(master_th), implicit_task_data, 1, __kmp_tid_from_gtid(gtid), ompt_task_implicit); OMPT_CUR_TASK_INFO(master_th) ->thread_num = __kmp_tid_from_gtid(gtid); } /* OMPT state */ master_th->th.ompt_thread_info.state = ompt_state_work_parallel; } else { exit_frame_p = &dummy; } #endif { KMP_TIME_PARTITIONED_BLOCK(OMP_parallel); KMP_SET_THREAD_STATE_BLOCK(IMPLICIT_TASK); __kmp_invoke_microtask(microtask, gtid, 0, argc, args #if OMPT_SUPPORT , exit_frame_p #endif ); } #if OMPT_SUPPORT if (ompt_enabled.enabled) { *exit_frame_p = NULL; if (ompt_enabled.ompt_callback_implicit_task) { ompt_callbacks.ompt_callback(ompt_callback_implicit_task)( ompt_scope_end, NULL, &(task_info->task_data), 1, OMPT_CUR_TASK_INFO(master_th)->thread_num, ompt_task_implicit); } ompt_parallel_data = *OMPT_CUR_TEAM_DATA(master_th); __ompt_lw_taskteam_unlink(master_th); if (ompt_enabled.ompt_callback_parallel_end) { ompt_callbacks.ompt_callback(ompt_callback_parallel_end)( &ompt_parallel_data, parent_task_data, OMPT_INVOKER(call_context) | ompt_parallel_team, return_address); } master_th->th.ompt_thread_info.state = ompt_state_overhead; } #endif } } else if (call_context == fork_context_gnu) { #if OMPT_SUPPORT ompt_lw_taskteam_t lwt; __ompt_lw_taskteam_init(&lwt, master_th, gtid, &ompt_parallel_data, return_address); lwt.ompt_task_info.frame.exit_frame = ompt_data_none; __ompt_lw_taskteam_link(&lwt, master_th, 1); // don't use lw_taskteam after linking. content was swaped #endif // we were called from GNU native code KA_TRACE(20, ("__kmp_fork_call: T#%d serial exit\n", gtid)); return FALSE; } else { KMP_ASSERT2(call_context < fork_context_last, "__kmp_fork_call: unknown fork_context parameter"); } KA_TRACE(20, ("__kmp_fork_call: T#%d serial exit\n", gtid)); KMP_MB(); return FALSE; } // if (nthreads == 1) // GEH: only modify the executing flag in the case when not serialized // serialized case is handled in kmpc_serialized_parallel KF_TRACE(10, ("__kmp_fork_call: parent_team_aclevel=%d, master_th=%p, " "curtask=%p, curtask_max_aclevel=%d\n", parent_team->t.t_active_level, master_th, master_th->th.th_current_task, master_th->th.th_current_task->td_icvs.max_active_levels)); // TODO: GEH - cannot do this assertion because root thread not set up as // executing // KMP_ASSERT( master_th->th.th_current_task->td_flags.executing == 1 ); master_th->th.th_current_task->td_flags.executing = 0; if (!master_th->th.th_teams_microtask || level > teams_level) { /* Increment our nested depth level */ KMP_ATOMIC_INC(&root->r.r_in_parallel); } // See if we need to make a copy of the ICVs. int nthreads_icv = master_th->th.th_current_task->td_icvs.nproc; if ((level + 1 < __kmp_nested_nth.used) && (__kmp_nested_nth.nth[level + 1] != nthreads_icv)) { nthreads_icv = __kmp_nested_nth.nth[level + 1]; } else { nthreads_icv = 0; // don't update } // Figure out the proc_bind_policy for the new team. kmp_proc_bind_t proc_bind = master_th->th.th_set_proc_bind; kmp_proc_bind_t proc_bind_icv = proc_bind_default; // proc_bind_default means don't update if (master_th->th.th_current_task->td_icvs.proc_bind == proc_bind_false) { proc_bind = proc_bind_false; } else { if (proc_bind == proc_bind_default) { // No proc_bind clause specified; use current proc-bind-var for this // parallel region proc_bind = master_th->th.th_current_task->td_icvs.proc_bind; } /* else: The proc_bind policy was specified explicitly on parallel clause. This overrides proc-bind-var for this parallel region, but does not change proc-bind-var. */ // Figure the value of proc-bind-var for the child threads. if ((level + 1 < __kmp_nested_proc_bind.used) && (__kmp_nested_proc_bind.bind_types[level + 1] != master_th->th.th_current_task->td_icvs.proc_bind)) { proc_bind_icv = __kmp_nested_proc_bind.bind_types[level + 1]; } } // Reset for next parallel region master_th->th.th_set_proc_bind = proc_bind_default; if ((nthreads_icv > 0) || (proc_bind_icv != proc_bind_default)) { kmp_internal_control_t new_icvs; copy_icvs(&new_icvs, &master_th->th.th_current_task->td_icvs); new_icvs.next = NULL; if (nthreads_icv > 0) { new_icvs.nproc = nthreads_icv; } if (proc_bind_icv != proc_bind_default) { new_icvs.proc_bind = proc_bind_icv; } /* allocate a new parallel team */ KF_TRACE(10, ("__kmp_fork_call: before __kmp_allocate_team\n")); team = __kmp_allocate_team(root, nthreads, nthreads, #if OMPT_SUPPORT ompt_parallel_data, #endif proc_bind, &new_icvs, argc USE_NESTED_HOT_ARG(master_th)); } else { /* allocate a new parallel team */ KF_TRACE(10, ("__kmp_fork_call: before __kmp_allocate_team\n")); team = __kmp_allocate_team(root, nthreads, nthreads, #if OMPT_SUPPORT ompt_parallel_data, #endif proc_bind, &master_th->th.th_current_task->td_icvs, argc USE_NESTED_HOT_ARG(master_th)); } KF_TRACE( 10, ("__kmp_fork_call: after __kmp_allocate_team - team = %p\n", team)); /* setup the new team */ KMP_CHECK_UPDATE(team->t.t_master_tid, master_tid); KMP_CHECK_UPDATE(team->t.t_master_this_cons, master_this_cons); KMP_CHECK_UPDATE(team->t.t_ident, loc); KMP_CHECK_UPDATE(team->t.t_parent, parent_team); KMP_CHECK_UPDATE_SYNC(team->t.t_pkfn, microtask); #if OMPT_SUPPORT KMP_CHECK_UPDATE_SYNC(team->t.ompt_team_info.master_return_address, return_address); #endif KMP_CHECK_UPDATE(team->t.t_invoke, invoker); // TODO move to root, maybe // TODO: parent_team->t.t_level == INT_MAX ??? if (!master_th->th.th_teams_microtask || level > teams_level) { int new_level = parent_team->t.t_level + 1; KMP_CHECK_UPDATE(team->t.t_level, new_level); new_level = parent_team->t.t_active_level + 1; KMP_CHECK_UPDATE(team->t.t_active_level, new_level); } else { // AC: Do not increase parallel level at start of the teams construct int new_level = parent_team->t.t_level; KMP_CHECK_UPDATE(team->t.t_level, new_level); new_level = parent_team->t.t_active_level; KMP_CHECK_UPDATE(team->t.t_active_level, new_level); } kmp_r_sched_t new_sched = get__sched_2(parent_team, master_tid); // set master's schedule as new run-time schedule KMP_CHECK_UPDATE(team->t.t_sched.sched, new_sched.sched); KMP_CHECK_UPDATE(team->t.t_cancel_request, cancel_noreq); KMP_CHECK_UPDATE(team->t.t_def_allocator, master_th->th.th_def_allocator); // Update the floating point rounding in the team if required. propagateFPControl(team); if (__kmp_tasking_mode != tskm_immediate_exec) { // Set master's task team to team's task team. Unless this is hot team, it // should be NULL. KMP_DEBUG_ASSERT(master_th->th.th_task_team == parent_team->t.t_task_team[master_th->th.th_task_state]); KA_TRACE(20, ("__kmp_fork_call: Master T#%d pushing task_team %p / team " "%p, new task_team %p / team %p\n", __kmp_gtid_from_thread(master_th), master_th->th.th_task_team, parent_team, team->t.t_task_team[master_th->th.th_task_state], team)); if (active_level || master_th->th.th_task_team) { // Take a memo of master's task_state KMP_DEBUG_ASSERT(master_th->th.th_task_state_memo_stack); if (master_th->th.th_task_state_top >= master_th->th.th_task_state_stack_sz) { // increase size kmp_uint32 new_size = 2 * master_th->th.th_task_state_stack_sz; kmp_uint8 *old_stack, *new_stack; kmp_uint32 i; new_stack = (kmp_uint8 *)__kmp_allocate(new_size); for (i = 0; i < master_th->th.th_task_state_stack_sz; ++i) { new_stack[i] = master_th->th.th_task_state_memo_stack[i]; } for (i = master_th->th.th_task_state_stack_sz; i < new_size; ++i) { // zero-init rest of stack new_stack[i] = 0; } old_stack = master_th->th.th_task_state_memo_stack; master_th->th.th_task_state_memo_stack = new_stack; master_th->th.th_task_state_stack_sz = new_size; __kmp_free(old_stack); } // Store master's task_state on stack master_th->th .th_task_state_memo_stack[master_th->th.th_task_state_top] = master_th->th.th_task_state; master_th->th.th_task_state_top++; #if KMP_NESTED_HOT_TEAMS if (master_th->th.th_hot_teams && active_level < __kmp_hot_teams_max_level && team == master_th->th.th_hot_teams[active_level].hot_team) { // Restore master's nested state if nested hot team master_th->th.th_task_state = master_th->th .th_task_state_memo_stack[master_th->th.th_task_state_top]; } else { #endif master_th->th.th_task_state = 0; #if KMP_NESTED_HOT_TEAMS } #endif } #if !KMP_NESTED_HOT_TEAMS KMP_DEBUG_ASSERT((master_th->th.th_task_team == NULL) || (team == root->r.r_hot_team)); #endif } KA_TRACE( 20, ("__kmp_fork_call: T#%d(%d:%d)->(%d:0) created a team of %d threads\n", gtid, parent_team->t.t_id, team->t.t_master_tid, team->t.t_id, team->t.t_nproc)); KMP_DEBUG_ASSERT(team != root->r.r_hot_team || (team->t.t_master_tid == 0 && (team->t.t_parent == root->r.r_root_team || team->t.t_parent->t.t_serialized))); KMP_MB(); /* now, setup the arguments */ argv = (void **)team->t.t_argv; if (ap) { for (i = argc - 1; i >= 0; --i) { -// TODO: revert workaround for Intel(R) 64 tracker #96 -#if (KMP_ARCH_X86_64 || KMP_ARCH_ARM || KMP_ARCH_AARCH64) && KMP_OS_LINUX - void *new_argv = va_arg(*ap, void *); -#else - void *new_argv = va_arg(ap, void *); -#endif + void *new_argv = va_arg(kmp_va_deref(ap), void *); KMP_CHECK_UPDATE(*argv, new_argv); argv++; } } else { for (i = 0; i < argc; ++i) { // Get args from parent team for teams construct KMP_CHECK_UPDATE(argv[i], team->t.t_parent->t.t_argv[i]); } } /* now actually fork the threads */ KMP_CHECK_UPDATE(team->t.t_master_active, master_active); if (!root->r.r_active) // Only do assignment if it prevents cache ping-pong root->r.r_active = TRUE; __kmp_fork_team_threads(root, team, master_th, gtid); __kmp_setup_icv_copy(team, nthreads, &master_th->th.th_current_task->td_icvs, loc); #if OMPT_SUPPORT master_th->th.ompt_thread_info.state = ompt_state_work_parallel; #endif __kmp_release_bootstrap_lock(&__kmp_forkjoin_lock); #if USE_ITT_BUILD if (team->t.t_active_level == 1 // only report frames at level 1 && !master_th->th.th_teams_microtask) { // not in teams construct #if USE_ITT_NOTIFY if ((__itt_frame_submit_v3_ptr || KMP_ITT_DEBUG) && (__kmp_forkjoin_frames_mode == 3 || __kmp_forkjoin_frames_mode == 1)) { kmp_uint64 tmp_time = 0; if (__itt_get_timestamp_ptr) tmp_time = __itt_get_timestamp(); // Internal fork - report frame begin master_th->th.th_frame_time = tmp_time; if (__kmp_forkjoin_frames_mode == 3) team->t.t_region_time = tmp_time; } else // only one notification scheme (either "submit" or "forking/joined", not both) #endif /* USE_ITT_NOTIFY */ if ((__itt_frame_begin_v3_ptr || KMP_ITT_DEBUG) && __kmp_forkjoin_frames && !__kmp_forkjoin_frames_mode) { // Mark start of "parallel" region for Intel(R) VTune(TM) analyzer. __kmp_itt_region_forking(gtid, team->t.t_nproc, 0); } } #endif /* USE_ITT_BUILD */ /* now go on and do the work */ KMP_DEBUG_ASSERT(team == __kmp_threads[gtid]->th.th_team); KMP_MB(); KF_TRACE(10, ("__kmp_internal_fork : root=%p, team=%p, master_th=%p, gtid=%d\n", root, team, master_th, gtid)); #if USE_ITT_BUILD if (__itt_stack_caller_create_ptr) { team->t.t_stack_id = __kmp_itt_stack_caller_create(); // create new stack stitching id // before entering fork barrier } #endif /* USE_ITT_BUILD */ // AC: skip __kmp_internal_fork at teams construct, let only master // threads execute if (ap) { __kmp_internal_fork(loc, gtid, team); KF_TRACE(10, ("__kmp_internal_fork : after : root=%p, team=%p, " "master_th=%p, gtid=%d\n", root, team, master_th, gtid)); } if (call_context == fork_context_gnu) { KA_TRACE(20, ("__kmp_fork_call: parallel exit T#%d\n", gtid)); return TRUE; } /* Invoke microtask for MASTER thread */ KA_TRACE(20, ("__kmp_fork_call: T#%d(%d:0) invoke microtask = %p\n", gtid, team->t.t_id, team->t.t_pkfn)); } // END of timer KMP_fork_call block #if KMP_STATS_ENABLED // If beginning a teams construct, then change thread state stats_state_e previous_state = KMP_GET_THREAD_STATE(); if (!ap) { KMP_SET_THREAD_STATE(stats_state_e::TEAMS_REGION); } #endif if (!team->t.t_invoke(gtid)) { KMP_ASSERT2(0, "cannot invoke microtask for MASTER thread"); } #if KMP_STATS_ENABLED // If was beginning of a teams construct, then reset thread state if (!ap) { KMP_SET_THREAD_STATE(previous_state); } #endif KA_TRACE(20, ("__kmp_fork_call: T#%d(%d:0) done microtask = %p\n", gtid, team->t.t_id, team->t.t_pkfn)); KMP_MB(); /* Flush all pending memory write invalidates. */ KA_TRACE(20, ("__kmp_fork_call: parallel exit T#%d\n", gtid)); #if OMPT_SUPPORT if (ompt_enabled.enabled) { master_th->th.ompt_thread_info.state = ompt_state_overhead; } #endif return TRUE; } #if OMPT_SUPPORT static inline void __kmp_join_restore_state(kmp_info_t *thread, kmp_team_t *team) { // restore state outside the region thread->th.ompt_thread_info.state = ((team->t.t_serialized) ? ompt_state_work_serial : ompt_state_work_parallel); } static inline void __kmp_join_ompt(int gtid, kmp_info_t *thread, kmp_team_t *team, ompt_data_t *parallel_data, int flags, void *codeptr) { ompt_task_info_t *task_info = __ompt_get_task_info_object(0); if (ompt_enabled.ompt_callback_parallel_end) { ompt_callbacks.ompt_callback(ompt_callback_parallel_end)( parallel_data, &(task_info->task_data), flags, codeptr); } task_info->frame.enter_frame = ompt_data_none; __kmp_join_restore_state(thread, team); } #endif void __kmp_join_call(ident_t *loc, int gtid #if OMPT_SUPPORT , enum fork_context_e fork_context #endif , int exit_teams) { KMP_TIME_DEVELOPER_PARTITIONED_BLOCK(KMP_join_call); kmp_team_t *team; kmp_team_t *parent_team; kmp_info_t *master_th; kmp_root_t *root; int master_active; KA_TRACE(20, ("__kmp_join_call: enter T#%d\n", gtid)); /* setup current data */ master_th = __kmp_threads[gtid]; root = master_th->th.th_root; team = master_th->th.th_team; parent_team = team->t.t_parent; master_th->th.th_ident = loc; #if OMPT_SUPPORT void *team_microtask = (void *)team->t.t_pkfn; if (ompt_enabled.enabled) { master_th->th.ompt_thread_info.state = ompt_state_overhead; } #endif #if KMP_DEBUG if (__kmp_tasking_mode != tskm_immediate_exec && !exit_teams) { KA_TRACE(20, ("__kmp_join_call: T#%d, old team = %p old task_team = %p, " "th_task_team = %p\n", __kmp_gtid_from_thread(master_th), team, team->t.t_task_team[master_th->th.th_task_state], master_th->th.th_task_team)); KMP_DEBUG_ASSERT(master_th->th.th_task_team == team->t.t_task_team[master_th->th.th_task_state]); } #endif if (team->t.t_serialized) { if (master_th->th.th_teams_microtask) { // We are in teams construct int level = team->t.t_level; int tlevel = master_th->th.th_teams_level; if (level == tlevel) { // AC: we haven't incremented it earlier at start of teams construct, // so do it here - at the end of teams construct team->t.t_level++; } else if (level == tlevel + 1) { // AC: we are exiting parallel inside teams, need to increment // serialization in order to restore it in the next call to // __kmpc_end_serialized_parallel team->t.t_serialized++; } } __kmpc_end_serialized_parallel(loc, gtid); #if OMPT_SUPPORT if (ompt_enabled.enabled) { __kmp_join_restore_state(master_th, parent_team); } #endif return; } master_active = team->t.t_master_active; if (!exit_teams) { // AC: No barrier for internal teams at exit from teams construct. // But there is barrier for external team (league). __kmp_internal_join(loc, gtid, team); } else { master_th->th.th_task_state = 0; // AC: no tasking in teams (out of any parallel) } KMP_MB(); #if OMPT_SUPPORT ompt_data_t *parallel_data = &(team->t.ompt_team_info.parallel_data); void *codeptr = team->t.ompt_team_info.master_return_address; #endif #if USE_ITT_BUILD if (__itt_stack_caller_create_ptr) { __kmp_itt_stack_caller_destroy( (__itt_caller)team->t .t_stack_id); // destroy the stack stitching id after join barrier } // Mark end of "parallel" region for Intel(R) VTune(TM) analyzer. if (team->t.t_active_level == 1 && !master_th->th.th_teams_microtask) { /* not in teams construct */ master_th->th.th_ident = loc; // only one notification scheme (either "submit" or "forking/joined", not // both) if ((__itt_frame_submit_v3_ptr || KMP_ITT_DEBUG) && __kmp_forkjoin_frames_mode == 3) __kmp_itt_frame_submit(gtid, team->t.t_region_time, master_th->th.th_frame_time, 0, loc, master_th->th.th_team_nproc, 1); else if ((__itt_frame_end_v3_ptr || KMP_ITT_DEBUG) && !__kmp_forkjoin_frames_mode && __kmp_forkjoin_frames) __kmp_itt_region_joined(gtid); } // active_level == 1 #endif /* USE_ITT_BUILD */ if (master_th->th.th_teams_microtask && !exit_teams && team->t.t_pkfn != (microtask_t)__kmp_teams_master && team->t.t_level == master_th->th.th_teams_level + 1) { // AC: We need to leave the team structure intact at the end of parallel // inside the teams construct, so that at the next parallel same (hot) team // works, only adjust nesting levels #if OMPT_SUPPORT ompt_data_t ompt_parallel_data = ompt_data_none; if (ompt_enabled.enabled) { ompt_task_info_t *task_info = __ompt_get_task_info_object(0); if (ompt_enabled.ompt_callback_implicit_task) { int ompt_team_size = team->t.t_nproc; ompt_callbacks.ompt_callback(ompt_callback_implicit_task)( ompt_scope_end, NULL, &(task_info->task_data), ompt_team_size, OMPT_CUR_TASK_INFO(master_th)->thread_num, ompt_task_implicit); } task_info->frame.exit_frame = ompt_data_none; task_info->task_data = ompt_data_none; ompt_parallel_data = *OMPT_CUR_TEAM_DATA(master_th); __ompt_lw_taskteam_unlink(master_th); } #endif /* Decrement our nested depth level */ team->t.t_level--; team->t.t_active_level--; KMP_ATOMIC_DEC(&root->r.r_in_parallel); // Restore number of threads in the team if needed. This code relies on // the proper adjustment of th_teams_size.nth after the fork in // __kmp_teams_master on each teams master in the case that // __kmp_reserve_threads reduced it. if (master_th->th.th_team_nproc < master_th->th.th_teams_size.nth) { int old_num = master_th->th.th_team_nproc; int new_num = master_th->th.th_teams_size.nth; kmp_info_t **other_threads = team->t.t_threads; team->t.t_nproc = new_num; for (int i = 0; i < old_num; ++i) { other_threads[i]->th.th_team_nproc = new_num; } // Adjust states of non-used threads of the team for (int i = old_num; i < new_num; ++i) { // Re-initialize thread's barrier data. KMP_DEBUG_ASSERT(other_threads[i]); kmp_balign_t *balign = other_threads[i]->th.th_bar; for (int b = 0; b < bs_last_barrier; ++b) { balign[b].bb.b_arrived = team->t.t_bar[b].b_arrived; KMP_DEBUG_ASSERT(balign[b].bb.wait_flag != KMP_BARRIER_PARENT_FLAG); #if USE_DEBUGGER balign[b].bb.b_worker_arrived = team->t.t_bar[b].b_team_arrived; #endif } if (__kmp_tasking_mode != tskm_immediate_exec) { // Synchronize thread's task state other_threads[i]->th.th_task_state = master_th->th.th_task_state; } } } #if OMPT_SUPPORT if (ompt_enabled.enabled) { __kmp_join_ompt(gtid, master_th, parent_team, &ompt_parallel_data, OMPT_INVOKER(fork_context) | ompt_parallel_team, codeptr); } #endif return; } /* do cleanup and restore the parent team */ master_th->th.th_info.ds.ds_tid = team->t.t_master_tid; master_th->th.th_local.this_construct = team->t.t_master_this_cons; master_th->th.th_dispatch = &parent_team->t.t_dispatch[team->t.t_master_tid]; /* jc: The following lock has instructions with REL and ACQ semantics, separating the parallel user code called in this parallel region from the serial user code called after this function returns. */ __kmp_acquire_bootstrap_lock(&__kmp_forkjoin_lock); if (!master_th->th.th_teams_microtask || team->t.t_level > master_th->th.th_teams_level) { /* Decrement our nested depth level */ KMP_ATOMIC_DEC(&root->r.r_in_parallel); } KMP_DEBUG_ASSERT(root->r.r_in_parallel >= 0); #if OMPT_SUPPORT if (ompt_enabled.enabled) { ompt_task_info_t *task_info = __ompt_get_task_info_object(0); if (ompt_enabled.ompt_callback_implicit_task) { int flags = (team_microtask == (void *)__kmp_teams_master) ? ompt_task_initial : ompt_task_implicit; int ompt_team_size = (flags == ompt_task_initial) ? 0 : team->t.t_nproc; ompt_callbacks.ompt_callback(ompt_callback_implicit_task)( ompt_scope_end, NULL, &(task_info->task_data), ompt_team_size, OMPT_CUR_TASK_INFO(master_th)->thread_num, flags); } task_info->frame.exit_frame = ompt_data_none; task_info->task_data = ompt_data_none; } #endif KF_TRACE(10, ("__kmp_join_call1: T#%d, this_thread=%p team=%p\n", 0, master_th, team)); __kmp_pop_current_task_from_thread(master_th); #if KMP_AFFINITY_SUPPORTED // Restore master thread's partition. master_th->th.th_first_place = team->t.t_first_place; master_th->th.th_last_place = team->t.t_last_place; #endif // KMP_AFFINITY_SUPPORTED master_th->th.th_def_allocator = team->t.t_def_allocator; updateHWFPControl(team); if (root->r.r_active != master_active) root->r.r_active = master_active; __kmp_free_team(root, team USE_NESTED_HOT_ARG( master_th)); // this will free worker threads /* this race was fun to find. make sure the following is in the critical region otherwise assertions may fail occasionally since the old team may be reallocated and the hierarchy appears inconsistent. it is actually safe to run and won't cause any bugs, but will cause those assertion failures. it's only one deref&assign so might as well put this in the critical region */ master_th->th.th_team = parent_team; master_th->th.th_team_nproc = parent_team->t.t_nproc; master_th->th.th_team_master = parent_team->t.t_threads[0]; master_th->th.th_team_serialized = parent_team->t.t_serialized; /* restore serialized team, if need be */ if (parent_team->t.t_serialized && parent_team != master_th->th.th_serial_team && parent_team != root->r.r_root_team) { __kmp_free_team(root, master_th->th.th_serial_team USE_NESTED_HOT_ARG(NULL)); master_th->th.th_serial_team = parent_team; } if (__kmp_tasking_mode != tskm_immediate_exec) { if (master_th->th.th_task_state_top > 0) { // Restore task state from memo stack KMP_DEBUG_ASSERT(master_th->th.th_task_state_memo_stack); // Remember master's state if we re-use this nested hot team master_th->th.th_task_state_memo_stack[master_th->th.th_task_state_top] = master_th->th.th_task_state; --master_th->th.th_task_state_top; // pop // Now restore state at this level master_th->th.th_task_state = master_th->th .th_task_state_memo_stack[master_th->th.th_task_state_top]; } // Copy the task team from the parent team to the master thread master_th->th.th_task_team = parent_team->t.t_task_team[master_th->th.th_task_state]; KA_TRACE(20, ("__kmp_join_call: Master T#%d restoring task_team %p / team %p\n", __kmp_gtid_from_thread(master_th), master_th->th.th_task_team, parent_team)); } // TODO: GEH - cannot do this assertion because root thread not set up as // executing // KMP_ASSERT( master_th->th.th_current_task->td_flags.executing == 0 ); master_th->th.th_current_task->td_flags.executing = 1; __kmp_release_bootstrap_lock(&__kmp_forkjoin_lock); #if OMPT_SUPPORT int flags = OMPT_INVOKER(fork_context) | ((team_microtask == (void *)__kmp_teams_master) ? ompt_parallel_league : ompt_parallel_team); if (ompt_enabled.enabled) { __kmp_join_ompt(gtid, master_th, parent_team, parallel_data, flags, codeptr); } #endif KMP_MB(); KA_TRACE(20, ("__kmp_join_call: exit T#%d\n", gtid)); } /* Check whether we should push an internal control record onto the serial team stack. If so, do it. */ void __kmp_save_internal_controls(kmp_info_t *thread) { if (thread->th.th_team != thread->th.th_serial_team) { return; } if (thread->th.th_team->t.t_serialized > 1) { int push = 0; if (thread->th.th_team->t.t_control_stack_top == NULL) { push = 1; } else { if (thread->th.th_team->t.t_control_stack_top->serial_nesting_level != thread->th.th_team->t.t_serialized) { push = 1; } } if (push) { /* push a record on the serial team's stack */ kmp_internal_control_t *control = (kmp_internal_control_t *)__kmp_allocate( sizeof(kmp_internal_control_t)); copy_icvs(control, &thread->th.th_current_task->td_icvs); control->serial_nesting_level = thread->th.th_team->t.t_serialized; control->next = thread->th.th_team->t.t_control_stack_top; thread->th.th_team->t.t_control_stack_top = control; } } } /* Changes set_nproc */ void __kmp_set_num_threads(int new_nth, int gtid) { kmp_info_t *thread; kmp_root_t *root; KF_TRACE(10, ("__kmp_set_num_threads: new __kmp_nth = %d\n", new_nth)); KMP_DEBUG_ASSERT(__kmp_init_serial); if (new_nth < 1) new_nth = 1; else if (new_nth > __kmp_max_nth) new_nth = __kmp_max_nth; KMP_COUNT_VALUE(OMP_set_numthreads, new_nth); thread = __kmp_threads[gtid]; if (thread->th.th_current_task->td_icvs.nproc == new_nth) return; // nothing to do __kmp_save_internal_controls(thread); set__nproc(thread, new_nth); // If this omp_set_num_threads() call will cause the hot team size to be // reduced (in the absence of a num_threads clause), then reduce it now, // rather than waiting for the next parallel region. root = thread->th.th_root; if (__kmp_init_parallel && (!root->r.r_active) && (root->r.r_hot_team->t.t_nproc > new_nth) #if KMP_NESTED_HOT_TEAMS && __kmp_hot_teams_max_level && !__kmp_hot_teams_mode #endif ) { kmp_team_t *hot_team = root->r.r_hot_team; int f; __kmp_acquire_bootstrap_lock(&__kmp_forkjoin_lock); // Release the extra threads we don't need any more. for (f = new_nth; f < hot_team->t.t_nproc; f++) { KMP_DEBUG_ASSERT(hot_team->t.t_threads[f] != NULL); if (__kmp_tasking_mode != tskm_immediate_exec) { // When decreasing team size, threads no longer in the team should unref // task team. hot_team->t.t_threads[f]->th.th_task_team = NULL; } __kmp_free_thread(hot_team->t.t_threads[f]); hot_team->t.t_threads[f] = NULL; } hot_team->t.t_nproc = new_nth; #if KMP_NESTED_HOT_TEAMS if (thread->th.th_hot_teams) { KMP_DEBUG_ASSERT(hot_team == thread->th.th_hot_teams[0].hot_team); thread->th.th_hot_teams[0].hot_team_nth = new_nth; } #endif __kmp_release_bootstrap_lock(&__kmp_forkjoin_lock); // Update the t_nproc field in the threads that are still active. for (f = 0; f < new_nth; f++) { KMP_DEBUG_ASSERT(hot_team->t.t_threads[f] != NULL); hot_team->t.t_threads[f]->th.th_team_nproc = new_nth; } // Special flag in case omp_set_num_threads() call hot_team->t.t_size_changed = -1; } } /* Changes max_active_levels */ void __kmp_set_max_active_levels(int gtid, int max_active_levels) { kmp_info_t *thread; KF_TRACE(10, ("__kmp_set_max_active_levels: new max_active_levels for thread " "%d = (%d)\n", gtid, max_active_levels)); KMP_DEBUG_ASSERT(__kmp_init_serial); // validate max_active_levels if (max_active_levels < 0) { KMP_WARNING(ActiveLevelsNegative, max_active_levels); // We ignore this call if the user has specified a negative value. // The current setting won't be changed. The last valid setting will be // used. A warning will be issued (if warnings are allowed as controlled by // the KMP_WARNINGS env var). KF_TRACE(10, ("__kmp_set_max_active_levels: the call is ignored: new " "max_active_levels for thread %d = (%d)\n", gtid, max_active_levels)); return; } if (max_active_levels <= KMP_MAX_ACTIVE_LEVELS_LIMIT) { // it's OK, the max_active_levels is within the valid range: [ 0; // KMP_MAX_ACTIVE_LEVELS_LIMIT ] // We allow a zero value. (implementation defined behavior) } else { KMP_WARNING(ActiveLevelsExceedLimit, max_active_levels, KMP_MAX_ACTIVE_LEVELS_LIMIT); max_active_levels = KMP_MAX_ACTIVE_LEVELS_LIMIT; // Current upper limit is MAX_INT. (implementation defined behavior) // If the input exceeds the upper limit, we correct the input to be the // upper limit. (implementation defined behavior) // Actually, the flow should never get here until we use MAX_INT limit. } KF_TRACE(10, ("__kmp_set_max_active_levels: after validation: new " "max_active_levels for thread %d = (%d)\n", gtid, max_active_levels)); thread = __kmp_threads[gtid]; __kmp_save_internal_controls(thread); set__max_active_levels(thread, max_active_levels); } /* Gets max_active_levels */ int __kmp_get_max_active_levels(int gtid) { kmp_info_t *thread; KF_TRACE(10, ("__kmp_get_max_active_levels: thread %d\n", gtid)); KMP_DEBUG_ASSERT(__kmp_init_serial); thread = __kmp_threads[gtid]; KMP_DEBUG_ASSERT(thread->th.th_current_task); KF_TRACE(10, ("__kmp_get_max_active_levels: thread %d, curtask=%p, " "curtask_maxaclevel=%d\n", gtid, thread->th.th_current_task, thread->th.th_current_task->td_icvs.max_active_levels)); return thread->th.th_current_task->td_icvs.max_active_levels; } KMP_BUILD_ASSERT(sizeof(kmp_sched_t) == sizeof(int)); KMP_BUILD_ASSERT(sizeof(enum sched_type) == sizeof(int)); /* Changes def_sched_var ICV values (run-time schedule kind and chunk) */ void __kmp_set_schedule(int gtid, kmp_sched_t kind, int chunk) { kmp_info_t *thread; kmp_sched_t orig_kind; // kmp_team_t *team; KF_TRACE(10, ("__kmp_set_schedule: new schedule for thread %d = (%d, %d)\n", gtid, (int)kind, chunk)); KMP_DEBUG_ASSERT(__kmp_init_serial); // Check if the kind parameter is valid, correct if needed. // Valid parameters should fit in one of two intervals - standard or extended: // , , , , , // 2008-01-25: 0, 1 - 4, 5, 100, 101 - 102, 103 orig_kind = kind; kind = __kmp_sched_without_mods(kind); if (kind <= kmp_sched_lower || kind >= kmp_sched_upper || (kind <= kmp_sched_lower_ext && kind >= kmp_sched_upper_std)) { // TODO: Hint needs attention in case we change the default schedule. __kmp_msg(kmp_ms_warning, KMP_MSG(ScheduleKindOutOfRange, kind), KMP_HNT(DefaultScheduleKindUsed, "static, no chunk"), __kmp_msg_null); kind = kmp_sched_default; chunk = 0; // ignore chunk value in case of bad kind } thread = __kmp_threads[gtid]; __kmp_save_internal_controls(thread); if (kind < kmp_sched_upper_std) { if (kind == kmp_sched_static && chunk < KMP_DEFAULT_CHUNK) { // differ static chunked vs. unchunked: chunk should be invalid to // indicate unchunked schedule (which is the default) thread->th.th_current_task->td_icvs.sched.r_sched_type = kmp_sch_static; } else { thread->th.th_current_task->td_icvs.sched.r_sched_type = __kmp_sch_map[kind - kmp_sched_lower - 1]; } } else { // __kmp_sch_map[ kind - kmp_sched_lower_ext + kmp_sched_upper_std - // kmp_sched_lower - 2 ]; thread->th.th_current_task->td_icvs.sched.r_sched_type = __kmp_sch_map[kind - kmp_sched_lower_ext + kmp_sched_upper_std - kmp_sched_lower - 2]; } __kmp_sched_apply_mods_intkind( orig_kind, &(thread->th.th_current_task->td_icvs.sched.r_sched_type)); if (kind == kmp_sched_auto || chunk < 1) { // ignore parameter chunk for schedule auto thread->th.th_current_task->td_icvs.sched.chunk = KMP_DEFAULT_CHUNK; } else { thread->th.th_current_task->td_icvs.sched.chunk = chunk; } } /* Gets def_sched_var ICV values */ void __kmp_get_schedule(int gtid, kmp_sched_t *kind, int *chunk) { kmp_info_t *thread; enum sched_type th_type; KF_TRACE(10, ("__kmp_get_schedule: thread %d\n", gtid)); KMP_DEBUG_ASSERT(__kmp_init_serial); thread = __kmp_threads[gtid]; th_type = thread->th.th_current_task->td_icvs.sched.r_sched_type; switch (SCHEDULE_WITHOUT_MODIFIERS(th_type)) { case kmp_sch_static: case kmp_sch_static_greedy: case kmp_sch_static_balanced: *kind = kmp_sched_static; __kmp_sched_apply_mods_stdkind(kind, th_type); *chunk = 0; // chunk was not set, try to show this fact via zero value return; case kmp_sch_static_chunked: *kind = kmp_sched_static; break; case kmp_sch_dynamic_chunked: *kind = kmp_sched_dynamic; break; case kmp_sch_guided_chunked: case kmp_sch_guided_iterative_chunked: case kmp_sch_guided_analytical_chunked: *kind = kmp_sched_guided; break; case kmp_sch_auto: *kind = kmp_sched_auto; break; case kmp_sch_trapezoidal: *kind = kmp_sched_trapezoidal; break; #if KMP_STATIC_STEAL_ENABLED case kmp_sch_static_steal: *kind = kmp_sched_static_steal; break; #endif default: KMP_FATAL(UnknownSchedulingType, th_type); } __kmp_sched_apply_mods_stdkind(kind, th_type); *chunk = thread->th.th_current_task->td_icvs.sched.chunk; } int __kmp_get_ancestor_thread_num(int gtid, int level) { int ii, dd; kmp_team_t *team; kmp_info_t *thr; KF_TRACE(10, ("__kmp_get_ancestor_thread_num: thread %d %d\n", gtid, level)); KMP_DEBUG_ASSERT(__kmp_init_serial); // validate level if (level == 0) return 0; if (level < 0) return -1; thr = __kmp_threads[gtid]; team = thr->th.th_team; ii = team->t.t_level; if (level > ii) return -1; if (thr->th.th_teams_microtask) { // AC: we are in teams region where multiple nested teams have same level int tlevel = thr->th.th_teams_level; // the level of the teams construct if (level <= tlevel) { // otherwise usual algorithm works (will not touch the teams) KMP_DEBUG_ASSERT(ii >= tlevel); // AC: As we need to pass by the teams league, we need to artificially // increase ii if (ii == tlevel) { ii += 2; // three teams have same level } else { ii++; // two teams have same level } } } if (ii == level) return __kmp_tid_from_gtid(gtid); dd = team->t.t_serialized; level++; while (ii > level) { for (dd = team->t.t_serialized; (dd > 0) && (ii > level); dd--, ii--) { } if ((team->t.t_serialized) && (!dd)) { team = team->t.t_parent; continue; } if (ii > level) { team = team->t.t_parent; dd = team->t.t_serialized; ii--; } } return (dd > 1) ? (0) : (team->t.t_master_tid); } int __kmp_get_team_size(int gtid, int level) { int ii, dd; kmp_team_t *team; kmp_info_t *thr; KF_TRACE(10, ("__kmp_get_team_size: thread %d %d\n", gtid, level)); KMP_DEBUG_ASSERT(__kmp_init_serial); // validate level if (level == 0) return 1; if (level < 0) return -1; thr = __kmp_threads[gtid]; team = thr->th.th_team; ii = team->t.t_level; if (level > ii) return -1; if (thr->th.th_teams_microtask) { // AC: we are in teams region where multiple nested teams have same level int tlevel = thr->th.th_teams_level; // the level of the teams construct if (level <= tlevel) { // otherwise usual algorithm works (will not touch the teams) KMP_DEBUG_ASSERT(ii >= tlevel); // AC: As we need to pass by the teams league, we need to artificially // increase ii if (ii == tlevel) { ii += 2; // three teams have same level } else { ii++; // two teams have same level } } } while (ii > level) { for (dd = team->t.t_serialized; (dd > 0) && (ii > level); dd--, ii--) { } if (team->t.t_serialized && (!dd)) { team = team->t.t_parent; continue; } if (ii > level) { team = team->t.t_parent; ii--; } } return team->t.t_nproc; } kmp_r_sched_t __kmp_get_schedule_global() { // This routine created because pairs (__kmp_sched, __kmp_chunk) and // (__kmp_static, __kmp_guided) may be changed by kmp_set_defaults // independently. So one can get the updated schedule here. kmp_r_sched_t r_sched; // create schedule from 4 globals: __kmp_sched, __kmp_chunk, __kmp_static, // __kmp_guided. __kmp_sched should keep original value, so that user can set // KMP_SCHEDULE multiple times, and thus have different run-time schedules in // different roots (even in OMP 2.5) enum sched_type s = SCHEDULE_WITHOUT_MODIFIERS(__kmp_sched); enum sched_type sched_modifiers = SCHEDULE_GET_MODIFIERS(__kmp_sched); if (s == kmp_sch_static) { // replace STATIC with more detailed schedule (balanced or greedy) r_sched.r_sched_type = __kmp_static; } else if (s == kmp_sch_guided_chunked) { // replace GUIDED with more detailed schedule (iterative or analytical) r_sched.r_sched_type = __kmp_guided; } else { // (STATIC_CHUNKED), or (DYNAMIC_CHUNKED), or other r_sched.r_sched_type = __kmp_sched; } SCHEDULE_SET_MODIFIERS(r_sched.r_sched_type, sched_modifiers); if (__kmp_chunk < KMP_DEFAULT_CHUNK) { // __kmp_chunk may be wrong here (if it was not ever set) r_sched.chunk = KMP_DEFAULT_CHUNK; } else { r_sched.chunk = __kmp_chunk; } return r_sched; } /* Allocate (realloc == FALSE) * or reallocate (realloc == TRUE) at least argc number of *t_argv entries for the requested team. */ static void __kmp_alloc_argv_entries(int argc, kmp_team_t *team, int realloc) { KMP_DEBUG_ASSERT(team); if (!realloc || argc > team->t.t_max_argc) { KA_TRACE(100, ("__kmp_alloc_argv_entries: team %d: needed entries=%d, " "current entries=%d\n", team->t.t_id, argc, (realloc) ? team->t.t_max_argc : 0)); /* if previously allocated heap space for args, free them */ if (realloc && team->t.t_argv != &team->t.t_inline_argv[0]) __kmp_free((void *)team->t.t_argv); if (argc <= KMP_INLINE_ARGV_ENTRIES) { /* use unused space in the cache line for arguments */ team->t.t_max_argc = KMP_INLINE_ARGV_ENTRIES; KA_TRACE(100, ("__kmp_alloc_argv_entries: team %d: inline allocate %d " "argv entries\n", team->t.t_id, team->t.t_max_argc)); team->t.t_argv = &team->t.t_inline_argv[0]; if (__kmp_storage_map) { __kmp_print_storage_map_gtid( -1, &team->t.t_inline_argv[0], &team->t.t_inline_argv[KMP_INLINE_ARGV_ENTRIES], (sizeof(void *) * KMP_INLINE_ARGV_ENTRIES), "team_%d.t_inline_argv", team->t.t_id); } } else { /* allocate space for arguments in the heap */ team->t.t_max_argc = (argc <= (KMP_MIN_MALLOC_ARGV_ENTRIES >> 1)) ? KMP_MIN_MALLOC_ARGV_ENTRIES : 2 * argc; KA_TRACE(100, ("__kmp_alloc_argv_entries: team %d: dynamic allocate %d " "argv entries\n", team->t.t_id, team->t.t_max_argc)); team->t.t_argv = (void **)__kmp_page_allocate(sizeof(void *) * team->t.t_max_argc); if (__kmp_storage_map) { __kmp_print_storage_map_gtid(-1, &team->t.t_argv[0], &team->t.t_argv[team->t.t_max_argc], sizeof(void *) * team->t.t_max_argc, "team_%d.t_argv", team->t.t_id); } } } } static void __kmp_allocate_team_arrays(kmp_team_t *team, int max_nth) { int i; int num_disp_buff = max_nth > 1 ? __kmp_dispatch_num_buffers : 2; team->t.t_threads = (kmp_info_t **)__kmp_allocate(sizeof(kmp_info_t *) * max_nth); team->t.t_disp_buffer = (dispatch_shared_info_t *)__kmp_allocate( sizeof(dispatch_shared_info_t) * num_disp_buff); team->t.t_dispatch = (kmp_disp_t *)__kmp_allocate(sizeof(kmp_disp_t) * max_nth); team->t.t_implicit_task_taskdata = (kmp_taskdata_t *)__kmp_allocate(sizeof(kmp_taskdata_t) * max_nth); team->t.t_max_nproc = max_nth; /* setup dispatch buffers */ for (i = 0; i < num_disp_buff; ++i) { team->t.t_disp_buffer[i].buffer_index = i; team->t.t_disp_buffer[i].doacross_buf_idx = i; } } static void __kmp_free_team_arrays(kmp_team_t *team) { /* Note: this does not free the threads in t_threads (__kmp_free_threads) */ int i; for (i = 0; i < team->t.t_max_nproc; ++i) { if (team->t.t_dispatch[i].th_disp_buffer != NULL) { __kmp_free(team->t.t_dispatch[i].th_disp_buffer); team->t.t_dispatch[i].th_disp_buffer = NULL; } } #if KMP_USE_HIER_SCHED __kmp_dispatch_free_hierarchies(team); #endif __kmp_free(team->t.t_threads); __kmp_free(team->t.t_disp_buffer); __kmp_free(team->t.t_dispatch); __kmp_free(team->t.t_implicit_task_taskdata); team->t.t_threads = NULL; team->t.t_disp_buffer = NULL; team->t.t_dispatch = NULL; team->t.t_implicit_task_taskdata = 0; } static void __kmp_reallocate_team_arrays(kmp_team_t *team, int max_nth) { kmp_info_t **oldThreads = team->t.t_threads; __kmp_free(team->t.t_disp_buffer); __kmp_free(team->t.t_dispatch); __kmp_free(team->t.t_implicit_task_taskdata); __kmp_allocate_team_arrays(team, max_nth); KMP_MEMCPY(team->t.t_threads, oldThreads, team->t.t_nproc * sizeof(kmp_info_t *)); __kmp_free(oldThreads); } static kmp_internal_control_t __kmp_get_global_icvs(void) { kmp_r_sched_t r_sched = __kmp_get_schedule_global(); // get current state of scheduling globals KMP_DEBUG_ASSERT(__kmp_nested_proc_bind.used > 0); kmp_internal_control_t g_icvs = { 0, // int serial_nesting_level; //corresponds to value of th_team_serialized (kmp_int8)__kmp_global.g.g_dynamic, // internal control for dynamic // adjustment of threads (per thread) (kmp_int8)__kmp_env_blocktime, // int bt_set; //internal control for // whether blocktime is explicitly set __kmp_dflt_blocktime, // int blocktime; //internal control for blocktime #if KMP_USE_MONITOR __kmp_bt_intervals, // int bt_intervals; //internal control for blocktime // intervals #endif __kmp_dflt_team_nth, // int nproc; //internal control for # of threads for // next parallel region (per thread) // (use a max ub on value if __kmp_parallel_initialize not called yet) __kmp_cg_max_nth, // int thread_limit; __kmp_dflt_max_active_levels, // int max_active_levels; //internal control // for max_active_levels r_sched, // kmp_r_sched_t sched; //internal control for runtime schedule // {sched,chunk} pair __kmp_nested_proc_bind.bind_types[0], __kmp_default_device, NULL // struct kmp_internal_control *next; }; return g_icvs; } static kmp_internal_control_t __kmp_get_x_global_icvs(const kmp_team_t *team) { kmp_internal_control_t gx_icvs; gx_icvs.serial_nesting_level = 0; // probably =team->t.t_serial like in save_inter_controls copy_icvs(&gx_icvs, &team->t.t_threads[0]->th.th_current_task->td_icvs); gx_icvs.next = NULL; return gx_icvs; } static void __kmp_initialize_root(kmp_root_t *root) { int f; kmp_team_t *root_team; kmp_team_t *hot_team; int hot_team_max_nth; kmp_r_sched_t r_sched = __kmp_get_schedule_global(); // get current state of scheduling globals kmp_internal_control_t r_icvs = __kmp_get_global_icvs(); KMP_DEBUG_ASSERT(root); KMP_ASSERT(!root->r.r_begin); /* setup the root state structure */ __kmp_init_lock(&root->r.r_begin_lock); root->r.r_begin = FALSE; root->r.r_active = FALSE; root->r.r_in_parallel = 0; root->r.r_blocktime = __kmp_dflt_blocktime; /* setup the root team for this task */ /* allocate the root team structure */ KF_TRACE(10, ("__kmp_initialize_root: before root_team\n")); root_team = __kmp_allocate_team(root, 1, // new_nproc 1, // max_nproc #if OMPT_SUPPORT ompt_data_none, // root parallel id #endif __kmp_nested_proc_bind.bind_types[0], &r_icvs, 0 // argc USE_NESTED_HOT_ARG(NULL) // master thread is unknown ); #if USE_DEBUGGER // Non-NULL value should be assigned to make the debugger display the root // team. TCW_SYNC_PTR(root_team->t.t_pkfn, (microtask_t)(~0)); #endif KF_TRACE(10, ("__kmp_initialize_root: after root_team = %p\n", root_team)); root->r.r_root_team = root_team; root_team->t.t_control_stack_top = NULL; /* initialize root team */ root_team->t.t_threads[0] = NULL; root_team->t.t_nproc = 1; root_team->t.t_serialized = 1; // TODO???: root_team->t.t_max_active_levels = __kmp_dflt_max_active_levels; root_team->t.t_sched.sched = r_sched.sched; KA_TRACE( 20, ("__kmp_initialize_root: init root team %d arrived: join=%u, plain=%u\n", root_team->t.t_id, KMP_INIT_BARRIER_STATE, KMP_INIT_BARRIER_STATE)); /* setup the hot team for this task */ /* allocate the hot team structure */ KF_TRACE(10, ("__kmp_initialize_root: before hot_team\n")); hot_team = __kmp_allocate_team(root, 1, // new_nproc __kmp_dflt_team_nth_ub * 2, // max_nproc #if OMPT_SUPPORT ompt_data_none, // root parallel id #endif __kmp_nested_proc_bind.bind_types[0], &r_icvs, 0 // argc USE_NESTED_HOT_ARG(NULL) // master thread is unknown ); KF_TRACE(10, ("__kmp_initialize_root: after hot_team = %p\n", hot_team)); root->r.r_hot_team = hot_team; root_team->t.t_control_stack_top = NULL; /* first-time initialization */ hot_team->t.t_parent = root_team; /* initialize hot team */ hot_team_max_nth = hot_team->t.t_max_nproc; for (f = 0; f < hot_team_max_nth; ++f) { hot_team->t.t_threads[f] = NULL; } hot_team->t.t_nproc = 1; // TODO???: hot_team->t.t_max_active_levels = __kmp_dflt_max_active_levels; hot_team->t.t_sched.sched = r_sched.sched; hot_team->t.t_size_changed = 0; } #ifdef KMP_DEBUG typedef struct kmp_team_list_item { kmp_team_p const *entry; struct kmp_team_list_item *next; } kmp_team_list_item_t; typedef kmp_team_list_item_t *kmp_team_list_t; static void __kmp_print_structure_team_accum( // Add team to list of teams. kmp_team_list_t list, // List of teams. kmp_team_p const *team // Team to add. ) { // List must terminate with item where both entry and next are NULL. // Team is added to the list only once. // List is sorted in ascending order by team id. // Team id is *not* a key. kmp_team_list_t l; KMP_DEBUG_ASSERT(list != NULL); if (team == NULL) { return; } __kmp_print_structure_team_accum(list, team->t.t_parent); __kmp_print_structure_team_accum(list, team->t.t_next_pool); // Search list for the team. l = list; while (l->next != NULL && l->entry != team) { l = l->next; } if (l->next != NULL) { return; // Team has been added before, exit. } // Team is not found. Search list again for insertion point. l = list; while (l->next != NULL && l->entry->t.t_id <= team->t.t_id) { l = l->next; } // Insert team. { kmp_team_list_item_t *item = (kmp_team_list_item_t *)KMP_INTERNAL_MALLOC( sizeof(kmp_team_list_item_t)); *item = *l; l->entry = team; l->next = item; } } static void __kmp_print_structure_team(char const *title, kmp_team_p const *team ) { __kmp_printf("%s", title); if (team != NULL) { __kmp_printf("%2x %p\n", team->t.t_id, team); } else { __kmp_printf(" - (nil)\n"); } } static void __kmp_print_structure_thread(char const *title, kmp_info_p const *thread) { __kmp_printf("%s", title); if (thread != NULL) { __kmp_printf("%2d %p\n", thread->th.th_info.ds.ds_gtid, thread); } else { __kmp_printf(" - (nil)\n"); } } void __kmp_print_structure(void) { kmp_team_list_t list; // Initialize list of teams. list = (kmp_team_list_item_t *)KMP_INTERNAL_MALLOC(sizeof(kmp_team_list_item_t)); list->entry = NULL; list->next = NULL; __kmp_printf("\n------------------------------\nGlobal Thread " "Table\n------------------------------\n"); { int gtid; for (gtid = 0; gtid < __kmp_threads_capacity; ++gtid) { __kmp_printf("%2d", gtid); if (__kmp_threads != NULL) { __kmp_printf(" %p", __kmp_threads[gtid]); } if (__kmp_root != NULL) { __kmp_printf(" %p", __kmp_root[gtid]); } __kmp_printf("\n"); } } // Print out __kmp_threads array. __kmp_printf("\n------------------------------\nThreads\n--------------------" "----------\n"); if (__kmp_threads != NULL) { int gtid; for (gtid = 0; gtid < __kmp_threads_capacity; ++gtid) { kmp_info_t const *thread = __kmp_threads[gtid]; if (thread != NULL) { __kmp_printf("GTID %2d %p:\n", gtid, thread); __kmp_printf(" Our Root: %p\n", thread->th.th_root); __kmp_print_structure_team(" Our Team: ", thread->th.th_team); __kmp_print_structure_team(" Serial Team: ", thread->th.th_serial_team); __kmp_printf(" Threads: %2d\n", thread->th.th_team_nproc); __kmp_print_structure_thread(" Master: ", thread->th.th_team_master); __kmp_printf(" Serialized?: %2d\n", thread->th.th_team_serialized); __kmp_printf(" Set NProc: %2d\n", thread->th.th_set_nproc); __kmp_printf(" Set Proc Bind: %2d\n", thread->th.th_set_proc_bind); __kmp_print_structure_thread(" Next in pool: ", thread->th.th_next_pool); __kmp_printf("\n"); __kmp_print_structure_team_accum(list, thread->th.th_team); __kmp_print_structure_team_accum(list, thread->th.th_serial_team); } } } else { __kmp_printf("Threads array is not allocated.\n"); } // Print out __kmp_root array. __kmp_printf("\n------------------------------\nUbers\n----------------------" "--------\n"); if (__kmp_root != NULL) { int gtid; for (gtid = 0; gtid < __kmp_threads_capacity; ++gtid) { kmp_root_t const *root = __kmp_root[gtid]; if (root != NULL) { __kmp_printf("GTID %2d %p:\n", gtid, root); __kmp_print_structure_team(" Root Team: ", root->r.r_root_team); __kmp_print_structure_team(" Hot Team: ", root->r.r_hot_team); __kmp_print_structure_thread(" Uber Thread: ", root->r.r_uber_thread); __kmp_printf(" Active?: %2d\n", root->r.r_active); __kmp_printf(" In Parallel: %2d\n", KMP_ATOMIC_LD_RLX(&root->r.r_in_parallel)); __kmp_printf("\n"); __kmp_print_structure_team_accum(list, root->r.r_root_team); __kmp_print_structure_team_accum(list, root->r.r_hot_team); } } } else { __kmp_printf("Ubers array is not allocated.\n"); } __kmp_printf("\n------------------------------\nTeams\n----------------------" "--------\n"); while (list->next != NULL) { kmp_team_p const *team = list->entry; int i; __kmp_printf("Team %2x %p:\n", team->t.t_id, team); __kmp_print_structure_team(" Parent Team: ", team->t.t_parent); __kmp_printf(" Master TID: %2d\n", team->t.t_master_tid); __kmp_printf(" Max threads: %2d\n", team->t.t_max_nproc); __kmp_printf(" Levels of serial: %2d\n", team->t.t_serialized); __kmp_printf(" Number threads: %2d\n", team->t.t_nproc); for (i = 0; i < team->t.t_nproc; ++i) { __kmp_printf(" Thread %2d: ", i); __kmp_print_structure_thread("", team->t.t_threads[i]); } __kmp_print_structure_team(" Next in pool: ", team->t.t_next_pool); __kmp_printf("\n"); list = list->next; } // Print out __kmp_thread_pool and __kmp_team_pool. __kmp_printf("\n------------------------------\nPools\n----------------------" "--------\n"); __kmp_print_structure_thread("Thread pool: ", CCAST(kmp_info_t *, __kmp_thread_pool)); __kmp_print_structure_team("Team pool: ", CCAST(kmp_team_t *, __kmp_team_pool)); __kmp_printf("\n"); // Free team list. while (list != NULL) { kmp_team_list_item_t *item = list; list = list->next; KMP_INTERNAL_FREE(item); } } #endif //--------------------------------------------------------------------------- // Stuff for per-thread fast random number generator // Table of primes static const unsigned __kmp_primes[] = { 0x9e3779b1, 0xffe6cc59, 0x2109f6dd, 0x43977ab5, 0xba5703f5, 0xb495a877, 0xe1626741, 0x79695e6b, 0xbc98c09f, 0xd5bee2b3, 0x287488f9, 0x3af18231, 0x9677cd4d, 0xbe3a6929, 0xadc6a877, 0xdcf0674b, 0xbe4d6fe9, 0x5f15e201, 0x99afc3fd, 0xf3f16801, 0xe222cfff, 0x24ba5fdb, 0x0620452d, 0x79f149e3, 0xc8b93f49, 0x972702cd, 0xb07dd827, 0x6c97d5ed, 0x085a3d61, 0x46eb5ea7, 0x3d9910ed, 0x2e687b5b, 0x29609227, 0x6eb081f1, 0x0954c4e1, 0x9d114db9, 0x542acfa9, 0xb3e6bd7b, 0x0742d917, 0xe9f3ffa7, 0x54581edb, 0xf2480f45, 0x0bb9288f, 0xef1affc7, 0x85fa0ca7, 0x3ccc14db, 0xe6baf34b, 0x343377f7, 0x5ca19031, 0xe6d9293b, 0xf0a9f391, 0x5d2e980b, 0xfc411073, 0xc3749363, 0xb892d829, 0x3549366b, 0x629750ad, 0xb98294e5, 0x892d9483, 0xc235baf3, 0x3d2402a3, 0x6bdef3c9, 0xbec333cd, 0x40c9520f}; //--------------------------------------------------------------------------- // __kmp_get_random: Get a random number using a linear congruential method. unsigned short __kmp_get_random(kmp_info_t *thread) { unsigned x = thread->th.th_x; unsigned short r = x >> 16; thread->th.th_x = x * thread->th.th_a + 1; KA_TRACE(30, ("__kmp_get_random: THREAD: %d, RETURN: %u\n", thread->th.th_info.ds.ds_tid, r)); return r; } //-------------------------------------------------------- // __kmp_init_random: Initialize a random number generator void __kmp_init_random(kmp_info_t *thread) { unsigned seed = thread->th.th_info.ds.ds_tid; thread->th.th_a = __kmp_primes[seed % (sizeof(__kmp_primes) / sizeof(__kmp_primes[0]))]; thread->th.th_x = (seed + 1) * thread->th.th_a + 1; KA_TRACE(30, ("__kmp_init_random: THREAD: %u; A: %u\n", seed, thread->th.th_a)); } #if KMP_OS_WINDOWS /* reclaim array entries for root threads that are already dead, returns number * reclaimed */ static int __kmp_reclaim_dead_roots(void) { int i, r = 0; for (i = 0; i < __kmp_threads_capacity; ++i) { if (KMP_UBER_GTID(i) && !__kmp_still_running((kmp_info_t *)TCR_SYNC_PTR(__kmp_threads[i])) && !__kmp_root[i] ->r.r_active) { // AC: reclaim only roots died in non-active state r += __kmp_unregister_root_other_thread(i); } } return r; } #endif /* This function attempts to create free entries in __kmp_threads and __kmp_root, and returns the number of free entries generated. For Windows* OS static library, the first mechanism used is to reclaim array entries for root threads that are already dead. On all platforms, expansion is attempted on the arrays __kmp_threads_ and __kmp_root, with appropriate update to __kmp_threads_capacity. Array capacity is increased by doubling with clipping to __kmp_tp_capacity, if threadprivate cache array has been created. Synchronization with __kmpc_threadprivate_cached is done using __kmp_tp_cached_lock. After any dead root reclamation, if the clipping value allows array expansion to result in the generation of a total of nNeed free slots, the function does that expansion. If not, nothing is done beyond the possible initial root thread reclamation. If any argument is negative, the behavior is undefined. */ static int __kmp_expand_threads(int nNeed) { int added = 0; int minimumRequiredCapacity; int newCapacity; kmp_info_t **newThreads; kmp_root_t **newRoot; // All calls to __kmp_expand_threads should be under __kmp_forkjoin_lock, so // resizing __kmp_threads does not need additional protection if foreign // threads are present #if KMP_OS_WINDOWS && !KMP_DYNAMIC_LIB /* only for Windows static library */ /* reclaim array entries for root threads that are already dead */ added = __kmp_reclaim_dead_roots(); if (nNeed) { nNeed -= added; if (nNeed < 0) nNeed = 0; } #endif if (nNeed <= 0) return added; // Note that __kmp_threads_capacity is not bounded by __kmp_max_nth. If // __kmp_max_nth is set to some value less than __kmp_sys_max_nth by the // user via KMP_DEVICE_THREAD_LIMIT, then __kmp_threads_capacity may become // > __kmp_max_nth in one of two ways: // // 1) The initialization thread (gtid = 0) exits. __kmp_threads[0] // may not be reused by another thread, so we may need to increase // __kmp_threads_capacity to __kmp_max_nth + 1. // // 2) New foreign root(s) are encountered. We always register new foreign // roots. This may cause a smaller # of threads to be allocated at // subsequent parallel regions, but the worker threads hang around (and // eventually go to sleep) and need slots in the __kmp_threads[] array. // // Anyway, that is the reason for moving the check to see if // __kmp_max_nth was exceeded into __kmp_reserve_threads() // instead of having it performed here. -BB KMP_DEBUG_ASSERT(__kmp_sys_max_nth >= __kmp_threads_capacity); /* compute expansion headroom to check if we can expand */ if (__kmp_sys_max_nth - __kmp_threads_capacity < nNeed) { /* possible expansion too small -- give up */ return added; } minimumRequiredCapacity = __kmp_threads_capacity + nNeed; newCapacity = __kmp_threads_capacity; do { newCapacity = newCapacity <= (__kmp_sys_max_nth >> 1) ? (newCapacity << 1) : __kmp_sys_max_nth; } while (newCapacity < minimumRequiredCapacity); newThreads = (kmp_info_t **)__kmp_allocate( (sizeof(kmp_info_t *) + sizeof(kmp_root_t *)) * newCapacity + CACHE_LINE); newRoot = (kmp_root_t **)((char *)newThreads + sizeof(kmp_info_t *) * newCapacity); KMP_MEMCPY(newThreads, __kmp_threads, __kmp_threads_capacity * sizeof(kmp_info_t *)); KMP_MEMCPY(newRoot, __kmp_root, __kmp_threads_capacity * sizeof(kmp_root_t *)); kmp_info_t **temp_threads = __kmp_threads; *(kmp_info_t * *volatile *)&__kmp_threads = newThreads; *(kmp_root_t * *volatile *)&__kmp_root = newRoot; __kmp_free(temp_threads); added += newCapacity - __kmp_threads_capacity; *(volatile int *)&__kmp_threads_capacity = newCapacity; if (newCapacity > __kmp_tp_capacity) { __kmp_acquire_bootstrap_lock(&__kmp_tp_cached_lock); if (__kmp_tp_cached && newCapacity > __kmp_tp_capacity) { __kmp_threadprivate_resize_cache(newCapacity); } else { // increase __kmp_tp_capacity to correspond with kmp_threads size *(volatile int *)&__kmp_tp_capacity = newCapacity; } __kmp_release_bootstrap_lock(&__kmp_tp_cached_lock); } return added; } /* Register the current thread as a root thread and obtain our gtid. We must have the __kmp_initz_lock held at this point. Argument TRUE only if are the thread that calls from __kmp_do_serial_initialize() */ int __kmp_register_root(int initial_thread) { kmp_info_t *root_thread; kmp_root_t *root; int gtid; int capacity; __kmp_acquire_bootstrap_lock(&__kmp_forkjoin_lock); KA_TRACE(20, ("__kmp_register_root: entered\n")); KMP_MB(); /* 2007-03-02: If initial thread did not invoke OpenMP RTL yet, and this thread is not an initial one, "__kmp_all_nth >= __kmp_threads_capacity" condition does not work as expected -- it may return false (that means there is at least one empty slot in __kmp_threads array), but it is possible the only free slot is #0, which is reserved for initial thread and so cannot be used for this one. Following code workarounds this bug. However, right solution seems to be not reserving slot #0 for initial thread because: (1) there is no magic in slot #0, (2) we cannot detect initial thread reliably (the first thread which does serial initialization may be not a real initial thread). */ capacity = __kmp_threads_capacity; if (!initial_thread && TCR_PTR(__kmp_threads[0]) == NULL) { --capacity; } /* see if there are too many threads */ if (__kmp_all_nth >= capacity && !__kmp_expand_threads(1)) { if (__kmp_tp_cached) { __kmp_fatal(KMP_MSG(CantRegisterNewThread), KMP_HNT(Set_ALL_THREADPRIVATE, __kmp_tp_capacity), KMP_HNT(PossibleSystemLimitOnThreads), __kmp_msg_null); } else { __kmp_fatal(KMP_MSG(CantRegisterNewThread), KMP_HNT(SystemLimitOnThreads), __kmp_msg_null); } } /* find an available thread slot */ /* Don't reassign the zero slot since we need that to only be used by initial thread */ for (gtid = (initial_thread ? 0 : 1); TCR_PTR(__kmp_threads[gtid]) != NULL; gtid++) ; KA_TRACE(1, ("__kmp_register_root: found slot in threads array: T#%d\n", gtid)); KMP_ASSERT(gtid < __kmp_threads_capacity); /* update global accounting */ __kmp_all_nth++; TCW_4(__kmp_nth, __kmp_nth + 1); // if __kmp_adjust_gtid_mode is set, then we use method #1 (sp search) for low // numbers of procs, and method #2 (keyed API call) for higher numbers. if (__kmp_adjust_gtid_mode) { if (__kmp_all_nth >= __kmp_tls_gtid_min) { if (TCR_4(__kmp_gtid_mode) != 2) { TCW_4(__kmp_gtid_mode, 2); } } else { if (TCR_4(__kmp_gtid_mode) != 1) { TCW_4(__kmp_gtid_mode, 1); } } } #ifdef KMP_ADJUST_BLOCKTIME /* Adjust blocktime to zero if necessary */ /* Middle initialization might not have occurred yet */ if (!__kmp_env_blocktime && (__kmp_avail_proc > 0)) { if (__kmp_nth > __kmp_avail_proc) { __kmp_zero_bt = TRUE; } } #endif /* KMP_ADJUST_BLOCKTIME */ /* setup this new hierarchy */ if (!(root = __kmp_root[gtid])) { root = __kmp_root[gtid] = (kmp_root_t *)__kmp_allocate(sizeof(kmp_root_t)); KMP_DEBUG_ASSERT(!root->r.r_root_team); } #if KMP_STATS_ENABLED // Initialize stats as soon as possible (right after gtid assignment). __kmp_stats_thread_ptr = __kmp_stats_list->push_back(gtid); __kmp_stats_thread_ptr->startLife(); KMP_SET_THREAD_STATE(SERIAL_REGION); KMP_INIT_PARTITIONED_TIMERS(OMP_serial); #endif __kmp_initialize_root(root); /* setup new root thread structure */ if (root->r.r_uber_thread) { root_thread = root->r.r_uber_thread; } else { root_thread = (kmp_info_t *)__kmp_allocate(sizeof(kmp_info_t)); if (__kmp_storage_map) { __kmp_print_thread_storage_map(root_thread, gtid); } root_thread->th.th_info.ds.ds_gtid = gtid; #if OMPT_SUPPORT root_thread->th.ompt_thread_info.thread_data = ompt_data_none; #endif root_thread->th.th_root = root; if (__kmp_env_consistency_check) { root_thread->th.th_cons = __kmp_allocate_cons_stack(gtid); } #if USE_FAST_MEMORY __kmp_initialize_fast_memory(root_thread); #endif /* USE_FAST_MEMORY */ #if KMP_USE_BGET KMP_DEBUG_ASSERT(root_thread->th.th_local.bget_data == NULL); __kmp_initialize_bget(root_thread); #endif __kmp_init_random(root_thread); // Initialize random number generator } /* setup the serial team held in reserve by the root thread */ if (!root_thread->th.th_serial_team) { kmp_internal_control_t r_icvs = __kmp_get_global_icvs(); KF_TRACE(10, ("__kmp_register_root: before serial_team\n")); root_thread->th.th_serial_team = __kmp_allocate_team( root, 1, 1, #if OMPT_SUPPORT ompt_data_none, // root parallel id #endif proc_bind_default, &r_icvs, 0 USE_NESTED_HOT_ARG(NULL)); } KMP_ASSERT(root_thread->th.th_serial_team); KF_TRACE(10, ("__kmp_register_root: after serial_team = %p\n", root_thread->th.th_serial_team)); /* drop root_thread into place */ TCW_SYNC_PTR(__kmp_threads[gtid], root_thread); root->r.r_root_team->t.t_threads[0] = root_thread; root->r.r_hot_team->t.t_threads[0] = root_thread; root_thread->th.th_serial_team->t.t_threads[0] = root_thread; // AC: the team created in reserve, not for execution (it is unused for now). root_thread->th.th_serial_team->t.t_serialized = 0; root->r.r_uber_thread = root_thread; /* initialize the thread, get it ready to go */ __kmp_initialize_info(root_thread, root->r.r_root_team, 0, gtid); TCW_4(__kmp_init_gtid, TRUE); /* prepare the master thread for get_gtid() */ __kmp_gtid_set_specific(gtid); #if USE_ITT_BUILD __kmp_itt_thread_name(gtid); #endif /* USE_ITT_BUILD */ #ifdef KMP_TDATA_GTID __kmp_gtid = gtid; #endif __kmp_create_worker(gtid, root_thread, __kmp_stksize); KMP_DEBUG_ASSERT(__kmp_gtid_get_specific() == gtid); KA_TRACE(20, ("__kmp_register_root: T#%d init T#%d(%d:%d) arrived: join=%u, " "plain=%u\n", gtid, __kmp_gtid_from_tid(0, root->r.r_hot_team), root->r.r_hot_team->t.t_id, 0, KMP_INIT_BARRIER_STATE, KMP_INIT_BARRIER_STATE)); { // Initialize barrier data. int b; for (b = 0; b < bs_last_barrier; ++b) { root_thread->th.th_bar[b].bb.b_arrived = KMP_INIT_BARRIER_STATE; #if USE_DEBUGGER root_thread->th.th_bar[b].bb.b_worker_arrived = 0; #endif } } KMP_DEBUG_ASSERT(root->r.r_hot_team->t.t_bar[bs_forkjoin_barrier].b_arrived == KMP_INIT_BARRIER_STATE); #if KMP_AFFINITY_SUPPORTED root_thread->th.th_current_place = KMP_PLACE_UNDEFINED; root_thread->th.th_new_place = KMP_PLACE_UNDEFINED; root_thread->th.th_first_place = KMP_PLACE_UNDEFINED; root_thread->th.th_last_place = KMP_PLACE_UNDEFINED; if (TCR_4(__kmp_init_middle)) { __kmp_affinity_set_init_mask(gtid, TRUE); } #endif /* KMP_AFFINITY_SUPPORTED */ root_thread->th.th_def_allocator = __kmp_def_allocator; root_thread->th.th_prev_level = 0; root_thread->th.th_prev_num_threads = 1; kmp_cg_root_t *tmp = (kmp_cg_root_t *)__kmp_allocate(sizeof(kmp_cg_root_t)); tmp->cg_root = root_thread; tmp->cg_thread_limit = __kmp_cg_max_nth; tmp->cg_nthreads = 1; KA_TRACE(100, ("__kmp_register_root: Thread %p created node %p with" " cg_nthreads init to 1\n", root_thread, tmp)); tmp->up = NULL; root_thread->th.th_cg_roots = tmp; __kmp_root_counter++; #if OMPT_SUPPORT if (!initial_thread && ompt_enabled.enabled) { kmp_info_t *root_thread = ompt_get_thread(); ompt_set_thread_state(root_thread, ompt_state_overhead); if (ompt_enabled.ompt_callback_thread_begin) { ompt_callbacks.ompt_callback(ompt_callback_thread_begin)( ompt_thread_initial, __ompt_get_thread_data_internal()); } ompt_data_t *task_data; ompt_data_t *parallel_data; __ompt_get_task_info_internal(0, NULL, &task_data, NULL, ¶llel_data, NULL); if (ompt_enabled.ompt_callback_implicit_task) { ompt_callbacks.ompt_callback(ompt_callback_implicit_task)( ompt_scope_begin, parallel_data, task_data, 1, 1, ompt_task_initial); } ompt_set_thread_state(root_thread, ompt_state_work_serial); } #endif KMP_MB(); __kmp_release_bootstrap_lock(&__kmp_forkjoin_lock); return gtid; } #if KMP_NESTED_HOT_TEAMS static int __kmp_free_hot_teams(kmp_root_t *root, kmp_info_t *thr, int level, const int max_level) { int i, n, nth; kmp_hot_team_ptr_t *hot_teams = thr->th.th_hot_teams; if (!hot_teams || !hot_teams[level].hot_team) { return 0; } KMP_DEBUG_ASSERT(level < max_level); kmp_team_t *team = hot_teams[level].hot_team; nth = hot_teams[level].hot_team_nth; n = nth - 1; // master is not freed if (level < max_level - 1) { for (i = 0; i < nth; ++i) { kmp_info_t *th = team->t.t_threads[i]; n += __kmp_free_hot_teams(root, th, level + 1, max_level); if (i > 0 && th->th.th_hot_teams) { __kmp_free(th->th.th_hot_teams); th->th.th_hot_teams = NULL; } } } __kmp_free_team(root, team, NULL); return n; } #endif // Resets a root thread and clear its root and hot teams. // Returns the number of __kmp_threads entries directly and indirectly freed. static int __kmp_reset_root(int gtid, kmp_root_t *root) { kmp_team_t *root_team = root->r.r_root_team; kmp_team_t *hot_team = root->r.r_hot_team; int n = hot_team->t.t_nproc; int i; KMP_DEBUG_ASSERT(!root->r.r_active); root->r.r_root_team = NULL; root->r.r_hot_team = NULL; // __kmp_free_team() does not free hot teams, so we have to clear r_hot_team // before call to __kmp_free_team(). __kmp_free_team(root, root_team USE_NESTED_HOT_ARG(NULL)); #if KMP_NESTED_HOT_TEAMS if (__kmp_hot_teams_max_level > 0) { // need to free nested hot teams and their threads if any for (i = 0; i < hot_team->t.t_nproc; ++i) { kmp_info_t *th = hot_team->t.t_threads[i]; if (__kmp_hot_teams_max_level > 1) { n += __kmp_free_hot_teams(root, th, 1, __kmp_hot_teams_max_level); } if (th->th.th_hot_teams) { __kmp_free(th->th.th_hot_teams); th->th.th_hot_teams = NULL; } } } #endif __kmp_free_team(root, hot_team USE_NESTED_HOT_ARG(NULL)); // Before we can reap the thread, we need to make certain that all other // threads in the teams that had this root as ancestor have stopped trying to // steal tasks. if (__kmp_tasking_mode != tskm_immediate_exec) { __kmp_wait_to_unref_task_teams(); } #if KMP_OS_WINDOWS /* Close Handle of root duplicated in __kmp_create_worker (tr #62919) */ KA_TRACE( 10, ("__kmp_reset_root: free handle, th = %p, handle = %" KMP_UINTPTR_SPEC "\n", (LPVOID) & (root->r.r_uber_thread->th), root->r.r_uber_thread->th.th_info.ds.ds_thread)); __kmp_free_handle(root->r.r_uber_thread->th.th_info.ds.ds_thread); #endif /* KMP_OS_WINDOWS */ #if OMPT_SUPPORT ompt_data_t *task_data; ompt_data_t *parallel_data; __ompt_get_task_info_internal(0, NULL, &task_data, NULL, ¶llel_data, NULL); if (ompt_enabled.ompt_callback_implicit_task) { ompt_callbacks.ompt_callback(ompt_callback_implicit_task)( ompt_scope_end, parallel_data, task_data, 0, 1, ompt_task_initial); } if (ompt_enabled.ompt_callback_thread_end) { ompt_callbacks.ompt_callback(ompt_callback_thread_end)( &(root->r.r_uber_thread->th.ompt_thread_info.thread_data)); } #endif TCW_4(__kmp_nth, __kmp_nth - 1); // __kmp_reap_thread will decrement __kmp_all_nth. i = root->r.r_uber_thread->th.th_cg_roots->cg_nthreads--; KA_TRACE(100, ("__kmp_reset_root: Thread %p decrement cg_nthreads on node %p" " to %d\n", root->r.r_uber_thread, root->r.r_uber_thread->th.th_cg_roots, root->r.r_uber_thread->th.th_cg_roots->cg_nthreads)); if (i == 1) { // need to free contention group structure KMP_DEBUG_ASSERT(root->r.r_uber_thread == root->r.r_uber_thread->th.th_cg_roots->cg_root); KMP_DEBUG_ASSERT(root->r.r_uber_thread->th.th_cg_roots->up == NULL); __kmp_free(root->r.r_uber_thread->th.th_cg_roots); root->r.r_uber_thread->th.th_cg_roots = NULL; } __kmp_reap_thread(root->r.r_uber_thread, 1); // We canot put root thread to __kmp_thread_pool, so we have to reap it // instead of freeing. root->r.r_uber_thread = NULL; /* mark root as no longer in use */ root->r.r_begin = FALSE; return n; } void __kmp_unregister_root_current_thread(int gtid) { KA_TRACE(1, ("__kmp_unregister_root_current_thread: enter T#%d\n", gtid)); /* this lock should be ok, since unregister_root_current_thread is never called during an abort, only during a normal close. furthermore, if you have the forkjoin lock, you should never try to get the initz lock */ __kmp_acquire_bootstrap_lock(&__kmp_forkjoin_lock); if (TCR_4(__kmp_global.g.g_done) || !__kmp_init_serial) { KC_TRACE(10, ("__kmp_unregister_root_current_thread: already finished, " "exiting T#%d\n", gtid)); __kmp_release_bootstrap_lock(&__kmp_forkjoin_lock); return; } kmp_root_t *root = __kmp_root[gtid]; KMP_DEBUG_ASSERT(__kmp_threads && __kmp_threads[gtid]); KMP_ASSERT(KMP_UBER_GTID(gtid)); KMP_ASSERT(root == __kmp_threads[gtid]->th.th_root); KMP_ASSERT(root->r.r_active == FALSE); KMP_MB(); kmp_info_t *thread = __kmp_threads[gtid]; kmp_team_t *team = thread->th.th_team; kmp_task_team_t *task_team = thread->th.th_task_team; // we need to wait for the proxy tasks before finishing the thread if (task_team != NULL && task_team->tt.tt_found_proxy_tasks) { #if OMPT_SUPPORT // the runtime is shutting down so we won't report any events thread->th.ompt_thread_info.state = ompt_state_undefined; #endif __kmp_task_team_wait(thread, team USE_ITT_BUILD_ARG(NULL)); } __kmp_reset_root(gtid, root); /* free up this thread slot */ __kmp_gtid_set_specific(KMP_GTID_DNE); #ifdef KMP_TDATA_GTID __kmp_gtid = KMP_GTID_DNE; #endif KMP_MB(); KC_TRACE(10, ("__kmp_unregister_root_current_thread: T#%d unregistered\n", gtid)); __kmp_release_bootstrap_lock(&__kmp_forkjoin_lock); } #if KMP_OS_WINDOWS /* __kmp_forkjoin_lock must be already held Unregisters a root thread that is not the current thread. Returns the number of __kmp_threads entries freed as a result. */ static int __kmp_unregister_root_other_thread(int gtid) { kmp_root_t *root = __kmp_root[gtid]; int r; KA_TRACE(1, ("__kmp_unregister_root_other_thread: enter T#%d\n", gtid)); KMP_DEBUG_ASSERT(__kmp_threads && __kmp_threads[gtid]); KMP_ASSERT(KMP_UBER_GTID(gtid)); KMP_ASSERT(root == __kmp_threads[gtid]->th.th_root); KMP_ASSERT(root->r.r_active == FALSE); r = __kmp_reset_root(gtid, root); KC_TRACE(10, ("__kmp_unregister_root_other_thread: T#%d unregistered\n", gtid)); return r; } #endif #if KMP_DEBUG void __kmp_task_info() { kmp_int32 gtid = __kmp_entry_gtid(); kmp_int32 tid = __kmp_tid_from_gtid(gtid); kmp_info_t *this_thr = __kmp_threads[gtid]; kmp_team_t *steam = this_thr->th.th_serial_team; kmp_team_t *team = this_thr->th.th_team; __kmp_printf( "__kmp_task_info: gtid=%d tid=%d t_thread=%p team=%p steam=%p curtask=%p " "ptask=%p\n", gtid, tid, this_thr, team, steam, this_thr->th.th_current_task, team->t.t_implicit_task_taskdata[tid].td_parent); } #endif // KMP_DEBUG /* TODO optimize with one big memclr, take out what isn't needed, split responsibility to workers as much as possible, and delay initialization of features as much as possible */ static void __kmp_initialize_info(kmp_info_t *this_thr, kmp_team_t *team, int tid, int gtid) { /* this_thr->th.th_info.ds.ds_gtid is setup in kmp_allocate_thread/create_worker. this_thr->th.th_serial_team is setup in __kmp_allocate_thread */ kmp_info_t *master = team->t.t_threads[0]; KMP_DEBUG_ASSERT(this_thr != NULL); KMP_DEBUG_ASSERT(this_thr->th.th_serial_team); KMP_DEBUG_ASSERT(team); KMP_DEBUG_ASSERT(team->t.t_threads); KMP_DEBUG_ASSERT(team->t.t_dispatch); KMP_DEBUG_ASSERT(master); KMP_DEBUG_ASSERT(master->th.th_root); KMP_MB(); TCW_SYNC_PTR(this_thr->th.th_team, team); this_thr->th.th_info.ds.ds_tid = tid; this_thr->th.th_set_nproc = 0; if (__kmp_tasking_mode != tskm_immediate_exec) // When tasking is possible, threads are not safe to reap until they are // done tasking; this will be set when tasking code is exited in wait this_thr->th.th_reap_state = KMP_NOT_SAFE_TO_REAP; else // no tasking --> always safe to reap this_thr->th.th_reap_state = KMP_SAFE_TO_REAP; this_thr->th.th_set_proc_bind = proc_bind_default; #if KMP_AFFINITY_SUPPORTED this_thr->th.th_new_place = this_thr->th.th_current_place; #endif this_thr->th.th_root = master->th.th_root; /* setup the thread's cache of the team structure */ this_thr->th.th_team_nproc = team->t.t_nproc; this_thr->th.th_team_master = master; this_thr->th.th_team_serialized = team->t.t_serialized; TCW_PTR(this_thr->th.th_sleep_loc, NULL); KMP_DEBUG_ASSERT(team->t.t_implicit_task_taskdata); KF_TRACE(10, ("__kmp_initialize_info1: T#%d:%d this_thread=%p curtask=%p\n", tid, gtid, this_thr, this_thr->th.th_current_task)); __kmp_init_implicit_task(this_thr->th.th_team_master->th.th_ident, this_thr, team, tid, TRUE); KF_TRACE(10, ("__kmp_initialize_info2: T#%d:%d this_thread=%p curtask=%p\n", tid, gtid, this_thr, this_thr->th.th_current_task)); // TODO: Initialize ICVs from parent; GEH - isn't that already done in // __kmp_initialize_team()? /* TODO no worksharing in speculative threads */ this_thr->th.th_dispatch = &team->t.t_dispatch[tid]; this_thr->th.th_local.this_construct = 0; if (!this_thr->th.th_pri_common) { this_thr->th.th_pri_common = (struct common_table *)__kmp_allocate(sizeof(struct common_table)); if (__kmp_storage_map) { __kmp_print_storage_map_gtid( gtid, this_thr->th.th_pri_common, this_thr->th.th_pri_common + 1, sizeof(struct common_table), "th_%d.th_pri_common\n", gtid); } this_thr->th.th_pri_head = NULL; } if (this_thr != master && // Master's CG root is initialized elsewhere this_thr->th.th_cg_roots != master->th.th_cg_roots) { // CG root not set // Make new thread's CG root same as master's KMP_DEBUG_ASSERT(master->th.th_cg_roots); kmp_cg_root_t *tmp = this_thr->th.th_cg_roots; if (tmp) { // worker changes CG, need to check if old CG should be freed int i = tmp->cg_nthreads--; KA_TRACE(100, ("__kmp_initialize_info: Thread %p decrement cg_nthreads" " on node %p of thread %p to %d\n", this_thr, tmp, tmp->cg_root, tmp->cg_nthreads)); if (i == 1) { __kmp_free(tmp); // last thread left CG --> free it } } this_thr->th.th_cg_roots = master->th.th_cg_roots; // Increment new thread's CG root's counter to add the new thread this_thr->th.th_cg_roots->cg_nthreads++; KA_TRACE(100, ("__kmp_initialize_info: Thread %p increment cg_nthreads on" " node %p of thread %p to %d\n", this_thr, this_thr->th.th_cg_roots, this_thr->th.th_cg_roots->cg_root, this_thr->th.th_cg_roots->cg_nthreads)); this_thr->th.th_current_task->td_icvs.thread_limit = this_thr->th.th_cg_roots->cg_thread_limit; } /* Initialize dynamic dispatch */ { volatile kmp_disp_t *dispatch = this_thr->th.th_dispatch; // Use team max_nproc since this will never change for the team. size_t disp_size = sizeof(dispatch_private_info_t) * (team->t.t_max_nproc == 1 ? 1 : __kmp_dispatch_num_buffers); KD_TRACE(10, ("__kmp_initialize_info: T#%d max_nproc: %d\n", gtid, team->t.t_max_nproc)); KMP_ASSERT(dispatch); KMP_DEBUG_ASSERT(team->t.t_dispatch); KMP_DEBUG_ASSERT(dispatch == &team->t.t_dispatch[tid]); dispatch->th_disp_index = 0; dispatch->th_doacross_buf_idx = 0; if (!dispatch->th_disp_buffer) { dispatch->th_disp_buffer = (dispatch_private_info_t *)__kmp_allocate(disp_size); if (__kmp_storage_map) { __kmp_print_storage_map_gtid( gtid, &dispatch->th_disp_buffer[0], &dispatch->th_disp_buffer[team->t.t_max_nproc == 1 ? 1 : __kmp_dispatch_num_buffers], disp_size, "th_%d.th_dispatch.th_disp_buffer " "(team_%d.t_dispatch[%d].th_disp_buffer)", gtid, team->t.t_id, gtid); } } else { memset(&dispatch->th_disp_buffer[0], '\0', disp_size); } dispatch->th_dispatch_pr_current = 0; dispatch->th_dispatch_sh_current = 0; dispatch->th_deo_fcn = 0; /* ORDERED */ dispatch->th_dxo_fcn = 0; /* END ORDERED */ } this_thr->th.th_next_pool = NULL; if (!this_thr->th.th_task_state_memo_stack) { size_t i; this_thr->th.th_task_state_memo_stack = (kmp_uint8 *)__kmp_allocate(4 * sizeof(kmp_uint8)); this_thr->th.th_task_state_top = 0; this_thr->th.th_task_state_stack_sz = 4; for (i = 0; i < this_thr->th.th_task_state_stack_sz; ++i) // zero init the stack this_thr->th.th_task_state_memo_stack[i] = 0; } KMP_DEBUG_ASSERT(!this_thr->th.th_spin_here); KMP_DEBUG_ASSERT(this_thr->th.th_next_waiting == 0); KMP_MB(); } /* allocate a new thread for the requesting team. this is only called from within a forkjoin critical section. we will first try to get an available thread from the thread pool. if none is available, we will fork a new one assuming we are able to create a new one. this should be assured, as the caller should check on this first. */ kmp_info_t *__kmp_allocate_thread(kmp_root_t *root, kmp_team_t *team, int new_tid) { kmp_team_t *serial_team; kmp_info_t *new_thr; int new_gtid; KA_TRACE(20, ("__kmp_allocate_thread: T#%d\n", __kmp_get_gtid())); KMP_DEBUG_ASSERT(root && team); #if !KMP_NESTED_HOT_TEAMS KMP_DEBUG_ASSERT(KMP_MASTER_GTID(__kmp_get_gtid())); #endif KMP_MB(); /* first, try to get one from the thread pool */ if (__kmp_thread_pool) { new_thr = CCAST(kmp_info_t *, __kmp_thread_pool); __kmp_thread_pool = (volatile kmp_info_t *)new_thr->th.th_next_pool; if (new_thr == __kmp_thread_pool_insert_pt) { __kmp_thread_pool_insert_pt = NULL; } TCW_4(new_thr->th.th_in_pool, FALSE); __kmp_suspend_initialize_thread(new_thr); __kmp_lock_suspend_mx(new_thr); if (new_thr->th.th_active_in_pool == TRUE) { KMP_DEBUG_ASSERT(new_thr->th.th_active == TRUE); KMP_ATOMIC_DEC(&__kmp_thread_pool_active_nth); new_thr->th.th_active_in_pool = FALSE; } __kmp_unlock_suspend_mx(new_thr); KA_TRACE(20, ("__kmp_allocate_thread: T#%d using thread T#%d\n", __kmp_get_gtid(), new_thr->th.th_info.ds.ds_gtid)); KMP_ASSERT(!new_thr->th.th_team); KMP_DEBUG_ASSERT(__kmp_nth < __kmp_threads_capacity); /* setup the thread structure */ __kmp_initialize_info(new_thr, team, new_tid, new_thr->th.th_info.ds.ds_gtid); KMP_DEBUG_ASSERT(new_thr->th.th_serial_team); TCW_4(__kmp_nth, __kmp_nth + 1); new_thr->th.th_task_state = 0; new_thr->th.th_task_state_top = 0; new_thr->th.th_task_state_stack_sz = 4; #ifdef KMP_ADJUST_BLOCKTIME /* Adjust blocktime back to zero if necessary */ /* Middle initialization might not have occurred yet */ if (!__kmp_env_blocktime && (__kmp_avail_proc > 0)) { if (__kmp_nth > __kmp_avail_proc) { __kmp_zero_bt = TRUE; } } #endif /* KMP_ADJUST_BLOCKTIME */ #if KMP_DEBUG // If thread entered pool via __kmp_free_thread, wait_flag should != // KMP_BARRIER_PARENT_FLAG. int b; kmp_balign_t *balign = new_thr->th.th_bar; for (b = 0; b < bs_last_barrier; ++b) KMP_DEBUG_ASSERT(balign[b].bb.wait_flag != KMP_BARRIER_PARENT_FLAG); #endif KF_TRACE(10, ("__kmp_allocate_thread: T#%d using thread %p T#%d\n", __kmp_get_gtid(), new_thr, new_thr->th.th_info.ds.ds_gtid)); KMP_MB(); return new_thr; } /* no, well fork a new one */ KMP_ASSERT(__kmp_nth == __kmp_all_nth); KMP_ASSERT(__kmp_all_nth < __kmp_threads_capacity); #if KMP_USE_MONITOR // If this is the first worker thread the RTL is creating, then also // launch the monitor thread. We try to do this as early as possible. if (!TCR_4(__kmp_init_monitor)) { __kmp_acquire_bootstrap_lock(&__kmp_monitor_lock); if (!TCR_4(__kmp_init_monitor)) { KF_TRACE(10, ("before __kmp_create_monitor\n")); TCW_4(__kmp_init_monitor, 1); __kmp_create_monitor(&__kmp_monitor); KF_TRACE(10, ("after __kmp_create_monitor\n")); #if KMP_OS_WINDOWS // AC: wait until monitor has started. This is a fix for CQ232808. // The reason is that if the library is loaded/unloaded in a loop with // small (parallel) work in between, then there is high probability that // monitor thread started after the library shutdown. At shutdown it is // too late to cope with the problem, because when the master is in // DllMain (process detach) the monitor has no chances to start (it is // blocked), and master has no means to inform the monitor that the // library has gone, because all the memory which the monitor can access // is going to be released/reset. while (TCR_4(__kmp_init_monitor) < 2) { KMP_YIELD(TRUE); } KF_TRACE(10, ("after monitor thread has started\n")); #endif } __kmp_release_bootstrap_lock(&__kmp_monitor_lock); } #endif KMP_MB(); for (new_gtid = 1; TCR_PTR(__kmp_threads[new_gtid]) != NULL; ++new_gtid) { KMP_DEBUG_ASSERT(new_gtid < __kmp_threads_capacity); } /* allocate space for it. */ new_thr = (kmp_info_t *)__kmp_allocate(sizeof(kmp_info_t)); TCW_SYNC_PTR(__kmp_threads[new_gtid], new_thr); if (__kmp_storage_map) { __kmp_print_thread_storage_map(new_thr, new_gtid); } // add the reserve serialized team, initialized from the team's master thread { kmp_internal_control_t r_icvs = __kmp_get_x_global_icvs(team); KF_TRACE(10, ("__kmp_allocate_thread: before th_serial/serial_team\n")); new_thr->th.th_serial_team = serial_team = (kmp_team_t *)__kmp_allocate_team(root, 1, 1, #if OMPT_SUPPORT ompt_data_none, // root parallel id #endif proc_bind_default, &r_icvs, 0 USE_NESTED_HOT_ARG(NULL)); } KMP_ASSERT(serial_team); serial_team->t.t_serialized = 0; // AC: the team created in reserve, not for // execution (it is unused for now). serial_team->t.t_threads[0] = new_thr; KF_TRACE(10, ("__kmp_allocate_thread: after th_serial/serial_team : new_thr=%p\n", new_thr)); /* setup the thread structures */ __kmp_initialize_info(new_thr, team, new_tid, new_gtid); #if USE_FAST_MEMORY __kmp_initialize_fast_memory(new_thr); #endif /* USE_FAST_MEMORY */ #if KMP_USE_BGET KMP_DEBUG_ASSERT(new_thr->th.th_local.bget_data == NULL); __kmp_initialize_bget(new_thr); #endif __kmp_init_random(new_thr); // Initialize random number generator /* Initialize these only once when thread is grabbed for a team allocation */ KA_TRACE(20, ("__kmp_allocate_thread: T#%d init go fork=%u, plain=%u\n", __kmp_get_gtid(), KMP_INIT_BARRIER_STATE, KMP_INIT_BARRIER_STATE)); int b; kmp_balign_t *balign = new_thr->th.th_bar; for (b = 0; b < bs_last_barrier; ++b) { balign[b].bb.b_go = KMP_INIT_BARRIER_STATE; balign[b].bb.team = NULL; balign[b].bb.wait_flag = KMP_BARRIER_NOT_WAITING; balign[b].bb.use_oncore_barrier = 0; } new_thr->th.th_spin_here = FALSE; new_thr->th.th_next_waiting = 0; #if KMP_OS_UNIX new_thr->th.th_blocking = false; #endif #if KMP_AFFINITY_SUPPORTED new_thr->th.th_current_place = KMP_PLACE_UNDEFINED; new_thr->th.th_new_place = KMP_PLACE_UNDEFINED; new_thr->th.th_first_place = KMP_PLACE_UNDEFINED; new_thr->th.th_last_place = KMP_PLACE_UNDEFINED; #endif new_thr->th.th_def_allocator = __kmp_def_allocator; new_thr->th.th_prev_level = 0; new_thr->th.th_prev_num_threads = 1; TCW_4(new_thr->th.th_in_pool, FALSE); new_thr->th.th_active_in_pool = FALSE; TCW_4(new_thr->th.th_active, TRUE); /* adjust the global counters */ __kmp_all_nth++; __kmp_nth++; // if __kmp_adjust_gtid_mode is set, then we use method #1 (sp search) for low // numbers of procs, and method #2 (keyed API call) for higher numbers. if (__kmp_adjust_gtid_mode) { if (__kmp_all_nth >= __kmp_tls_gtid_min) { if (TCR_4(__kmp_gtid_mode) != 2) { TCW_4(__kmp_gtid_mode, 2); } } else { if (TCR_4(__kmp_gtid_mode) != 1) { TCW_4(__kmp_gtid_mode, 1); } } } #ifdef KMP_ADJUST_BLOCKTIME /* Adjust blocktime back to zero if necessary */ /* Middle initialization might not have occurred yet */ if (!__kmp_env_blocktime && (__kmp_avail_proc > 0)) { if (__kmp_nth > __kmp_avail_proc) { __kmp_zero_bt = TRUE; } } #endif /* KMP_ADJUST_BLOCKTIME */ /* actually fork it and create the new worker thread */ KF_TRACE( 10, ("__kmp_allocate_thread: before __kmp_create_worker: %p\n", new_thr)); __kmp_create_worker(new_gtid, new_thr, __kmp_stksize); KF_TRACE(10, ("__kmp_allocate_thread: after __kmp_create_worker: %p\n", new_thr)); KA_TRACE(20, ("__kmp_allocate_thread: T#%d forked T#%d\n", __kmp_get_gtid(), new_gtid)); KMP_MB(); return new_thr; } /* Reinitialize team for reuse. The hot team code calls this case at every fork barrier, so EPCC barrier test are extremely sensitive to changes in it, esp. writes to the team struct, which cause a cache invalidation in all threads. IF YOU TOUCH THIS ROUTINE, RUN EPCC C SYNCBENCH ON A BIG-IRON MACHINE!!! */ static void __kmp_reinitialize_team(kmp_team_t *team, kmp_internal_control_t *new_icvs, ident_t *loc) { KF_TRACE(10, ("__kmp_reinitialize_team: enter this_thread=%p team=%p\n", team->t.t_threads[0], team)); KMP_DEBUG_ASSERT(team && new_icvs); KMP_DEBUG_ASSERT((!TCR_4(__kmp_init_parallel)) || new_icvs->nproc); KMP_CHECK_UPDATE(team->t.t_ident, loc); KMP_CHECK_UPDATE(team->t.t_id, KMP_GEN_TEAM_ID()); // Copy ICVs to the master thread's implicit taskdata __kmp_init_implicit_task(loc, team->t.t_threads[0], team, 0, FALSE); copy_icvs(&team->t.t_implicit_task_taskdata[0].td_icvs, new_icvs); KF_TRACE(10, ("__kmp_reinitialize_team: exit this_thread=%p team=%p\n", team->t.t_threads[0], team)); } /* Initialize the team data structure. This assumes the t_threads and t_max_nproc are already set. Also, we don't touch the arguments */ static void __kmp_initialize_team(kmp_team_t *team, int new_nproc, kmp_internal_control_t *new_icvs, ident_t *loc) { KF_TRACE(10, ("__kmp_initialize_team: enter: team=%p\n", team)); /* verify */ KMP_DEBUG_ASSERT(team); KMP_DEBUG_ASSERT(new_nproc <= team->t.t_max_nproc); KMP_DEBUG_ASSERT(team->t.t_threads); KMP_MB(); team->t.t_master_tid = 0; /* not needed */ /* team->t.t_master_bar; not needed */ team->t.t_serialized = new_nproc > 1 ? 0 : 1; team->t.t_nproc = new_nproc; /* team->t.t_parent = NULL; TODO not needed & would mess up hot team */ team->t.t_next_pool = NULL; /* memset( team->t.t_threads, 0, sizeof(kmp_info_t*)*new_nproc ); would mess * up hot team */ TCW_SYNC_PTR(team->t.t_pkfn, NULL); /* not needed */ team->t.t_invoke = NULL; /* not needed */ // TODO???: team->t.t_max_active_levels = new_max_active_levels; team->t.t_sched.sched = new_icvs->sched.sched; #if KMP_ARCH_X86 || KMP_ARCH_X86_64 team->t.t_fp_control_saved = FALSE; /* not needed */ team->t.t_x87_fpu_control_word = 0; /* not needed */ team->t.t_mxcsr = 0; /* not needed */ #endif /* KMP_ARCH_X86 || KMP_ARCH_X86_64 */ team->t.t_construct = 0; team->t.t_ordered.dt.t_value = 0; team->t.t_master_active = FALSE; #ifdef KMP_DEBUG team->t.t_copypriv_data = NULL; /* not necessary, but nice for debugging */ #endif #if KMP_OS_WINDOWS team->t.t_copyin_counter = 0; /* for barrier-free copyin implementation */ #endif team->t.t_control_stack_top = NULL; __kmp_reinitialize_team(team, new_icvs, loc); KMP_MB(); KF_TRACE(10, ("__kmp_initialize_team: exit: team=%p\n", team)); } #if (KMP_OS_LINUX || KMP_OS_FREEBSD) && KMP_AFFINITY_SUPPORTED /* Sets full mask for thread and returns old mask, no changes to structures. */ static void __kmp_set_thread_affinity_mask_full_tmp(kmp_affin_mask_t *old_mask) { if (KMP_AFFINITY_CAPABLE()) { int status; if (old_mask != NULL) { status = __kmp_get_system_affinity(old_mask, TRUE); int error = errno; if (status != 0) { __kmp_fatal(KMP_MSG(ChangeThreadAffMaskError), KMP_ERR(error), __kmp_msg_null); } } __kmp_set_system_affinity(__kmp_affin_fullMask, TRUE); } } #endif #if KMP_AFFINITY_SUPPORTED // __kmp_partition_places() is the heart of the OpenMP 4.0 affinity mechanism. // It calculates the worker + master thread's partition based upon the parent // thread's partition, and binds each worker to a thread in their partition. // The master thread's partition should already include its current binding. static void __kmp_partition_places(kmp_team_t *team, int update_master_only) { // Copy the master thread's place partition to the team struct kmp_info_t *master_th = team->t.t_threads[0]; KMP_DEBUG_ASSERT(master_th != NULL); kmp_proc_bind_t proc_bind = team->t.t_proc_bind; int first_place = master_th->th.th_first_place; int last_place = master_th->th.th_last_place; int masters_place = master_th->th.th_current_place; team->t.t_first_place = first_place; team->t.t_last_place = last_place; KA_TRACE(20, ("__kmp_partition_places: enter: proc_bind = %d T#%d(%d:0) " "bound to place %d partition = [%d,%d]\n", proc_bind, __kmp_gtid_from_thread(team->t.t_threads[0]), team->t.t_id, masters_place, first_place, last_place)); switch (proc_bind) { case proc_bind_default: // serial teams might have the proc_bind policy set to proc_bind_default. It // doesn't matter, as we don't rebind master thread for any proc_bind policy KMP_DEBUG_ASSERT(team->t.t_nproc == 1); break; case proc_bind_master: { int f; int n_th = team->t.t_nproc; for (f = 1; f < n_th; f++) { kmp_info_t *th = team->t.t_threads[f]; KMP_DEBUG_ASSERT(th != NULL); th->th.th_first_place = first_place; th->th.th_last_place = last_place; th->th.th_new_place = masters_place; if (__kmp_display_affinity && masters_place != th->th.th_current_place && team->t.t_display_affinity != 1) { team->t.t_display_affinity = 1; } KA_TRACE(100, ("__kmp_partition_places: master: T#%d(%d:%d) place %d " "partition = [%d,%d]\n", __kmp_gtid_from_thread(team->t.t_threads[f]), team->t.t_id, f, masters_place, first_place, last_place)); } } break; case proc_bind_close: { int f; int n_th = team->t.t_nproc; int n_places; if (first_place <= last_place) { n_places = last_place - first_place + 1; } else { n_places = __kmp_affinity_num_masks - first_place + last_place + 1; } if (n_th <= n_places) { int place = masters_place; for (f = 1; f < n_th; f++) { kmp_info_t *th = team->t.t_threads[f]; KMP_DEBUG_ASSERT(th != NULL); if (place == last_place) { place = first_place; } else if (place == (int)(__kmp_affinity_num_masks - 1)) { place = 0; } else { place++; } th->th.th_first_place = first_place; th->th.th_last_place = last_place; th->th.th_new_place = place; if (__kmp_display_affinity && place != th->th.th_current_place && team->t.t_display_affinity != 1) { team->t.t_display_affinity = 1; } KA_TRACE(100, ("__kmp_partition_places: close: T#%d(%d:%d) place %d " "partition = [%d,%d]\n", __kmp_gtid_from_thread(team->t.t_threads[f]), team->t.t_id, f, place, first_place, last_place)); } } else { int S, rem, gap, s_count; S = n_th / n_places; s_count = 0; rem = n_th - (S * n_places); gap = rem > 0 ? n_places / rem : n_places; int place = masters_place; int gap_ct = gap; for (f = 0; f < n_th; f++) { kmp_info_t *th = team->t.t_threads[f]; KMP_DEBUG_ASSERT(th != NULL); th->th.th_first_place = first_place; th->th.th_last_place = last_place; th->th.th_new_place = place; if (__kmp_display_affinity && place != th->th.th_current_place && team->t.t_display_affinity != 1) { team->t.t_display_affinity = 1; } s_count++; if ((s_count == S) && rem && (gap_ct == gap)) { // do nothing, add an extra thread to place on next iteration } else if ((s_count == S + 1) && rem && (gap_ct == gap)) { // we added an extra thread to this place; move to next place if (place == last_place) { place = first_place; } else if (place == (int)(__kmp_affinity_num_masks - 1)) { place = 0; } else { place++; } s_count = 0; gap_ct = 1; rem--; } else if (s_count == S) { // place full; don't add extra if (place == last_place) { place = first_place; } else if (place == (int)(__kmp_affinity_num_masks - 1)) { place = 0; } else { place++; } gap_ct++; s_count = 0; } KA_TRACE(100, ("__kmp_partition_places: close: T#%d(%d:%d) place %d " "partition = [%d,%d]\n", __kmp_gtid_from_thread(team->t.t_threads[f]), team->t.t_id, f, th->th.th_new_place, first_place, last_place)); } KMP_DEBUG_ASSERT(place == masters_place); } } break; case proc_bind_spread: { int f; int n_th = team->t.t_nproc; int n_places; int thidx; if (first_place <= last_place) { n_places = last_place - first_place + 1; } else { n_places = __kmp_affinity_num_masks - first_place + last_place + 1; } if (n_th <= n_places) { int place = -1; if (n_places != static_cast(__kmp_affinity_num_masks)) { int S = n_places / n_th; int s_count, rem, gap, gap_ct; place = masters_place; rem = n_places - n_th * S; gap = rem ? n_th / rem : 1; gap_ct = gap; thidx = n_th; if (update_master_only == 1) thidx = 1; for (f = 0; f < thidx; f++) { kmp_info_t *th = team->t.t_threads[f]; KMP_DEBUG_ASSERT(th != NULL); th->th.th_first_place = place; th->th.th_new_place = place; if (__kmp_display_affinity && place != th->th.th_current_place && team->t.t_display_affinity != 1) { team->t.t_display_affinity = 1; } s_count = 1; while (s_count < S) { if (place == last_place) { place = first_place; } else if (place == (int)(__kmp_affinity_num_masks - 1)) { place = 0; } else { place++; } s_count++; } if (rem && (gap_ct == gap)) { if (place == last_place) { place = first_place; } else if (place == (int)(__kmp_affinity_num_masks - 1)) { place = 0; } else { place++; } rem--; gap_ct = 0; } th->th.th_last_place = place; gap_ct++; if (place == last_place) { place = first_place; } else if (place == (int)(__kmp_affinity_num_masks - 1)) { place = 0; } else { place++; } KA_TRACE(100, ("__kmp_partition_places: spread: T#%d(%d:%d) place %d " "partition = [%d,%d], __kmp_affinity_num_masks: %u\n", __kmp_gtid_from_thread(team->t.t_threads[f]), team->t.t_id, f, th->th.th_new_place, th->th.th_first_place, th->th.th_last_place, __kmp_affinity_num_masks)); } } else { /* Having uniform space of available computation places I can create T partitions of round(P/T) size and put threads into the first place of each partition. */ double current = static_cast(masters_place); double spacing = (static_cast(n_places + 1) / static_cast(n_th)); int first, last; kmp_info_t *th; thidx = n_th + 1; if (update_master_only == 1) thidx = 1; for (f = 0; f < thidx; f++) { first = static_cast(current); last = static_cast(current + spacing) - 1; KMP_DEBUG_ASSERT(last >= first); if (first >= n_places) { if (masters_place) { first -= n_places; last -= n_places; if (first == (masters_place + 1)) { KMP_DEBUG_ASSERT(f == n_th); first--; } if (last == masters_place) { KMP_DEBUG_ASSERT(f == (n_th - 1)); last--; } } else { KMP_DEBUG_ASSERT(f == n_th); first = 0; last = 0; } } if (last >= n_places) { last = (n_places - 1); } place = first; current += spacing; if (f < n_th) { KMP_DEBUG_ASSERT(0 <= first); KMP_DEBUG_ASSERT(n_places > first); KMP_DEBUG_ASSERT(0 <= last); KMP_DEBUG_ASSERT(n_places > last); KMP_DEBUG_ASSERT(last_place >= first_place); th = team->t.t_threads[f]; KMP_DEBUG_ASSERT(th); th->th.th_first_place = first; th->th.th_new_place = place; th->th.th_last_place = last; if (__kmp_display_affinity && place != th->th.th_current_place && team->t.t_display_affinity != 1) { team->t.t_display_affinity = 1; } KA_TRACE(100, ("__kmp_partition_places: spread: T#%d(%d:%d) place %d " "partition = [%d,%d], spacing = %.4f\n", __kmp_gtid_from_thread(team->t.t_threads[f]), team->t.t_id, f, th->th.th_new_place, th->th.th_first_place, th->th.th_last_place, spacing)); } } } KMP_DEBUG_ASSERT(update_master_only || place == masters_place); } else { int S, rem, gap, s_count; S = n_th / n_places; s_count = 0; rem = n_th - (S * n_places); gap = rem > 0 ? n_places / rem : n_places; int place = masters_place; int gap_ct = gap; thidx = n_th; if (update_master_only == 1) thidx = 1; for (f = 0; f < thidx; f++) { kmp_info_t *th = team->t.t_threads[f]; KMP_DEBUG_ASSERT(th != NULL); th->th.th_first_place = place; th->th.th_last_place = place; th->th.th_new_place = place; if (__kmp_display_affinity && place != th->th.th_current_place && team->t.t_display_affinity != 1) { team->t.t_display_affinity = 1; } s_count++; if ((s_count == S) && rem && (gap_ct == gap)) { // do nothing, add an extra thread to place on next iteration } else if ((s_count == S + 1) && rem && (gap_ct == gap)) { // we added an extra thread to this place; move on to next place if (place == last_place) { place = first_place; } else if (place == (int)(__kmp_affinity_num_masks - 1)) { place = 0; } else { place++; } s_count = 0; gap_ct = 1; rem--; } else if (s_count == S) { // place is full; don't add extra thread if (place == last_place) { place = first_place; } else if (place == (int)(__kmp_affinity_num_masks - 1)) { place = 0; } else { place++; } gap_ct++; s_count = 0; } KA_TRACE(100, ("__kmp_partition_places: spread: T#%d(%d:%d) place %d " "partition = [%d,%d]\n", __kmp_gtid_from_thread(team->t.t_threads[f]), team->t.t_id, f, th->th.th_new_place, th->th.th_first_place, th->th.th_last_place)); } KMP_DEBUG_ASSERT(update_master_only || place == masters_place); } } break; default: break; } KA_TRACE(20, ("__kmp_partition_places: exit T#%d\n", team->t.t_id)); } #endif // KMP_AFFINITY_SUPPORTED /* allocate a new team data structure to use. take one off of the free pool if available */ kmp_team_t * __kmp_allocate_team(kmp_root_t *root, int new_nproc, int max_nproc, #if OMPT_SUPPORT ompt_data_t ompt_parallel_data, #endif kmp_proc_bind_t new_proc_bind, kmp_internal_control_t *new_icvs, int argc USE_NESTED_HOT_ARG(kmp_info_t *master)) { KMP_TIME_DEVELOPER_PARTITIONED_BLOCK(KMP_allocate_team); int f; kmp_team_t *team; int use_hot_team = !root->r.r_active; int level = 0; KA_TRACE(20, ("__kmp_allocate_team: called\n")); KMP_DEBUG_ASSERT(new_nproc >= 1 && argc >= 0); KMP_DEBUG_ASSERT(max_nproc >= new_nproc); KMP_MB(); #if KMP_NESTED_HOT_TEAMS kmp_hot_team_ptr_t *hot_teams; if (master) { team = master->th.th_team; level = team->t.t_active_level; if (master->th.th_teams_microtask) { // in teams construct? if (master->th.th_teams_size.nteams > 1 && ( // #teams > 1 team->t.t_pkfn == (microtask_t)__kmp_teams_master || // inner fork of the teams master->th.th_teams_level < team->t.t_level)) { // or nested parallel inside the teams ++level; // not increment if #teams==1, or for outer fork of the teams; // increment otherwise } } hot_teams = master->th.th_hot_teams; if (level < __kmp_hot_teams_max_level && hot_teams && hot_teams[level] .hot_team) { // hot team has already been allocated for given level use_hot_team = 1; } else { use_hot_team = 0; } } #endif // Optimization to use a "hot" team if (use_hot_team && new_nproc > 1) { KMP_DEBUG_ASSERT(new_nproc <= max_nproc); #if KMP_NESTED_HOT_TEAMS team = hot_teams[level].hot_team; #else team = root->r.r_hot_team; #endif #if KMP_DEBUG if (__kmp_tasking_mode != tskm_immediate_exec) { KA_TRACE(20, ("__kmp_allocate_team: hot team task_team[0] = %p " "task_team[1] = %p before reinit\n", team->t.t_task_team[0], team->t.t_task_team[1])); } #endif // Has the number of threads changed? /* Let's assume the most common case is that the number of threads is unchanged, and put that case first. */ if (team->t.t_nproc == new_nproc) { // Check changes in number of threads KA_TRACE(20, ("__kmp_allocate_team: reusing hot team\n")); // This case can mean that omp_set_num_threads() was called and the hot // team size was already reduced, so we check the special flag if (team->t.t_size_changed == -1) { team->t.t_size_changed = 1; } else { KMP_CHECK_UPDATE(team->t.t_size_changed, 0); } // TODO???: team->t.t_max_active_levels = new_max_active_levels; kmp_r_sched_t new_sched = new_icvs->sched; // set master's schedule as new run-time schedule KMP_CHECK_UPDATE(team->t.t_sched.sched, new_sched.sched); __kmp_reinitialize_team(team, new_icvs, root->r.r_uber_thread->th.th_ident); KF_TRACE(10, ("__kmp_allocate_team2: T#%d, this_thread=%p team=%p\n", 0, team->t.t_threads[0], team)); __kmp_push_current_task_to_thread(team->t.t_threads[0], team, 0); #if KMP_AFFINITY_SUPPORTED if ((team->t.t_size_changed == 0) && (team->t.t_proc_bind == new_proc_bind)) { if (new_proc_bind == proc_bind_spread) { __kmp_partition_places( team, 1); // add flag to update only master for spread } KA_TRACE(200, ("__kmp_allocate_team: reusing hot team #%d bindings: " "proc_bind = %d, partition = [%d,%d]\n", team->t.t_id, new_proc_bind, team->t.t_first_place, team->t.t_last_place)); } else { KMP_CHECK_UPDATE(team->t.t_proc_bind, new_proc_bind); __kmp_partition_places(team); } #else KMP_CHECK_UPDATE(team->t.t_proc_bind, new_proc_bind); #endif /* KMP_AFFINITY_SUPPORTED */ } else if (team->t.t_nproc > new_nproc) { KA_TRACE(20, ("__kmp_allocate_team: decreasing hot team thread count to %d\n", new_nproc)); team->t.t_size_changed = 1; #if KMP_NESTED_HOT_TEAMS if (__kmp_hot_teams_mode == 0) { // AC: saved number of threads should correspond to team's value in this // mode, can be bigger in mode 1, when hot team has threads in reserve KMP_DEBUG_ASSERT(hot_teams[level].hot_team_nth == team->t.t_nproc); hot_teams[level].hot_team_nth = new_nproc; #endif // KMP_NESTED_HOT_TEAMS /* release the extra threads we don't need any more */ for (f = new_nproc; f < team->t.t_nproc; f++) { KMP_DEBUG_ASSERT(team->t.t_threads[f]); if (__kmp_tasking_mode != tskm_immediate_exec) { // When decreasing team size, threads no longer in the team should // unref task team. team->t.t_threads[f]->th.th_task_team = NULL; } __kmp_free_thread(team->t.t_threads[f]); team->t.t_threads[f] = NULL; } #if KMP_NESTED_HOT_TEAMS } // (__kmp_hot_teams_mode == 0) else { // When keeping extra threads in team, switch threads to wait on own // b_go flag for (f = new_nproc; f < team->t.t_nproc; ++f) { KMP_DEBUG_ASSERT(team->t.t_threads[f]); kmp_balign_t *balign = team->t.t_threads[f]->th.th_bar; for (int b = 0; b < bs_last_barrier; ++b) { if (balign[b].bb.wait_flag == KMP_BARRIER_PARENT_FLAG) { balign[b].bb.wait_flag = KMP_BARRIER_SWITCH_TO_OWN_FLAG; } KMP_CHECK_UPDATE(balign[b].bb.leaf_kids, 0); } } } #endif // KMP_NESTED_HOT_TEAMS team->t.t_nproc = new_nproc; // TODO???: team->t.t_max_active_levels = new_max_active_levels; KMP_CHECK_UPDATE(team->t.t_sched.sched, new_icvs->sched.sched); __kmp_reinitialize_team(team, new_icvs, root->r.r_uber_thread->th.th_ident); // Update remaining threads for (f = 0; f < new_nproc; ++f) { team->t.t_threads[f]->th.th_team_nproc = new_nproc; } // restore the current task state of the master thread: should be the // implicit task KF_TRACE(10, ("__kmp_allocate_team: T#%d, this_thread=%p team=%p\n", 0, team->t.t_threads[0], team)); __kmp_push_current_task_to_thread(team->t.t_threads[0], team, 0); #ifdef KMP_DEBUG for (f = 0; f < team->t.t_nproc; f++) { KMP_DEBUG_ASSERT(team->t.t_threads[f] && team->t.t_threads[f]->th.th_team_nproc == team->t.t_nproc); } #endif KMP_CHECK_UPDATE(team->t.t_proc_bind, new_proc_bind); #if KMP_AFFINITY_SUPPORTED __kmp_partition_places(team); #endif } else { // team->t.t_nproc < new_nproc #if (KMP_OS_LINUX || KMP_OS_FREEBSD) && KMP_AFFINITY_SUPPORTED kmp_affin_mask_t *old_mask; if (KMP_AFFINITY_CAPABLE()) { KMP_CPU_ALLOC(old_mask); } #endif KA_TRACE(20, ("__kmp_allocate_team: increasing hot team thread count to %d\n", new_nproc)); team->t.t_size_changed = 1; #if KMP_NESTED_HOT_TEAMS int avail_threads = hot_teams[level].hot_team_nth; if (new_nproc < avail_threads) avail_threads = new_nproc; kmp_info_t **other_threads = team->t.t_threads; for (f = team->t.t_nproc; f < avail_threads; ++f) { // Adjust barrier data of reserved threads (if any) of the team // Other data will be set in __kmp_initialize_info() below. int b; kmp_balign_t *balign = other_threads[f]->th.th_bar; for (b = 0; b < bs_last_barrier; ++b) { balign[b].bb.b_arrived = team->t.t_bar[b].b_arrived; KMP_DEBUG_ASSERT(balign[b].bb.wait_flag != KMP_BARRIER_PARENT_FLAG); #if USE_DEBUGGER balign[b].bb.b_worker_arrived = team->t.t_bar[b].b_team_arrived; #endif } } if (hot_teams[level].hot_team_nth >= new_nproc) { // we have all needed threads in reserve, no need to allocate any // this only possible in mode 1, cannot have reserved threads in mode 0 KMP_DEBUG_ASSERT(__kmp_hot_teams_mode == 1); team->t.t_nproc = new_nproc; // just get reserved threads involved } else { // we may have some threads in reserve, but not enough team->t.t_nproc = hot_teams[level] .hot_team_nth; // get reserved threads involved if any hot_teams[level].hot_team_nth = new_nproc; // adjust hot team max size #endif // KMP_NESTED_HOT_TEAMS if (team->t.t_max_nproc < new_nproc) { /* reallocate larger arrays */ __kmp_reallocate_team_arrays(team, new_nproc); __kmp_reinitialize_team(team, new_icvs, NULL); } #if (KMP_OS_LINUX || KMP_OS_FREEBSD) && KMP_AFFINITY_SUPPORTED /* Temporarily set full mask for master thread before creation of workers. The reason is that workers inherit the affinity from master, so if a lot of workers are created on the single core quickly, they don't get a chance to set their own affinity for a long time. */ __kmp_set_thread_affinity_mask_full_tmp(old_mask); #endif /* allocate new threads for the hot team */ for (f = team->t.t_nproc; f < new_nproc; f++) { kmp_info_t *new_worker = __kmp_allocate_thread(root, team, f); KMP_DEBUG_ASSERT(new_worker); team->t.t_threads[f] = new_worker; KA_TRACE(20, ("__kmp_allocate_team: team %d init T#%d arrived: " "join=%llu, plain=%llu\n", team->t.t_id, __kmp_gtid_from_tid(f, team), team->t.t_id, f, team->t.t_bar[bs_forkjoin_barrier].b_arrived, team->t.t_bar[bs_plain_barrier].b_arrived)); { // Initialize barrier data for new threads. int b; kmp_balign_t *balign = new_worker->th.th_bar; for (b = 0; b < bs_last_barrier; ++b) { balign[b].bb.b_arrived = team->t.t_bar[b].b_arrived; KMP_DEBUG_ASSERT(balign[b].bb.wait_flag != KMP_BARRIER_PARENT_FLAG); #if USE_DEBUGGER balign[b].bb.b_worker_arrived = team->t.t_bar[b].b_team_arrived; #endif } } } #if (KMP_OS_LINUX || KMP_OS_FREEBSD) && KMP_AFFINITY_SUPPORTED if (KMP_AFFINITY_CAPABLE()) { /* Restore initial master thread's affinity mask */ __kmp_set_system_affinity(old_mask, TRUE); KMP_CPU_FREE(old_mask); } #endif #if KMP_NESTED_HOT_TEAMS } // end of check of t_nproc vs. new_nproc vs. hot_team_nth #endif // KMP_NESTED_HOT_TEAMS /* make sure everyone is syncronized */ int old_nproc = team->t.t_nproc; // save old value and use to update only // new threads below __kmp_initialize_team(team, new_nproc, new_icvs, root->r.r_uber_thread->th.th_ident); /* reinitialize the threads */ KMP_DEBUG_ASSERT(team->t.t_nproc == new_nproc); for (f = 0; f < team->t.t_nproc; ++f) __kmp_initialize_info(team->t.t_threads[f], team, f, __kmp_gtid_from_tid(f, team)); if (level) { // set th_task_state for new threads in nested hot team // __kmp_initialize_info() no longer zeroes th_task_state, so we should // only need to set the th_task_state for the new threads. th_task_state // for master thread will not be accurate until after this in // __kmp_fork_call(), so we look to the master's memo_stack to get the // correct value. for (f = old_nproc; f < team->t.t_nproc; ++f) team->t.t_threads[f]->th.th_task_state = team->t.t_threads[0]->th.th_task_state_memo_stack[level]; } else { // set th_task_state for new threads in non-nested hot team int old_state = team->t.t_threads[0]->th.th_task_state; // copy master's state for (f = old_nproc; f < team->t.t_nproc; ++f) team->t.t_threads[f]->th.th_task_state = old_state; } #ifdef KMP_DEBUG for (f = 0; f < team->t.t_nproc; ++f) { KMP_DEBUG_ASSERT(team->t.t_threads[f] && team->t.t_threads[f]->th.th_team_nproc == team->t.t_nproc); } #endif KMP_CHECK_UPDATE(team->t.t_proc_bind, new_proc_bind); #if KMP_AFFINITY_SUPPORTED __kmp_partition_places(team); #endif } // Check changes in number of threads kmp_info_t *master = team->t.t_threads[0]; if (master->th.th_teams_microtask) { for (f = 1; f < new_nproc; ++f) { // propagate teams construct specific info to workers kmp_info_t *thr = team->t.t_threads[f]; thr->th.th_teams_microtask = master->th.th_teams_microtask; thr->th.th_teams_level = master->th.th_teams_level; thr->th.th_teams_size = master->th.th_teams_size; } } #if KMP_NESTED_HOT_TEAMS if (level) { // Sync barrier state for nested hot teams, not needed for outermost hot // team. for (f = 1; f < new_nproc; ++f) { kmp_info_t *thr = team->t.t_threads[f]; int b; kmp_balign_t *balign = thr->th.th_bar; for (b = 0; b < bs_last_barrier; ++b) { balign[b].bb.b_arrived = team->t.t_bar[b].b_arrived; KMP_DEBUG_ASSERT(balign[b].bb.wait_flag != KMP_BARRIER_PARENT_FLAG); #if USE_DEBUGGER balign[b].bb.b_worker_arrived = team->t.t_bar[b].b_team_arrived; #endif } } } #endif // KMP_NESTED_HOT_TEAMS /* reallocate space for arguments if necessary */ __kmp_alloc_argv_entries(argc, team, TRUE); KMP_CHECK_UPDATE(team->t.t_argc, argc); // The hot team re-uses the previous task team, // if untouched during the previous release->gather phase. KF_TRACE(10, (" hot_team = %p\n", team)); #if KMP_DEBUG if (__kmp_tasking_mode != tskm_immediate_exec) { KA_TRACE(20, ("__kmp_allocate_team: hot team task_team[0] = %p " "task_team[1] = %p after reinit\n", team->t.t_task_team[0], team->t.t_task_team[1])); } #endif #if OMPT_SUPPORT __ompt_team_assign_id(team, ompt_parallel_data); #endif KMP_MB(); return team; } /* next, let's try to take one from the team pool */ KMP_MB(); for (team = CCAST(kmp_team_t *, __kmp_team_pool); (team);) { /* TODO: consider resizing undersized teams instead of reaping them, now that we have a resizing mechanism */ if (team->t.t_max_nproc >= max_nproc) { /* take this team from the team pool */ __kmp_team_pool = team->t.t_next_pool; /* setup the team for fresh use */ __kmp_initialize_team(team, new_nproc, new_icvs, NULL); KA_TRACE(20, ("__kmp_allocate_team: setting task_team[0] %p and " "task_team[1] %p to NULL\n", &team->t.t_task_team[0], &team->t.t_task_team[1])); team->t.t_task_team[0] = NULL; team->t.t_task_team[1] = NULL; /* reallocate space for arguments if necessary */ __kmp_alloc_argv_entries(argc, team, TRUE); KMP_CHECK_UPDATE(team->t.t_argc, argc); KA_TRACE( 20, ("__kmp_allocate_team: team %d init arrived: join=%u, plain=%u\n", team->t.t_id, KMP_INIT_BARRIER_STATE, KMP_INIT_BARRIER_STATE)); { // Initialize barrier data. int b; for (b = 0; b < bs_last_barrier; ++b) { team->t.t_bar[b].b_arrived = KMP_INIT_BARRIER_STATE; #if USE_DEBUGGER team->t.t_bar[b].b_master_arrived = 0; team->t.t_bar[b].b_team_arrived = 0; #endif } } team->t.t_proc_bind = new_proc_bind; KA_TRACE(20, ("__kmp_allocate_team: using team from pool %d.\n", team->t.t_id)); #if OMPT_SUPPORT __ompt_team_assign_id(team, ompt_parallel_data); #endif KMP_MB(); return team; } /* reap team if it is too small, then loop back and check the next one */ // not sure if this is wise, but, will be redone during the hot-teams // rewrite. /* TODO: Use technique to find the right size hot-team, don't reap them */ team = __kmp_reap_team(team); __kmp_team_pool = team; } /* nothing available in the pool, no matter, make a new team! */ KMP_MB(); team = (kmp_team_t *)__kmp_allocate(sizeof(kmp_team_t)); /* and set it up */ team->t.t_max_nproc = max_nproc; /* NOTE well, for some reason allocating one big buffer and dividing it up seems to really hurt performance a lot on the P4, so, let's not use this */ __kmp_allocate_team_arrays(team, max_nproc); KA_TRACE(20, ("__kmp_allocate_team: making a new team\n")); __kmp_initialize_team(team, new_nproc, new_icvs, NULL); KA_TRACE(20, ("__kmp_allocate_team: setting task_team[0] %p and task_team[1] " "%p to NULL\n", &team->t.t_task_team[0], &team->t.t_task_team[1])); team->t.t_task_team[0] = NULL; // to be removed, as __kmp_allocate zeroes // memory, no need to duplicate team->t.t_task_team[1] = NULL; // to be removed, as __kmp_allocate zeroes // memory, no need to duplicate if (__kmp_storage_map) { __kmp_print_team_storage_map("team", team, team->t.t_id, new_nproc); } /* allocate space for arguments */ __kmp_alloc_argv_entries(argc, team, FALSE); team->t.t_argc = argc; KA_TRACE(20, ("__kmp_allocate_team: team %d init arrived: join=%u, plain=%u\n", team->t.t_id, KMP_INIT_BARRIER_STATE, KMP_INIT_BARRIER_STATE)); { // Initialize barrier data. int b; for (b = 0; b < bs_last_barrier; ++b) { team->t.t_bar[b].b_arrived = KMP_INIT_BARRIER_STATE; #if USE_DEBUGGER team->t.t_bar[b].b_master_arrived = 0; team->t.t_bar[b].b_team_arrived = 0; #endif } } team->t.t_proc_bind = new_proc_bind; #if OMPT_SUPPORT __ompt_team_assign_id(team, ompt_parallel_data); team->t.ompt_serialized_team_info = NULL; #endif KMP_MB(); KA_TRACE(20, ("__kmp_allocate_team: done creating a new team %d.\n", team->t.t_id)); return team; } /* TODO implement hot-teams at all levels */ /* TODO implement lazy thread release on demand (disband request) */ /* free the team. return it to the team pool. release all the threads * associated with it */ void __kmp_free_team(kmp_root_t *root, kmp_team_t *team USE_NESTED_HOT_ARG(kmp_info_t *master)) { int f; KA_TRACE(20, ("__kmp_free_team: T#%d freeing team %d\n", __kmp_get_gtid(), team->t.t_id)); /* verify state */ KMP_DEBUG_ASSERT(root); KMP_DEBUG_ASSERT(team); KMP_DEBUG_ASSERT(team->t.t_nproc <= team->t.t_max_nproc); KMP_DEBUG_ASSERT(team->t.t_threads); int use_hot_team = team == root->r.r_hot_team; #if KMP_NESTED_HOT_TEAMS int level; kmp_hot_team_ptr_t *hot_teams; if (master) { level = team->t.t_active_level - 1; if (master->th.th_teams_microtask) { // in teams construct? if (master->th.th_teams_size.nteams > 1) { ++level; // level was not increased in teams construct for // team_of_masters } if (team->t.t_pkfn != (microtask_t)__kmp_teams_master && master->th.th_teams_level == team->t.t_level) { ++level; // level was not increased in teams construct for // team_of_workers before the parallel } // team->t.t_level will be increased inside parallel } hot_teams = master->th.th_hot_teams; if (level < __kmp_hot_teams_max_level) { KMP_DEBUG_ASSERT(team == hot_teams[level].hot_team); use_hot_team = 1; } } #endif // KMP_NESTED_HOT_TEAMS /* team is done working */ TCW_SYNC_PTR(team->t.t_pkfn, NULL); // Important for Debugging Support Library. #if KMP_OS_WINDOWS team->t.t_copyin_counter = 0; // init counter for possible reuse #endif // Do not reset pointer to parent team to NULL for hot teams. /* if we are non-hot team, release our threads */ if (!use_hot_team) { if (__kmp_tasking_mode != tskm_immediate_exec) { // Wait for threads to reach reapable state for (f = 1; f < team->t.t_nproc; ++f) { KMP_DEBUG_ASSERT(team->t.t_threads[f]); kmp_info_t *th = team->t.t_threads[f]; volatile kmp_uint32 *state = &th->th.th_reap_state; while (*state != KMP_SAFE_TO_REAP) { #if KMP_OS_WINDOWS // On Windows a thread can be killed at any time, check this DWORD ecode; if (!__kmp_is_thread_alive(th, &ecode)) { *state = KMP_SAFE_TO_REAP; // reset the flag for dead thread break; } #endif // first check if thread is sleeping kmp_flag_64 fl(&th->th.th_bar[bs_forkjoin_barrier].bb.b_go, th); if (fl.is_sleeping()) fl.resume(__kmp_gtid_from_thread(th)); KMP_CPU_PAUSE(); } } // Delete task teams int tt_idx; for (tt_idx = 0; tt_idx < 2; ++tt_idx) { kmp_task_team_t *task_team = team->t.t_task_team[tt_idx]; if (task_team != NULL) { for (f = 0; f < team->t.t_nproc; ++f) { // threads unref task teams KMP_DEBUG_ASSERT(team->t.t_threads[f]); team->t.t_threads[f]->th.th_task_team = NULL; } KA_TRACE( 20, ("__kmp_free_team: T#%d deactivating task_team %p on team %d\n", __kmp_get_gtid(), task_team, team->t.t_id)); #if KMP_NESTED_HOT_TEAMS __kmp_free_task_team(master, task_team); #endif team->t.t_task_team[tt_idx] = NULL; } } } // Reset pointer to parent team only for non-hot teams. team->t.t_parent = NULL; team->t.t_level = 0; team->t.t_active_level = 0; /* free the worker threads */ for (f = 1; f < team->t.t_nproc; ++f) { KMP_DEBUG_ASSERT(team->t.t_threads[f]); __kmp_free_thread(team->t.t_threads[f]); team->t.t_threads[f] = NULL; } /* put the team back in the team pool */ /* TODO limit size of team pool, call reap_team if pool too large */ team->t.t_next_pool = CCAST(kmp_team_t *, __kmp_team_pool); __kmp_team_pool = (volatile kmp_team_t *)team; } else { // Check if team was created for the masters in a teams construct // See if first worker is a CG root KMP_DEBUG_ASSERT(team->t.t_threads[1] && team->t.t_threads[1]->th.th_cg_roots); if (team->t.t_threads[1]->th.th_cg_roots->cg_root == team->t.t_threads[1]) { // Clean up the CG root nodes on workers so that this team can be re-used for (f = 1; f < team->t.t_nproc; ++f) { kmp_info_t *thr = team->t.t_threads[f]; KMP_DEBUG_ASSERT(thr && thr->th.th_cg_roots && thr->th.th_cg_roots->cg_root == thr); // Pop current CG root off list kmp_cg_root_t *tmp = thr->th.th_cg_roots; thr->th.th_cg_roots = tmp->up; KA_TRACE(100, ("__kmp_free_team: Thread %p popping node %p and moving" " up to node %p. cg_nthreads was %d\n", thr, tmp, thr->th.th_cg_roots, tmp->cg_nthreads)); int i = tmp->cg_nthreads--; if (i == 1) { __kmp_free(tmp); // free CG if we are the last thread in it } // Restore current task's thread_limit from CG root if (thr->th.th_cg_roots) thr->th.th_current_task->td_icvs.thread_limit = thr->th.th_cg_roots->cg_thread_limit; } } } KMP_MB(); } /* reap the team. destroy it, reclaim all its resources and free its memory */ kmp_team_t *__kmp_reap_team(kmp_team_t *team) { kmp_team_t *next_pool = team->t.t_next_pool; KMP_DEBUG_ASSERT(team); KMP_DEBUG_ASSERT(team->t.t_dispatch); KMP_DEBUG_ASSERT(team->t.t_disp_buffer); KMP_DEBUG_ASSERT(team->t.t_threads); KMP_DEBUG_ASSERT(team->t.t_argv); /* TODO clean the threads that are a part of this? */ /* free stuff */ __kmp_free_team_arrays(team); if (team->t.t_argv != &team->t.t_inline_argv[0]) __kmp_free((void *)team->t.t_argv); __kmp_free(team); KMP_MB(); return next_pool; } // Free the thread. Don't reap it, just place it on the pool of available // threads. // // Changes for Quad issue 527845: We need a predictable OMP tid <-> gtid // binding for the affinity mechanism to be useful. // // Now, we always keep the free list (__kmp_thread_pool) sorted by gtid. // However, we want to avoid a potential performance problem by always // scanning through the list to find the correct point at which to insert // the thread (potential N**2 behavior). To do this we keep track of the // last place a thread struct was inserted (__kmp_thread_pool_insert_pt). // With single-level parallelism, threads will always be added to the tail // of the list, kept track of by __kmp_thread_pool_insert_pt. With nested // parallelism, all bets are off and we may need to scan through the entire // free list. // // This change also has a potentially large performance benefit, for some // applications. Previously, as threads were freed from the hot team, they // would be placed back on the free list in inverse order. If the hot team // grew back to it's original size, then the freed thread would be placed // back on the hot team in reverse order. This could cause bad cache // locality problems on programs where the size of the hot team regularly // grew and shrunk. // // Now, for single-level parallelism, the OMP tid is always == gtid. void __kmp_free_thread(kmp_info_t *this_th) { int gtid; kmp_info_t **scan; KA_TRACE(20, ("__kmp_free_thread: T#%d putting T#%d back on free pool.\n", __kmp_get_gtid(), this_th->th.th_info.ds.ds_gtid)); KMP_DEBUG_ASSERT(this_th); // When moving thread to pool, switch thread to wait on own b_go flag, and // uninitialized (NULL team). int b; kmp_balign_t *balign = this_th->th.th_bar; for (b = 0; b < bs_last_barrier; ++b) { if (balign[b].bb.wait_flag == KMP_BARRIER_PARENT_FLAG) balign[b].bb.wait_flag = KMP_BARRIER_SWITCH_TO_OWN_FLAG; balign[b].bb.team = NULL; balign[b].bb.leaf_kids = 0; } this_th->th.th_task_state = 0; this_th->th.th_reap_state = KMP_SAFE_TO_REAP; /* put thread back on the free pool */ TCW_PTR(this_th->th.th_team, NULL); TCW_PTR(this_th->th.th_root, NULL); TCW_PTR(this_th->th.th_dispatch, NULL); /* NOT NEEDED */ while (this_th->th.th_cg_roots) { this_th->th.th_cg_roots->cg_nthreads--; KA_TRACE(100, ("__kmp_free_thread: Thread %p decrement cg_nthreads on node" " %p of thread %p to %d\n", this_th, this_th->th.th_cg_roots, this_th->th.th_cg_roots->cg_root, this_th->th.th_cg_roots->cg_nthreads)); kmp_cg_root_t *tmp = this_th->th.th_cg_roots; if (tmp->cg_root == this_th) { // Thread is a cg_root KMP_DEBUG_ASSERT(tmp->cg_nthreads == 0); KA_TRACE( 5, ("__kmp_free_thread: Thread %p freeing node %p\n", this_th, tmp)); this_th->th.th_cg_roots = tmp->up; __kmp_free(tmp); } else { // Worker thread if (tmp->cg_nthreads == 0) { // last thread leaves contention group __kmp_free(tmp); } this_th->th.th_cg_roots = NULL; break; } } /* If the implicit task assigned to this thread can be used by other threads * -> multiple threads can share the data and try to free the task at * __kmp_reap_thread at exit. This duplicate use of the task data can happen * with higher probability when hot team is disabled but can occurs even when * the hot team is enabled */ __kmp_free_implicit_task(this_th); this_th->th.th_current_task = NULL; // If the __kmp_thread_pool_insert_pt is already past the new insert // point, then we need to re-scan the entire list. gtid = this_th->th.th_info.ds.ds_gtid; if (__kmp_thread_pool_insert_pt != NULL) { KMP_DEBUG_ASSERT(__kmp_thread_pool != NULL); if (__kmp_thread_pool_insert_pt->th.th_info.ds.ds_gtid > gtid) { __kmp_thread_pool_insert_pt = NULL; } } // Scan down the list to find the place to insert the thread. // scan is the address of a link in the list, possibly the address of // __kmp_thread_pool itself. // // In the absence of nested parallelism, the for loop will have 0 iterations. if (__kmp_thread_pool_insert_pt != NULL) { scan = &(__kmp_thread_pool_insert_pt->th.th_next_pool); } else { scan = CCAST(kmp_info_t **, &__kmp_thread_pool); } for (; (*scan != NULL) && ((*scan)->th.th_info.ds.ds_gtid < gtid); scan = &((*scan)->th.th_next_pool)) ; // Insert the new element on the list, and set __kmp_thread_pool_insert_pt // to its address. TCW_PTR(this_th->th.th_next_pool, *scan); __kmp_thread_pool_insert_pt = *scan = this_th; KMP_DEBUG_ASSERT((this_th->th.th_next_pool == NULL) || (this_th->th.th_info.ds.ds_gtid < this_th->th.th_next_pool->th.th_info.ds.ds_gtid)); TCW_4(this_th->th.th_in_pool, TRUE); __kmp_suspend_initialize_thread(this_th); __kmp_lock_suspend_mx(this_th); if (this_th->th.th_active == TRUE) { KMP_ATOMIC_INC(&__kmp_thread_pool_active_nth); this_th->th.th_active_in_pool = TRUE; } #if KMP_DEBUG else { KMP_DEBUG_ASSERT(this_th->th.th_active_in_pool == FALSE); } #endif __kmp_unlock_suspend_mx(this_th); TCW_4(__kmp_nth, __kmp_nth - 1); #ifdef KMP_ADJUST_BLOCKTIME /* Adjust blocktime back to user setting or default if necessary */ /* Middle initialization might never have occurred */ if (!__kmp_env_blocktime && (__kmp_avail_proc > 0)) { KMP_DEBUG_ASSERT(__kmp_avail_proc > 0); if (__kmp_nth <= __kmp_avail_proc) { __kmp_zero_bt = FALSE; } } #endif /* KMP_ADJUST_BLOCKTIME */ KMP_MB(); } /* ------------------------------------------------------------------------ */ void *__kmp_launch_thread(kmp_info_t *this_thr) { int gtid = this_thr->th.th_info.ds.ds_gtid; /* void *stack_data;*/ kmp_team_t **volatile pteam; KMP_MB(); KA_TRACE(10, ("__kmp_launch_thread: T#%d start\n", gtid)); if (__kmp_env_consistency_check) { this_thr->th.th_cons = __kmp_allocate_cons_stack(gtid); // ATT: Memory leak? } #if OMPT_SUPPORT ompt_data_t *thread_data; if (ompt_enabled.enabled) { thread_data = &(this_thr->th.ompt_thread_info.thread_data); *thread_data = ompt_data_none; this_thr->th.ompt_thread_info.state = ompt_state_overhead; this_thr->th.ompt_thread_info.wait_id = 0; this_thr->th.ompt_thread_info.idle_frame = OMPT_GET_FRAME_ADDRESS(0); this_thr->th.ompt_thread_info.parallel_flags = 0; if (ompt_enabled.ompt_callback_thread_begin) { ompt_callbacks.ompt_callback(ompt_callback_thread_begin)( ompt_thread_worker, thread_data); } this_thr->th.ompt_thread_info.state = ompt_state_idle; } #endif /* This is the place where threads wait for work */ while (!TCR_4(__kmp_global.g.g_done)) { KMP_DEBUG_ASSERT(this_thr == __kmp_threads[gtid]); KMP_MB(); /* wait for work to do */ KA_TRACE(20, ("__kmp_launch_thread: T#%d waiting for work\n", gtid)); /* No tid yet since not part of a team */ __kmp_fork_barrier(gtid, KMP_GTID_DNE); #if OMPT_SUPPORT if (ompt_enabled.enabled) { this_thr->th.ompt_thread_info.state = ompt_state_overhead; } #endif pteam = &this_thr->th.th_team; /* have we been allocated? */ if (TCR_SYNC_PTR(*pteam) && !TCR_4(__kmp_global.g.g_done)) { /* we were just woken up, so run our new task */ if (TCR_SYNC_PTR((*pteam)->t.t_pkfn) != NULL) { int rc; KA_TRACE(20, ("__kmp_launch_thread: T#%d(%d:%d) invoke microtask = %p\n", gtid, (*pteam)->t.t_id, __kmp_tid_from_gtid(gtid), (*pteam)->t.t_pkfn)); updateHWFPControl(*pteam); #if OMPT_SUPPORT if (ompt_enabled.enabled) { this_thr->th.ompt_thread_info.state = ompt_state_work_parallel; } #endif rc = (*pteam)->t.t_invoke(gtid); KMP_ASSERT(rc); KMP_MB(); KA_TRACE(20, ("__kmp_launch_thread: T#%d(%d:%d) done microtask = %p\n", gtid, (*pteam)->t.t_id, __kmp_tid_from_gtid(gtid), (*pteam)->t.t_pkfn)); } #if OMPT_SUPPORT if (ompt_enabled.enabled) { /* no frame set while outside task */ __ompt_get_task_info_object(0)->frame.exit_frame = ompt_data_none; this_thr->th.ompt_thread_info.state = ompt_state_overhead; } #endif /* join barrier after parallel region */ __kmp_join_barrier(gtid); } } TCR_SYNC_PTR((intptr_t)__kmp_global.g.g_done); #if OMPT_SUPPORT if (ompt_enabled.ompt_callback_thread_end) { ompt_callbacks.ompt_callback(ompt_callback_thread_end)(thread_data); } #endif this_thr->th.th_task_team = NULL; /* run the destructors for the threadprivate data for this thread */ __kmp_common_destroy_gtid(gtid); KA_TRACE(10, ("__kmp_launch_thread: T#%d done\n", gtid)); KMP_MB(); return this_thr; } /* ------------------------------------------------------------------------ */ void __kmp_internal_end_dest(void *specific_gtid) { #if KMP_COMPILER_ICC #pragma warning(push) #pragma warning(disable : 810) // conversion from "void *" to "int" may lose // significant bits #endif // Make sure no significant bits are lost int gtid = (kmp_intptr_t)specific_gtid - 1; #if KMP_COMPILER_ICC #pragma warning(pop) #endif KA_TRACE(30, ("__kmp_internal_end_dest: T#%d\n", gtid)); /* NOTE: the gtid is stored as gitd+1 in the thread-local-storage * this is because 0 is reserved for the nothing-stored case */ /* josh: One reason for setting the gtid specific data even when it is being destroyed by pthread is to allow gtid lookup through thread specific data (__kmp_gtid_get_specific). Some of the code, especially stat code, that gets executed in the call to __kmp_internal_end_thread, actually gets the gtid through the thread specific data. Setting it here seems rather inelegant and perhaps wrong, but allows __kmp_internal_end_thread to run smoothly. todo: get rid of this after we remove the dependence on __kmp_gtid_get_specific */ if (gtid >= 0 && KMP_UBER_GTID(gtid)) __kmp_gtid_set_specific(gtid); #ifdef KMP_TDATA_GTID __kmp_gtid = gtid; #endif __kmp_internal_end_thread(gtid); } #if KMP_OS_UNIX && KMP_DYNAMIC_LIB __attribute__((destructor)) void __kmp_internal_end_dtor(void) { __kmp_internal_end_atexit(); } #endif /* [Windows] josh: when the atexit handler is called, there may still be more than one thread alive */ void __kmp_internal_end_atexit(void) { KA_TRACE(30, ("__kmp_internal_end_atexit\n")); /* [Windows] josh: ideally, we want to completely shutdown the library in this atexit handler, but stat code that depends on thread specific data for gtid fails because that data becomes unavailable at some point during the shutdown, so we call __kmp_internal_end_thread instead. We should eventually remove the dependency on __kmp_get_specific_gtid in the stat code and use __kmp_internal_end_library to cleanly shutdown the library. // TODO: Can some of this comment about GVS be removed? I suspect that the offending stat code is executed when the calling thread tries to clean up a dead root thread's data structures, resulting in GVS code trying to close the GVS structures for that thread, but since the stat code uses __kmp_get_specific_gtid to get the gtid with the assumption that the calling thread is cleaning up itself instead of another thread, it get confused. This happens because allowing a thread to unregister and cleanup another thread is a recent modification for addressing an issue. Based on the current design (20050722), a thread may end up trying to unregister another thread only if thread death does not trigger the calling of __kmp_internal_end_thread. For Linux* OS, there is the thread specific data destructor function to detect thread death. For Windows dynamic, there is DllMain(THREAD_DETACH). For Windows static, there is nothing. Thus, the workaround is applicable only for Windows static stat library. */ __kmp_internal_end_library(-1); #if KMP_OS_WINDOWS __kmp_close_console(); #endif } static void __kmp_reap_thread(kmp_info_t *thread, int is_root) { // It is assumed __kmp_forkjoin_lock is acquired. int gtid; KMP_DEBUG_ASSERT(thread != NULL); gtid = thread->th.th_info.ds.ds_gtid; if (!is_root) { if (__kmp_dflt_blocktime != KMP_MAX_BLOCKTIME) { /* Assume the threads are at the fork barrier here */ KA_TRACE( 20, ("__kmp_reap_thread: releasing T#%d from fork barrier for reap\n", gtid)); /* Need release fence here to prevent seg faults for tree forkjoin barrier * (GEH) */ ANNOTATE_HAPPENS_BEFORE(thread); kmp_flag_64 flag(&thread->th.th_bar[bs_forkjoin_barrier].bb.b_go, thread); __kmp_release_64(&flag); } // Terminate OS thread. __kmp_reap_worker(thread); // The thread was killed asynchronously. If it was actively // spinning in the thread pool, decrement the global count. // // There is a small timing hole here - if the worker thread was just waking // up after sleeping in the pool, had reset it's th_active_in_pool flag but // not decremented the global counter __kmp_thread_pool_active_nth yet, then // the global counter might not get updated. // // Currently, this can only happen as the library is unloaded, // so there are no harmful side effects. if (thread->th.th_active_in_pool) { thread->th.th_active_in_pool = FALSE; KMP_ATOMIC_DEC(&__kmp_thread_pool_active_nth); KMP_DEBUG_ASSERT(__kmp_thread_pool_active_nth >= 0); } } __kmp_free_implicit_task(thread); // Free the fast memory for tasking #if USE_FAST_MEMORY __kmp_free_fast_memory(thread); #endif /* USE_FAST_MEMORY */ __kmp_suspend_uninitialize_thread(thread); KMP_DEBUG_ASSERT(__kmp_threads[gtid] == thread); TCW_SYNC_PTR(__kmp_threads[gtid], NULL); --__kmp_all_nth; // __kmp_nth was decremented when thread is added to the pool. #ifdef KMP_ADJUST_BLOCKTIME /* Adjust blocktime back to user setting or default if necessary */ /* Middle initialization might never have occurred */ if (!__kmp_env_blocktime && (__kmp_avail_proc > 0)) { KMP_DEBUG_ASSERT(__kmp_avail_proc > 0); if (__kmp_nth <= __kmp_avail_proc) { __kmp_zero_bt = FALSE; } } #endif /* KMP_ADJUST_BLOCKTIME */ /* free the memory being used */ if (__kmp_env_consistency_check) { if (thread->th.th_cons) { __kmp_free_cons_stack(thread->th.th_cons); thread->th.th_cons = NULL; } } if (thread->th.th_pri_common != NULL) { __kmp_free(thread->th.th_pri_common); thread->th.th_pri_common = NULL; } if (thread->th.th_task_state_memo_stack != NULL) { __kmp_free(thread->th.th_task_state_memo_stack); thread->th.th_task_state_memo_stack = NULL; } #if KMP_USE_BGET if (thread->th.th_local.bget_data != NULL) { __kmp_finalize_bget(thread); } #endif #if KMP_AFFINITY_SUPPORTED if (thread->th.th_affin_mask != NULL) { KMP_CPU_FREE(thread->th.th_affin_mask); thread->th.th_affin_mask = NULL; } #endif /* KMP_AFFINITY_SUPPORTED */ #if KMP_USE_HIER_SCHED if (thread->th.th_hier_bar_data != NULL) { __kmp_free(thread->th.th_hier_bar_data); thread->th.th_hier_bar_data = NULL; } #endif __kmp_reap_team(thread->th.th_serial_team); thread->th.th_serial_team = NULL; __kmp_free(thread); KMP_MB(); } // __kmp_reap_thread static void __kmp_internal_end(void) { int i; /* First, unregister the library */ __kmp_unregister_library(); #if KMP_OS_WINDOWS /* In Win static library, we can't tell when a root actually dies, so we reclaim the data structures for any root threads that have died but not unregistered themselves, in order to shut down cleanly. In Win dynamic library we also can't tell when a thread dies. */ __kmp_reclaim_dead_roots(); // AC: moved here to always clean resources of // dead roots #endif for (i = 0; i < __kmp_threads_capacity; i++) if (__kmp_root[i]) if (__kmp_root[i]->r.r_active) break; KMP_MB(); /* Flush all pending memory write invalidates. */ TCW_SYNC_4(__kmp_global.g.g_done, TRUE); if (i < __kmp_threads_capacity) { #if KMP_USE_MONITOR // 2009-09-08 (lev): Other alive roots found. Why do we kill the monitor?? KMP_MB(); /* Flush all pending memory write invalidates. */ // Need to check that monitor was initialized before reaping it. If we are // called form __kmp_atfork_child (which sets __kmp_init_parallel = 0), then // __kmp_monitor will appear to contain valid data, but it is only valid in // the parent process, not the child. // New behavior (201008): instead of keying off of the flag // __kmp_init_parallel, the monitor thread creation is keyed off // of the new flag __kmp_init_monitor. __kmp_acquire_bootstrap_lock(&__kmp_monitor_lock); if (TCR_4(__kmp_init_monitor)) { __kmp_reap_monitor(&__kmp_monitor); TCW_4(__kmp_init_monitor, 0); } __kmp_release_bootstrap_lock(&__kmp_monitor_lock); KA_TRACE(10, ("__kmp_internal_end: monitor reaped\n")); #endif // KMP_USE_MONITOR } else { /* TODO move this to cleanup code */ #ifdef KMP_DEBUG /* make sure that everything has properly ended */ for (i = 0; i < __kmp_threads_capacity; i++) { if (__kmp_root[i]) { // KMP_ASSERT( ! KMP_UBER_GTID( i ) ); // AC: // there can be uber threads alive here KMP_ASSERT(!__kmp_root[i]->r.r_active); // TODO: can they be active? } } #endif KMP_MB(); // Reap the worker threads. // This is valid for now, but be careful if threads are reaped sooner. while (__kmp_thread_pool != NULL) { // Loop thru all the thread in the pool. // Get the next thread from the pool. kmp_info_t *thread = CCAST(kmp_info_t *, __kmp_thread_pool); __kmp_thread_pool = thread->th.th_next_pool; // Reap it. KMP_DEBUG_ASSERT(thread->th.th_reap_state == KMP_SAFE_TO_REAP); thread->th.th_next_pool = NULL; thread->th.th_in_pool = FALSE; __kmp_reap_thread(thread, 0); } __kmp_thread_pool_insert_pt = NULL; // Reap teams. while (__kmp_team_pool != NULL) { // Loop thru all the teams in the pool. // Get the next team from the pool. kmp_team_t *team = CCAST(kmp_team_t *, __kmp_team_pool); __kmp_team_pool = team->t.t_next_pool; // Reap it. team->t.t_next_pool = NULL; __kmp_reap_team(team); } __kmp_reap_task_teams(); #if KMP_OS_UNIX // Threads that are not reaped should not access any resources since they // are going to be deallocated soon, so the shutdown sequence should wait // until all threads either exit the final spin-waiting loop or begin // sleeping after the given blocktime. for (i = 0; i < __kmp_threads_capacity; i++) { kmp_info_t *thr = __kmp_threads[i]; while (thr && KMP_ATOMIC_LD_ACQ(&thr->th.th_blocking)) KMP_CPU_PAUSE(); } #endif for (i = 0; i < __kmp_threads_capacity; ++i) { // TBD: Add some checking... // Something like KMP_DEBUG_ASSERT( __kmp_thread[ i ] == NULL ); } /* Make sure all threadprivate destructors get run by joining with all worker threads before resetting this flag */ TCW_SYNC_4(__kmp_init_common, FALSE); KA_TRACE(10, ("__kmp_internal_end: all workers reaped\n")); KMP_MB(); #if KMP_USE_MONITOR // See note above: One of the possible fixes for CQ138434 / CQ140126 // // FIXME: push both code fragments down and CSE them? // push them into __kmp_cleanup() ? __kmp_acquire_bootstrap_lock(&__kmp_monitor_lock); if (TCR_4(__kmp_init_monitor)) { __kmp_reap_monitor(&__kmp_monitor); TCW_4(__kmp_init_monitor, 0); } __kmp_release_bootstrap_lock(&__kmp_monitor_lock); KA_TRACE(10, ("__kmp_internal_end: monitor reaped\n")); #endif } /* else !__kmp_global.t_active */ TCW_4(__kmp_init_gtid, FALSE); KMP_MB(); /* Flush all pending memory write invalidates. */ __kmp_cleanup(); #if OMPT_SUPPORT ompt_fini(); #endif } void __kmp_internal_end_library(int gtid_req) { /* if we have already cleaned up, don't try again, it wouldn't be pretty */ /* this shouldn't be a race condition because __kmp_internal_end() is the only place to clear __kmp_serial_init */ /* we'll check this later too, after we get the lock */ // 2009-09-06: We do not set g_abort without setting g_done. This check looks // redundant, because the next check will work in any case. if (__kmp_global.g.g_abort) { KA_TRACE(11, ("__kmp_internal_end_library: abort, exiting\n")); /* TODO abort? */ return; } if (TCR_4(__kmp_global.g.g_done) || !__kmp_init_serial) { KA_TRACE(10, ("__kmp_internal_end_library: already finished\n")); return; } KMP_MB(); /* Flush all pending memory write invalidates. */ /* find out who we are and what we should do */ { int gtid = (gtid_req >= 0) ? gtid_req : __kmp_gtid_get_specific(); KA_TRACE( 10, ("__kmp_internal_end_library: enter T#%d (%d)\n", gtid, gtid_req)); if (gtid == KMP_GTID_SHUTDOWN) { KA_TRACE(10, ("__kmp_internal_end_library: !__kmp_init_runtime, system " "already shutdown\n")); return; } else if (gtid == KMP_GTID_MONITOR) { KA_TRACE(10, ("__kmp_internal_end_library: monitor thread, gtid not " "registered, or system shutdown\n")); return; } else if (gtid == KMP_GTID_DNE) { KA_TRACE(10, ("__kmp_internal_end_library: gtid not registered or system " "shutdown\n")); /* we don't know who we are, but we may still shutdown the library */ } else if (KMP_UBER_GTID(gtid)) { /* unregister ourselves as an uber thread. gtid is no longer valid */ if (__kmp_root[gtid]->r.r_active) { __kmp_global.g.g_abort = -1; TCW_SYNC_4(__kmp_global.g.g_done, TRUE); KA_TRACE(10, ("__kmp_internal_end_library: root still active, abort T#%d\n", gtid)); return; } else { KA_TRACE( 10, ("__kmp_internal_end_library: unregistering sibling T#%d\n", gtid)); __kmp_unregister_root_current_thread(gtid); } } else { /* worker threads may call this function through the atexit handler, if they * call exit() */ /* For now, skip the usual subsequent processing and just dump the debug buffer. TODO: do a thorough shutdown instead */ #ifdef DUMP_DEBUG_ON_EXIT if (__kmp_debug_buf) __kmp_dump_debug_buffer(); #endif return; } } /* synchronize the termination process */ __kmp_acquire_bootstrap_lock(&__kmp_initz_lock); /* have we already finished */ if (__kmp_global.g.g_abort) { KA_TRACE(10, ("__kmp_internal_end_library: abort, exiting\n")); /* TODO abort? */ __kmp_release_bootstrap_lock(&__kmp_initz_lock); return; } if (TCR_4(__kmp_global.g.g_done) || !__kmp_init_serial) { __kmp_release_bootstrap_lock(&__kmp_initz_lock); return; } /* We need this lock to enforce mutex between this reading of __kmp_threads_capacity and the writing by __kmp_register_root. Alternatively, we can use a counter of roots that is atomically updated by __kmp_get_global_thread_id_reg, __kmp_do_serial_initialize and __kmp_internal_end_*. */ __kmp_acquire_bootstrap_lock(&__kmp_forkjoin_lock); /* now we can safely conduct the actual termination */ __kmp_internal_end(); __kmp_release_bootstrap_lock(&__kmp_forkjoin_lock); __kmp_release_bootstrap_lock(&__kmp_initz_lock); KA_TRACE(10, ("__kmp_internal_end_library: exit\n")); #ifdef DUMP_DEBUG_ON_EXIT if (__kmp_debug_buf) __kmp_dump_debug_buffer(); #endif #if KMP_OS_WINDOWS __kmp_close_console(); #endif __kmp_fini_allocator(); } // __kmp_internal_end_library void __kmp_internal_end_thread(int gtid_req) { int i; /* if we have already cleaned up, don't try again, it wouldn't be pretty */ /* this shouldn't be a race condition because __kmp_internal_end() is the * only place to clear __kmp_serial_init */ /* we'll check this later too, after we get the lock */ // 2009-09-06: We do not set g_abort without setting g_done. This check looks // redundant, because the next check will work in any case. if (__kmp_global.g.g_abort) { KA_TRACE(11, ("__kmp_internal_end_thread: abort, exiting\n")); /* TODO abort? */ return; } if (TCR_4(__kmp_global.g.g_done) || !__kmp_init_serial) { KA_TRACE(10, ("__kmp_internal_end_thread: already finished\n")); return; } KMP_MB(); /* Flush all pending memory write invalidates. */ /* find out who we are and what we should do */ { int gtid = (gtid_req >= 0) ? gtid_req : __kmp_gtid_get_specific(); KA_TRACE(10, ("__kmp_internal_end_thread: enter T#%d (%d)\n", gtid, gtid_req)); if (gtid == KMP_GTID_SHUTDOWN) { KA_TRACE(10, ("__kmp_internal_end_thread: !__kmp_init_runtime, system " "already shutdown\n")); return; } else if (gtid == KMP_GTID_MONITOR) { KA_TRACE(10, ("__kmp_internal_end_thread: monitor thread, gtid not " "registered, or system shutdown\n")); return; } else if (gtid == KMP_GTID_DNE) { KA_TRACE(10, ("__kmp_internal_end_thread: gtid not registered or system " "shutdown\n")); return; /* we don't know who we are */ } else if (KMP_UBER_GTID(gtid)) { /* unregister ourselves as an uber thread. gtid is no longer valid */ if (__kmp_root[gtid]->r.r_active) { __kmp_global.g.g_abort = -1; TCW_SYNC_4(__kmp_global.g.g_done, TRUE); KA_TRACE(10, ("__kmp_internal_end_thread: root still active, abort T#%d\n", gtid)); return; } else { KA_TRACE(10, ("__kmp_internal_end_thread: unregistering sibling T#%d\n", gtid)); __kmp_unregister_root_current_thread(gtid); } } else { /* just a worker thread, let's leave */ KA_TRACE(10, ("__kmp_internal_end_thread: worker thread T#%d\n", gtid)); if (gtid >= 0) { __kmp_threads[gtid]->th.th_task_team = NULL; } KA_TRACE(10, ("__kmp_internal_end_thread: worker thread done, exiting T#%d\n", gtid)); return; } } #if KMP_DYNAMIC_LIB if (__kmp_pause_status != kmp_hard_paused) // AC: lets not shutdown the dynamic library at the exit of uber thread, // because we will better shutdown later in the library destructor. { KA_TRACE(10, ("__kmp_internal_end_thread: exiting T#%d\n", gtid_req)); return; } #endif /* synchronize the termination process */ __kmp_acquire_bootstrap_lock(&__kmp_initz_lock); /* have we already finished */ if (__kmp_global.g.g_abort) { KA_TRACE(10, ("__kmp_internal_end_thread: abort, exiting\n")); /* TODO abort? */ __kmp_release_bootstrap_lock(&__kmp_initz_lock); return; } if (TCR_4(__kmp_global.g.g_done) || !__kmp_init_serial) { __kmp_release_bootstrap_lock(&__kmp_initz_lock); return; } /* We need this lock to enforce mutex between this reading of __kmp_threads_capacity and the writing by __kmp_register_root. Alternatively, we can use a counter of roots that is atomically updated by __kmp_get_global_thread_id_reg, __kmp_do_serial_initialize and __kmp_internal_end_*. */ /* should we finish the run-time? are all siblings done? */ __kmp_acquire_bootstrap_lock(&__kmp_forkjoin_lock); for (i = 0; i < __kmp_threads_capacity; ++i) { if (KMP_UBER_GTID(i)) { KA_TRACE( 10, ("__kmp_internal_end_thread: remaining sibling task: gtid==%d\n", i)); __kmp_release_bootstrap_lock(&__kmp_forkjoin_lock); __kmp_release_bootstrap_lock(&__kmp_initz_lock); return; } } /* now we can safely conduct the actual termination */ __kmp_internal_end(); __kmp_release_bootstrap_lock(&__kmp_forkjoin_lock); __kmp_release_bootstrap_lock(&__kmp_initz_lock); KA_TRACE(10, ("__kmp_internal_end_thread: exit T#%d\n", gtid_req)); #ifdef DUMP_DEBUG_ON_EXIT if (__kmp_debug_buf) __kmp_dump_debug_buffer(); #endif } // __kmp_internal_end_thread // ----------------------------------------------------------------------------- // Library registration stuff. static long __kmp_registration_flag = 0; // Random value used to indicate library initialization. static char *__kmp_registration_str = NULL; // Value to be saved in env var __KMP_REGISTERED_LIB_. static inline char *__kmp_reg_status_name() { /* On RHEL 3u5 if linked statically, getpid() returns different values in each thread. If registration and unregistration go in different threads (omp_misc_other_root_exit.cpp test case), the name of registered_lib_env env var can not be found, because the name will contain different pid. */ return __kmp_str_format("__KMP_REGISTERED_LIB_%d", (int)getpid()); } // __kmp_reg_status_get void __kmp_register_library_startup(void) { char *name = __kmp_reg_status_name(); // Name of the environment variable. int done = 0; union { double dtime; long ltime; } time; #if KMP_ARCH_X86 || KMP_ARCH_X86_64 __kmp_initialize_system_tick(); #endif __kmp_read_system_time(&time.dtime); __kmp_registration_flag = 0xCAFE0000L | (time.ltime & 0x0000FFFFL); __kmp_registration_str = __kmp_str_format("%p-%lx-%s", &__kmp_registration_flag, __kmp_registration_flag, KMP_LIBRARY_FILE); KA_TRACE(50, ("__kmp_register_library_startup: %s=\"%s\"\n", name, __kmp_registration_str)); while (!done) { char *value = NULL; // Actual value of the environment variable. // Set environment variable, but do not overwrite if it is exist. __kmp_env_set(name, __kmp_registration_str, 0); // Check the variable is written. value = __kmp_env_get(name); if (value != NULL && strcmp(value, __kmp_registration_str) == 0) { done = 1; // Ok, environment variable set successfully, exit the loop. } else { // Oops. Write failed. Another copy of OpenMP RTL is in memory. // Check whether it alive or dead. int neighbor = 0; // 0 -- unknown status, 1 -- alive, 2 -- dead. char *tail = value; char *flag_addr_str = NULL; char *flag_val_str = NULL; char const *file_name = NULL; __kmp_str_split(tail, '-', &flag_addr_str, &tail); __kmp_str_split(tail, '-', &flag_val_str, &tail); file_name = tail; if (tail != NULL) { long *flag_addr = 0; long flag_val = 0; KMP_SSCANF(flag_addr_str, "%p", RCAST(void**, &flag_addr)); KMP_SSCANF(flag_val_str, "%lx", &flag_val); if (flag_addr != 0 && flag_val != 0 && strcmp(file_name, "") != 0) { // First, check whether environment-encoded address is mapped into // addr space. // If so, dereference it to see if it still has the right value. if (__kmp_is_address_mapped(flag_addr) && *flag_addr == flag_val) { neighbor = 1; } else { // If not, then we know the other copy of the library is no longer // running. neighbor = 2; } } } switch (neighbor) { case 0: // Cannot parse environment variable -- neighbor status unknown. // Assume it is the incompatible format of future version of the // library. Assume the other library is alive. // WARN( ... ); // TODO: Issue a warning. file_name = "unknown library"; KMP_FALLTHROUGH(); // Attention! Falling to the next case. That's intentional. case 1: { // Neighbor is alive. // Check it is allowed. char *duplicate_ok = __kmp_env_get("KMP_DUPLICATE_LIB_OK"); if (!__kmp_str_match_true(duplicate_ok)) { // That's not allowed. Issue fatal error. __kmp_fatal(KMP_MSG(DuplicateLibrary, KMP_LIBRARY_FILE, file_name), KMP_HNT(DuplicateLibrary), __kmp_msg_null); } KMP_INTERNAL_FREE(duplicate_ok); __kmp_duplicate_library_ok = 1; done = 1; // Exit the loop. } break; case 2: { // Neighbor is dead. // Clear the variable and try to register library again. __kmp_env_unset(name); } break; default: { KMP_DEBUG_ASSERT(0); } break; } } KMP_INTERNAL_FREE((void *)value); } KMP_INTERNAL_FREE((void *)name); } // func __kmp_register_library_startup void __kmp_unregister_library(void) { char *name = __kmp_reg_status_name(); char *value = __kmp_env_get(name); KMP_DEBUG_ASSERT(__kmp_registration_flag != 0); KMP_DEBUG_ASSERT(__kmp_registration_str != NULL); if (value != NULL && strcmp(value, __kmp_registration_str) == 0) { // Ok, this is our variable. Delete it. __kmp_env_unset(name); } KMP_INTERNAL_FREE(__kmp_registration_str); KMP_INTERNAL_FREE(value); KMP_INTERNAL_FREE(name); __kmp_registration_flag = 0; __kmp_registration_str = NULL; } // __kmp_unregister_library // End of Library registration stuff. // ----------------------------------------------------------------------------- #if KMP_MIC_SUPPORTED static void __kmp_check_mic_type() { kmp_cpuid_t cpuid_state = {0}; kmp_cpuid_t *cs_p = &cpuid_state; __kmp_x86_cpuid(1, 0, cs_p); // We don't support mic1 at the moment if ((cs_p->eax & 0xff0) == 0xB10) { __kmp_mic_type = mic2; } else if ((cs_p->eax & 0xf0ff0) == 0x50670) { __kmp_mic_type = mic3; } else { __kmp_mic_type = non_mic; } } #endif /* KMP_MIC_SUPPORTED */ static void __kmp_do_serial_initialize(void) { int i, gtid; int size; KA_TRACE(10, ("__kmp_do_serial_initialize: enter\n")); KMP_DEBUG_ASSERT(sizeof(kmp_int32) == 4); KMP_DEBUG_ASSERT(sizeof(kmp_uint32) == 4); KMP_DEBUG_ASSERT(sizeof(kmp_int64) == 8); KMP_DEBUG_ASSERT(sizeof(kmp_uint64) == 8); KMP_DEBUG_ASSERT(sizeof(kmp_intptr_t) == sizeof(void *)); #if OMPT_SUPPORT ompt_pre_init(); #endif __kmp_validate_locks(); /* Initialize internal memory allocator */ __kmp_init_allocator(); /* Register the library startup via an environment variable and check to see whether another copy of the library is already registered. */ __kmp_register_library_startup(); /* TODO reinitialization of library */ if (TCR_4(__kmp_global.g.g_done)) { KA_TRACE(10, ("__kmp_do_serial_initialize: reinitialization of library\n")); } __kmp_global.g.g_abort = 0; TCW_SYNC_4(__kmp_global.g.g_done, FALSE); /* initialize the locks */ #if KMP_USE_ADAPTIVE_LOCKS #if KMP_DEBUG_ADAPTIVE_LOCKS __kmp_init_speculative_stats(); #endif #endif #if KMP_STATS_ENABLED __kmp_stats_init(); #endif __kmp_init_lock(&__kmp_global_lock); __kmp_init_queuing_lock(&__kmp_dispatch_lock); __kmp_init_lock(&__kmp_debug_lock); __kmp_init_atomic_lock(&__kmp_atomic_lock); __kmp_init_atomic_lock(&__kmp_atomic_lock_1i); __kmp_init_atomic_lock(&__kmp_atomic_lock_2i); __kmp_init_atomic_lock(&__kmp_atomic_lock_4i); __kmp_init_atomic_lock(&__kmp_atomic_lock_4r); __kmp_init_atomic_lock(&__kmp_atomic_lock_8i); __kmp_init_atomic_lock(&__kmp_atomic_lock_8r); __kmp_init_atomic_lock(&__kmp_atomic_lock_8c); __kmp_init_atomic_lock(&__kmp_atomic_lock_10r); __kmp_init_atomic_lock(&__kmp_atomic_lock_16r); __kmp_init_atomic_lock(&__kmp_atomic_lock_16c); __kmp_init_atomic_lock(&__kmp_atomic_lock_20c); __kmp_init_atomic_lock(&__kmp_atomic_lock_32c); __kmp_init_bootstrap_lock(&__kmp_forkjoin_lock); __kmp_init_bootstrap_lock(&__kmp_exit_lock); #if KMP_USE_MONITOR __kmp_init_bootstrap_lock(&__kmp_monitor_lock); #endif __kmp_init_bootstrap_lock(&__kmp_tp_cached_lock); /* conduct initialization and initial setup of configuration */ __kmp_runtime_initialize(); #if KMP_MIC_SUPPORTED __kmp_check_mic_type(); #endif // Some global variable initialization moved here from kmp_env_initialize() #ifdef KMP_DEBUG kmp_diag = 0; #endif __kmp_abort_delay = 0; // From __kmp_init_dflt_team_nth() /* assume the entire machine will be used */ __kmp_dflt_team_nth_ub = __kmp_xproc; if (__kmp_dflt_team_nth_ub < KMP_MIN_NTH) { __kmp_dflt_team_nth_ub = KMP_MIN_NTH; } if (__kmp_dflt_team_nth_ub > __kmp_sys_max_nth) { __kmp_dflt_team_nth_ub = __kmp_sys_max_nth; } __kmp_max_nth = __kmp_sys_max_nth; __kmp_cg_max_nth = __kmp_sys_max_nth; __kmp_teams_max_nth = __kmp_xproc; // set a "reasonable" default if (__kmp_teams_max_nth > __kmp_sys_max_nth) { __kmp_teams_max_nth = __kmp_sys_max_nth; } // Three vars below moved here from __kmp_env_initialize() "KMP_BLOCKTIME" // part __kmp_dflt_blocktime = KMP_DEFAULT_BLOCKTIME; #if KMP_USE_MONITOR __kmp_monitor_wakeups = KMP_WAKEUPS_FROM_BLOCKTIME(__kmp_dflt_blocktime, __kmp_monitor_wakeups); __kmp_bt_intervals = KMP_INTERVALS_FROM_BLOCKTIME(__kmp_dflt_blocktime, __kmp_monitor_wakeups); #endif // From "KMP_LIBRARY" part of __kmp_env_initialize() __kmp_library = library_throughput; // From KMP_SCHEDULE initialization __kmp_static = kmp_sch_static_balanced; // AC: do not use analytical here, because it is non-monotonous //__kmp_guided = kmp_sch_guided_iterative_chunked; //__kmp_auto = kmp_sch_guided_analytical_chunked; // AC: it is the default, no // need to repeat assignment // Barrier initialization. Moved here from __kmp_env_initialize() Barrier branch // bit control and barrier method control parts #if KMP_FAST_REDUCTION_BARRIER #define kmp_reduction_barrier_gather_bb ((int)1) #define kmp_reduction_barrier_release_bb ((int)1) #define kmp_reduction_barrier_gather_pat bp_hyper_bar #define kmp_reduction_barrier_release_pat bp_hyper_bar #endif // KMP_FAST_REDUCTION_BARRIER for (i = bs_plain_barrier; i < bs_last_barrier; i++) { __kmp_barrier_gather_branch_bits[i] = __kmp_barrier_gather_bb_dflt; __kmp_barrier_release_branch_bits[i] = __kmp_barrier_release_bb_dflt; __kmp_barrier_gather_pattern[i] = __kmp_barrier_gather_pat_dflt; __kmp_barrier_release_pattern[i] = __kmp_barrier_release_pat_dflt; #if KMP_FAST_REDUCTION_BARRIER if (i == bs_reduction_barrier) { // tested and confirmed on ALTIX only ( // lin_64 ): hyper,1 __kmp_barrier_gather_branch_bits[i] = kmp_reduction_barrier_gather_bb; __kmp_barrier_release_branch_bits[i] = kmp_reduction_barrier_release_bb; __kmp_barrier_gather_pattern[i] = kmp_reduction_barrier_gather_pat; __kmp_barrier_release_pattern[i] = kmp_reduction_barrier_release_pat; } #endif // KMP_FAST_REDUCTION_BARRIER } #if KMP_FAST_REDUCTION_BARRIER #undef kmp_reduction_barrier_release_pat #undef kmp_reduction_barrier_gather_pat #undef kmp_reduction_barrier_release_bb #undef kmp_reduction_barrier_gather_bb #endif // KMP_FAST_REDUCTION_BARRIER #if KMP_MIC_SUPPORTED if (__kmp_mic_type == mic2) { // KNC // AC: plane=3,2, forkjoin=2,1 are optimal for 240 threads on KNC __kmp_barrier_gather_branch_bits[bs_plain_barrier] = 3; // plain gather __kmp_barrier_release_branch_bits[bs_forkjoin_barrier] = 1; // forkjoin release __kmp_barrier_gather_pattern[bs_forkjoin_barrier] = bp_hierarchical_bar; __kmp_barrier_release_pattern[bs_forkjoin_barrier] = bp_hierarchical_bar; } #if KMP_FAST_REDUCTION_BARRIER if (__kmp_mic_type == mic2) { // KNC __kmp_barrier_gather_pattern[bs_reduction_barrier] = bp_hierarchical_bar; __kmp_barrier_release_pattern[bs_reduction_barrier] = bp_hierarchical_bar; } #endif // KMP_FAST_REDUCTION_BARRIER #endif // KMP_MIC_SUPPORTED // From KMP_CHECKS initialization #ifdef KMP_DEBUG __kmp_env_checks = TRUE; /* development versions have the extra checks */ #else __kmp_env_checks = FALSE; /* port versions do not have the extra checks */ #endif // From "KMP_FOREIGN_THREADS_THREADPRIVATE" initialization __kmp_foreign_tp = TRUE; __kmp_global.g.g_dynamic = FALSE; __kmp_global.g.g_dynamic_mode = dynamic_default; __kmp_env_initialize(NULL); // Print all messages in message catalog for testing purposes. #ifdef KMP_DEBUG char const *val = __kmp_env_get("KMP_DUMP_CATALOG"); if (__kmp_str_match_true(val)) { kmp_str_buf_t buffer; __kmp_str_buf_init(&buffer); __kmp_i18n_dump_catalog(&buffer); __kmp_printf("%s", buffer.str); __kmp_str_buf_free(&buffer); } __kmp_env_free(&val); #endif __kmp_threads_capacity = __kmp_initial_threads_capacity(__kmp_dflt_team_nth_ub); // Moved here from __kmp_env_initialize() "KMP_ALL_THREADPRIVATE" part __kmp_tp_capacity = __kmp_default_tp_capacity( __kmp_dflt_team_nth_ub, __kmp_max_nth, __kmp_allThreadsSpecified); // If the library is shut down properly, both pools must be NULL. Just in // case, set them to NULL -- some memory may leak, but subsequent code will // work even if pools are not freed. KMP_DEBUG_ASSERT(__kmp_thread_pool == NULL); KMP_DEBUG_ASSERT(__kmp_thread_pool_insert_pt == NULL); KMP_DEBUG_ASSERT(__kmp_team_pool == NULL); __kmp_thread_pool = NULL; __kmp_thread_pool_insert_pt = NULL; __kmp_team_pool = NULL; /* Allocate all of the variable sized records */ /* NOTE: __kmp_threads_capacity entries are allocated, but the arrays are * expandable */ /* Since allocation is cache-aligned, just add extra padding at the end */ size = (sizeof(kmp_info_t *) + sizeof(kmp_root_t *)) * __kmp_threads_capacity + CACHE_LINE; __kmp_threads = (kmp_info_t **)__kmp_allocate(size); __kmp_root = (kmp_root_t **)((char *)__kmp_threads + sizeof(kmp_info_t *) * __kmp_threads_capacity); /* init thread counts */ KMP_DEBUG_ASSERT(__kmp_all_nth == 0); // Asserts fail if the library is reinitializing and KMP_DEBUG_ASSERT(__kmp_nth == 0); // something was wrong in termination. __kmp_all_nth = 0; __kmp_nth = 0; /* setup the uber master thread and hierarchy */ gtid = __kmp_register_root(TRUE); KA_TRACE(10, ("__kmp_do_serial_initialize T#%d\n", gtid)); KMP_ASSERT(KMP_UBER_GTID(gtid)); KMP_ASSERT(KMP_INITIAL_GTID(gtid)); KMP_MB(); /* Flush all pending memory write invalidates. */ __kmp_common_initialize(); #if KMP_OS_UNIX /* invoke the child fork handler */ __kmp_register_atfork(); #endif #if !KMP_DYNAMIC_LIB { /* Invoke the exit handler when the program finishes, only for static library. For dynamic library, we already have _fini and DllMain. */ int rc = atexit(__kmp_internal_end_atexit); if (rc != 0) { __kmp_fatal(KMP_MSG(FunctionError, "atexit()"), KMP_ERR(rc), __kmp_msg_null); } } #endif #if KMP_HANDLE_SIGNALS #if KMP_OS_UNIX /* NOTE: make sure that this is called before the user installs their own signal handlers so that the user handlers are called first. this way they can return false, not call our handler, avoid terminating the library, and continue execution where they left off. */ __kmp_install_signals(FALSE); #endif /* KMP_OS_UNIX */ #if KMP_OS_WINDOWS __kmp_install_signals(TRUE); #endif /* KMP_OS_WINDOWS */ #endif /* we have finished the serial initialization */ __kmp_init_counter++; __kmp_init_serial = TRUE; if (__kmp_settings) { __kmp_env_print(); } if (__kmp_display_env || __kmp_display_env_verbose) { __kmp_env_print_2(); } #if OMPT_SUPPORT ompt_post_init(); #endif KMP_MB(); KA_TRACE(10, ("__kmp_do_serial_initialize: exit\n")); } void __kmp_serial_initialize(void) { if (__kmp_init_serial) { return; } __kmp_acquire_bootstrap_lock(&__kmp_initz_lock); if (__kmp_init_serial) { __kmp_release_bootstrap_lock(&__kmp_initz_lock); return; } __kmp_do_serial_initialize(); __kmp_release_bootstrap_lock(&__kmp_initz_lock); } static void __kmp_do_middle_initialize(void) { int i, j; int prev_dflt_team_nth; if (!__kmp_init_serial) { __kmp_do_serial_initialize(); } KA_TRACE(10, ("__kmp_middle_initialize: enter\n")); // Save the previous value for the __kmp_dflt_team_nth so that // we can avoid some reinitialization if it hasn't changed. prev_dflt_team_nth = __kmp_dflt_team_nth; #if KMP_AFFINITY_SUPPORTED // __kmp_affinity_initialize() will try to set __kmp_ncores to the // number of cores on the machine. __kmp_affinity_initialize(); // Run through the __kmp_threads array and set the affinity mask // for each root thread that is currently registered with the RTL. for (i = 0; i < __kmp_threads_capacity; i++) { if (TCR_PTR(__kmp_threads[i]) != NULL) { __kmp_affinity_set_init_mask(i, TRUE); } } #endif /* KMP_AFFINITY_SUPPORTED */ KMP_ASSERT(__kmp_xproc > 0); if (__kmp_avail_proc == 0) { __kmp_avail_proc = __kmp_xproc; } // If there were empty places in num_threads list (OMP_NUM_THREADS=,,2,3), // correct them now j = 0; while ((j < __kmp_nested_nth.used) && !__kmp_nested_nth.nth[j]) { __kmp_nested_nth.nth[j] = __kmp_dflt_team_nth = __kmp_dflt_team_nth_ub = __kmp_avail_proc; j++; } if (__kmp_dflt_team_nth == 0) { #ifdef KMP_DFLT_NTH_CORES // Default #threads = #cores __kmp_dflt_team_nth = __kmp_ncores; KA_TRACE(20, ("__kmp_middle_initialize: setting __kmp_dflt_team_nth = " "__kmp_ncores (%d)\n", __kmp_dflt_team_nth)); #else // Default #threads = #available OS procs __kmp_dflt_team_nth = __kmp_avail_proc; KA_TRACE(20, ("__kmp_middle_initialize: setting __kmp_dflt_team_nth = " "__kmp_avail_proc(%d)\n", __kmp_dflt_team_nth)); #endif /* KMP_DFLT_NTH_CORES */ } if (__kmp_dflt_team_nth < KMP_MIN_NTH) { __kmp_dflt_team_nth = KMP_MIN_NTH; } if (__kmp_dflt_team_nth > __kmp_sys_max_nth) { __kmp_dflt_team_nth = __kmp_sys_max_nth; } // There's no harm in continuing if the following check fails, // but it indicates an error in the previous logic. KMP_DEBUG_ASSERT(__kmp_dflt_team_nth <= __kmp_dflt_team_nth_ub); if (__kmp_dflt_team_nth != prev_dflt_team_nth) { // Run through the __kmp_threads array and set the num threads icv for each // root thread that is currently registered with the RTL (which has not // already explicitly set its nthreads-var with a call to // omp_set_num_threads()). for (i = 0; i < __kmp_threads_capacity; i++) { kmp_info_t *thread = __kmp_threads[i]; if (thread == NULL) continue; if (thread->th.th_current_task->td_icvs.nproc != 0) continue; set__nproc(__kmp_threads[i], __kmp_dflt_team_nth); } } KA_TRACE( 20, ("__kmp_middle_initialize: final value for __kmp_dflt_team_nth = %d\n", __kmp_dflt_team_nth)); #ifdef KMP_ADJUST_BLOCKTIME /* Adjust blocktime to zero if necessary now that __kmp_avail_proc is set */ if (!__kmp_env_blocktime && (__kmp_avail_proc > 0)) { KMP_DEBUG_ASSERT(__kmp_avail_proc > 0); if (__kmp_nth > __kmp_avail_proc) { __kmp_zero_bt = TRUE; } } #endif /* KMP_ADJUST_BLOCKTIME */ /* we have finished middle initialization */ TCW_SYNC_4(__kmp_init_middle, TRUE); KA_TRACE(10, ("__kmp_do_middle_initialize: exit\n")); } void __kmp_middle_initialize(void) { if (__kmp_init_middle) { return; } __kmp_acquire_bootstrap_lock(&__kmp_initz_lock); if (__kmp_init_middle) { __kmp_release_bootstrap_lock(&__kmp_initz_lock); return; } __kmp_do_middle_initialize(); __kmp_release_bootstrap_lock(&__kmp_initz_lock); } void __kmp_parallel_initialize(void) { int gtid = __kmp_entry_gtid(); // this might be a new root /* synchronize parallel initialization (for sibling) */ if (TCR_4(__kmp_init_parallel)) return; __kmp_acquire_bootstrap_lock(&__kmp_initz_lock); if (TCR_4(__kmp_init_parallel)) { __kmp_release_bootstrap_lock(&__kmp_initz_lock); return; } /* TODO reinitialization after we have already shut down */ if (TCR_4(__kmp_global.g.g_done)) { KA_TRACE( 10, ("__kmp_parallel_initialize: attempt to init while shutting down\n")); __kmp_infinite_loop(); } /* jc: The lock __kmp_initz_lock is already held, so calling __kmp_serial_initialize would cause a deadlock. So we call __kmp_do_serial_initialize directly. */ if (!__kmp_init_middle) { __kmp_do_middle_initialize(); } __kmp_resume_if_hard_paused(); /* begin initialization */ KA_TRACE(10, ("__kmp_parallel_initialize: enter\n")); KMP_ASSERT(KMP_UBER_GTID(gtid)); #if KMP_ARCH_X86 || KMP_ARCH_X86_64 // Save the FP control regs. // Worker threads will set theirs to these values at thread startup. __kmp_store_x87_fpu_control_word(&__kmp_init_x87_fpu_control_word); __kmp_store_mxcsr(&__kmp_init_mxcsr); __kmp_init_mxcsr &= KMP_X86_MXCSR_MASK; #endif /* KMP_ARCH_X86 || KMP_ARCH_X86_64 */ #if KMP_OS_UNIX #if KMP_HANDLE_SIGNALS /* must be after __kmp_serial_initialize */ __kmp_install_signals(TRUE); #endif #endif __kmp_suspend_initialize(); #if defined(USE_LOAD_BALANCE) if (__kmp_global.g.g_dynamic_mode == dynamic_default) { __kmp_global.g.g_dynamic_mode = dynamic_load_balance; } #else if (__kmp_global.g.g_dynamic_mode == dynamic_default) { __kmp_global.g.g_dynamic_mode = dynamic_thread_limit; } #endif if (__kmp_version) { __kmp_print_version_2(); } /* we have finished parallel initialization */ TCW_SYNC_4(__kmp_init_parallel, TRUE); KMP_MB(); KA_TRACE(10, ("__kmp_parallel_initialize: exit\n")); __kmp_release_bootstrap_lock(&__kmp_initz_lock); } /* ------------------------------------------------------------------------ */ void __kmp_run_before_invoked_task(int gtid, int tid, kmp_info_t *this_thr, kmp_team_t *team) { kmp_disp_t *dispatch; KMP_MB(); /* none of the threads have encountered any constructs, yet. */ this_thr->th.th_local.this_construct = 0; #if KMP_CACHE_MANAGE KMP_CACHE_PREFETCH(&this_thr->th.th_bar[bs_forkjoin_barrier].bb.b_arrived); #endif /* KMP_CACHE_MANAGE */ dispatch = (kmp_disp_t *)TCR_PTR(this_thr->th.th_dispatch); KMP_DEBUG_ASSERT(dispatch); KMP_DEBUG_ASSERT(team->t.t_dispatch); // KMP_DEBUG_ASSERT( this_thr->th.th_dispatch == &team->t.t_dispatch[ // this_thr->th.th_info.ds.ds_tid ] ); dispatch->th_disp_index = 0; /* reset the dispatch buffer counter */ dispatch->th_doacross_buf_idx = 0; // reset doacross dispatch buffer counter if (__kmp_env_consistency_check) __kmp_push_parallel(gtid, team->t.t_ident); KMP_MB(); /* Flush all pending memory write invalidates. */ } void __kmp_run_after_invoked_task(int gtid, int tid, kmp_info_t *this_thr, kmp_team_t *team) { if (__kmp_env_consistency_check) __kmp_pop_parallel(gtid, team->t.t_ident); __kmp_finish_implicit_task(this_thr); } int __kmp_invoke_task_func(int gtid) { int rc; int tid = __kmp_tid_from_gtid(gtid); kmp_info_t *this_thr = __kmp_threads[gtid]; kmp_team_t *team = this_thr->th.th_team; __kmp_run_before_invoked_task(gtid, tid, this_thr, team); #if USE_ITT_BUILD if (__itt_stack_caller_create_ptr) { __kmp_itt_stack_callee_enter( (__itt_caller) team->t.t_stack_id); // inform ittnotify about entering user's code } #endif /* USE_ITT_BUILD */ #if INCLUDE_SSC_MARKS SSC_MARK_INVOKING(); #endif #if OMPT_SUPPORT void *dummy; void **exit_frame_p; ompt_data_t *my_task_data; ompt_data_t *my_parallel_data; int ompt_team_size; if (ompt_enabled.enabled) { exit_frame_p = &( team->t.t_implicit_task_taskdata[tid].ompt_task_info.frame.exit_frame.ptr); } else { exit_frame_p = &dummy; } my_task_data = &(team->t.t_implicit_task_taskdata[tid].ompt_task_info.task_data); my_parallel_data = &(team->t.ompt_team_info.parallel_data); if (ompt_enabled.ompt_callback_implicit_task) { ompt_team_size = team->t.t_nproc; ompt_callbacks.ompt_callback(ompt_callback_implicit_task)( ompt_scope_begin, my_parallel_data, my_task_data, ompt_team_size, __kmp_tid_from_gtid(gtid), ompt_task_implicit); OMPT_CUR_TASK_INFO(this_thr)->thread_num = __kmp_tid_from_gtid(gtid); } #endif #if KMP_STATS_ENABLED stats_state_e previous_state = KMP_GET_THREAD_STATE(); if (previous_state == stats_state_e::TEAMS_REGION) { KMP_PUSH_PARTITIONED_TIMER(OMP_teams); } else { KMP_PUSH_PARTITIONED_TIMER(OMP_parallel); } KMP_SET_THREAD_STATE(IMPLICIT_TASK); #endif rc = __kmp_invoke_microtask((microtask_t)TCR_SYNC_PTR(team->t.t_pkfn), gtid, tid, (int)team->t.t_argc, (void **)team->t.t_argv #if OMPT_SUPPORT , exit_frame_p #endif ); #if OMPT_SUPPORT *exit_frame_p = NULL; this_thr->th.ompt_thread_info.parallel_flags |= ompt_parallel_team; #endif #if KMP_STATS_ENABLED if (previous_state == stats_state_e::TEAMS_REGION) { KMP_SET_THREAD_STATE(previous_state); } KMP_POP_PARTITIONED_TIMER(); #endif #if USE_ITT_BUILD if (__itt_stack_caller_create_ptr) { __kmp_itt_stack_callee_leave( (__itt_caller) team->t.t_stack_id); // inform ittnotify about leaving user's code } #endif /* USE_ITT_BUILD */ __kmp_run_after_invoked_task(gtid, tid, this_thr, team); return rc; } void __kmp_teams_master(int gtid) { // This routine is called by all master threads in teams construct kmp_info_t *thr = __kmp_threads[gtid]; kmp_team_t *team = thr->th.th_team; ident_t *loc = team->t.t_ident; thr->th.th_set_nproc = thr->th.th_teams_size.nth; KMP_DEBUG_ASSERT(thr->th.th_teams_microtask); KMP_DEBUG_ASSERT(thr->th.th_set_nproc); KA_TRACE(20, ("__kmp_teams_master: T#%d, Tid %d, microtask %p\n", gtid, __kmp_tid_from_gtid(gtid), thr->th.th_teams_microtask)); // This thread is a new CG root. Set up the proper variables. kmp_cg_root_t *tmp = (kmp_cg_root_t *)__kmp_allocate(sizeof(kmp_cg_root_t)); tmp->cg_root = thr; // Make thr the CG root // Init to thread limit that was stored when league masters were forked tmp->cg_thread_limit = thr->th.th_current_task->td_icvs.thread_limit; tmp->cg_nthreads = 1; // Init counter to one active thread, this one KA_TRACE(100, ("__kmp_teams_master: Thread %p created node %p and init" " cg_nthreads to 1\n", thr, tmp)); tmp->up = thr->th.th_cg_roots; thr->th.th_cg_roots = tmp; // Launch league of teams now, but not let workers execute // (they hang on fork barrier until next parallel) #if INCLUDE_SSC_MARKS SSC_MARK_FORKING(); #endif __kmp_fork_call(loc, gtid, fork_context_intel, team->t.t_argc, (microtask_t)thr->th.th_teams_microtask, // "wrapped" task VOLATILE_CAST(launch_t) __kmp_invoke_task_func, NULL); #if INCLUDE_SSC_MARKS SSC_MARK_JOINING(); #endif // If the team size was reduced from the limit, set it to the new size if (thr->th.th_team_nproc < thr->th.th_teams_size.nth) thr->th.th_teams_size.nth = thr->th.th_team_nproc; // AC: last parameter "1" eliminates join barrier which won't work because // worker threads are in a fork barrier waiting for more parallel regions __kmp_join_call(loc, gtid #if OMPT_SUPPORT , fork_context_intel #endif , 1); } int __kmp_invoke_teams_master(int gtid) { kmp_info_t *this_thr = __kmp_threads[gtid]; kmp_team_t *team = this_thr->th.th_team; #if KMP_DEBUG if (!__kmp_threads[gtid]->th.th_team->t.t_serialized) KMP_DEBUG_ASSERT((void *)__kmp_threads[gtid]->th.th_team->t.t_pkfn == (void *)__kmp_teams_master); #endif __kmp_run_before_invoked_task(gtid, 0, this_thr, team); #if OMPT_SUPPORT int tid = __kmp_tid_from_gtid(gtid); ompt_data_t *task_data = &team->t.t_implicit_task_taskdata[tid].ompt_task_info.task_data; ompt_data_t *parallel_data = &team->t.ompt_team_info.parallel_data; if (ompt_enabled.ompt_callback_implicit_task) { ompt_callbacks.ompt_callback(ompt_callback_implicit_task)( ompt_scope_begin, parallel_data, task_data, team->t.t_nproc, tid, ompt_task_initial); OMPT_CUR_TASK_INFO(this_thr)->thread_num = tid; } #endif __kmp_teams_master(gtid); #if OMPT_SUPPORT this_thr->th.ompt_thread_info.parallel_flags |= ompt_parallel_league; #endif __kmp_run_after_invoked_task(gtid, 0, this_thr, team); return 1; } /* this sets the requested number of threads for the next parallel region encountered by this team. since this should be enclosed in the forkjoin critical section it should avoid race conditions with asymmetrical nested parallelism */ void __kmp_push_num_threads(ident_t *id, int gtid, int num_threads) { kmp_info_t *thr = __kmp_threads[gtid]; if (num_threads > 0) thr->th.th_set_nproc = num_threads; } /* this sets the requested number of teams for the teams region and/or the number of threads for the next parallel region encountered */ void __kmp_push_num_teams(ident_t *id, int gtid, int num_teams, int num_threads) { kmp_info_t *thr = __kmp_threads[gtid]; KMP_DEBUG_ASSERT(num_teams >= 0); KMP_DEBUG_ASSERT(num_threads >= 0); if (num_teams == 0) num_teams = 1; // default number of teams is 1. if (num_teams > __kmp_teams_max_nth) { // if too many teams requested? if (!__kmp_reserve_warn) { __kmp_reserve_warn = 1; __kmp_msg(kmp_ms_warning, KMP_MSG(CantFormThrTeam, num_teams, __kmp_teams_max_nth), KMP_HNT(Unset_ALL_THREADS), __kmp_msg_null); } num_teams = __kmp_teams_max_nth; } // Set number of teams (number of threads in the outer "parallel" of the // teams) thr->th.th_set_nproc = thr->th.th_teams_size.nteams = num_teams; // Remember the number of threads for inner parallel regions if (!TCR_4(__kmp_init_middle)) __kmp_middle_initialize(); // get internal globals calculated KMP_DEBUG_ASSERT(__kmp_avail_proc); KMP_DEBUG_ASSERT(__kmp_dflt_team_nth); if (num_threads == 0) { num_threads = __kmp_avail_proc / num_teams; // adjust num_threads w/o warning as it is not user setting // num_threads = min(num_threads, nthreads-var, thread-limit-var) // no thread_limit clause specified - do not change thread-limit-var ICV if (num_threads > __kmp_dflt_team_nth) { num_threads = __kmp_dflt_team_nth; // honor nthreads-var ICV } if (num_threads > thr->th.th_current_task->td_icvs.thread_limit) { num_threads = thr->th.th_current_task->td_icvs.thread_limit; } // prevent team size to exceed thread-limit-var if (num_teams * num_threads > __kmp_teams_max_nth) { num_threads = __kmp_teams_max_nth / num_teams; } } else { // This thread will be the master of the league masters // Store new thread limit; old limit is saved in th_cg_roots list thr->th.th_current_task->td_icvs.thread_limit = num_threads; // num_threads = min(num_threads, nthreads-var) if (num_threads > __kmp_dflt_team_nth) { num_threads = __kmp_dflt_team_nth; // honor nthreads-var ICV } if (num_teams * num_threads > __kmp_teams_max_nth) { int new_threads = __kmp_teams_max_nth / num_teams; if (!__kmp_reserve_warn) { // user asked for too many threads __kmp_reserve_warn = 1; // conflicts with KMP_TEAMS_THREAD_LIMIT __kmp_msg(kmp_ms_warning, KMP_MSG(CantFormThrTeam, num_threads, new_threads), KMP_HNT(Unset_ALL_THREADS), __kmp_msg_null); } num_threads = new_threads; } } thr->th.th_teams_size.nth = num_threads; } // Set the proc_bind var to use in the following parallel region. void __kmp_push_proc_bind(ident_t *id, int gtid, kmp_proc_bind_t proc_bind) { kmp_info_t *thr = __kmp_threads[gtid]; thr->th.th_set_proc_bind = proc_bind; } /* Launch the worker threads into the microtask. */ void __kmp_internal_fork(ident_t *id, int gtid, kmp_team_t *team) { kmp_info_t *this_thr = __kmp_threads[gtid]; #ifdef KMP_DEBUG int f; #endif /* KMP_DEBUG */ KMP_DEBUG_ASSERT(team); KMP_DEBUG_ASSERT(this_thr->th.th_team == team); KMP_ASSERT(KMP_MASTER_GTID(gtid)); KMP_MB(); /* Flush all pending memory write invalidates. */ team->t.t_construct = 0; /* no single directives seen yet */ team->t.t_ordered.dt.t_value = 0; /* thread 0 enters the ordered section first */ /* Reset the identifiers on the dispatch buffer */ KMP_DEBUG_ASSERT(team->t.t_disp_buffer); if (team->t.t_max_nproc > 1) { int i; for (i = 0; i < __kmp_dispatch_num_buffers; ++i) { team->t.t_disp_buffer[i].buffer_index = i; team->t.t_disp_buffer[i].doacross_buf_idx = i; } } else { team->t.t_disp_buffer[0].buffer_index = 0; team->t.t_disp_buffer[0].doacross_buf_idx = 0; } KMP_MB(); /* Flush all pending memory write invalidates. */ KMP_ASSERT(this_thr->th.th_team == team); #ifdef KMP_DEBUG for (f = 0; f < team->t.t_nproc; f++) { KMP_DEBUG_ASSERT(team->t.t_threads[f] && team->t.t_threads[f]->th.th_team_nproc == team->t.t_nproc); } #endif /* KMP_DEBUG */ /* release the worker threads so they may begin working */ __kmp_fork_barrier(gtid, 0); } void __kmp_internal_join(ident_t *id, int gtid, kmp_team_t *team) { kmp_info_t *this_thr = __kmp_threads[gtid]; KMP_DEBUG_ASSERT(team); KMP_DEBUG_ASSERT(this_thr->th.th_team == team); KMP_ASSERT(KMP_MASTER_GTID(gtid)); KMP_MB(); /* Flush all pending memory write invalidates. */ /* Join barrier after fork */ #ifdef KMP_DEBUG if (__kmp_threads[gtid] && __kmp_threads[gtid]->th.th_team_nproc != team->t.t_nproc) { __kmp_printf("GTID: %d, __kmp_threads[%d]=%p\n", gtid, gtid, __kmp_threads[gtid]); __kmp_printf("__kmp_threads[%d]->th.th_team_nproc=%d, TEAM: %p, " "team->t.t_nproc=%d\n", gtid, __kmp_threads[gtid]->th.th_team_nproc, team, team->t.t_nproc); __kmp_print_structure(); } KMP_DEBUG_ASSERT(__kmp_threads[gtid] && __kmp_threads[gtid]->th.th_team_nproc == team->t.t_nproc); #endif /* KMP_DEBUG */ __kmp_join_barrier(gtid); /* wait for everyone */ #if OMPT_SUPPORT if (ompt_enabled.enabled && this_thr->th.ompt_thread_info.state == ompt_state_wait_barrier_implicit) { int ds_tid = this_thr->th.th_info.ds.ds_tid; ompt_data_t *task_data = OMPT_CUR_TASK_DATA(this_thr); this_thr->th.ompt_thread_info.state = ompt_state_overhead; #if OMPT_OPTIONAL void *codeptr = NULL; if (KMP_MASTER_TID(ds_tid) && (ompt_callbacks.ompt_callback(ompt_callback_sync_region_wait) || ompt_callbacks.ompt_callback(ompt_callback_sync_region))) codeptr = OMPT_CUR_TEAM_INFO(this_thr)->master_return_address; if (ompt_enabled.ompt_callback_sync_region_wait) { ompt_callbacks.ompt_callback(ompt_callback_sync_region_wait)( ompt_sync_region_barrier_implicit, ompt_scope_end, NULL, task_data, codeptr); } if (ompt_enabled.ompt_callback_sync_region) { ompt_callbacks.ompt_callback(ompt_callback_sync_region)( ompt_sync_region_barrier_implicit, ompt_scope_end, NULL, task_data, codeptr); } #endif if (!KMP_MASTER_TID(ds_tid) && ompt_enabled.ompt_callback_implicit_task) { ompt_callbacks.ompt_callback(ompt_callback_implicit_task)( ompt_scope_end, NULL, task_data, 0, ds_tid, ompt_task_implicit); // TODO: Can this be ompt_task_initial? } } #endif KMP_MB(); /* Flush all pending memory write invalidates. */ KMP_ASSERT(this_thr->th.th_team == team); } /* ------------------------------------------------------------------------ */ #ifdef USE_LOAD_BALANCE // Return the worker threads actively spinning in the hot team, if we // are at the outermost level of parallelism. Otherwise, return 0. static int __kmp_active_hot_team_nproc(kmp_root_t *root) { int i; int retval; kmp_team_t *hot_team; if (root->r.r_active) { return 0; } hot_team = root->r.r_hot_team; if (__kmp_dflt_blocktime == KMP_MAX_BLOCKTIME) { return hot_team->t.t_nproc - 1; // Don't count master thread } // Skip the master thread - it is accounted for elsewhere. retval = 0; for (i = 1; i < hot_team->t.t_nproc; i++) { if (hot_team->t.t_threads[i]->th.th_active) { retval++; } } return retval; } // Perform an automatic adjustment to the number of // threads used by the next parallel region. static int __kmp_load_balance_nproc(kmp_root_t *root, int set_nproc) { int retval; int pool_active; int hot_team_active; int team_curr_active; int system_active; KB_TRACE(20, ("__kmp_load_balance_nproc: called root:%p set_nproc:%d\n", root, set_nproc)); KMP_DEBUG_ASSERT(root); KMP_DEBUG_ASSERT(root->r.r_root_team->t.t_threads[0] ->th.th_current_task->td_icvs.dynamic == TRUE); KMP_DEBUG_ASSERT(set_nproc > 1); if (set_nproc == 1) { KB_TRACE(20, ("__kmp_load_balance_nproc: serial execution.\n")); return 1; } // Threads that are active in the thread pool, active in the hot team for this // particular root (if we are at the outer par level), and the currently // executing thread (to become the master) are available to add to the new // team, but are currently contributing to the system load, and must be // accounted for. pool_active = __kmp_thread_pool_active_nth; hot_team_active = __kmp_active_hot_team_nproc(root); team_curr_active = pool_active + hot_team_active + 1; // Check the system load. system_active = __kmp_get_load_balance(__kmp_avail_proc + team_curr_active); KB_TRACE(30, ("__kmp_load_balance_nproc: system active = %d pool active = %d " "hot team active = %d\n", system_active, pool_active, hot_team_active)); if (system_active < 0) { // There was an error reading the necessary info from /proc, so use the // thread limit algorithm instead. Once we set __kmp_global.g.g_dynamic_mode // = dynamic_thread_limit, we shouldn't wind up getting back here. __kmp_global.g.g_dynamic_mode = dynamic_thread_limit; KMP_WARNING(CantLoadBalUsing, "KMP_DYNAMIC_MODE=thread limit"); // Make this call behave like the thread limit algorithm. retval = __kmp_avail_proc - __kmp_nth + (root->r.r_active ? 1 : root->r.r_hot_team->t.t_nproc); if (retval > set_nproc) { retval = set_nproc; } if (retval < KMP_MIN_NTH) { retval = KMP_MIN_NTH; } KB_TRACE(20, ("__kmp_load_balance_nproc: thread limit exit. retval:%d\n", retval)); return retval; } // There is a slight delay in the load balance algorithm in detecting new // running procs. The real system load at this instant should be at least as // large as the #active omp thread that are available to add to the team. if (system_active < team_curr_active) { system_active = team_curr_active; } retval = __kmp_avail_proc - system_active + team_curr_active; if (retval > set_nproc) { retval = set_nproc; } if (retval < KMP_MIN_NTH) { retval = KMP_MIN_NTH; } KB_TRACE(20, ("__kmp_load_balance_nproc: exit. retval:%d\n", retval)); return retval; } // __kmp_load_balance_nproc() #endif /* USE_LOAD_BALANCE */ /* ------------------------------------------------------------------------ */ /* NOTE: this is called with the __kmp_init_lock held */ void __kmp_cleanup(void) { int f; KA_TRACE(10, ("__kmp_cleanup: enter\n")); if (TCR_4(__kmp_init_parallel)) { #if KMP_HANDLE_SIGNALS __kmp_remove_signals(); #endif TCW_4(__kmp_init_parallel, FALSE); } if (TCR_4(__kmp_init_middle)) { #if KMP_AFFINITY_SUPPORTED __kmp_affinity_uninitialize(); #endif /* KMP_AFFINITY_SUPPORTED */ __kmp_cleanup_hierarchy(); TCW_4(__kmp_init_middle, FALSE); } KA_TRACE(10, ("__kmp_cleanup: go serial cleanup\n")); if (__kmp_init_serial) { __kmp_runtime_destroy(); __kmp_init_serial = FALSE; } __kmp_cleanup_threadprivate_caches(); for (f = 0; f < __kmp_threads_capacity; f++) { if (__kmp_root[f] != NULL) { __kmp_free(__kmp_root[f]); __kmp_root[f] = NULL; } } __kmp_free(__kmp_threads); // __kmp_threads and __kmp_root were allocated at once, as single block, so // there is no need in freeing __kmp_root. __kmp_threads = NULL; __kmp_root = NULL; __kmp_threads_capacity = 0; #if KMP_USE_DYNAMIC_LOCK __kmp_cleanup_indirect_user_locks(); #else __kmp_cleanup_user_locks(); #endif #if KMP_AFFINITY_SUPPORTED KMP_INTERNAL_FREE(CCAST(char *, __kmp_cpuinfo_file)); __kmp_cpuinfo_file = NULL; #endif /* KMP_AFFINITY_SUPPORTED */ #if KMP_USE_ADAPTIVE_LOCKS #if KMP_DEBUG_ADAPTIVE_LOCKS __kmp_print_speculative_stats(); #endif #endif KMP_INTERNAL_FREE(__kmp_nested_nth.nth); __kmp_nested_nth.nth = NULL; __kmp_nested_nth.size = 0; __kmp_nested_nth.used = 0; KMP_INTERNAL_FREE(__kmp_nested_proc_bind.bind_types); __kmp_nested_proc_bind.bind_types = NULL; __kmp_nested_proc_bind.size = 0; __kmp_nested_proc_bind.used = 0; if (__kmp_affinity_format) { KMP_INTERNAL_FREE(__kmp_affinity_format); __kmp_affinity_format = NULL; } __kmp_i18n_catclose(); #if KMP_USE_HIER_SCHED __kmp_hier_scheds.deallocate(); #endif #if KMP_STATS_ENABLED __kmp_stats_fini(); #endif KA_TRACE(10, ("__kmp_cleanup: exit\n")); } /* ------------------------------------------------------------------------ */ int __kmp_ignore_mppbeg(void) { char *env; if ((env = getenv("KMP_IGNORE_MPPBEG")) != NULL) { if (__kmp_str_match_false(env)) return FALSE; } // By default __kmpc_begin() is no-op. return TRUE; } int __kmp_ignore_mppend(void) { char *env; if ((env = getenv("KMP_IGNORE_MPPEND")) != NULL) { if (__kmp_str_match_false(env)) return FALSE; } // By default __kmpc_end() is no-op. return TRUE; } void __kmp_internal_begin(void) { int gtid; kmp_root_t *root; /* this is a very important step as it will register new sibling threads and assign these new uber threads a new gtid */ gtid = __kmp_entry_gtid(); root = __kmp_threads[gtid]->th.th_root; KMP_ASSERT(KMP_UBER_GTID(gtid)); if (root->r.r_begin) return; __kmp_acquire_lock(&root->r.r_begin_lock, gtid); if (root->r.r_begin) { __kmp_release_lock(&root->r.r_begin_lock, gtid); return; } root->r.r_begin = TRUE; __kmp_release_lock(&root->r.r_begin_lock, gtid); } /* ------------------------------------------------------------------------ */ void __kmp_user_set_library(enum library_type arg) { int gtid; kmp_root_t *root; kmp_info_t *thread; /* first, make sure we are initialized so we can get our gtid */ gtid = __kmp_entry_gtid(); thread = __kmp_threads[gtid]; root = thread->th.th_root; KA_TRACE(20, ("__kmp_user_set_library: enter T#%d, arg: %d, %d\n", gtid, arg, library_serial)); if (root->r.r_in_parallel) { /* Must be called in serial section of top-level thread */ KMP_WARNING(SetLibraryIncorrectCall); return; } switch (arg) { case library_serial: thread->th.th_set_nproc = 0; set__nproc(thread, 1); break; case library_turnaround: thread->th.th_set_nproc = 0; set__nproc(thread, __kmp_dflt_team_nth ? __kmp_dflt_team_nth : __kmp_dflt_team_nth_ub); break; case library_throughput: thread->th.th_set_nproc = 0; set__nproc(thread, __kmp_dflt_team_nth ? __kmp_dflt_team_nth : __kmp_dflt_team_nth_ub); break; default: KMP_FATAL(UnknownLibraryType, arg); } __kmp_aux_set_library(arg); } void __kmp_aux_set_stacksize(size_t arg) { if (!__kmp_init_serial) __kmp_serial_initialize(); #if KMP_OS_DARWIN if (arg & (0x1000 - 1)) { arg &= ~(0x1000 - 1); if (arg + 0x1000) /* check for overflow if we round up */ arg += 0x1000; } #endif __kmp_acquire_bootstrap_lock(&__kmp_initz_lock); /* only change the default stacksize before the first parallel region */ if (!TCR_4(__kmp_init_parallel)) { size_t value = arg; /* argument is in bytes */ if (value < __kmp_sys_min_stksize) value = __kmp_sys_min_stksize; else if (value > KMP_MAX_STKSIZE) value = KMP_MAX_STKSIZE; __kmp_stksize = value; __kmp_env_stksize = TRUE; /* was KMP_STACKSIZE specified? */ } __kmp_release_bootstrap_lock(&__kmp_initz_lock); } /* set the behaviour of the runtime library */ /* TODO this can cause some odd behaviour with sibling parallelism... */ void __kmp_aux_set_library(enum library_type arg) { __kmp_library = arg; switch (__kmp_library) { case library_serial: { KMP_INFORM(LibraryIsSerial); } break; case library_turnaround: if (__kmp_use_yield == 1 && !__kmp_use_yield_exp_set) __kmp_use_yield = 2; // only yield when oversubscribed break; case library_throughput: if (__kmp_dflt_blocktime == KMP_MAX_BLOCKTIME) __kmp_dflt_blocktime = 200; break; default: KMP_FATAL(UnknownLibraryType, arg); } } /* Getting team information common for all team API */ // Returns NULL if not in teams construct static kmp_team_t *__kmp_aux_get_team_info(int &teams_serialized) { kmp_info_t *thr = __kmp_entry_thread(); teams_serialized = 0; if (thr->th.th_teams_microtask) { kmp_team_t *team = thr->th.th_team; int tlevel = thr->th.th_teams_level; // the level of the teams construct int ii = team->t.t_level; teams_serialized = team->t.t_serialized; int level = tlevel + 1; KMP_DEBUG_ASSERT(ii >= tlevel); while (ii > level) { for (teams_serialized = team->t.t_serialized; (teams_serialized > 0) && (ii > level); teams_serialized--, ii--) { } if (team->t.t_serialized && (!teams_serialized)) { team = team->t.t_parent; continue; } if (ii > level) { team = team->t.t_parent; ii--; } } return team; } return NULL; } int __kmp_aux_get_team_num() { int serialized; kmp_team_t *team = __kmp_aux_get_team_info(serialized); if (team) { if (serialized > 1) { return 0; // teams region is serialized ( 1 team of 1 thread ). } else { return team->t.t_master_tid; } } return 0; } int __kmp_aux_get_num_teams() { int serialized; kmp_team_t *team = __kmp_aux_get_team_info(serialized); if (team) { if (serialized > 1) { return 1; } else { return team->t.t_parent->t.t_nproc; } } return 1; } /* ------------------------------------------------------------------------ */ /* * Affinity Format Parser * * Field is in form of: %[[[0].]size]type * % and type are required (%% means print a literal '%') * type is either single char or long name surrounded by {}, * e.g., N or {num_threads} * 0 => leading zeros * . => right justified when size is specified * by default output is left justified * size is the *minimum* field length * All other characters are printed as is * * Available field types: * L {thread_level} - omp_get_level() * n {thread_num} - omp_get_thread_num() * h {host} - name of host machine * P {process_id} - process id (integer) * T {thread_identifier} - native thread identifier (integer) * N {num_threads} - omp_get_num_threads() * A {ancestor_tnum} - omp_get_ancestor_thread_num(omp_get_level()-1) * a {thread_affinity} - comma separated list of integers or integer ranges * (values of affinity mask) * * Implementation-specific field types can be added * If a type is unknown, print "undefined" */ // Structure holding the short name, long name, and corresponding data type // for snprintf. A table of these will represent the entire valid keyword // field types. typedef struct kmp_affinity_format_field_t { char short_name; // from spec e.g., L -> thread level const char *long_name; // from spec thread_level -> thread level char field_format; // data type for snprintf (typically 'd' or 's' // for integer or string) } kmp_affinity_format_field_t; static const kmp_affinity_format_field_t __kmp_affinity_format_table[] = { #if KMP_AFFINITY_SUPPORTED {'A', "thread_affinity", 's'}, #endif {'t', "team_num", 'd'}, {'T', "num_teams", 'd'}, {'L', "nesting_level", 'd'}, {'n', "thread_num", 'd'}, {'N', "num_threads", 'd'}, {'a', "ancestor_tnum", 'd'}, {'H', "host", 's'}, {'P', "process_id", 'd'}, {'i', "native_thread_id", 'd'}}; // Return the number of characters it takes to hold field static int __kmp_aux_capture_affinity_field(int gtid, const kmp_info_t *th, const char **ptr, kmp_str_buf_t *field_buffer) { int rc, format_index, field_value; const char *width_left, *width_right; bool pad_zeros, right_justify, parse_long_name, found_valid_name; static const int FORMAT_SIZE = 20; char format[FORMAT_SIZE] = {0}; char absolute_short_name = 0; KMP_DEBUG_ASSERT(gtid >= 0); KMP_DEBUG_ASSERT(th); KMP_DEBUG_ASSERT(**ptr == '%'); KMP_DEBUG_ASSERT(field_buffer); __kmp_str_buf_clear(field_buffer); // Skip the initial % (*ptr)++; // Check for %% first if (**ptr == '%') { __kmp_str_buf_cat(field_buffer, "%", 1); (*ptr)++; // skip over the second % return 1; } // Parse field modifiers if they are present pad_zeros = false; if (**ptr == '0') { pad_zeros = true; (*ptr)++; // skip over 0 } right_justify = false; if (**ptr == '.') { right_justify = true; (*ptr)++; // skip over . } // Parse width of field: [width_left, width_right) width_left = width_right = NULL; if (**ptr >= '0' && **ptr <= '9') { width_left = *ptr; SKIP_DIGITS(*ptr); width_right = *ptr; } // Create the format for KMP_SNPRINTF based on flags parsed above format_index = 0; format[format_index++] = '%'; if (!right_justify) format[format_index++] = '-'; if (pad_zeros) format[format_index++] = '0'; if (width_left && width_right) { int i = 0; // Only allow 8 digit number widths. // This also prevents overflowing format variable while (i < 8 && width_left < width_right) { format[format_index++] = *width_left; width_left++; i++; } } // Parse a name (long or short) // Canonicalize the name into absolute_short_name found_valid_name = false; parse_long_name = (**ptr == '{'); if (parse_long_name) (*ptr)++; // skip initial left brace for (size_t i = 0; i < sizeof(__kmp_affinity_format_table) / sizeof(__kmp_affinity_format_table[0]); ++i) { char short_name = __kmp_affinity_format_table[i].short_name; const char *long_name = __kmp_affinity_format_table[i].long_name; char field_format = __kmp_affinity_format_table[i].field_format; if (parse_long_name) { int length = KMP_STRLEN(long_name); if (strncmp(*ptr, long_name, length) == 0) { found_valid_name = true; (*ptr) += length; // skip the long name } } else if (**ptr == short_name) { found_valid_name = true; (*ptr)++; // skip the short name } if (found_valid_name) { format[format_index++] = field_format; format[format_index++] = '\0'; absolute_short_name = short_name; break; } } if (parse_long_name) { if (**ptr != '}') { absolute_short_name = 0; } else { (*ptr)++; // skip over the right brace } } // Attempt to fill the buffer with the requested // value using snprintf within __kmp_str_buf_print() switch (absolute_short_name) { case 't': rc = __kmp_str_buf_print(field_buffer, format, __kmp_aux_get_team_num()); break; case 'T': rc = __kmp_str_buf_print(field_buffer, format, __kmp_aux_get_num_teams()); break; case 'L': rc = __kmp_str_buf_print(field_buffer, format, th->th.th_team->t.t_level); break; case 'n': rc = __kmp_str_buf_print(field_buffer, format, __kmp_tid_from_gtid(gtid)); break; case 'H': { static const int BUFFER_SIZE = 256; char buf[BUFFER_SIZE]; __kmp_expand_host_name(buf, BUFFER_SIZE); rc = __kmp_str_buf_print(field_buffer, format, buf); } break; case 'P': rc = __kmp_str_buf_print(field_buffer, format, getpid()); break; case 'i': rc = __kmp_str_buf_print(field_buffer, format, __kmp_gettid()); break; case 'N': rc = __kmp_str_buf_print(field_buffer, format, th->th.th_team->t.t_nproc); break; case 'a': field_value = __kmp_get_ancestor_thread_num(gtid, th->th.th_team->t.t_level - 1); rc = __kmp_str_buf_print(field_buffer, format, field_value); break; #if KMP_AFFINITY_SUPPORTED case 'A': { kmp_str_buf_t buf; __kmp_str_buf_init(&buf); __kmp_affinity_str_buf_mask(&buf, th->th.th_affin_mask); rc = __kmp_str_buf_print(field_buffer, format, buf.str); __kmp_str_buf_free(&buf); } break; #endif default: // According to spec, If an implementation does not have info for field // type, then "undefined" is printed rc = __kmp_str_buf_print(field_buffer, "%s", "undefined"); // Skip the field if (parse_long_name) { SKIP_TOKEN(*ptr); if (**ptr == '}') (*ptr)++; } else { (*ptr)++; } } KMP_ASSERT(format_index <= FORMAT_SIZE); return rc; } /* * Return number of characters needed to hold the affinity string * (not including null byte character) * The resultant string is printed to buffer, which the caller can then * handle afterwards */ size_t __kmp_aux_capture_affinity(int gtid, const char *format, kmp_str_buf_t *buffer) { const char *parse_ptr; size_t retval; const kmp_info_t *th; kmp_str_buf_t field; KMP_DEBUG_ASSERT(buffer); KMP_DEBUG_ASSERT(gtid >= 0); __kmp_str_buf_init(&field); __kmp_str_buf_clear(buffer); th = __kmp_threads[gtid]; retval = 0; // If format is NULL or zero-length string, then we use // affinity-format-var ICV parse_ptr = format; if (parse_ptr == NULL || *parse_ptr == '\0') { parse_ptr = __kmp_affinity_format; } KMP_DEBUG_ASSERT(parse_ptr); while (*parse_ptr != '\0') { // Parse a field if (*parse_ptr == '%') { // Put field in the buffer int rc = __kmp_aux_capture_affinity_field(gtid, th, &parse_ptr, &field); __kmp_str_buf_catbuf(buffer, &field); retval += rc; } else { // Put literal character in buffer __kmp_str_buf_cat(buffer, parse_ptr, 1); retval++; parse_ptr++; } } __kmp_str_buf_free(&field); return retval; } // Displays the affinity string to stdout void __kmp_aux_display_affinity(int gtid, const char *format) { kmp_str_buf_t buf; __kmp_str_buf_init(&buf); __kmp_aux_capture_affinity(gtid, format, &buf); __kmp_fprintf(kmp_out, "%s" KMP_END_OF_LINE, buf.str); __kmp_str_buf_free(&buf); } /* ------------------------------------------------------------------------ */ void __kmp_aux_set_blocktime(int arg, kmp_info_t *thread, int tid) { int blocktime = arg; /* argument is in milliseconds */ #if KMP_USE_MONITOR int bt_intervals; #endif int bt_set; __kmp_save_internal_controls(thread); /* Normalize and set blocktime for the teams */ if (blocktime < KMP_MIN_BLOCKTIME) blocktime = KMP_MIN_BLOCKTIME; else if (blocktime > KMP_MAX_BLOCKTIME) blocktime = KMP_MAX_BLOCKTIME; set__blocktime_team(thread->th.th_team, tid, blocktime); set__blocktime_team(thread->th.th_serial_team, 0, blocktime); #if KMP_USE_MONITOR /* Calculate and set blocktime intervals for the teams */ bt_intervals = KMP_INTERVALS_FROM_BLOCKTIME(blocktime, __kmp_monitor_wakeups); set__bt_intervals_team(thread->th.th_team, tid, bt_intervals); set__bt_intervals_team(thread->th.th_serial_team, 0, bt_intervals); #endif /* Set whether blocktime has been set to "TRUE" */ bt_set = TRUE; set__bt_set_team(thread->th.th_team, tid, bt_set); set__bt_set_team(thread->th.th_serial_team, 0, bt_set); #if KMP_USE_MONITOR KF_TRACE(10, ("kmp_set_blocktime: T#%d(%d:%d), blocktime=%d, " "bt_intervals=%d, monitor_updates=%d\n", __kmp_gtid_from_tid(tid, thread->th.th_team), thread->th.th_team->t.t_id, tid, blocktime, bt_intervals, __kmp_monitor_wakeups)); #else KF_TRACE(10, ("kmp_set_blocktime: T#%d(%d:%d), blocktime=%d\n", __kmp_gtid_from_tid(tid, thread->th.th_team), thread->th.th_team->t.t_id, tid, blocktime)); #endif } void __kmp_aux_set_defaults(char const *str, int len) { if (!__kmp_init_serial) { __kmp_serial_initialize(); } __kmp_env_initialize(str); if (__kmp_settings || __kmp_display_env || __kmp_display_env_verbose) { __kmp_env_print(); } } // __kmp_aux_set_defaults /* ------------------------------------------------------------------------ */ /* internal fast reduction routines */ PACKED_REDUCTION_METHOD_T __kmp_determine_reduction_method( ident_t *loc, kmp_int32 global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck) { // Default reduction method: critical construct ( lck != NULL, like in current // PAROPT ) // If ( reduce_data!=NULL && reduce_func!=NULL ): the tree-reduction method // can be selected by RTL // If loc->flags contains KMP_IDENT_ATOMIC_REDUCE, the atomic reduce method // can be selected by RTL // Finally, it's up to OpenMP RTL to make a decision on which method to select // among generated by PAROPT. PACKED_REDUCTION_METHOD_T retval; int team_size; KMP_DEBUG_ASSERT(loc); // it would be nice to test ( loc != 0 ) KMP_DEBUG_ASSERT(lck); // it would be nice to test ( lck != 0 ) #define FAST_REDUCTION_ATOMIC_METHOD_GENERATED \ ((loc->flags & (KMP_IDENT_ATOMIC_REDUCE)) == (KMP_IDENT_ATOMIC_REDUCE)) #define FAST_REDUCTION_TREE_METHOD_GENERATED ((reduce_data) && (reduce_func)) retval = critical_reduce_block; // another choice of getting a team size (with 1 dynamic deference) is slower team_size = __kmp_get_team_num_threads(global_tid); if (team_size == 1) { retval = empty_reduce_block; } else { int atomic_available = FAST_REDUCTION_ATOMIC_METHOD_GENERATED; #if KMP_ARCH_X86_64 || KMP_ARCH_PPC64 || KMP_ARCH_AARCH64 || \ KMP_ARCH_MIPS64 || KMP_ARCH_RISCV64 #if KMP_OS_LINUX || KMP_OS_DRAGONFLY || KMP_OS_FREEBSD || KMP_OS_NETBSD || \ KMP_OS_OPENBSD || KMP_OS_WINDOWS || KMP_OS_DARWIN || KMP_OS_HURD int teamsize_cutoff = 4; #if KMP_MIC_SUPPORTED if (__kmp_mic_type != non_mic) { teamsize_cutoff = 8; } #endif int tree_available = FAST_REDUCTION_TREE_METHOD_GENERATED; if (tree_available) { if (team_size <= teamsize_cutoff) { if (atomic_available) { retval = atomic_reduce_block; } } else { retval = TREE_REDUCE_BLOCK_WITH_REDUCTION_BARRIER; } } else if (atomic_available) { retval = atomic_reduce_block; } #else #error "Unknown or unsupported OS" #endif // KMP_OS_LINUX || KMP_OS_DRAGONFLY || KMP_OS_FREEBSD || KMP_OS_NETBSD || // KMP_OS_OPENBSD || KMP_OS_WINDOWS || KMP_OS_DARWIN || KMP_OS_HURD #elif KMP_ARCH_X86 || KMP_ARCH_ARM || KMP_ARCH_AARCH || KMP_ARCH_MIPS #if KMP_OS_LINUX || KMP_OS_FREEBSD || KMP_OS_WINDOWS || KMP_OS_HURD // basic tuning if (atomic_available) { if (num_vars <= 2) { // && ( team_size <= 8 ) due to false-sharing ??? retval = atomic_reduce_block; } } // otherwise: use critical section #elif KMP_OS_DARWIN int tree_available = FAST_REDUCTION_TREE_METHOD_GENERATED; if (atomic_available && (num_vars <= 3)) { retval = atomic_reduce_block; } else if (tree_available) { if ((reduce_size > (9 * sizeof(kmp_real64))) && (reduce_size < (2000 * sizeof(kmp_real64)))) { retval = TREE_REDUCE_BLOCK_WITH_PLAIN_BARRIER; } } // otherwise: use critical section #else #error "Unknown or unsupported OS" #endif #else #error "Unknown or unsupported architecture" #endif } // KMP_FORCE_REDUCTION // If the team is serialized (team_size == 1), ignore the forced reduction // method and stay with the unsynchronized method (empty_reduce_block) if (__kmp_force_reduction_method != reduction_method_not_defined && team_size != 1) { PACKED_REDUCTION_METHOD_T forced_retval = critical_reduce_block; int atomic_available, tree_available; switch ((forced_retval = __kmp_force_reduction_method)) { case critical_reduce_block: KMP_ASSERT(lck); // lck should be != 0 break; case atomic_reduce_block: atomic_available = FAST_REDUCTION_ATOMIC_METHOD_GENERATED; if (!atomic_available) { KMP_WARNING(RedMethodNotSupported, "atomic"); forced_retval = critical_reduce_block; } break; case tree_reduce_block: tree_available = FAST_REDUCTION_TREE_METHOD_GENERATED; if (!tree_available) { KMP_WARNING(RedMethodNotSupported, "tree"); forced_retval = critical_reduce_block; } else { #if KMP_FAST_REDUCTION_BARRIER forced_retval = TREE_REDUCE_BLOCK_WITH_REDUCTION_BARRIER; #endif } break; default: KMP_ASSERT(0); // "unsupported method specified" } retval = forced_retval; } KA_TRACE(10, ("reduction method selected=%08x\n", retval)); #undef FAST_REDUCTION_TREE_METHOD_GENERATED #undef FAST_REDUCTION_ATOMIC_METHOD_GENERATED return (retval); } // this function is for testing set/get/determine reduce method kmp_int32 __kmp_get_reduce_method(void) { return ((__kmp_entry_thread()->th.th_local.packed_reduction_method) >> 8); } // Soft pause sets up threads to ignore blocktime and just go to sleep. // Spin-wait code checks __kmp_pause_status and reacts accordingly. void __kmp_soft_pause() { __kmp_pause_status = kmp_soft_paused; } // Hard pause shuts down the runtime completely. Resume happens naturally when // OpenMP is used subsequently. void __kmp_hard_pause() { __kmp_pause_status = kmp_hard_paused; __kmp_internal_end_thread(-1); } // Soft resume sets __kmp_pause_status, and wakes up all threads. void __kmp_resume_if_soft_paused() { if (__kmp_pause_status == kmp_soft_paused) { __kmp_pause_status = kmp_not_paused; for (int gtid = 1; gtid < __kmp_threads_capacity; ++gtid) { kmp_info_t *thread = __kmp_threads[gtid]; if (thread) { // Wake it if sleeping kmp_flag_64 fl(&thread->th.th_bar[bs_forkjoin_barrier].bb.b_go, thread); if (fl.is_sleeping()) fl.resume(gtid); else if (__kmp_try_suspend_mx(thread)) { // got suspend lock __kmp_unlock_suspend_mx(thread); // unlock it; it won't sleep } else { // thread holds the lock and may sleep soon do { // until either the thread sleeps, or we can get the lock if (fl.is_sleeping()) { fl.resume(gtid); break; } else if (__kmp_try_suspend_mx(thread)) { __kmp_unlock_suspend_mx(thread); break; } } while (1); } } } } } // This function is called via __kmpc_pause_resource. Returns 0 if successful. // TODO: add warning messages int __kmp_pause_resource(kmp_pause_status_t level) { if (level == kmp_not_paused) { // requesting resume if (__kmp_pause_status == kmp_not_paused) { // error message about runtime not being paused, so can't resume return 1; } else { KMP_DEBUG_ASSERT(__kmp_pause_status == kmp_soft_paused || __kmp_pause_status == kmp_hard_paused); __kmp_pause_status = kmp_not_paused; return 0; } } else if (level == kmp_soft_paused) { // requesting soft pause if (__kmp_pause_status != kmp_not_paused) { // error message about already being paused return 1; } else { __kmp_soft_pause(); return 0; } } else if (level == kmp_hard_paused) { // requesting hard pause if (__kmp_pause_status != kmp_not_paused) { // error message about already being paused return 1; } else { __kmp_hard_pause(); return 0; } } else { // error message about invalid level return 1; } } void __kmp_omp_display_env(int verbose) { __kmp_acquire_bootstrap_lock(&__kmp_initz_lock); if (__kmp_init_serial == 0) __kmp_do_serial_initialize(); __kmp_display_env_impl(!verbose, verbose); __kmp_release_bootstrap_lock(&__kmp_initz_lock); }