Samuel Antao | 45bfe4c | 2016-02-08 15:59:20 +0000 | [diff] [blame] | 1 | //===---- CGOpenMPRuntimeNVPTX.cpp - Interface to OpenMP NVPTX Runtimes ---===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This provides a class for OpenMP runtime code generation specialized to NVPTX |
| 11 | // targets. |
| 12 | // |
| 13 | //===----------------------------------------------------------------------===// |
| 14 | |
| 15 | #include "CGOpenMPRuntimeNVPTX.h" |
Alexey Bataev | c5b1d32 | 2016-03-04 09:22:22 +0000 | [diff] [blame] | 16 | #include "clang/AST/DeclOpenMP.h" |
Carlo Bertolli | c687225 | 2016-04-04 15:55:02 +0000 | [diff] [blame] | 17 | #include "CodeGenFunction.h" |
| 18 | #include "clang/AST/StmtOpenMP.h" |
Samuel Antao | 45bfe4c | 2016-02-08 15:59:20 +0000 | [diff] [blame] | 19 | |
| 20 | using namespace clang; |
| 21 | using namespace CodeGen; |
| 22 | |
Arpith Chacko Jacob | ccf2f73 | 2017-01-03 20:19:56 +0000 | [diff] [blame] | 23 | namespace { |
| 24 | enum OpenMPRTLFunctionNVPTX { |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 25 | /// \brief Call to void __kmpc_kernel_init(kmp_int32 thread_limit); |
Arpith Chacko Jacob | ccf2f73 | 2017-01-03 20:19:56 +0000 | [diff] [blame] | 26 | OMPRTL_NVPTX__kmpc_kernel_init, |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 27 | /// \brief Call to void __kmpc_kernel_deinit(); |
| 28 | OMPRTL_NVPTX__kmpc_kernel_deinit, |
Arpith Chacko Jacob | 44a87c9 | 2017-01-18 19:35:00 +0000 | [diff] [blame] | 29 | /// \brief Call to void __kmpc_spmd_kernel_init(kmp_int32 thread_limit, |
| 30 | /// short RequiresOMPRuntime, short RequiresDataSharing); |
| 31 | OMPRTL_NVPTX__kmpc_spmd_kernel_init, |
| 32 | /// \brief Call to void __kmpc_spmd_kernel_deinit(); |
| 33 | OMPRTL_NVPTX__kmpc_spmd_kernel_deinit, |
Arpith Chacko Jacob | bb36fe8 | 2017-01-10 15:42:51 +0000 | [diff] [blame] | 34 | /// \brief Call to void __kmpc_kernel_prepare_parallel(void |
| 35 | /// *outlined_function); |
| 36 | OMPRTL_NVPTX__kmpc_kernel_prepare_parallel, |
| 37 | /// \brief Call to bool __kmpc_kernel_parallel(void **outlined_function); |
| 38 | OMPRTL_NVPTX__kmpc_kernel_parallel, |
| 39 | /// \brief Call to void __kmpc_kernel_end_parallel(); |
| 40 | OMPRTL_NVPTX__kmpc_kernel_end_parallel, |
| 41 | /// Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32 |
| 42 | /// global_tid); |
| 43 | OMPRTL_NVPTX__kmpc_serialized_parallel, |
| 44 | /// Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32 |
| 45 | /// global_tid); |
| 46 | OMPRTL_NVPTX__kmpc_end_serialized_parallel, |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 47 | /// \brief Call to int32_t __kmpc_shuffle_int32(int32_t element, |
| 48 | /// int16_t lane_offset, int16_t warp_size); |
| 49 | OMPRTL_NVPTX__kmpc_shuffle_int32, |
| 50 | /// \brief Call to int64_t __kmpc_shuffle_int64(int64_t element, |
| 51 | /// int16_t lane_offset, int16_t warp_size); |
| 52 | OMPRTL_NVPTX__kmpc_shuffle_int64, |
| 53 | /// \brief Call to __kmpc_nvptx_parallel_reduce_nowait(kmp_int32 |
| 54 | /// global_tid, kmp_int32 num_vars, size_t reduce_size, void* reduce_data, |
| 55 | /// void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t |
| 56 | /// lane_offset, int16_t shortCircuit), |
| 57 | /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num)); |
| 58 | OMPRTL_NVPTX__kmpc_parallel_reduce_nowait, |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 59 | /// \brief Call to __kmpc_nvptx_teams_reduce_nowait(int32_t global_tid, |
| 60 | /// int32_t num_vars, size_t reduce_size, void *reduce_data, |
| 61 | /// void (*kmp_ShuffleReductFctPtr)(void *rhs, int16_t lane_id, int16_t |
| 62 | /// lane_offset, int16_t shortCircuit), |
| 63 | /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num), |
| 64 | /// void (*kmp_CopyToScratchpadFctPtr)(void *reduce_data, void * scratchpad, |
| 65 | /// int32_t index, int32_t width), |
| 66 | /// void (*kmp_LoadReduceFctPtr)(void *reduce_data, void * scratchpad, int32_t |
| 67 | /// index, int32_t width, int32_t reduce)) |
| 68 | OMPRTL_NVPTX__kmpc_teams_reduce_nowait, |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 69 | /// \brief Call to __kmpc_nvptx_end_reduce_nowait(int32_t global_tid); |
| 70 | OMPRTL_NVPTX__kmpc_end_reduce_nowait |
Arpith Chacko Jacob | ccf2f73 | 2017-01-03 20:19:56 +0000 | [diff] [blame] | 71 | }; |
Arpith Chacko Jacob | bb36fe8 | 2017-01-10 15:42:51 +0000 | [diff] [blame] | 72 | |
| 73 | /// Pre(post)-action for different OpenMP constructs specialized for NVPTX. |
| 74 | class NVPTXActionTy final : public PrePostActionTy { |
| 75 | llvm::Value *EnterCallee; |
| 76 | ArrayRef<llvm::Value *> EnterArgs; |
| 77 | llvm::Value *ExitCallee; |
| 78 | ArrayRef<llvm::Value *> ExitArgs; |
| 79 | bool Conditional; |
| 80 | llvm::BasicBlock *ContBlock = nullptr; |
| 81 | |
| 82 | public: |
| 83 | NVPTXActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs, |
| 84 | llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs, |
| 85 | bool Conditional = false) |
| 86 | : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee), |
| 87 | ExitArgs(ExitArgs), Conditional(Conditional) {} |
| 88 | void Enter(CodeGenFunction &CGF) override { |
| 89 | llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs); |
| 90 | if (Conditional) { |
| 91 | llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes); |
| 92 | auto *ThenBlock = CGF.createBasicBlock("omp_if.then"); |
| 93 | ContBlock = CGF.createBasicBlock("omp_if.end"); |
| 94 | // Generate the branch (If-stmt) |
| 95 | CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock); |
| 96 | CGF.EmitBlock(ThenBlock); |
| 97 | } |
| 98 | } |
| 99 | void Done(CodeGenFunction &CGF) { |
| 100 | // Emit the rest of blocks/branches |
| 101 | CGF.EmitBranch(ContBlock); |
| 102 | CGF.EmitBlock(ContBlock, true); |
| 103 | } |
| 104 | void Exit(CodeGenFunction &CGF) override { |
| 105 | CGF.EmitRuntimeCall(ExitCallee, ExitArgs); |
| 106 | } |
| 107 | }; |
Arpith Chacko Jacob | 44a87c9 | 2017-01-18 19:35:00 +0000 | [diff] [blame] | 108 | |
| 109 | // A class to track the execution mode when codegening directives within |
| 110 | // a target region. The appropriate mode (generic/spmd) is set on entry |
| 111 | // to the target region and used by containing directives such as 'parallel' |
| 112 | // to emit optimized code. |
| 113 | class ExecutionModeRAII { |
| 114 | private: |
| 115 | CGOpenMPRuntimeNVPTX::ExecutionMode SavedMode; |
| 116 | CGOpenMPRuntimeNVPTX::ExecutionMode &Mode; |
| 117 | |
| 118 | public: |
| 119 | ExecutionModeRAII(CGOpenMPRuntimeNVPTX::ExecutionMode &Mode, |
| 120 | CGOpenMPRuntimeNVPTX::ExecutionMode NewMode) |
| 121 | : Mode(Mode) { |
| 122 | SavedMode = Mode; |
| 123 | Mode = NewMode; |
| 124 | } |
| 125 | ~ExecutionModeRAII() { Mode = SavedMode; } |
| 126 | }; |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 127 | |
| 128 | /// GPU Configuration: This information can be derived from cuda registers, |
| 129 | /// however, providing compile time constants helps generate more efficient |
| 130 | /// code. For all practical purposes this is fine because the configuration |
| 131 | /// is the same for all known NVPTX architectures. |
| 132 | enum MachineConfiguration : unsigned { |
| 133 | WarpSize = 32, |
| 134 | /// Number of bits required to represent a lane identifier, which is |
| 135 | /// computed as log_2(WarpSize). |
| 136 | LaneIDBits = 5, |
| 137 | LaneIDMask = WarpSize - 1, |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 138 | |
| 139 | /// Global memory alignment for performance. |
| 140 | GlobalMemoryAlignment = 256, |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 141 | }; |
| 142 | |
| 143 | enum NamedBarrier : unsigned { |
| 144 | /// Synchronize on this barrier #ID using a named barrier primitive. |
| 145 | /// Only the subset of active threads in a parallel region arrive at the |
| 146 | /// barrier. |
| 147 | NB_Parallel = 1, |
| 148 | }; |
Arpith Chacko Jacob | bb36fe8 | 2017-01-10 15:42:51 +0000 | [diff] [blame] | 149 | } // anonymous namespace |
Arpith Chacko Jacob | ccf2f73 | 2017-01-03 20:19:56 +0000 | [diff] [blame] | 150 | |
| 151 | /// Get the GPU warp size. |
| 152 | static llvm::Value *getNVPTXWarpSize(CodeGenFunction &CGF) { |
Alexey Bataev | 3c595a6 | 2017-08-14 15:01:03 +0000 | [diff] [blame] | 153 | return CGF.EmitRuntimeCall( |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 154 | llvm::Intrinsic::getDeclaration( |
Arpith Chacko Jacob | ccf2f73 | 2017-01-03 20:19:56 +0000 | [diff] [blame] | 155 | &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_warpsize), |
Alexey Bataev | 3c595a6 | 2017-08-14 15:01:03 +0000 | [diff] [blame] | 156 | "nvptx_warp_size"); |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 157 | } |
| 158 | |
Arpith Chacko Jacob | ccf2f73 | 2017-01-03 20:19:56 +0000 | [diff] [blame] | 159 | /// Get the id of the current thread on the GPU. |
| 160 | static llvm::Value *getNVPTXThreadID(CodeGenFunction &CGF) { |
Alexey Bataev | 3c595a6 | 2017-08-14 15:01:03 +0000 | [diff] [blame] | 161 | return CGF.EmitRuntimeCall( |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 162 | llvm::Intrinsic::getDeclaration( |
Arpith Chacko Jacob | ccf2f73 | 2017-01-03 20:19:56 +0000 | [diff] [blame] | 163 | &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_tid_x), |
Alexey Bataev | 3c595a6 | 2017-08-14 15:01:03 +0000 | [diff] [blame] | 164 | "nvptx_tid"); |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 165 | } |
| 166 | |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 167 | /// Get the id of the warp in the block. |
| 168 | /// We assume that the warp size is 32, which is always the case |
| 169 | /// on the NVPTX device, to generate more efficient code. |
| 170 | static llvm::Value *getNVPTXWarpID(CodeGenFunction &CGF) { |
| 171 | CGBuilderTy &Bld = CGF.Builder; |
| 172 | return Bld.CreateAShr(getNVPTXThreadID(CGF), LaneIDBits, "nvptx_warp_id"); |
| 173 | } |
| 174 | |
| 175 | /// Get the id of the current lane in the Warp. |
| 176 | /// We assume that the warp size is 32, which is always the case |
| 177 | /// on the NVPTX device, to generate more efficient code. |
| 178 | static llvm::Value *getNVPTXLaneID(CodeGenFunction &CGF) { |
| 179 | CGBuilderTy &Bld = CGF.Builder; |
| 180 | return Bld.CreateAnd(getNVPTXThreadID(CGF), Bld.getInt32(LaneIDMask), |
| 181 | "nvptx_lane_id"); |
| 182 | } |
| 183 | |
Arpith Chacko Jacob | ccf2f73 | 2017-01-03 20:19:56 +0000 | [diff] [blame] | 184 | /// Get the maximum number of threads in a block of the GPU. |
| 185 | static llvm::Value *getNVPTXNumThreads(CodeGenFunction &CGF) { |
Alexey Bataev | 3c595a6 | 2017-08-14 15:01:03 +0000 | [diff] [blame] | 186 | return CGF.EmitRuntimeCall( |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 187 | llvm::Intrinsic::getDeclaration( |
Arpith Chacko Jacob | ccf2f73 | 2017-01-03 20:19:56 +0000 | [diff] [blame] | 188 | &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_ntid_x), |
Alexey Bataev | 3c595a6 | 2017-08-14 15:01:03 +0000 | [diff] [blame] | 189 | "nvptx_num_threads"); |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 190 | } |
| 191 | |
Arpith Chacko Jacob | ccf2f73 | 2017-01-03 20:19:56 +0000 | [diff] [blame] | 192 | /// Get barrier to synchronize all threads in a block. |
| 193 | static void getNVPTXCTABarrier(CodeGenFunction &CGF) { |
Alexey Bataev | 3c595a6 | 2017-08-14 15:01:03 +0000 | [diff] [blame] | 194 | CGF.EmitRuntimeCall(llvm::Intrinsic::getDeclaration( |
Arpith Chacko Jacob | ccf2f73 | 2017-01-03 20:19:56 +0000 | [diff] [blame] | 195 | &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_barrier0)); |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 196 | } |
| 197 | |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 198 | /// Get barrier #ID to synchronize selected (multiple of warp size) threads in |
| 199 | /// a CTA. |
| 200 | static void getNVPTXBarrier(CodeGenFunction &CGF, int ID, |
| 201 | llvm::Value *NumThreads) { |
| 202 | CGBuilderTy &Bld = CGF.Builder; |
| 203 | llvm::Value *Args[] = {Bld.getInt32(ID), NumThreads}; |
Alexey Bataev | 3c595a6 | 2017-08-14 15:01:03 +0000 | [diff] [blame] | 204 | CGF.EmitRuntimeCall(llvm::Intrinsic::getDeclaration( |
| 205 | &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_barrier), |
| 206 | Args); |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 207 | } |
| 208 | |
Arpith Chacko Jacob | ccf2f73 | 2017-01-03 20:19:56 +0000 | [diff] [blame] | 209 | /// Synchronize all GPU threads in a block. |
| 210 | static void syncCTAThreads(CodeGenFunction &CGF) { getNVPTXCTABarrier(CGF); } |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 211 | |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 212 | /// Synchronize worker threads in a parallel region. |
| 213 | static void syncParallelThreads(CodeGenFunction &CGF, llvm::Value *NumThreads) { |
| 214 | return getNVPTXBarrier(CGF, NB_Parallel, NumThreads); |
| 215 | } |
| 216 | |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 217 | /// Get the value of the thread_limit clause in the teams directive. |
Arpith Chacko Jacob | 44a87c9 | 2017-01-18 19:35:00 +0000 | [diff] [blame] | 218 | /// For the 'generic' execution mode, the runtime encodes thread_limit in |
| 219 | /// the launch parameters, always starting thread_limit+warpSize threads per |
| 220 | /// CTA. The threads in the last warp are reserved for master execution. |
| 221 | /// For the 'spmd' execution mode, all threads in a CTA are part of the team. |
| 222 | static llvm::Value *getThreadLimit(CodeGenFunction &CGF, |
| 223 | bool IsInSpmdExecutionMode = false) { |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 224 | CGBuilderTy &Bld = CGF.Builder; |
Arpith Chacko Jacob | 44a87c9 | 2017-01-18 19:35:00 +0000 | [diff] [blame] | 225 | return IsInSpmdExecutionMode |
| 226 | ? getNVPTXNumThreads(CGF) |
| 227 | : Bld.CreateSub(getNVPTXNumThreads(CGF), getNVPTXWarpSize(CGF), |
| 228 | "thread_limit"); |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 229 | } |
| 230 | |
Arpith Chacko Jacob | ccf2f73 | 2017-01-03 20:19:56 +0000 | [diff] [blame] | 231 | /// Get the thread id of the OMP master thread. |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 232 | /// The master thread id is the first thread (lane) of the last warp in the |
| 233 | /// GPU block. Warp size is assumed to be some power of 2. |
| 234 | /// Thread id is 0 indexed. |
| 235 | /// E.g: If NumThreads is 33, master id is 32. |
| 236 | /// If NumThreads is 64, master id is 32. |
| 237 | /// If NumThreads is 1024, master id is 992. |
Arpith Chacko Jacob | ccf2f73 | 2017-01-03 20:19:56 +0000 | [diff] [blame] | 238 | static llvm::Value *getMasterThreadID(CodeGenFunction &CGF) { |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 239 | CGBuilderTy &Bld = CGF.Builder; |
| 240 | llvm::Value *NumThreads = getNVPTXNumThreads(CGF); |
| 241 | |
| 242 | // We assume that the warp size is a power of 2. |
| 243 | llvm::Value *Mask = Bld.CreateSub(getNVPTXWarpSize(CGF), Bld.getInt32(1)); |
| 244 | |
| 245 | return Bld.CreateAnd(Bld.CreateSub(NumThreads, Bld.getInt32(1)), |
| 246 | Bld.CreateNot(Mask), "master_tid"); |
| 247 | } |
| 248 | |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 249 | CGOpenMPRuntimeNVPTX::WorkerFunctionState::WorkerFunctionState( |
| 250 | CodeGenModule &CGM) |
| 251 | : WorkerFn(nullptr), CGFI(nullptr) { |
| 252 | createWorkerFunction(CGM); |
Vasileios Kalintiris | e5c0959 | 2016-03-22 10:41:20 +0000 | [diff] [blame] | 253 | } |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 254 | |
| 255 | void CGOpenMPRuntimeNVPTX::WorkerFunctionState::createWorkerFunction( |
| 256 | CodeGenModule &CGM) { |
| 257 | // Create an worker function with no arguments. |
| 258 | CGFI = &CGM.getTypes().arrangeNullaryFunction(); |
| 259 | |
| 260 | WorkerFn = llvm::Function::Create( |
| 261 | CGM.getTypes().GetFunctionType(*CGFI), llvm::GlobalValue::InternalLinkage, |
| 262 | /* placeholder */ "_worker", &CGM.getModule()); |
| 263 | CGM.SetInternalFunctionAttributes(/*D=*/nullptr, WorkerFn, *CGFI); |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 264 | } |
| 265 | |
Arpith Chacko Jacob | 44a87c9 | 2017-01-18 19:35:00 +0000 | [diff] [blame] | 266 | bool CGOpenMPRuntimeNVPTX::isInSpmdExecutionMode() const { |
| 267 | return CurrentExecutionMode == CGOpenMPRuntimeNVPTX::ExecutionMode::Spmd; |
| 268 | } |
| 269 | |
| 270 | static CGOpenMPRuntimeNVPTX::ExecutionMode |
| 271 | getExecutionModeForDirective(CodeGenModule &CGM, |
| 272 | const OMPExecutableDirective &D) { |
| 273 | OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind(); |
| 274 | switch (DirectiveKind) { |
| 275 | case OMPD_target: |
Arpith Chacko Jacob | cca61a3 | 2017-01-26 15:43:27 +0000 | [diff] [blame] | 276 | case OMPD_target_teams: |
Arpith Chacko Jacob | 44a87c9 | 2017-01-18 19:35:00 +0000 | [diff] [blame] | 277 | return CGOpenMPRuntimeNVPTX::ExecutionMode::Generic; |
| 278 | case OMPD_target_parallel: |
| 279 | return CGOpenMPRuntimeNVPTX::ExecutionMode::Spmd; |
| 280 | default: |
| 281 | llvm_unreachable("Unsupported directive on NVPTX device."); |
| 282 | } |
| 283 | llvm_unreachable("Unsupported directive on NVPTX device."); |
| 284 | } |
| 285 | |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 286 | void CGOpenMPRuntimeNVPTX::emitGenericKernel(const OMPExecutableDirective &D, |
| 287 | StringRef ParentName, |
| 288 | llvm::Function *&OutlinedFn, |
| 289 | llvm::Constant *&OutlinedFnID, |
| 290 | bool IsOffloadEntry, |
| 291 | const RegionCodeGenTy &CodeGen) { |
Arpith Chacko Jacob | 44a87c9 | 2017-01-18 19:35:00 +0000 | [diff] [blame] | 292 | ExecutionModeRAII ModeRAII(CurrentExecutionMode, |
| 293 | CGOpenMPRuntimeNVPTX::ExecutionMode::Generic); |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 294 | EntryFunctionState EST; |
| 295 | WorkerFunctionState WST(CGM); |
Arpith Chacko Jacob | bb36fe8 | 2017-01-10 15:42:51 +0000 | [diff] [blame] | 296 | Work.clear(); |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 297 | |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 298 | // Emit target region as a standalone region. |
| 299 | class NVPTXPrePostActionTy : public PrePostActionTy { |
| 300 | CGOpenMPRuntimeNVPTX &RT; |
| 301 | CGOpenMPRuntimeNVPTX::EntryFunctionState &EST; |
| 302 | CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST; |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 303 | |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 304 | public: |
| 305 | NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT, |
| 306 | CGOpenMPRuntimeNVPTX::EntryFunctionState &EST, |
| 307 | CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST) |
| 308 | : RT(RT), EST(EST), WST(WST) {} |
| 309 | void Enter(CodeGenFunction &CGF) override { |
| 310 | RT.emitGenericEntryHeader(CGF, EST, WST); |
| 311 | } |
| 312 | void Exit(CodeGenFunction &CGF) override { |
| 313 | RT.emitGenericEntryFooter(CGF, EST); |
| 314 | } |
| 315 | } Action(*this, EST, WST); |
| 316 | CodeGen.setAction(Action); |
| 317 | emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID, |
| 318 | IsOffloadEntry, CodeGen); |
| 319 | |
| 320 | // Create the worker function |
| 321 | emitWorkerFunction(WST); |
| 322 | |
| 323 | // Now change the name of the worker function to correspond to this target |
| 324 | // region's entry function. |
| 325 | WST.WorkerFn->setName(OutlinedFn->getName() + "_worker"); |
| 326 | } |
| 327 | |
| 328 | // Setup NVPTX threads for master-worker OpenMP scheme. |
| 329 | void CGOpenMPRuntimeNVPTX::emitGenericEntryHeader(CodeGenFunction &CGF, |
| 330 | EntryFunctionState &EST, |
| 331 | WorkerFunctionState &WST) { |
| 332 | CGBuilderTy &Bld = CGF.Builder; |
| 333 | |
| 334 | llvm::BasicBlock *WorkerBB = CGF.createBasicBlock(".worker"); |
| 335 | llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck"); |
| 336 | llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master"); |
| 337 | EST.ExitBB = CGF.createBasicBlock(".exit"); |
| 338 | |
| 339 | auto *IsWorker = |
| 340 | Bld.CreateICmpULT(getNVPTXThreadID(CGF), getThreadLimit(CGF)); |
| 341 | Bld.CreateCondBr(IsWorker, WorkerBB, MasterCheckBB); |
| 342 | |
| 343 | CGF.EmitBlock(WorkerBB); |
Alexey Bataev | 3c595a6 | 2017-08-14 15:01:03 +0000 | [diff] [blame] | 344 | emitCall(CGF, WST.WorkerFn); |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 345 | CGF.EmitBranch(EST.ExitBB); |
| 346 | |
| 347 | CGF.EmitBlock(MasterCheckBB); |
| 348 | auto *IsMaster = |
| 349 | Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF)); |
| 350 | Bld.CreateCondBr(IsMaster, MasterBB, EST.ExitBB); |
| 351 | |
| 352 | CGF.EmitBlock(MasterBB); |
| 353 | // First action in sequential region: |
| 354 | // Initialize the state of the OpenMP runtime library on the GPU. |
| 355 | llvm::Value *Args[] = {getThreadLimit(CGF)}; |
| 356 | CGF.EmitRuntimeCall( |
| 357 | createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_init), Args); |
| 358 | } |
| 359 | |
| 360 | void CGOpenMPRuntimeNVPTX::emitGenericEntryFooter(CodeGenFunction &CGF, |
| 361 | EntryFunctionState &EST) { |
| 362 | if (!EST.ExitBB) |
| 363 | EST.ExitBB = CGF.createBasicBlock(".exit"); |
| 364 | |
| 365 | llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".termination.notifier"); |
| 366 | CGF.EmitBranch(TerminateBB); |
| 367 | |
| 368 | CGF.EmitBlock(TerminateBB); |
| 369 | // Signal termination condition. |
| 370 | CGF.EmitRuntimeCall( |
| 371 | createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_deinit), None); |
| 372 | // Barrier to terminate worker threads. |
| 373 | syncCTAThreads(CGF); |
| 374 | // Master thread jumps to exit point. |
| 375 | CGF.EmitBranch(EST.ExitBB); |
| 376 | |
| 377 | CGF.EmitBlock(EST.ExitBB); |
| 378 | EST.ExitBB = nullptr; |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 379 | } |
| 380 | |
Arpith Chacko Jacob | 44a87c9 | 2017-01-18 19:35:00 +0000 | [diff] [blame] | 381 | void CGOpenMPRuntimeNVPTX::emitSpmdKernel(const OMPExecutableDirective &D, |
| 382 | StringRef ParentName, |
| 383 | llvm::Function *&OutlinedFn, |
| 384 | llvm::Constant *&OutlinedFnID, |
| 385 | bool IsOffloadEntry, |
| 386 | const RegionCodeGenTy &CodeGen) { |
| 387 | ExecutionModeRAII ModeRAII(CurrentExecutionMode, |
| 388 | CGOpenMPRuntimeNVPTX::ExecutionMode::Spmd); |
| 389 | EntryFunctionState EST; |
| 390 | |
| 391 | // Emit target region as a standalone region. |
| 392 | class NVPTXPrePostActionTy : public PrePostActionTy { |
| 393 | CGOpenMPRuntimeNVPTX &RT; |
| 394 | CGOpenMPRuntimeNVPTX::EntryFunctionState &EST; |
| 395 | const OMPExecutableDirective &D; |
| 396 | |
| 397 | public: |
| 398 | NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT, |
| 399 | CGOpenMPRuntimeNVPTX::EntryFunctionState &EST, |
| 400 | const OMPExecutableDirective &D) |
| 401 | : RT(RT), EST(EST), D(D) {} |
| 402 | void Enter(CodeGenFunction &CGF) override { |
| 403 | RT.emitSpmdEntryHeader(CGF, EST, D); |
| 404 | } |
| 405 | void Exit(CodeGenFunction &CGF) override { |
| 406 | RT.emitSpmdEntryFooter(CGF, EST); |
| 407 | } |
| 408 | } Action(*this, EST, D); |
| 409 | CodeGen.setAction(Action); |
| 410 | emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID, |
| 411 | IsOffloadEntry, CodeGen); |
| 412 | return; |
| 413 | } |
| 414 | |
| 415 | void CGOpenMPRuntimeNVPTX::emitSpmdEntryHeader( |
| 416 | CodeGenFunction &CGF, EntryFunctionState &EST, |
| 417 | const OMPExecutableDirective &D) { |
| 418 | auto &Bld = CGF.Builder; |
| 419 | |
| 420 | // Setup BBs in entry function. |
| 421 | llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute"); |
| 422 | EST.ExitBB = CGF.createBasicBlock(".exit"); |
| 423 | |
| 424 | // Initialize the OMP state in the runtime; called by all active threads. |
| 425 | // TODO: Set RequiresOMPRuntime and RequiresDataSharing parameters |
| 426 | // based on code analysis of the target region. |
| 427 | llvm::Value *Args[] = {getThreadLimit(CGF, /*IsInSpmdExecutionMode=*/true), |
| 428 | /*RequiresOMPRuntime=*/Bld.getInt16(1), |
| 429 | /*RequiresDataSharing=*/Bld.getInt16(1)}; |
| 430 | CGF.EmitRuntimeCall( |
| 431 | createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_init), Args); |
| 432 | CGF.EmitBranch(ExecuteBB); |
| 433 | |
| 434 | CGF.EmitBlock(ExecuteBB); |
| 435 | } |
| 436 | |
| 437 | void CGOpenMPRuntimeNVPTX::emitSpmdEntryFooter(CodeGenFunction &CGF, |
| 438 | EntryFunctionState &EST) { |
| 439 | if (!EST.ExitBB) |
| 440 | EST.ExitBB = CGF.createBasicBlock(".exit"); |
| 441 | |
| 442 | llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit"); |
| 443 | CGF.EmitBranch(OMPDeInitBB); |
| 444 | |
| 445 | CGF.EmitBlock(OMPDeInitBB); |
| 446 | // DeInitialize the OMP state in the runtime; called by all active threads. |
| 447 | CGF.EmitRuntimeCall( |
| 448 | createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_deinit), None); |
| 449 | CGF.EmitBranch(EST.ExitBB); |
| 450 | |
| 451 | CGF.EmitBlock(EST.ExitBB); |
| 452 | EST.ExitBB = nullptr; |
| 453 | } |
| 454 | |
| 455 | // Create a unique global variable to indicate the execution mode of this target |
| 456 | // region. The execution mode is either 'generic', or 'spmd' depending on the |
| 457 | // target directive. This variable is picked up by the offload library to setup |
| 458 | // the device appropriately before kernel launch. If the execution mode is |
| 459 | // 'generic', the runtime reserves one warp for the master, otherwise, all |
| 460 | // warps participate in parallel work. |
| 461 | static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name, |
| 462 | CGOpenMPRuntimeNVPTX::ExecutionMode Mode) { |
| 463 | (void)new llvm::GlobalVariable( |
| 464 | CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true, |
| 465 | llvm::GlobalValue::WeakAnyLinkage, |
| 466 | llvm::ConstantInt::get(CGM.Int8Ty, Mode), Name + Twine("_exec_mode")); |
| 467 | } |
| 468 | |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 469 | void CGOpenMPRuntimeNVPTX::emitWorkerFunction(WorkerFunctionState &WST) { |
| 470 | auto &Ctx = CGM.getContext(); |
| 471 | |
| 472 | CodeGenFunction CGF(CGM, /*suppressNewContext=*/true); |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 473 | CGF.disableDebugInfo(); |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 474 | CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, *WST.CGFI, {}); |
| 475 | emitWorkerLoop(CGF, WST); |
| 476 | CGF.FinishFunction(); |
| 477 | } |
| 478 | |
| 479 | void CGOpenMPRuntimeNVPTX::emitWorkerLoop(CodeGenFunction &CGF, |
| 480 | WorkerFunctionState &WST) { |
| 481 | // |
| 482 | // The workers enter this loop and wait for parallel work from the master. |
| 483 | // When the master encounters a parallel region it sets up the work + variable |
| 484 | // arguments, and wakes up the workers. The workers first check to see if |
| 485 | // they are required for the parallel region, i.e., within the # of requested |
| 486 | // parallel threads. The activated workers load the variable arguments and |
| 487 | // execute the parallel work. |
| 488 | // |
| 489 | |
| 490 | CGBuilderTy &Bld = CGF.Builder; |
| 491 | |
| 492 | llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work"); |
| 493 | llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers"); |
| 494 | llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel"); |
| 495 | llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel"); |
| 496 | llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel"); |
| 497 | llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit"); |
| 498 | |
| 499 | CGF.EmitBranch(AwaitBB); |
| 500 | |
| 501 | // Workers wait for work from master. |
| 502 | CGF.EmitBlock(AwaitBB); |
| 503 | // Wait for parallel work |
| 504 | syncCTAThreads(CGF); |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 505 | |
| 506 | Address WorkFn = |
| 507 | CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn"); |
| 508 | Address ExecStatus = |
| 509 | CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status"); |
| 510 | CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0)); |
| 511 | CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy)); |
| 512 | |
Arpith Chacko Jacob | bb36fe8 | 2017-01-10 15:42:51 +0000 | [diff] [blame] | 513 | llvm::Value *Args[] = {WorkFn.getPointer()}; |
| 514 | llvm::Value *Ret = CGF.EmitRuntimeCall( |
| 515 | createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args); |
| 516 | Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus); |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 517 | |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 518 | // On termination condition (workid == 0), exit loop. |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 519 | llvm::Value *ShouldTerminate = |
| 520 | Bld.CreateIsNull(Bld.CreateLoad(WorkFn), "should_terminate"); |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 521 | Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB); |
| 522 | |
| 523 | // Activate requested workers. |
| 524 | CGF.EmitBlock(SelectWorkersBB); |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 525 | llvm::Value *IsActive = |
| 526 | Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active"); |
| 527 | Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB); |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 528 | |
| 529 | // Signal start of parallel region. |
| 530 | CGF.EmitBlock(ExecuteBB); |
Arpith Chacko Jacob | bb36fe8 | 2017-01-10 15:42:51 +0000 | [diff] [blame] | 531 | |
| 532 | // Process work items: outlined parallel functions. |
| 533 | for (auto *W : Work) { |
| 534 | // Try to match this outlined function. |
| 535 | auto *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy); |
| 536 | |
| 537 | llvm::Value *WorkFnMatch = |
| 538 | Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match"); |
| 539 | |
| 540 | llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn"); |
| 541 | llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next"); |
| 542 | Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB); |
| 543 | |
| 544 | // Execute this outlined function. |
| 545 | CGF.EmitBlock(ExecuteFNBB); |
| 546 | |
| 547 | // Insert call to work function. |
| 548 | // FIXME: Pass arguments to outlined function from master thread. |
| 549 | auto *Fn = cast<llvm::Function>(W); |
| 550 | Address ZeroAddr = |
| 551 | CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty, /*Name=*/".zero.addr"); |
| 552 | CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C=*/0)); |
| 553 | llvm::Value *FnArgs[] = {ZeroAddr.getPointer(), ZeroAddr.getPointer()}; |
Alexey Bataev | 3c595a6 | 2017-08-14 15:01:03 +0000 | [diff] [blame] | 554 | emitCall(CGF, Fn, FnArgs); |
Arpith Chacko Jacob | bb36fe8 | 2017-01-10 15:42:51 +0000 | [diff] [blame] | 555 | |
| 556 | // Go to end of parallel region. |
| 557 | CGF.EmitBranch(TerminateBB); |
| 558 | |
| 559 | CGF.EmitBlock(CheckNextBB); |
| 560 | } |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 561 | |
| 562 | // Signal end of parallel region. |
| 563 | CGF.EmitBlock(TerminateBB); |
Arpith Chacko Jacob | bb36fe8 | 2017-01-10 15:42:51 +0000 | [diff] [blame] | 564 | CGF.EmitRuntimeCall( |
| 565 | createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_end_parallel), |
| 566 | llvm::None); |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 567 | CGF.EmitBranch(BarrierBB); |
| 568 | |
| 569 | // All active and inactive workers wait at a barrier after parallel region. |
| 570 | CGF.EmitBlock(BarrierBB); |
| 571 | // Barrier after parallel region. |
| 572 | syncCTAThreads(CGF); |
| 573 | CGF.EmitBranch(AwaitBB); |
| 574 | |
| 575 | // Exit target region. |
| 576 | CGF.EmitBlock(ExitBB); |
| 577 | } |
| 578 | |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 579 | /// \brief Returns specified OpenMP runtime function for the current OpenMP |
| 580 | /// implementation. Specialized for the NVPTX device. |
| 581 | /// \param Function OpenMP runtime function. |
| 582 | /// \return Specified function. |
| 583 | llvm::Constant * |
| 584 | CGOpenMPRuntimeNVPTX::createNVPTXRuntimeFunction(unsigned Function) { |
| 585 | llvm::Constant *RTLFn = nullptr; |
| 586 | switch (static_cast<OpenMPRTLFunctionNVPTX>(Function)) { |
| 587 | case OMPRTL_NVPTX__kmpc_kernel_init: { |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 588 | // Build void __kmpc_kernel_init(kmp_int32 thread_limit); |
| 589 | llvm::Type *TypeParams[] = {CGM.Int32Ty}; |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 590 | llvm::FunctionType *FnTy = |
| 591 | llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); |
| 592 | RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_init"); |
| 593 | break; |
| 594 | } |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 595 | case OMPRTL_NVPTX__kmpc_kernel_deinit: { |
| 596 | // Build void __kmpc_kernel_deinit(); |
| 597 | llvm::FunctionType *FnTy = |
Arpith Chacko Jacob | bb36fe8 | 2017-01-10 15:42:51 +0000 | [diff] [blame] | 598 | llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false); |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 599 | RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_deinit"); |
| 600 | break; |
| 601 | } |
Arpith Chacko Jacob | 44a87c9 | 2017-01-18 19:35:00 +0000 | [diff] [blame] | 602 | case OMPRTL_NVPTX__kmpc_spmd_kernel_init: { |
| 603 | // Build void __kmpc_spmd_kernel_init(kmp_int32 thread_limit, |
| 604 | // short RequiresOMPRuntime, short RequiresDataSharing); |
| 605 | llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty}; |
| 606 | llvm::FunctionType *FnTy = |
| 607 | llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); |
| 608 | RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_init"); |
| 609 | break; |
| 610 | } |
| 611 | case OMPRTL_NVPTX__kmpc_spmd_kernel_deinit: { |
| 612 | // Build void __kmpc_spmd_kernel_deinit(); |
| 613 | llvm::FunctionType *FnTy = |
| 614 | llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false); |
| 615 | RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_deinit"); |
| 616 | break; |
| 617 | } |
Arpith Chacko Jacob | bb36fe8 | 2017-01-10 15:42:51 +0000 | [diff] [blame] | 618 | case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: { |
| 619 | /// Build void __kmpc_kernel_prepare_parallel( |
| 620 | /// void *outlined_function); |
| 621 | llvm::Type *TypeParams[] = {CGM.Int8PtrTy}; |
| 622 | llvm::FunctionType *FnTy = |
| 623 | llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); |
| 624 | RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_prepare_parallel"); |
| 625 | break; |
| 626 | } |
| 627 | case OMPRTL_NVPTX__kmpc_kernel_parallel: { |
| 628 | /// Build bool __kmpc_kernel_parallel(void **outlined_function); |
| 629 | llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy}; |
| 630 | llvm::Type *RetTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy); |
| 631 | llvm::FunctionType *FnTy = |
| 632 | llvm::FunctionType::get(RetTy, TypeParams, /*isVarArg*/ false); |
| 633 | RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_parallel"); |
| 634 | break; |
| 635 | } |
| 636 | case OMPRTL_NVPTX__kmpc_kernel_end_parallel: { |
| 637 | /// Build void __kmpc_kernel_end_parallel(); |
| 638 | llvm::FunctionType *FnTy = |
| 639 | llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false); |
| 640 | RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_end_parallel"); |
| 641 | break; |
| 642 | } |
| 643 | case OMPRTL_NVPTX__kmpc_serialized_parallel: { |
| 644 | // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32 |
| 645 | // global_tid); |
| 646 | llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty}; |
| 647 | llvm::FunctionType *FnTy = |
| 648 | llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); |
| 649 | RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel"); |
| 650 | break; |
| 651 | } |
| 652 | case OMPRTL_NVPTX__kmpc_end_serialized_parallel: { |
| 653 | // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32 |
| 654 | // global_tid); |
| 655 | llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty}; |
| 656 | llvm::FunctionType *FnTy = |
| 657 | llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); |
| 658 | RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel"); |
| 659 | break; |
| 660 | } |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 661 | case OMPRTL_NVPTX__kmpc_shuffle_int32: { |
| 662 | // Build int32_t __kmpc_shuffle_int32(int32_t element, |
| 663 | // int16_t lane_offset, int16_t warp_size); |
| 664 | llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty}; |
| 665 | llvm::FunctionType *FnTy = |
| 666 | llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false); |
| 667 | RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int32"); |
| 668 | break; |
| 669 | } |
| 670 | case OMPRTL_NVPTX__kmpc_shuffle_int64: { |
| 671 | // Build int64_t __kmpc_shuffle_int64(int64_t element, |
| 672 | // int16_t lane_offset, int16_t warp_size); |
| 673 | llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int16Ty, CGM.Int16Ty}; |
| 674 | llvm::FunctionType *FnTy = |
| 675 | llvm::FunctionType::get(CGM.Int64Ty, TypeParams, /*isVarArg*/ false); |
| 676 | RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int64"); |
| 677 | break; |
| 678 | } |
| 679 | case OMPRTL_NVPTX__kmpc_parallel_reduce_nowait: { |
| 680 | // Build int32_t kmpc_nvptx_parallel_reduce_nowait(kmp_int32 global_tid, |
| 681 | // kmp_int32 num_vars, size_t reduce_size, void* reduce_data, |
| 682 | // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t |
| 683 | // lane_offset, int16_t Algorithm Version), |
| 684 | // void (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num)); |
| 685 | llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty, |
| 686 | CGM.Int16Ty, CGM.Int16Ty}; |
| 687 | auto *ShuffleReduceFnTy = |
| 688 | llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams, |
| 689 | /*isVarArg=*/false); |
| 690 | llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty}; |
| 691 | auto *InterWarpCopyFnTy = |
| 692 | llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams, |
| 693 | /*isVarArg=*/false); |
| 694 | llvm::Type *TypeParams[] = {CGM.Int32Ty, |
| 695 | CGM.Int32Ty, |
| 696 | CGM.SizeTy, |
| 697 | CGM.VoidPtrTy, |
| 698 | ShuffleReduceFnTy->getPointerTo(), |
| 699 | InterWarpCopyFnTy->getPointerTo()}; |
| 700 | llvm::FunctionType *FnTy = |
| 701 | llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false); |
| 702 | RTLFn = CGM.CreateRuntimeFunction( |
| 703 | FnTy, /*Name=*/"__kmpc_nvptx_parallel_reduce_nowait"); |
| 704 | break; |
| 705 | } |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 706 | case OMPRTL_NVPTX__kmpc_teams_reduce_nowait: { |
| 707 | // Build int32_t __kmpc_nvptx_teams_reduce_nowait(int32_t global_tid, |
| 708 | // int32_t num_vars, size_t reduce_size, void *reduce_data, |
| 709 | // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t |
| 710 | // lane_offset, int16_t shortCircuit), |
| 711 | // void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num), |
| 712 | // void (*kmp_CopyToScratchpadFctPtr)(void *reduce_data, void * scratchpad, |
| 713 | // int32_t index, int32_t width), |
| 714 | // void (*kmp_LoadReduceFctPtr)(void *reduce_data, void * scratchpad, |
| 715 | // int32_t index, int32_t width, int32_t reduce)) |
| 716 | llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty, |
| 717 | CGM.Int16Ty, CGM.Int16Ty}; |
| 718 | auto *ShuffleReduceFnTy = |
| 719 | llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams, |
| 720 | /*isVarArg=*/false); |
| 721 | llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty}; |
| 722 | auto *InterWarpCopyFnTy = |
| 723 | llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams, |
| 724 | /*isVarArg=*/false); |
| 725 | llvm::Type *CopyToScratchpadTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy, |
| 726 | CGM.Int32Ty, CGM.Int32Ty}; |
| 727 | auto *CopyToScratchpadFnTy = |
| 728 | llvm::FunctionType::get(CGM.VoidTy, CopyToScratchpadTypeParams, |
| 729 | /*isVarArg=*/false); |
| 730 | llvm::Type *LoadReduceTypeParams[] = { |
| 731 | CGM.VoidPtrTy, CGM.VoidPtrTy, CGM.Int32Ty, CGM.Int32Ty, CGM.Int32Ty}; |
| 732 | auto *LoadReduceFnTy = |
| 733 | llvm::FunctionType::get(CGM.VoidTy, LoadReduceTypeParams, |
| 734 | /*isVarArg=*/false); |
| 735 | llvm::Type *TypeParams[] = {CGM.Int32Ty, |
| 736 | CGM.Int32Ty, |
| 737 | CGM.SizeTy, |
| 738 | CGM.VoidPtrTy, |
| 739 | ShuffleReduceFnTy->getPointerTo(), |
| 740 | InterWarpCopyFnTy->getPointerTo(), |
| 741 | CopyToScratchpadFnTy->getPointerTo(), |
| 742 | LoadReduceFnTy->getPointerTo()}; |
| 743 | llvm::FunctionType *FnTy = |
| 744 | llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false); |
| 745 | RTLFn = CGM.CreateRuntimeFunction( |
| 746 | FnTy, /*Name=*/"__kmpc_nvptx_teams_reduce_nowait"); |
| 747 | break; |
| 748 | } |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 749 | case OMPRTL_NVPTX__kmpc_end_reduce_nowait: { |
| 750 | // Build __kmpc_end_reduce_nowait(kmp_int32 global_tid); |
| 751 | llvm::Type *TypeParams[] = {CGM.Int32Ty}; |
| 752 | llvm::FunctionType *FnTy = |
| 753 | llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); |
| 754 | RTLFn = CGM.CreateRuntimeFunction( |
| 755 | FnTy, /*Name=*/"__kmpc_nvptx_end_reduce_nowait"); |
| 756 | break; |
| 757 | } |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 758 | } |
| 759 | return RTLFn; |
| 760 | } |
| 761 | |
| 762 | void CGOpenMPRuntimeNVPTX::createOffloadEntry(llvm::Constant *ID, |
| 763 | llvm::Constant *Addr, |
Samuel Antao | f83efdb | 2017-01-05 16:02:49 +0000 | [diff] [blame] | 764 | uint64_t Size, int32_t) { |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 765 | auto *F = dyn_cast<llvm::Function>(Addr); |
| 766 | // TODO: Add support for global variables on the device after declare target |
| 767 | // support. |
| 768 | if (!F) |
| 769 | return; |
| 770 | llvm::Module *M = F->getParent(); |
| 771 | llvm::LLVMContext &Ctx = M->getContext(); |
| 772 | |
| 773 | // Get "nvvm.annotations" metadata node |
| 774 | llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations"); |
| 775 | |
| 776 | llvm::Metadata *MDVals[] = { |
| 777 | llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, "kernel"), |
| 778 | llvm::ConstantAsMetadata::get( |
| 779 | llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))}; |
| 780 | // Append metadata to nvvm.annotations |
| 781 | MD->addOperand(llvm::MDNode::get(Ctx, MDVals)); |
| 782 | } |
| 783 | |
| 784 | void CGOpenMPRuntimeNVPTX::emitTargetOutlinedFunction( |
| 785 | const OMPExecutableDirective &D, StringRef ParentName, |
| 786 | llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID, |
Alexey Bataev | 14fa1c6 | 2016-03-29 05:34:15 +0000 | [diff] [blame] | 787 | bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) { |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 788 | if (!IsOffloadEntry) // Nothing to do. |
| 789 | return; |
| 790 | |
| 791 | assert(!ParentName.empty() && "Invalid target region parent name!"); |
| 792 | |
Arpith Chacko Jacob | 44a87c9 | 2017-01-18 19:35:00 +0000 | [diff] [blame] | 793 | CGOpenMPRuntimeNVPTX::ExecutionMode Mode = |
| 794 | getExecutionModeForDirective(CGM, D); |
| 795 | switch (Mode) { |
| 796 | case CGOpenMPRuntimeNVPTX::ExecutionMode::Generic: |
| 797 | emitGenericKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry, |
| 798 | CodeGen); |
| 799 | break; |
| 800 | case CGOpenMPRuntimeNVPTX::ExecutionMode::Spmd: |
| 801 | emitSpmdKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry, |
| 802 | CodeGen); |
| 803 | break; |
| 804 | case CGOpenMPRuntimeNVPTX::ExecutionMode::Unknown: |
| 805 | llvm_unreachable( |
| 806 | "Unknown programming model for OpenMP directive on NVPTX target."); |
| 807 | } |
| 808 | |
| 809 | setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode); |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 810 | } |
| 811 | |
Samuel Antao | 45bfe4c | 2016-02-08 15:59:20 +0000 | [diff] [blame] | 812 | CGOpenMPRuntimeNVPTX::CGOpenMPRuntimeNVPTX(CodeGenModule &CGM) |
Arpith Chacko Jacob | 44a87c9 | 2017-01-18 19:35:00 +0000 | [diff] [blame] | 813 | : CGOpenMPRuntime(CGM), CurrentExecutionMode(ExecutionMode::Unknown) { |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 814 | if (!CGM.getLangOpts().OpenMPIsDevice) |
| 815 | llvm_unreachable("OpenMP NVPTX can only handle device code."); |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 816 | } |
Carlo Bertolli | c687225 | 2016-04-04 15:55:02 +0000 | [diff] [blame] | 817 | |
Arpith Chacko Jacob | 2cd6eea | 2017-01-25 16:55:10 +0000 | [diff] [blame] | 818 | void CGOpenMPRuntimeNVPTX::emitProcBindClause(CodeGenFunction &CGF, |
| 819 | OpenMPProcBindClauseKind ProcBind, |
| 820 | SourceLocation Loc) { |
| 821 | // Do nothing in case of Spmd mode and L0 parallel. |
| 822 | // TODO: If in Spmd mode and L1 parallel emit the clause. |
| 823 | if (isInSpmdExecutionMode()) |
| 824 | return; |
| 825 | |
| 826 | CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc); |
| 827 | } |
| 828 | |
Arpith Chacko Jacob | e04da5d | 2017-01-25 01:18:34 +0000 | [diff] [blame] | 829 | void CGOpenMPRuntimeNVPTX::emitNumThreadsClause(CodeGenFunction &CGF, |
| 830 | llvm::Value *NumThreads, |
| 831 | SourceLocation Loc) { |
| 832 | // Do nothing in case of Spmd mode and L0 parallel. |
| 833 | // TODO: If in Spmd mode and L1 parallel emit the clause. |
| 834 | if (isInSpmdExecutionMode()) |
| 835 | return; |
| 836 | |
| 837 | CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc); |
| 838 | } |
| 839 | |
Carlo Bertolli | c687225 | 2016-04-04 15:55:02 +0000 | [diff] [blame] | 840 | void CGOpenMPRuntimeNVPTX::emitNumTeamsClause(CodeGenFunction &CGF, |
| 841 | const Expr *NumTeams, |
| 842 | const Expr *ThreadLimit, |
| 843 | SourceLocation Loc) {} |
| 844 | |
Arpith Chacko Jacob | 19b911c | 2017-01-18 18:18:53 +0000 | [diff] [blame] | 845 | llvm::Value *CGOpenMPRuntimeNVPTX::emitParallelOutlinedFunction( |
| 846 | const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, |
| 847 | OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) { |
| 848 | return CGOpenMPRuntime::emitParallelOutlinedFunction(D, ThreadIDVar, |
| 849 | InnermostKind, CodeGen); |
| 850 | } |
| 851 | |
| 852 | llvm::Value *CGOpenMPRuntimeNVPTX::emitTeamsOutlinedFunction( |
Carlo Bertolli | c687225 | 2016-04-04 15:55:02 +0000 | [diff] [blame] | 853 | const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, |
| 854 | OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) { |
| 855 | |
Arpith Chacko Jacob | 19b911c | 2017-01-18 18:18:53 +0000 | [diff] [blame] | 856 | llvm::Value *OutlinedFunVal = CGOpenMPRuntime::emitTeamsOutlinedFunction( |
| 857 | D, ThreadIDVar, InnermostKind, CodeGen); |
| 858 | llvm::Function *OutlinedFun = cast<llvm::Function>(OutlinedFunVal); |
| 859 | OutlinedFun->removeFnAttr(llvm::Attribute::NoInline); |
Mehdi Amini | 6aa9e9b | 2017-05-29 05:38:20 +0000 | [diff] [blame] | 860 | OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone); |
Arpith Chacko Jacob | 19b911c | 2017-01-18 18:18:53 +0000 | [diff] [blame] | 861 | OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline); |
Carlo Bertolli | c687225 | 2016-04-04 15:55:02 +0000 | [diff] [blame] | 862 | |
| 863 | return OutlinedFun; |
| 864 | } |
| 865 | |
| 866 | void CGOpenMPRuntimeNVPTX::emitTeamsCall(CodeGenFunction &CGF, |
| 867 | const OMPExecutableDirective &D, |
| 868 | SourceLocation Loc, |
| 869 | llvm::Value *OutlinedFn, |
| 870 | ArrayRef<llvm::Value *> CapturedVars) { |
| 871 | if (!CGF.HaveInsertPoint()) |
| 872 | return; |
| 873 | |
| 874 | Address ZeroAddr = |
| 875 | CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4), |
| 876 | /*Name*/ ".zero.addr"); |
| 877 | CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0)); |
| 878 | llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs; |
| 879 | OutlinedFnArgs.push_back(ZeroAddr.getPointer()); |
| 880 | OutlinedFnArgs.push_back(ZeroAddr.getPointer()); |
| 881 | OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end()); |
Alexey Bataev | 3c595a6 | 2017-08-14 15:01:03 +0000 | [diff] [blame] | 882 | emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs); |
Carlo Bertolli | c687225 | 2016-04-04 15:55:02 +0000 | [diff] [blame] | 883 | } |
Arpith Chacko Jacob | bb36fe8 | 2017-01-10 15:42:51 +0000 | [diff] [blame] | 884 | |
| 885 | void CGOpenMPRuntimeNVPTX::emitParallelCall( |
| 886 | CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn, |
| 887 | ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) { |
| 888 | if (!CGF.HaveInsertPoint()) |
| 889 | return; |
| 890 | |
Arpith Chacko Jacob | 44a87c9 | 2017-01-18 19:35:00 +0000 | [diff] [blame] | 891 | if (isInSpmdExecutionMode()) |
| 892 | emitSpmdParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond); |
| 893 | else |
| 894 | emitGenericParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond); |
Arpith Chacko Jacob | bb36fe8 | 2017-01-10 15:42:51 +0000 | [diff] [blame] | 895 | } |
| 896 | |
| 897 | void CGOpenMPRuntimeNVPTX::emitGenericParallelCall( |
| 898 | CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn, |
| 899 | ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) { |
| 900 | llvm::Function *Fn = cast<llvm::Function>(OutlinedFn); |
| 901 | |
Malcolm Parsons | c6e4583 | 2017-01-13 18:55:32 +0000 | [diff] [blame] | 902 | auto &&L0ParallelGen = [this, Fn](CodeGenFunction &CGF, PrePostActionTy &) { |
Arpith Chacko Jacob | bb36fe8 | 2017-01-10 15:42:51 +0000 | [diff] [blame] | 903 | CGBuilderTy &Bld = CGF.Builder; |
| 904 | |
| 905 | // Prepare for parallel region. Indicate the outlined function. |
| 906 | llvm::Value *Args[] = {Bld.CreateBitOrPointerCast(Fn, CGM.Int8PtrTy)}; |
| 907 | CGF.EmitRuntimeCall( |
| 908 | createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_prepare_parallel), |
| 909 | Args); |
| 910 | |
| 911 | // Activate workers. This barrier is used by the master to signal |
| 912 | // work for the workers. |
| 913 | syncCTAThreads(CGF); |
| 914 | |
| 915 | // OpenMP [2.5, Parallel Construct, p.49] |
| 916 | // There is an implied barrier at the end of a parallel region. After the |
| 917 | // end of a parallel region, only the master thread of the team resumes |
| 918 | // execution of the enclosing task region. |
| 919 | // |
| 920 | // The master waits at this barrier until all workers are done. |
| 921 | syncCTAThreads(CGF); |
| 922 | |
| 923 | // Remember for post-processing in worker loop. |
| 924 | Work.push_back(Fn); |
| 925 | }; |
| 926 | |
| 927 | auto *RTLoc = emitUpdateLocation(CGF, Loc); |
| 928 | auto *ThreadID = getThreadID(CGF, Loc); |
| 929 | llvm::Value *Args[] = {RTLoc, ThreadID}; |
| 930 | |
Alexey Bataev | 3c595a6 | 2017-08-14 15:01:03 +0000 | [diff] [blame] | 931 | auto &&SeqGen = [this, Fn, &CapturedVars, &Args, Loc](CodeGenFunction &CGF, |
| 932 | PrePostActionTy &) { |
| 933 | auto &&CodeGen = [this, Fn, &CapturedVars, Loc](CodeGenFunction &CGF, |
| 934 | PrePostActionTy &Action) { |
Arpith Chacko Jacob | bb36fe8 | 2017-01-10 15:42:51 +0000 | [diff] [blame] | 935 | Action.Enter(CGF); |
| 936 | |
| 937 | llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs; |
| 938 | OutlinedFnArgs.push_back( |
| 939 | llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo())); |
| 940 | OutlinedFnArgs.push_back( |
| 941 | llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo())); |
| 942 | OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end()); |
Alexey Bataev | 3c595a6 | 2017-08-14 15:01:03 +0000 | [diff] [blame] | 943 | emitOutlinedFunctionCall(CGF, Loc, Fn, OutlinedFnArgs); |
Arpith Chacko Jacob | bb36fe8 | 2017-01-10 15:42:51 +0000 | [diff] [blame] | 944 | }; |
| 945 | |
| 946 | RegionCodeGenTy RCG(CodeGen); |
| 947 | NVPTXActionTy Action( |
| 948 | createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel), |
| 949 | Args, |
| 950 | createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel), |
| 951 | Args); |
| 952 | RCG.setAction(Action); |
| 953 | RCG(CGF); |
| 954 | }; |
| 955 | |
| 956 | if (IfCond) |
| 957 | emitOMPIfClause(CGF, IfCond, L0ParallelGen, SeqGen); |
| 958 | else { |
| 959 | CodeGenFunction::RunCleanupsScope Scope(CGF); |
| 960 | RegionCodeGenTy ThenRCG(L0ParallelGen); |
| 961 | ThenRCG(CGF); |
| 962 | } |
| 963 | } |
Arpith Chacko Jacob | 44a87c9 | 2017-01-18 19:35:00 +0000 | [diff] [blame] | 964 | |
| 965 | void CGOpenMPRuntimeNVPTX::emitSpmdParallelCall( |
| 966 | CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn, |
| 967 | ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) { |
| 968 | // Just call the outlined function to execute the parallel region. |
| 969 | // OutlinedFn(>id, &zero, CapturedStruct); |
| 970 | // |
| 971 | // TODO: Do something with IfCond when support for the 'if' clause |
| 972 | // is added on Spmd target directives. |
| 973 | llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs; |
| 974 | OutlinedFnArgs.push_back( |
| 975 | llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo())); |
| 976 | OutlinedFnArgs.push_back( |
| 977 | llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo())); |
| 978 | OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end()); |
Alexey Bataev | 3c595a6 | 2017-08-14 15:01:03 +0000 | [diff] [blame] | 979 | emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs); |
Arpith Chacko Jacob | 44a87c9 | 2017-01-18 19:35:00 +0000 | [diff] [blame] | 980 | } |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 981 | |
| 982 | /// This function creates calls to one of two shuffle functions to copy |
| 983 | /// variables between lanes in a warp. |
| 984 | static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF, |
| 985 | QualType ElemTy, |
| 986 | llvm::Value *Elem, |
| 987 | llvm::Value *Offset) { |
| 988 | auto &CGM = CGF.CGM; |
| 989 | auto &C = CGM.getContext(); |
| 990 | auto &Bld = CGF.Builder; |
| 991 | CGOpenMPRuntimeNVPTX &RT = |
| 992 | *(static_cast<CGOpenMPRuntimeNVPTX *>(&CGM.getOpenMPRuntime())); |
| 993 | |
| 994 | unsigned Size = CGM.getContext().getTypeSizeInChars(ElemTy).getQuantity(); |
| 995 | assert(Size <= 8 && "Unsupported bitwidth in shuffle instruction."); |
| 996 | |
| 997 | OpenMPRTLFunctionNVPTX ShuffleFn = Size <= 4 |
| 998 | ? OMPRTL_NVPTX__kmpc_shuffle_int32 |
| 999 | : OMPRTL_NVPTX__kmpc_shuffle_int64; |
| 1000 | |
| 1001 | // Cast all types to 32- or 64-bit values before calling shuffle routines. |
| 1002 | auto CastTy = Size <= 4 ? CGM.Int32Ty : CGM.Int64Ty; |
| 1003 | auto *ElemCast = Bld.CreateSExtOrBitCast(Elem, CastTy); |
| 1004 | auto *WarpSize = CGF.EmitScalarConversion( |
| 1005 | getNVPTXWarpSize(CGF), C.getIntTypeForBitwidth(32, /* Signed */ true), |
| 1006 | C.getIntTypeForBitwidth(16, /* Signed */ true), SourceLocation()); |
| 1007 | |
| 1008 | auto *ShuffledVal = |
| 1009 | CGF.EmitRuntimeCall(RT.createNVPTXRuntimeFunction(ShuffleFn), |
| 1010 | {ElemCast, Offset, WarpSize}); |
| 1011 | |
| 1012 | return Bld.CreateTruncOrBitCast(ShuffledVal, CGF.ConvertTypeForMem(ElemTy)); |
| 1013 | } |
| 1014 | |
| 1015 | namespace { |
| 1016 | enum CopyAction : unsigned { |
| 1017 | // RemoteLaneToThread: Copy over a Reduce list from a remote lane in |
| 1018 | // the warp using shuffle instructions. |
| 1019 | RemoteLaneToThread, |
| 1020 | // ThreadCopy: Make a copy of a Reduce list on the thread's stack. |
| 1021 | ThreadCopy, |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1022 | // ThreadToScratchpad: Copy a team-reduced array to the scratchpad. |
| 1023 | ThreadToScratchpad, |
| 1024 | // ScratchpadToThread: Copy from a scratchpad array in global memory |
| 1025 | // containing team-reduced data to a thread's stack. |
| 1026 | ScratchpadToThread, |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1027 | }; |
| 1028 | } // namespace |
| 1029 | |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1030 | struct CopyOptionsTy { |
| 1031 | llvm::Value *RemoteLaneOffset; |
| 1032 | llvm::Value *ScratchpadIndex; |
| 1033 | llvm::Value *ScratchpadWidth; |
| 1034 | }; |
| 1035 | |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1036 | /// Emit instructions to copy a Reduce list, which contains partially |
| 1037 | /// aggregated values, in the specified direction. |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1038 | static void emitReductionListCopy( |
| 1039 | CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy, |
| 1040 | ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase, |
| 1041 | CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) { |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1042 | |
| 1043 | auto &CGM = CGF.CGM; |
| 1044 | auto &C = CGM.getContext(); |
| 1045 | auto &Bld = CGF.Builder; |
| 1046 | |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1047 | auto *RemoteLaneOffset = CopyOptions.RemoteLaneOffset; |
| 1048 | auto *ScratchpadIndex = CopyOptions.ScratchpadIndex; |
| 1049 | auto *ScratchpadWidth = CopyOptions.ScratchpadWidth; |
| 1050 | |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1051 | // Iterates, element-by-element, through the source Reduce list and |
| 1052 | // make a copy. |
| 1053 | unsigned Idx = 0; |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1054 | unsigned Size = Privates.size(); |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1055 | for (auto &Private : Privates) { |
| 1056 | Address SrcElementAddr = Address::invalid(); |
| 1057 | Address DestElementAddr = Address::invalid(); |
| 1058 | Address DestElementPtrAddr = Address::invalid(); |
| 1059 | // Should we shuffle in an element from a remote lane? |
| 1060 | bool ShuffleInElement = false; |
| 1061 | // Set to true to update the pointer in the dest Reduce list to a |
| 1062 | // newly created element. |
| 1063 | bool UpdateDestListPtr = false; |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1064 | // Increment the src or dest pointer to the scratchpad, for each |
| 1065 | // new element. |
| 1066 | bool IncrScratchpadSrc = false; |
| 1067 | bool IncrScratchpadDest = false; |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1068 | |
| 1069 | switch (Action) { |
| 1070 | case RemoteLaneToThread: { |
| 1071 | // Step 1.1: Get the address for the src element in the Reduce list. |
| 1072 | Address SrcElementPtrAddr = |
| 1073 | Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize()); |
| 1074 | llvm::Value *SrcElementPtrPtr = CGF.EmitLoadOfScalar( |
| 1075 | SrcElementPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation()); |
| 1076 | SrcElementAddr = |
| 1077 | Address(SrcElementPtrPtr, C.getTypeAlignInChars(Private->getType())); |
| 1078 | |
| 1079 | // Step 1.2: Create a temporary to store the element in the destination |
| 1080 | // Reduce list. |
| 1081 | DestElementPtrAddr = |
| 1082 | Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize()); |
| 1083 | DestElementAddr = |
| 1084 | CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element"); |
| 1085 | ShuffleInElement = true; |
| 1086 | UpdateDestListPtr = true; |
| 1087 | break; |
| 1088 | } |
| 1089 | case ThreadCopy: { |
| 1090 | // Step 1.1: Get the address for the src element in the Reduce list. |
| 1091 | Address SrcElementPtrAddr = |
| 1092 | Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize()); |
| 1093 | llvm::Value *SrcElementPtrPtr = CGF.EmitLoadOfScalar( |
| 1094 | SrcElementPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation()); |
| 1095 | SrcElementAddr = |
| 1096 | Address(SrcElementPtrPtr, C.getTypeAlignInChars(Private->getType())); |
| 1097 | |
| 1098 | // Step 1.2: Get the address for dest element. The destination |
| 1099 | // element has already been created on the thread's stack. |
| 1100 | DestElementPtrAddr = |
| 1101 | Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize()); |
| 1102 | llvm::Value *DestElementPtr = |
| 1103 | CGF.EmitLoadOfScalar(DestElementPtrAddr, /*Volatile=*/false, |
| 1104 | C.VoidPtrTy, SourceLocation()); |
| 1105 | Address DestElemAddr = |
| 1106 | Address(DestElementPtr, C.getTypeAlignInChars(Private->getType())); |
| 1107 | DestElementAddr = Bld.CreateElementBitCast( |
| 1108 | DestElemAddr, CGF.ConvertTypeForMem(Private->getType())); |
| 1109 | break; |
| 1110 | } |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1111 | case ThreadToScratchpad: { |
| 1112 | // Step 1.1: Get the address for the src element in the Reduce list. |
| 1113 | Address SrcElementPtrAddr = |
| 1114 | Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize()); |
| 1115 | llvm::Value *SrcElementPtrPtr = CGF.EmitLoadOfScalar( |
| 1116 | SrcElementPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation()); |
| 1117 | SrcElementAddr = |
| 1118 | Address(SrcElementPtrPtr, C.getTypeAlignInChars(Private->getType())); |
| 1119 | |
| 1120 | // Step 1.2: Get the address for dest element: |
| 1121 | // address = base + index * ElementSizeInChars. |
| 1122 | unsigned ElementSizeInChars = |
| 1123 | C.getTypeSizeInChars(Private->getType()).getQuantity(); |
| 1124 | auto *CurrentOffset = |
| 1125 | Bld.CreateMul(llvm::ConstantInt::get(CGM.SizeTy, ElementSizeInChars), |
| 1126 | ScratchpadIndex); |
| 1127 | auto *ScratchPadElemAbsolutePtrVal = |
| 1128 | Bld.CreateAdd(DestBase.getPointer(), CurrentOffset); |
| 1129 | ScratchPadElemAbsolutePtrVal = |
| 1130 | Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy); |
| 1131 | Address ScratchpadPtr = |
| 1132 | Address(ScratchPadElemAbsolutePtrVal, |
| 1133 | C.getTypeAlignInChars(Private->getType())); |
| 1134 | DestElementAddr = Bld.CreateElementBitCast( |
| 1135 | ScratchpadPtr, CGF.ConvertTypeForMem(Private->getType())); |
| 1136 | IncrScratchpadDest = true; |
| 1137 | break; |
| 1138 | } |
| 1139 | case ScratchpadToThread: { |
| 1140 | // Step 1.1: Get the address for the src element in the scratchpad. |
| 1141 | // address = base + index * ElementSizeInChars. |
| 1142 | unsigned ElementSizeInChars = |
| 1143 | C.getTypeSizeInChars(Private->getType()).getQuantity(); |
| 1144 | auto *CurrentOffset = |
| 1145 | Bld.CreateMul(llvm::ConstantInt::get(CGM.SizeTy, ElementSizeInChars), |
| 1146 | ScratchpadIndex); |
| 1147 | auto *ScratchPadElemAbsolutePtrVal = |
| 1148 | Bld.CreateAdd(SrcBase.getPointer(), CurrentOffset); |
| 1149 | ScratchPadElemAbsolutePtrVal = |
| 1150 | Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy); |
| 1151 | SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal, |
| 1152 | C.getTypeAlignInChars(Private->getType())); |
| 1153 | IncrScratchpadSrc = true; |
| 1154 | |
| 1155 | // Step 1.2: Create a temporary to store the element in the destination |
| 1156 | // Reduce list. |
| 1157 | DestElementPtrAddr = |
| 1158 | Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize()); |
| 1159 | DestElementAddr = |
| 1160 | CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element"); |
| 1161 | UpdateDestListPtr = true; |
| 1162 | break; |
| 1163 | } |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1164 | } |
| 1165 | |
| 1166 | // Regardless of src and dest of copy, we emit the load of src |
| 1167 | // element as this is required in all directions |
| 1168 | SrcElementAddr = Bld.CreateElementBitCast( |
| 1169 | SrcElementAddr, CGF.ConvertTypeForMem(Private->getType())); |
| 1170 | llvm::Value *Elem = |
| 1171 | CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false, |
| 1172 | Private->getType(), SourceLocation()); |
| 1173 | |
| 1174 | // Now that all active lanes have read the element in the |
| 1175 | // Reduce list, shuffle over the value from the remote lane. |
| 1176 | if (ShuffleInElement) { |
| 1177 | Elem = createRuntimeShuffleFunction(CGF, Private->getType(), Elem, |
| 1178 | RemoteLaneOffset); |
| 1179 | } |
| 1180 | |
| 1181 | // Store the source element value to the dest element address. |
| 1182 | CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false, |
| 1183 | Private->getType()); |
| 1184 | |
| 1185 | // Step 3.1: Modify reference in dest Reduce list as needed. |
| 1186 | // Modifying the reference in Reduce list to point to the newly |
| 1187 | // created element. The element is live in the current function |
| 1188 | // scope and that of functions it invokes (i.e., reduce_function). |
| 1189 | // RemoteReduceData[i] = (void*)&RemoteElem |
| 1190 | if (UpdateDestListPtr) { |
| 1191 | CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast( |
| 1192 | DestElementAddr.getPointer(), CGF.VoidPtrTy), |
| 1193 | DestElementPtrAddr, /*Volatile=*/false, |
| 1194 | C.VoidPtrTy); |
| 1195 | } |
| 1196 | |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1197 | // Step 4.1: Increment SrcBase/DestBase so that it points to the starting |
| 1198 | // address of the next element in scratchpad memory, unless we're currently |
| 1199 | // processing the last one. Memory alignment is also taken care of here. |
| 1200 | if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) { |
| 1201 | llvm::Value *ScratchpadBasePtr = |
| 1202 | IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer(); |
| 1203 | unsigned ElementSizeInChars = |
| 1204 | C.getTypeSizeInChars(Private->getType()).getQuantity(); |
| 1205 | ScratchpadBasePtr = Bld.CreateAdd( |
| 1206 | ScratchpadBasePtr, |
| 1207 | Bld.CreateMul(ScratchpadWidth, llvm::ConstantInt::get( |
| 1208 | CGM.SizeTy, ElementSizeInChars))); |
| 1209 | |
| 1210 | // Take care of global memory alignment for performance |
| 1211 | ScratchpadBasePtr = Bld.CreateSub(ScratchpadBasePtr, |
| 1212 | llvm::ConstantInt::get(CGM.SizeTy, 1)); |
| 1213 | ScratchpadBasePtr = Bld.CreateSDiv( |
| 1214 | ScratchpadBasePtr, |
| 1215 | llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment)); |
| 1216 | ScratchpadBasePtr = Bld.CreateAdd(ScratchpadBasePtr, |
| 1217 | llvm::ConstantInt::get(CGM.SizeTy, 1)); |
| 1218 | ScratchpadBasePtr = Bld.CreateMul( |
| 1219 | ScratchpadBasePtr, |
| 1220 | llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment)); |
| 1221 | |
| 1222 | if (IncrScratchpadDest) |
| 1223 | DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign()); |
| 1224 | else /* IncrScratchpadSrc = true */ |
| 1225 | SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign()); |
| 1226 | } |
| 1227 | |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1228 | Idx++; |
| 1229 | } |
| 1230 | } |
| 1231 | |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1232 | /// This function emits a helper that loads data from the scratchpad array |
| 1233 | /// and (optionally) reduces it with the input operand. |
| 1234 | /// |
| 1235 | /// load_and_reduce(local, scratchpad, index, width, should_reduce) |
| 1236 | /// reduce_data remote; |
| 1237 | /// for elem in remote: |
| 1238 | /// remote.elem = Scratchpad[elem_id][index] |
| 1239 | /// if (should_reduce) |
| 1240 | /// local = local @ remote |
| 1241 | /// else |
| 1242 | /// local = remote |
Benjamin Kramer | 674d579 | 2017-05-26 20:08:24 +0000 | [diff] [blame] | 1243 | static llvm::Value * |
| 1244 | emitReduceScratchpadFunction(CodeGenModule &CGM, |
| 1245 | ArrayRef<const Expr *> Privates, |
| 1246 | QualType ReductionArrayTy, llvm::Value *ReduceFn) { |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1247 | auto &C = CGM.getContext(); |
| 1248 | auto Int32Ty = C.getIntTypeForBitwidth(32, /* Signed */ true); |
| 1249 | |
| 1250 | // Destination of the copy. |
Alexey Bataev | 5622323 | 2017-06-09 13:40:18 +0000 | [diff] [blame] | 1251 | ImplicitParamDecl ReduceListArg(C, C.VoidPtrTy, ImplicitParamDecl::Other); |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1252 | // Base address of the scratchpad array, with each element storing a |
| 1253 | // Reduce list per team. |
Alexey Bataev | 5622323 | 2017-06-09 13:40:18 +0000 | [diff] [blame] | 1254 | ImplicitParamDecl ScratchPadArg(C, C.VoidPtrTy, ImplicitParamDecl::Other); |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1255 | // A source index into the scratchpad array. |
Alexey Bataev | 5622323 | 2017-06-09 13:40:18 +0000 | [diff] [blame] | 1256 | ImplicitParamDecl IndexArg(C, Int32Ty, ImplicitParamDecl::Other); |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1257 | // Row width of an element in the scratchpad array, typically |
| 1258 | // the number of teams. |
Alexey Bataev | 5622323 | 2017-06-09 13:40:18 +0000 | [diff] [blame] | 1259 | ImplicitParamDecl WidthArg(C, Int32Ty, ImplicitParamDecl::Other); |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1260 | // If should_reduce == 1, then it's load AND reduce, |
| 1261 | // If should_reduce == 0 (or otherwise), then it only loads (+ copy). |
| 1262 | // The latter case is used for initialization. |
Alexey Bataev | 5622323 | 2017-06-09 13:40:18 +0000 | [diff] [blame] | 1263 | ImplicitParamDecl ShouldReduceArg(C, Int32Ty, ImplicitParamDecl::Other); |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1264 | |
| 1265 | FunctionArgList Args; |
| 1266 | Args.push_back(&ReduceListArg); |
| 1267 | Args.push_back(&ScratchPadArg); |
| 1268 | Args.push_back(&IndexArg); |
| 1269 | Args.push_back(&WidthArg); |
| 1270 | Args.push_back(&ShouldReduceArg); |
| 1271 | |
| 1272 | auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); |
| 1273 | auto *Fn = llvm::Function::Create( |
| 1274 | CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage, |
| 1275 | "_omp_reduction_load_and_reduce", &CGM.getModule()); |
| 1276 | CGM.SetInternalFunctionAttributes(/*DC=*/nullptr, Fn, CGFI); |
| 1277 | CodeGenFunction CGF(CGM); |
| 1278 | // We don't need debug information in this function as nothing here refers to |
| 1279 | // user code. |
| 1280 | CGF.disableDebugInfo(); |
| 1281 | CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args); |
| 1282 | |
| 1283 | auto &Bld = CGF.Builder; |
| 1284 | |
| 1285 | // Get local Reduce list pointer. |
| 1286 | Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg); |
| 1287 | Address ReduceListAddr( |
| 1288 | Bld.CreatePointerBitCastOrAddrSpaceCast( |
| 1289 | CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false, |
| 1290 | C.VoidPtrTy, SourceLocation()), |
| 1291 | CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()), |
| 1292 | CGF.getPointerAlign()); |
| 1293 | |
| 1294 | Address AddrScratchPadArg = CGF.GetAddrOfLocalVar(&ScratchPadArg); |
| 1295 | llvm::Value *ScratchPadBase = CGF.EmitLoadOfScalar( |
| 1296 | AddrScratchPadArg, /*Volatile=*/false, C.VoidPtrTy, SourceLocation()); |
| 1297 | |
| 1298 | Address AddrIndexArg = CGF.GetAddrOfLocalVar(&IndexArg); |
| 1299 | llvm::Value *IndexVal = |
| 1300 | Bld.CreateIntCast(CGF.EmitLoadOfScalar(AddrIndexArg, /*Volatile=*/false, |
| 1301 | Int32Ty, SourceLocation()), |
| 1302 | CGM.SizeTy, /*isSigned=*/true); |
| 1303 | |
| 1304 | Address AddrWidthArg = CGF.GetAddrOfLocalVar(&WidthArg); |
| 1305 | llvm::Value *WidthVal = |
| 1306 | Bld.CreateIntCast(CGF.EmitLoadOfScalar(AddrWidthArg, /*Volatile=*/false, |
| 1307 | Int32Ty, SourceLocation()), |
| 1308 | CGM.SizeTy, /*isSigned=*/true); |
| 1309 | |
| 1310 | Address AddrShouldReduceArg = CGF.GetAddrOfLocalVar(&ShouldReduceArg); |
| 1311 | llvm::Value *ShouldReduceVal = CGF.EmitLoadOfScalar( |
| 1312 | AddrShouldReduceArg, /*Volatile=*/false, Int32Ty, SourceLocation()); |
| 1313 | |
| 1314 | // The absolute ptr address to the base addr of the next element to copy. |
| 1315 | llvm::Value *CumulativeElemBasePtr = |
| 1316 | Bld.CreatePtrToInt(ScratchPadBase, CGM.SizeTy); |
| 1317 | Address SrcDataAddr(CumulativeElemBasePtr, CGF.getPointerAlign()); |
| 1318 | |
| 1319 | // Create a Remote Reduce list to store the elements read from the |
| 1320 | // scratchpad array. |
| 1321 | Address RemoteReduceList = |
| 1322 | CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_red_list"); |
| 1323 | |
| 1324 | // Assemble remote Reduce list from scratchpad array. |
| 1325 | emitReductionListCopy(ScratchpadToThread, CGF, ReductionArrayTy, Privates, |
| 1326 | SrcDataAddr, RemoteReduceList, |
| 1327 | {/*RemoteLaneOffset=*/nullptr, |
| 1328 | /*ScratchpadIndex=*/IndexVal, |
| 1329 | /*ScratchpadWidth=*/WidthVal}); |
| 1330 | |
| 1331 | llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then"); |
| 1332 | llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else"); |
| 1333 | llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont"); |
| 1334 | |
| 1335 | auto CondReduce = Bld.CreateICmpEQ(ShouldReduceVal, Bld.getInt32(1)); |
| 1336 | Bld.CreateCondBr(CondReduce, ThenBB, ElseBB); |
| 1337 | |
| 1338 | CGF.EmitBlock(ThenBB); |
| 1339 | // We should reduce with the local Reduce list. |
| 1340 | // reduce_function(LocalReduceList, RemoteReduceList) |
| 1341 | llvm::Value *LocalDataPtr = Bld.CreatePointerBitCastOrAddrSpaceCast( |
| 1342 | ReduceListAddr.getPointer(), CGF.VoidPtrTy); |
| 1343 | llvm::Value *RemoteDataPtr = Bld.CreatePointerBitCastOrAddrSpaceCast( |
| 1344 | RemoteReduceList.getPointer(), CGF.VoidPtrTy); |
| 1345 | CGF.EmitCallOrInvoke(ReduceFn, {LocalDataPtr, RemoteDataPtr}); |
| 1346 | Bld.CreateBr(MergeBB); |
| 1347 | |
| 1348 | CGF.EmitBlock(ElseBB); |
| 1349 | // No reduction; just copy: |
| 1350 | // Local Reduce list = Remote Reduce list. |
| 1351 | emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates, |
| 1352 | RemoteReduceList, ReduceListAddr); |
| 1353 | Bld.CreateBr(MergeBB); |
| 1354 | |
| 1355 | CGF.EmitBlock(MergeBB); |
| 1356 | |
| 1357 | CGF.FinishFunction(); |
| 1358 | return Fn; |
| 1359 | } |
| 1360 | |
| 1361 | /// This function emits a helper that stores reduced data from the team |
| 1362 | /// master to a scratchpad array in global memory. |
| 1363 | /// |
| 1364 | /// for elem in Reduce List: |
| 1365 | /// scratchpad[elem_id][index] = elem |
| 1366 | /// |
Benjamin Kramer | 674d579 | 2017-05-26 20:08:24 +0000 | [diff] [blame] | 1367 | static llvm::Value *emitCopyToScratchpad(CodeGenModule &CGM, |
| 1368 | ArrayRef<const Expr *> Privates, |
| 1369 | QualType ReductionArrayTy) { |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1370 | |
| 1371 | auto &C = CGM.getContext(); |
| 1372 | auto Int32Ty = C.getIntTypeForBitwidth(32, /* Signed */ true); |
| 1373 | |
| 1374 | // Source of the copy. |
Alexey Bataev | 5622323 | 2017-06-09 13:40:18 +0000 | [diff] [blame] | 1375 | ImplicitParamDecl ReduceListArg(C, C.VoidPtrTy, ImplicitParamDecl::Other); |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1376 | // Base address of the scratchpad array, with each element storing a |
| 1377 | // Reduce list per team. |
Alexey Bataev | 5622323 | 2017-06-09 13:40:18 +0000 | [diff] [blame] | 1378 | ImplicitParamDecl ScratchPadArg(C, C.VoidPtrTy, ImplicitParamDecl::Other); |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1379 | // A destination index into the scratchpad array, typically the team |
| 1380 | // identifier. |
Alexey Bataev | 5622323 | 2017-06-09 13:40:18 +0000 | [diff] [blame] | 1381 | ImplicitParamDecl IndexArg(C, Int32Ty, ImplicitParamDecl::Other); |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1382 | // Row width of an element in the scratchpad array, typically |
| 1383 | // the number of teams. |
Alexey Bataev | 5622323 | 2017-06-09 13:40:18 +0000 | [diff] [blame] | 1384 | ImplicitParamDecl WidthArg(C, Int32Ty, ImplicitParamDecl::Other); |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1385 | |
| 1386 | FunctionArgList Args; |
| 1387 | Args.push_back(&ReduceListArg); |
| 1388 | Args.push_back(&ScratchPadArg); |
| 1389 | Args.push_back(&IndexArg); |
| 1390 | Args.push_back(&WidthArg); |
| 1391 | |
| 1392 | auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); |
| 1393 | auto *Fn = llvm::Function::Create( |
| 1394 | CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage, |
| 1395 | "_omp_reduction_copy_to_scratchpad", &CGM.getModule()); |
| 1396 | CGM.SetInternalFunctionAttributes(/*DC=*/nullptr, Fn, CGFI); |
| 1397 | CodeGenFunction CGF(CGM); |
| 1398 | // We don't need debug information in this function as nothing here refers to |
| 1399 | // user code. |
| 1400 | CGF.disableDebugInfo(); |
| 1401 | CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args); |
| 1402 | |
| 1403 | auto &Bld = CGF.Builder; |
| 1404 | |
| 1405 | Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg); |
| 1406 | Address SrcDataAddr( |
| 1407 | Bld.CreatePointerBitCastOrAddrSpaceCast( |
| 1408 | CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false, |
| 1409 | C.VoidPtrTy, SourceLocation()), |
| 1410 | CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()), |
| 1411 | CGF.getPointerAlign()); |
| 1412 | |
| 1413 | Address AddrScratchPadArg = CGF.GetAddrOfLocalVar(&ScratchPadArg); |
| 1414 | llvm::Value *ScratchPadBase = CGF.EmitLoadOfScalar( |
| 1415 | AddrScratchPadArg, /*Volatile=*/false, C.VoidPtrTy, SourceLocation()); |
| 1416 | |
| 1417 | Address AddrIndexArg = CGF.GetAddrOfLocalVar(&IndexArg); |
| 1418 | llvm::Value *IndexVal = |
| 1419 | Bld.CreateIntCast(CGF.EmitLoadOfScalar(AddrIndexArg, /*Volatile=*/false, |
| 1420 | Int32Ty, SourceLocation()), |
| 1421 | CGF.SizeTy, /*isSigned=*/true); |
| 1422 | |
| 1423 | Address AddrWidthArg = CGF.GetAddrOfLocalVar(&WidthArg); |
| 1424 | llvm::Value *WidthVal = |
| 1425 | Bld.CreateIntCast(CGF.EmitLoadOfScalar(AddrWidthArg, /*Volatile=*/false, |
| 1426 | Int32Ty, SourceLocation()), |
| 1427 | CGF.SizeTy, /*isSigned=*/true); |
| 1428 | |
| 1429 | // The absolute ptr address to the base addr of the next element to copy. |
| 1430 | llvm::Value *CumulativeElemBasePtr = |
| 1431 | Bld.CreatePtrToInt(ScratchPadBase, CGM.SizeTy); |
| 1432 | Address DestDataAddr(CumulativeElemBasePtr, CGF.getPointerAlign()); |
| 1433 | |
| 1434 | emitReductionListCopy(ThreadToScratchpad, CGF, ReductionArrayTy, Privates, |
| 1435 | SrcDataAddr, DestDataAddr, |
| 1436 | {/*RemoteLaneOffset=*/nullptr, |
| 1437 | /*ScratchpadIndex=*/IndexVal, |
| 1438 | /*ScratchpadWidth=*/WidthVal}); |
| 1439 | |
| 1440 | CGF.FinishFunction(); |
| 1441 | return Fn; |
| 1442 | } |
| 1443 | |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1444 | /// This function emits a helper that gathers Reduce lists from the first |
| 1445 | /// lane of every active warp to lanes in the first warp. |
| 1446 | /// |
| 1447 | /// void inter_warp_copy_func(void* reduce_data, num_warps) |
| 1448 | /// shared smem[warp_size]; |
| 1449 | /// For all data entries D in reduce_data: |
| 1450 | /// If (I am the first lane in each warp) |
| 1451 | /// Copy my local D to smem[warp_id] |
| 1452 | /// sync |
| 1453 | /// if (I am the first warp) |
| 1454 | /// Copy smem[thread_id] to my local D |
| 1455 | /// sync |
| 1456 | static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM, |
| 1457 | ArrayRef<const Expr *> Privates, |
| 1458 | QualType ReductionArrayTy) { |
| 1459 | auto &C = CGM.getContext(); |
| 1460 | auto &M = CGM.getModule(); |
| 1461 | |
| 1462 | // ReduceList: thread local Reduce list. |
| 1463 | // At the stage of the computation when this function is called, partially |
| 1464 | // aggregated values reside in the first lane of every active warp. |
Alexey Bataev | 5622323 | 2017-06-09 13:40:18 +0000 | [diff] [blame] | 1465 | ImplicitParamDecl ReduceListArg(C, C.VoidPtrTy, ImplicitParamDecl::Other); |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1466 | // NumWarps: number of warps active in the parallel region. This could |
| 1467 | // be smaller than 32 (max warps in a CTA) for partial block reduction. |
Alexey Bataev | 5622323 | 2017-06-09 13:40:18 +0000 | [diff] [blame] | 1468 | ImplicitParamDecl NumWarpsArg(C, |
| 1469 | C.getIntTypeForBitwidth(32, /* Signed */ true), |
| 1470 | ImplicitParamDecl::Other); |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1471 | FunctionArgList Args; |
| 1472 | Args.push_back(&ReduceListArg); |
| 1473 | Args.push_back(&NumWarpsArg); |
| 1474 | |
| 1475 | auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); |
| 1476 | auto *Fn = llvm::Function::Create( |
| 1477 | CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage, |
| 1478 | "_omp_reduction_inter_warp_copy_func", &CGM.getModule()); |
| 1479 | CGM.SetInternalFunctionAttributes(/*DC=*/nullptr, Fn, CGFI); |
| 1480 | CodeGenFunction CGF(CGM); |
| 1481 | // We don't need debug information in this function as nothing here refers to |
| 1482 | // user code. |
| 1483 | CGF.disableDebugInfo(); |
| 1484 | CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args); |
| 1485 | |
| 1486 | auto &Bld = CGF.Builder; |
| 1487 | |
| 1488 | // This array is used as a medium to transfer, one reduce element at a time, |
| 1489 | // the data from the first lane of every warp to lanes in the first warp |
| 1490 | // in order to perform the final step of a reduction in a parallel region |
| 1491 | // (reduction across warps). The array is placed in NVPTX __shared__ memory |
| 1492 | // for reduced latency, as well as to have a distinct copy for concurrently |
| 1493 | // executing target regions. The array is declared with common linkage so |
| 1494 | // as to be shared across compilation units. |
| 1495 | const char *TransferMediumName = |
| 1496 | "__openmp_nvptx_data_transfer_temporary_storage"; |
| 1497 | llvm::GlobalVariable *TransferMedium = |
| 1498 | M.getGlobalVariable(TransferMediumName); |
| 1499 | if (!TransferMedium) { |
| 1500 | auto *Ty = llvm::ArrayType::get(CGM.Int64Ty, WarpSize); |
| 1501 | unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared); |
| 1502 | TransferMedium = new llvm::GlobalVariable( |
| 1503 | M, Ty, |
| 1504 | /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage, |
| 1505 | llvm::Constant::getNullValue(Ty), TransferMediumName, |
| 1506 | /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, |
| 1507 | SharedAddressSpace); |
| 1508 | } |
| 1509 | |
| 1510 | // Get the CUDA thread id of the current OpenMP thread on the GPU. |
| 1511 | auto *ThreadID = getNVPTXThreadID(CGF); |
| 1512 | // nvptx_lane_id = nvptx_id % warpsize |
| 1513 | auto *LaneID = getNVPTXLaneID(CGF); |
| 1514 | // nvptx_warp_id = nvptx_id / warpsize |
| 1515 | auto *WarpID = getNVPTXWarpID(CGF); |
| 1516 | |
| 1517 | Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg); |
| 1518 | Address LocalReduceList( |
| 1519 | Bld.CreatePointerBitCastOrAddrSpaceCast( |
| 1520 | CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false, |
| 1521 | C.VoidPtrTy, SourceLocation()), |
| 1522 | CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()), |
| 1523 | CGF.getPointerAlign()); |
| 1524 | |
| 1525 | unsigned Idx = 0; |
| 1526 | for (auto &Private : Privates) { |
| 1527 | // |
| 1528 | // Warp master copies reduce element to transfer medium in __shared__ |
| 1529 | // memory. |
| 1530 | // |
| 1531 | llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then"); |
| 1532 | llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else"); |
| 1533 | llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont"); |
| 1534 | |
| 1535 | // if (lane_id == 0) |
| 1536 | auto IsWarpMaster = |
| 1537 | Bld.CreateICmpEQ(LaneID, Bld.getInt32(0), "warp_master"); |
| 1538 | Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB); |
| 1539 | CGF.EmitBlock(ThenBB); |
| 1540 | |
| 1541 | // Reduce element = LocalReduceList[i] |
| 1542 | Address ElemPtrPtrAddr = |
| 1543 | Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize()); |
| 1544 | llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar( |
| 1545 | ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation()); |
| 1546 | // elemptr = (type[i]*)(elemptrptr) |
| 1547 | Address ElemPtr = |
| 1548 | Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType())); |
| 1549 | ElemPtr = Bld.CreateElementBitCast( |
| 1550 | ElemPtr, CGF.ConvertTypeForMem(Private->getType())); |
| 1551 | // elem = *elemptr |
| 1552 | llvm::Value *Elem = CGF.EmitLoadOfScalar( |
| 1553 | ElemPtr, /*Volatile=*/false, Private->getType(), SourceLocation()); |
| 1554 | |
| 1555 | // Get pointer to location in transfer medium. |
| 1556 | // MediumPtr = &medium[warp_id] |
| 1557 | llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP( |
| 1558 | TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID}); |
| 1559 | Address MediumPtr(MediumPtrVal, C.getTypeAlignInChars(Private->getType())); |
| 1560 | // Casting to actual data type. |
| 1561 | // MediumPtr = (type[i]*)MediumPtrAddr; |
| 1562 | MediumPtr = Bld.CreateElementBitCast( |
| 1563 | MediumPtr, CGF.ConvertTypeForMem(Private->getType())); |
| 1564 | |
| 1565 | //*MediumPtr = elem |
| 1566 | Bld.CreateStore(Elem, MediumPtr); |
| 1567 | |
| 1568 | Bld.CreateBr(MergeBB); |
| 1569 | |
| 1570 | CGF.EmitBlock(ElseBB); |
| 1571 | Bld.CreateBr(MergeBB); |
| 1572 | |
| 1573 | CGF.EmitBlock(MergeBB); |
| 1574 | |
| 1575 | Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg); |
| 1576 | llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar( |
| 1577 | AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, SourceLocation()); |
| 1578 | |
| 1579 | auto *NumActiveThreads = Bld.CreateNSWMul( |
| 1580 | NumWarpsVal, getNVPTXWarpSize(CGF), "num_active_threads"); |
| 1581 | // named_barrier_sync(ParallelBarrierID, num_active_threads) |
| 1582 | syncParallelThreads(CGF, NumActiveThreads); |
| 1583 | |
| 1584 | // |
| 1585 | // Warp 0 copies reduce element from transfer medium. |
| 1586 | // |
| 1587 | llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then"); |
| 1588 | llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else"); |
| 1589 | llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont"); |
| 1590 | |
| 1591 | // Up to 32 threads in warp 0 are active. |
| 1592 | auto IsActiveThread = |
| 1593 | Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread"); |
| 1594 | Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB); |
| 1595 | |
| 1596 | CGF.EmitBlock(W0ThenBB); |
| 1597 | |
| 1598 | // SrcMediumPtr = &medium[tid] |
| 1599 | llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP( |
| 1600 | TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID}); |
| 1601 | Address SrcMediumPtr(SrcMediumPtrVal, |
| 1602 | C.getTypeAlignInChars(Private->getType())); |
| 1603 | // SrcMediumVal = *SrcMediumPtr; |
| 1604 | SrcMediumPtr = Bld.CreateElementBitCast( |
| 1605 | SrcMediumPtr, CGF.ConvertTypeForMem(Private->getType())); |
| 1606 | llvm::Value *SrcMediumValue = CGF.EmitLoadOfScalar( |
| 1607 | SrcMediumPtr, /*Volatile=*/false, Private->getType(), SourceLocation()); |
| 1608 | |
| 1609 | // TargetElemPtr = (type[i]*)(SrcDataAddr[i]) |
| 1610 | Address TargetElemPtrPtr = |
| 1611 | Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize()); |
| 1612 | llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar( |
| 1613 | TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation()); |
| 1614 | Address TargetElemPtr = |
| 1615 | Address(TargetElemPtrVal, C.getTypeAlignInChars(Private->getType())); |
| 1616 | TargetElemPtr = Bld.CreateElementBitCast( |
| 1617 | TargetElemPtr, CGF.ConvertTypeForMem(Private->getType())); |
| 1618 | |
| 1619 | // *TargetElemPtr = SrcMediumVal; |
| 1620 | CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false, |
| 1621 | Private->getType()); |
| 1622 | Bld.CreateBr(W0MergeBB); |
| 1623 | |
| 1624 | CGF.EmitBlock(W0ElseBB); |
| 1625 | Bld.CreateBr(W0MergeBB); |
| 1626 | |
| 1627 | CGF.EmitBlock(W0MergeBB); |
| 1628 | |
| 1629 | // While warp 0 copies values from transfer medium, all other warps must |
| 1630 | // wait. |
| 1631 | syncParallelThreads(CGF, NumActiveThreads); |
| 1632 | Idx++; |
| 1633 | } |
| 1634 | |
| 1635 | CGF.FinishFunction(); |
| 1636 | return Fn; |
| 1637 | } |
| 1638 | |
| 1639 | /// Emit a helper that reduces data across two OpenMP threads (lanes) |
| 1640 | /// in the same warp. It uses shuffle instructions to copy over data from |
| 1641 | /// a remote lane's stack. The reduction algorithm performed is specified |
| 1642 | /// by the fourth parameter. |
| 1643 | /// |
| 1644 | /// Algorithm Versions. |
| 1645 | /// Full Warp Reduce (argument value 0): |
| 1646 | /// This algorithm assumes that all 32 lanes are active and gathers |
| 1647 | /// data from these 32 lanes, producing a single resultant value. |
| 1648 | /// Contiguous Partial Warp Reduce (argument value 1): |
| 1649 | /// This algorithm assumes that only a *contiguous* subset of lanes |
| 1650 | /// are active. This happens for the last warp in a parallel region |
| 1651 | /// when the user specified num_threads is not an integer multiple of |
| 1652 | /// 32. This contiguous subset always starts with the zeroth lane. |
| 1653 | /// Partial Warp Reduce (argument value 2): |
| 1654 | /// This algorithm gathers data from any number of lanes at any position. |
| 1655 | /// All reduced values are stored in the lowest possible lane. The set |
| 1656 | /// of problems every algorithm addresses is a super set of those |
| 1657 | /// addressable by algorithms with a lower version number. Overhead |
| 1658 | /// increases as algorithm version increases. |
| 1659 | /// |
| 1660 | /// Terminology |
| 1661 | /// Reduce element: |
| 1662 | /// Reduce element refers to the individual data field with primitive |
| 1663 | /// data types to be combined and reduced across threads. |
| 1664 | /// Reduce list: |
| 1665 | /// Reduce list refers to a collection of local, thread-private |
| 1666 | /// reduce elements. |
| 1667 | /// Remote Reduce list: |
| 1668 | /// Remote Reduce list refers to a collection of remote (relative to |
| 1669 | /// the current thread) reduce elements. |
| 1670 | /// |
| 1671 | /// We distinguish between three states of threads that are important to |
| 1672 | /// the implementation of this function. |
| 1673 | /// Alive threads: |
| 1674 | /// Threads in a warp executing the SIMT instruction, as distinguished from |
| 1675 | /// threads that are inactive due to divergent control flow. |
| 1676 | /// Active threads: |
| 1677 | /// The minimal set of threads that has to be alive upon entry to this |
| 1678 | /// function. The computation is correct iff active threads are alive. |
| 1679 | /// Some threads are alive but they are not active because they do not |
| 1680 | /// contribute to the computation in any useful manner. Turning them off |
| 1681 | /// may introduce control flow overheads without any tangible benefits. |
| 1682 | /// Effective threads: |
| 1683 | /// In order to comply with the argument requirements of the shuffle |
| 1684 | /// function, we must keep all lanes holding data alive. But at most |
| 1685 | /// half of them perform value aggregation; we refer to this half of |
| 1686 | /// threads as effective. The other half is simply handing off their |
| 1687 | /// data. |
| 1688 | /// |
| 1689 | /// Procedure |
| 1690 | /// Value shuffle: |
| 1691 | /// In this step active threads transfer data from higher lane positions |
| 1692 | /// in the warp to lower lane positions, creating Remote Reduce list. |
| 1693 | /// Value aggregation: |
| 1694 | /// In this step, effective threads combine their thread local Reduce list |
| 1695 | /// with Remote Reduce list and store the result in the thread local |
| 1696 | /// Reduce list. |
| 1697 | /// Value copy: |
| 1698 | /// In this step, we deal with the assumption made by algorithm 2 |
| 1699 | /// (i.e. contiguity assumption). When we have an odd number of lanes |
| 1700 | /// active, say 2k+1, only k threads will be effective and therefore k |
| 1701 | /// new values will be produced. However, the Reduce list owned by the |
| 1702 | /// (2k+1)th thread is ignored in the value aggregation. Therefore |
| 1703 | /// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so |
| 1704 | /// that the contiguity assumption still holds. |
| 1705 | static llvm::Value * |
| 1706 | emitShuffleAndReduceFunction(CodeGenModule &CGM, |
| 1707 | ArrayRef<const Expr *> Privates, |
| 1708 | QualType ReductionArrayTy, llvm::Value *ReduceFn) { |
| 1709 | auto &C = CGM.getContext(); |
| 1710 | |
| 1711 | // Thread local Reduce list used to host the values of data to be reduced. |
Alexey Bataev | 5622323 | 2017-06-09 13:40:18 +0000 | [diff] [blame] | 1712 | ImplicitParamDecl ReduceListArg(C, C.VoidPtrTy, ImplicitParamDecl::Other); |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1713 | // Current lane id; could be logical. |
Alexey Bataev | 5622323 | 2017-06-09 13:40:18 +0000 | [diff] [blame] | 1714 | ImplicitParamDecl LaneIDArg(C, C.ShortTy, ImplicitParamDecl::Other); |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1715 | // Offset of the remote source lane relative to the current lane. |
Alexey Bataev | 5622323 | 2017-06-09 13:40:18 +0000 | [diff] [blame] | 1716 | ImplicitParamDecl RemoteLaneOffsetArg(C, C.ShortTy, |
| 1717 | ImplicitParamDecl::Other); |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1718 | // Algorithm version. This is expected to be known at compile time. |
Alexey Bataev | 5622323 | 2017-06-09 13:40:18 +0000 | [diff] [blame] | 1719 | ImplicitParamDecl AlgoVerArg(C, C.ShortTy, ImplicitParamDecl::Other); |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1720 | FunctionArgList Args; |
| 1721 | Args.push_back(&ReduceListArg); |
| 1722 | Args.push_back(&LaneIDArg); |
| 1723 | Args.push_back(&RemoteLaneOffsetArg); |
| 1724 | Args.push_back(&AlgoVerArg); |
| 1725 | |
| 1726 | auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); |
| 1727 | auto *Fn = llvm::Function::Create( |
| 1728 | CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage, |
| 1729 | "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule()); |
| 1730 | CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI); |
| 1731 | CodeGenFunction CGF(CGM); |
| 1732 | // We don't need debug information in this function as nothing here refers to |
| 1733 | // user code. |
| 1734 | CGF.disableDebugInfo(); |
| 1735 | CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args); |
| 1736 | |
| 1737 | auto &Bld = CGF.Builder; |
| 1738 | |
| 1739 | Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg); |
| 1740 | Address LocalReduceList( |
| 1741 | Bld.CreatePointerBitCastOrAddrSpaceCast( |
| 1742 | CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false, |
| 1743 | C.VoidPtrTy, SourceLocation()), |
| 1744 | CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()), |
| 1745 | CGF.getPointerAlign()); |
| 1746 | |
| 1747 | Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg); |
| 1748 | llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar( |
| 1749 | AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation()); |
| 1750 | |
| 1751 | Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg); |
| 1752 | llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar( |
| 1753 | AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation()); |
| 1754 | |
| 1755 | Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg); |
| 1756 | llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar( |
| 1757 | AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation()); |
| 1758 | |
| 1759 | // Create a local thread-private variable to host the Reduce list |
| 1760 | // from a remote lane. |
| 1761 | Address RemoteReduceList = |
| 1762 | CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list"); |
| 1763 | |
| 1764 | // This loop iterates through the list of reduce elements and copies, |
| 1765 | // element by element, from a remote lane in the warp to RemoteReduceList, |
| 1766 | // hosted on the thread's stack. |
| 1767 | emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates, |
| 1768 | LocalReduceList, RemoteReduceList, |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1769 | {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal, |
| 1770 | /*ScratchpadIndex=*/nullptr, |
| 1771 | /*ScratchpadWidth=*/nullptr}); |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1772 | |
| 1773 | // The actions to be performed on the Remote Reduce list is dependent |
| 1774 | // on the algorithm version. |
| 1775 | // |
| 1776 | // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 && |
| 1777 | // LaneId % 2 == 0 && Offset > 0): |
| 1778 | // do the reduction value aggregation |
| 1779 | // |
| 1780 | // The thread local variable Reduce list is mutated in place to host the |
| 1781 | // reduced data, which is the aggregated value produced from local and |
| 1782 | // remote lanes. |
| 1783 | // |
| 1784 | // Note that AlgoVer is expected to be a constant integer known at compile |
| 1785 | // time. |
| 1786 | // When AlgoVer==0, the first conjunction evaluates to true, making |
| 1787 | // the entire predicate true during compile time. |
| 1788 | // When AlgoVer==1, the second conjunction has only the second part to be |
| 1789 | // evaluated during runtime. Other conjunctions evaluates to false |
| 1790 | // during compile time. |
| 1791 | // When AlgoVer==2, the third conjunction has only the second part to be |
| 1792 | // evaluated during runtime. Other conjunctions evaluates to false |
| 1793 | // during compile time. |
| 1794 | auto CondAlgo0 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(0)); |
| 1795 | |
| 1796 | auto Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1)); |
| 1797 | auto CondAlgo1 = Bld.CreateAnd( |
| 1798 | Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal)); |
| 1799 | |
| 1800 | auto Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2)); |
| 1801 | auto CondAlgo2 = Bld.CreateAnd( |
| 1802 | Algo2, |
| 1803 | Bld.CreateICmpEQ(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1)), |
| 1804 | Bld.getInt16(0))); |
| 1805 | CondAlgo2 = Bld.CreateAnd( |
| 1806 | CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0))); |
| 1807 | |
| 1808 | auto CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1); |
| 1809 | CondReduce = Bld.CreateOr(CondReduce, CondAlgo2); |
| 1810 | |
| 1811 | llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then"); |
| 1812 | llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else"); |
| 1813 | llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont"); |
| 1814 | Bld.CreateCondBr(CondReduce, ThenBB, ElseBB); |
| 1815 | |
| 1816 | CGF.EmitBlock(ThenBB); |
| 1817 | // reduce_function(LocalReduceList, RemoteReduceList) |
| 1818 | llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast( |
| 1819 | LocalReduceList.getPointer(), CGF.VoidPtrTy); |
| 1820 | llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast( |
| 1821 | RemoteReduceList.getPointer(), CGF.VoidPtrTy); |
| 1822 | CGF.EmitCallOrInvoke(ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr}); |
| 1823 | Bld.CreateBr(MergeBB); |
| 1824 | |
| 1825 | CGF.EmitBlock(ElseBB); |
| 1826 | Bld.CreateBr(MergeBB); |
| 1827 | |
| 1828 | CGF.EmitBlock(MergeBB); |
| 1829 | |
| 1830 | // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local |
| 1831 | // Reduce list. |
| 1832 | Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1)); |
| 1833 | auto CondCopy = Bld.CreateAnd( |
| 1834 | Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal)); |
| 1835 | |
| 1836 | llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then"); |
| 1837 | llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else"); |
| 1838 | llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont"); |
| 1839 | Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB); |
| 1840 | |
| 1841 | CGF.EmitBlock(CpyThenBB); |
| 1842 | emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates, |
| 1843 | RemoteReduceList, LocalReduceList); |
| 1844 | Bld.CreateBr(CpyMergeBB); |
| 1845 | |
| 1846 | CGF.EmitBlock(CpyElseBB); |
| 1847 | Bld.CreateBr(CpyMergeBB); |
| 1848 | |
| 1849 | CGF.EmitBlock(CpyMergeBB); |
| 1850 | |
| 1851 | CGF.FinishFunction(); |
| 1852 | return Fn; |
| 1853 | } |
| 1854 | |
| 1855 | /// |
| 1856 | /// Design of OpenMP reductions on the GPU |
| 1857 | /// |
| 1858 | /// Consider a typical OpenMP program with one or more reduction |
| 1859 | /// clauses: |
| 1860 | /// |
| 1861 | /// float foo; |
| 1862 | /// double bar; |
| 1863 | /// #pragma omp target teams distribute parallel for \ |
| 1864 | /// reduction(+:foo) reduction(*:bar) |
| 1865 | /// for (int i = 0; i < N; i++) { |
| 1866 | /// foo += A[i]; bar *= B[i]; |
| 1867 | /// } |
| 1868 | /// |
| 1869 | /// where 'foo' and 'bar' are reduced across all OpenMP threads in |
| 1870 | /// all teams. In our OpenMP implementation on the NVPTX device an |
| 1871 | /// OpenMP team is mapped to a CUDA threadblock and OpenMP threads |
| 1872 | /// within a team are mapped to CUDA threads within a threadblock. |
| 1873 | /// Our goal is to efficiently aggregate values across all OpenMP |
| 1874 | /// threads such that: |
| 1875 | /// |
| 1876 | /// - the compiler and runtime are logically concise, and |
| 1877 | /// - the reduction is performed efficiently in a hierarchical |
| 1878 | /// manner as follows: within OpenMP threads in the same warp, |
| 1879 | /// across warps in a threadblock, and finally across teams on |
| 1880 | /// the NVPTX device. |
| 1881 | /// |
| 1882 | /// Introduction to Decoupling |
| 1883 | /// |
| 1884 | /// We would like to decouple the compiler and the runtime so that the |
| 1885 | /// latter is ignorant of the reduction variables (number, data types) |
| 1886 | /// and the reduction operators. This allows a simpler interface |
| 1887 | /// and implementation while still attaining good performance. |
| 1888 | /// |
| 1889 | /// Pseudocode for the aforementioned OpenMP program generated by the |
| 1890 | /// compiler is as follows: |
| 1891 | /// |
| 1892 | /// 1. Create private copies of reduction variables on each OpenMP |
| 1893 | /// thread: 'foo_private', 'bar_private' |
| 1894 | /// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned |
| 1895 | /// to it and writes the result in 'foo_private' and 'bar_private' |
| 1896 | /// respectively. |
| 1897 | /// 3. Call the OpenMP runtime on the GPU to reduce within a team |
| 1898 | /// and store the result on the team master: |
| 1899 | /// |
| 1900 | /// __kmpc_nvptx_parallel_reduce_nowait(..., |
| 1901 | /// reduceData, shuffleReduceFn, interWarpCpyFn) |
| 1902 | /// |
| 1903 | /// where: |
| 1904 | /// struct ReduceData { |
| 1905 | /// double *foo; |
| 1906 | /// double *bar; |
| 1907 | /// } reduceData |
| 1908 | /// reduceData.foo = &foo_private |
| 1909 | /// reduceData.bar = &bar_private |
| 1910 | /// |
| 1911 | /// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two |
| 1912 | /// auxiliary functions generated by the compiler that operate on |
| 1913 | /// variables of type 'ReduceData'. They aid the runtime perform |
| 1914 | /// algorithmic steps in a data agnostic manner. |
| 1915 | /// |
| 1916 | /// 'shuffleReduceFn' is a pointer to a function that reduces data |
| 1917 | /// of type 'ReduceData' across two OpenMP threads (lanes) in the |
| 1918 | /// same warp. It takes the following arguments as input: |
| 1919 | /// |
| 1920 | /// a. variable of type 'ReduceData' on the calling lane, |
| 1921 | /// b. its lane_id, |
| 1922 | /// c. an offset relative to the current lane_id to generate a |
| 1923 | /// remote_lane_id. The remote lane contains the second |
| 1924 | /// variable of type 'ReduceData' that is to be reduced. |
| 1925 | /// d. an algorithm version parameter determining which reduction |
| 1926 | /// algorithm to use. |
| 1927 | /// |
| 1928 | /// 'shuffleReduceFn' retrieves data from the remote lane using |
| 1929 | /// efficient GPU shuffle intrinsics and reduces, using the |
| 1930 | /// algorithm specified by the 4th parameter, the two operands |
| 1931 | /// element-wise. The result is written to the first operand. |
| 1932 | /// |
| 1933 | /// Different reduction algorithms are implemented in different |
| 1934 | /// runtime functions, all calling 'shuffleReduceFn' to perform |
| 1935 | /// the essential reduction step. Therefore, based on the 4th |
| 1936 | /// parameter, this function behaves slightly differently to |
| 1937 | /// cooperate with the runtime to ensure correctness under |
| 1938 | /// different circumstances. |
| 1939 | /// |
| 1940 | /// 'InterWarpCpyFn' is a pointer to a function that transfers |
| 1941 | /// reduced variables across warps. It tunnels, through CUDA |
| 1942 | /// shared memory, the thread-private data of type 'ReduceData' |
| 1943 | /// from lane 0 of each warp to a lane in the first warp. |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1944 | /// 4. Call the OpenMP runtime on the GPU to reduce across teams. |
| 1945 | /// The last team writes the global reduced value to memory. |
| 1946 | /// |
| 1947 | /// ret = __kmpc_nvptx_teams_reduce_nowait(..., |
| 1948 | /// reduceData, shuffleReduceFn, interWarpCpyFn, |
| 1949 | /// scratchpadCopyFn, loadAndReduceFn) |
| 1950 | /// |
| 1951 | /// 'scratchpadCopyFn' is a helper that stores reduced |
| 1952 | /// data from the team master to a scratchpad array in |
| 1953 | /// global memory. |
| 1954 | /// |
| 1955 | /// 'loadAndReduceFn' is a helper that loads data from |
| 1956 | /// the scratchpad array and reduces it with the input |
| 1957 | /// operand. |
| 1958 | /// |
| 1959 | /// These compiler generated functions hide address |
| 1960 | /// calculation and alignment information from the runtime. |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1961 | /// 5. if ret == 1: |
| 1962 | /// The team master of the last team stores the reduced |
| 1963 | /// result to the globals in memory. |
| 1964 | /// foo += reduceData.foo; bar *= reduceData.bar |
| 1965 | /// |
| 1966 | /// |
| 1967 | /// Warp Reduction Algorithms |
| 1968 | /// |
| 1969 | /// On the warp level, we have three algorithms implemented in the |
| 1970 | /// OpenMP runtime depending on the number of active lanes: |
| 1971 | /// |
| 1972 | /// Full Warp Reduction |
| 1973 | /// |
| 1974 | /// The reduce algorithm within a warp where all lanes are active |
| 1975 | /// is implemented in the runtime as follows: |
| 1976 | /// |
| 1977 | /// full_warp_reduce(void *reduce_data, |
| 1978 | /// kmp_ShuffleReductFctPtr ShuffleReduceFn) { |
| 1979 | /// for (int offset = WARPSIZE/2; offset > 0; offset /= 2) |
| 1980 | /// ShuffleReduceFn(reduce_data, 0, offset, 0); |
| 1981 | /// } |
| 1982 | /// |
| 1983 | /// The algorithm completes in log(2, WARPSIZE) steps. |
| 1984 | /// |
| 1985 | /// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is |
| 1986 | /// not used therefore we save instructions by not retrieving lane_id |
| 1987 | /// from the corresponding special registers. The 4th parameter, which |
| 1988 | /// represents the version of the algorithm being used, is set to 0 to |
| 1989 | /// signify full warp reduction. |
| 1990 | /// |
| 1991 | /// In this version, 'ShuffleReduceFn' behaves, per element, as follows: |
| 1992 | /// |
| 1993 | /// #reduce_elem refers to an element in the local lane's data structure |
| 1994 | /// #remote_elem is retrieved from a remote lane |
| 1995 | /// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE); |
| 1996 | /// reduce_elem = reduce_elem REDUCE_OP remote_elem; |
| 1997 | /// |
| 1998 | /// Contiguous Partial Warp Reduction |
| 1999 | /// |
| 2000 | /// This reduce algorithm is used within a warp where only the first |
| 2001 | /// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the |
| 2002 | /// number of OpenMP threads in a parallel region is not a multiple of |
| 2003 | /// WARPSIZE. The algorithm is implemented in the runtime as follows: |
| 2004 | /// |
| 2005 | /// void |
| 2006 | /// contiguous_partial_reduce(void *reduce_data, |
| 2007 | /// kmp_ShuffleReductFctPtr ShuffleReduceFn, |
| 2008 | /// int size, int lane_id) { |
| 2009 | /// int curr_size; |
| 2010 | /// int offset; |
| 2011 | /// curr_size = size; |
| 2012 | /// mask = curr_size/2; |
| 2013 | /// while (offset>0) { |
| 2014 | /// ShuffleReduceFn(reduce_data, lane_id, offset, 1); |
| 2015 | /// curr_size = (curr_size+1)/2; |
| 2016 | /// offset = curr_size/2; |
| 2017 | /// } |
| 2018 | /// } |
| 2019 | /// |
| 2020 | /// In this version, 'ShuffleReduceFn' behaves, per element, as follows: |
| 2021 | /// |
| 2022 | /// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE); |
| 2023 | /// if (lane_id < offset) |
| 2024 | /// reduce_elem = reduce_elem REDUCE_OP remote_elem |
| 2025 | /// else |
| 2026 | /// reduce_elem = remote_elem |
| 2027 | /// |
| 2028 | /// This algorithm assumes that the data to be reduced are located in a |
| 2029 | /// contiguous subset of lanes starting from the first. When there is |
| 2030 | /// an odd number of active lanes, the data in the last lane is not |
| 2031 | /// aggregated with any other lane's dat but is instead copied over. |
| 2032 | /// |
| 2033 | /// Dispersed Partial Warp Reduction |
| 2034 | /// |
| 2035 | /// This algorithm is used within a warp when any discontiguous subset of |
| 2036 | /// lanes are active. It is used to implement the reduction operation |
| 2037 | /// across lanes in an OpenMP simd region or in a nested parallel region. |
| 2038 | /// |
| 2039 | /// void |
| 2040 | /// dispersed_partial_reduce(void *reduce_data, |
| 2041 | /// kmp_ShuffleReductFctPtr ShuffleReduceFn) { |
| 2042 | /// int size, remote_id; |
| 2043 | /// int logical_lane_id = number_of_active_lanes_before_me() * 2; |
| 2044 | /// do { |
| 2045 | /// remote_id = next_active_lane_id_right_after_me(); |
| 2046 | /// # the above function returns 0 of no active lane |
| 2047 | /// # is present right after the current lane. |
| 2048 | /// size = number_of_active_lanes_in_this_warp(); |
| 2049 | /// logical_lane_id /= 2; |
| 2050 | /// ShuffleReduceFn(reduce_data, logical_lane_id, |
| 2051 | /// remote_id-1-threadIdx.x, 2); |
| 2052 | /// } while (logical_lane_id % 2 == 0 && size > 1); |
| 2053 | /// } |
| 2054 | /// |
| 2055 | /// There is no assumption made about the initial state of the reduction. |
| 2056 | /// Any number of lanes (>=1) could be active at any position. The reduction |
| 2057 | /// result is returned in the first active lane. |
| 2058 | /// |
| 2059 | /// In this version, 'ShuffleReduceFn' behaves, per element, as follows: |
| 2060 | /// |
| 2061 | /// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE); |
| 2062 | /// if (lane_id % 2 == 0 && offset > 0) |
| 2063 | /// reduce_elem = reduce_elem REDUCE_OP remote_elem |
| 2064 | /// else |
| 2065 | /// reduce_elem = remote_elem |
| 2066 | /// |
| 2067 | /// |
| 2068 | /// Intra-Team Reduction |
| 2069 | /// |
| 2070 | /// This function, as implemented in the runtime call |
| 2071 | /// '__kmpc_nvptx_parallel_reduce_nowait', aggregates data across OpenMP |
| 2072 | /// threads in a team. It first reduces within a warp using the |
| 2073 | /// aforementioned algorithms. We then proceed to gather all such |
| 2074 | /// reduced values at the first warp. |
| 2075 | /// |
| 2076 | /// The runtime makes use of the function 'InterWarpCpyFn', which copies |
| 2077 | /// data from each of the "warp master" (zeroth lane of each warp, where |
| 2078 | /// warp-reduced data is held) to the zeroth warp. This step reduces (in |
| 2079 | /// a mathematical sense) the problem of reduction across warp masters in |
| 2080 | /// a block to the problem of warp reduction. |
| 2081 | /// |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 2082 | /// |
| 2083 | /// Inter-Team Reduction |
| 2084 | /// |
| 2085 | /// Once a team has reduced its data to a single value, it is stored in |
| 2086 | /// a global scratchpad array. Since each team has a distinct slot, this |
| 2087 | /// can be done without locking. |
| 2088 | /// |
| 2089 | /// The last team to write to the scratchpad array proceeds to reduce the |
| 2090 | /// scratchpad array. One or more workers in the last team use the helper |
| 2091 | /// 'loadAndReduceDataFn' to load and reduce values from the array, i.e., |
| 2092 | /// the k'th worker reduces every k'th element. |
| 2093 | /// |
| 2094 | /// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait' to |
| 2095 | /// reduce across workers and compute a globally reduced value. |
| 2096 | /// |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 2097 | void CGOpenMPRuntimeNVPTX::emitReduction( |
| 2098 | CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates, |
| 2099 | ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs, |
| 2100 | ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) { |
| 2101 | if (!CGF.HaveInsertPoint()) |
| 2102 | return; |
| 2103 | |
| 2104 | bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind); |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 2105 | bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind); |
| 2106 | // FIXME: Add support for simd reduction. |
| 2107 | assert((TeamsReduction || ParallelReduction) && |
| 2108 | "Invalid reduction selection in emitReduction."); |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 2109 | |
| 2110 | auto &C = CGM.getContext(); |
| 2111 | |
| 2112 | // 1. Build a list of reduction variables. |
| 2113 | // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]}; |
| 2114 | auto Size = RHSExprs.size(); |
| 2115 | for (auto *E : Privates) { |
| 2116 | if (E->getType()->isVariablyModifiedType()) |
| 2117 | // Reserve place for array size. |
| 2118 | ++Size; |
| 2119 | } |
| 2120 | llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size); |
| 2121 | QualType ReductionArrayTy = |
| 2122 | C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal, |
| 2123 | /*IndexTypeQuals=*/0); |
| 2124 | Address ReductionList = |
| 2125 | CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list"); |
| 2126 | auto IPriv = Privates.begin(); |
| 2127 | unsigned Idx = 0; |
| 2128 | for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) { |
| 2129 | Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, |
| 2130 | CGF.getPointerSize()); |
| 2131 | CGF.Builder.CreateStore( |
| 2132 | CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( |
| 2133 | CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy), |
| 2134 | Elem); |
| 2135 | if ((*IPriv)->getType()->isVariablyModifiedType()) { |
| 2136 | // Store array size. |
| 2137 | ++Idx; |
| 2138 | Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, |
| 2139 | CGF.getPointerSize()); |
| 2140 | llvm::Value *Size = CGF.Builder.CreateIntCast( |
| 2141 | CGF.getVLASize( |
| 2142 | CGF.getContext().getAsVariableArrayType((*IPriv)->getType())) |
| 2143 | .first, |
| 2144 | CGF.SizeTy, /*isSigned=*/false); |
| 2145 | CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy), |
| 2146 | Elem); |
| 2147 | } |
| 2148 | } |
| 2149 | |
| 2150 | // 2. Emit reduce_func(). |
| 2151 | auto *ReductionFn = emitReductionFunction( |
| 2152 | CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates, |
| 2153 | LHSExprs, RHSExprs, ReductionOps); |
| 2154 | |
| 2155 | // 4. Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList), |
| 2156 | // RedList, shuffle_reduce_func, interwarp_copy_func); |
| 2157 | auto *ThreadId = getThreadID(CGF, Loc); |
| 2158 | auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy); |
| 2159 | auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( |
| 2160 | ReductionList.getPointer(), CGF.VoidPtrTy); |
| 2161 | |
| 2162 | auto *ShuffleAndReduceFn = emitShuffleAndReduceFunction( |
| 2163 | CGM, Privates, ReductionArrayTy, ReductionFn); |
| 2164 | auto *InterWarpCopyFn = |
| 2165 | emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy); |
| 2166 | |
| 2167 | llvm::Value *Res = nullptr; |
| 2168 | if (ParallelReduction) { |
| 2169 | llvm::Value *Args[] = {ThreadId, |
| 2170 | CGF.Builder.getInt32(RHSExprs.size()), |
| 2171 | ReductionArrayTySize, |
| 2172 | RL, |
| 2173 | ShuffleAndReduceFn, |
| 2174 | InterWarpCopyFn}; |
| 2175 | |
| 2176 | Res = CGF.EmitRuntimeCall( |
| 2177 | createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_reduce_nowait), |
| 2178 | Args); |
| 2179 | } |
| 2180 | |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 2181 | if (TeamsReduction) { |
| 2182 | auto *ScratchPadCopyFn = |
| 2183 | emitCopyToScratchpad(CGM, Privates, ReductionArrayTy); |
| 2184 | auto *LoadAndReduceFn = emitReduceScratchpadFunction( |
| 2185 | CGM, Privates, ReductionArrayTy, ReductionFn); |
| 2186 | |
| 2187 | llvm::Value *Args[] = {ThreadId, |
| 2188 | CGF.Builder.getInt32(RHSExprs.size()), |
| 2189 | ReductionArrayTySize, |
| 2190 | RL, |
| 2191 | ShuffleAndReduceFn, |
| 2192 | InterWarpCopyFn, |
| 2193 | ScratchPadCopyFn, |
| 2194 | LoadAndReduceFn}; |
| 2195 | Res = CGF.EmitRuntimeCall( |
| 2196 | createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_teams_reduce_nowait), |
| 2197 | Args); |
| 2198 | } |
| 2199 | |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 2200 | // 5. Build switch(res) |
| 2201 | auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default"); |
| 2202 | auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/1); |
| 2203 | |
| 2204 | // 6. Build case 1: where we have reduced values in the master |
| 2205 | // thread in each team. |
| 2206 | // __kmpc_end_reduce{_nowait}(<gtid>); |
| 2207 | // break; |
| 2208 | auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1"); |
| 2209 | SwInst->addCase(CGF.Builder.getInt32(1), Case1BB); |
| 2210 | CGF.EmitBlock(Case1BB); |
| 2211 | |
| 2212 | // Add emission of __kmpc_end_reduce{_nowait}(<gtid>); |
| 2213 | llvm::Value *EndArgs[] = {ThreadId}; |
| 2214 | auto &&CodeGen = [&Privates, &LHSExprs, &RHSExprs, &ReductionOps, |
| 2215 | this](CodeGenFunction &CGF, PrePostActionTy &Action) { |
| 2216 | auto IPriv = Privates.begin(); |
| 2217 | auto ILHS = LHSExprs.begin(); |
| 2218 | auto IRHS = RHSExprs.begin(); |
| 2219 | for (auto *E : ReductionOps) { |
| 2220 | emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS), |
| 2221 | cast<DeclRefExpr>(*IRHS)); |
| 2222 | ++IPriv; |
| 2223 | ++ILHS; |
| 2224 | ++IRHS; |
| 2225 | } |
| 2226 | }; |
| 2227 | RegionCodeGenTy RCG(CodeGen); |
| 2228 | NVPTXActionTy Action( |
| 2229 | nullptr, llvm::None, |
| 2230 | createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_reduce_nowait), |
| 2231 | EndArgs); |
| 2232 | RCG.setAction(Action); |
| 2233 | RCG(CGF); |
| 2234 | CGF.EmitBranch(DefaultBB); |
| 2235 | CGF.EmitBlock(DefaultBB, /*IsFinished=*/true); |
| 2236 | } |
Alexey Bataev | 3b8d558 | 2017-08-08 18:04:06 +0000 | [diff] [blame] | 2237 | |
| 2238 | const VarDecl * |
| 2239 | CGOpenMPRuntimeNVPTX::translateParameter(const FieldDecl *FD, |
| 2240 | const VarDecl *NativeParam) const { |
| 2241 | if (!NativeParam->getType()->isReferenceType()) |
| 2242 | return NativeParam; |
| 2243 | QualType ArgType = NativeParam->getType(); |
| 2244 | QualifierCollector QC; |
| 2245 | const Type *NonQualTy = QC.strip(ArgType); |
| 2246 | QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType(); |
| 2247 | if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) { |
| 2248 | if (Attr->getCaptureKind() == OMPC_map) { |
| 2249 | PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy, |
| 2250 | LangAS::opencl_global); |
| 2251 | } |
| 2252 | } |
| 2253 | ArgType = CGM.getContext().getPointerType(PointeeTy); |
| 2254 | QC.addRestrict(); |
| 2255 | enum { NVPTX_local_addr = 5 }; |
| 2256 | QC.addAddressSpace(NVPTX_local_addr); |
| 2257 | ArgType = QC.apply(CGM.getContext(), ArgType); |
| 2258 | return ImplicitParamDecl::Create( |
| 2259 | CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(), |
| 2260 | NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other); |
| 2261 | } |
| 2262 | |
| 2263 | Address |
| 2264 | CGOpenMPRuntimeNVPTX::getParameterAddress(CodeGenFunction &CGF, |
| 2265 | const VarDecl *NativeParam, |
| 2266 | const VarDecl *TargetParam) const { |
| 2267 | assert(NativeParam != TargetParam && |
| 2268 | NativeParam->getType()->isReferenceType() && |
| 2269 | "Native arg must not be the same as target arg."); |
| 2270 | Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam); |
| 2271 | QualType NativeParamType = NativeParam->getType(); |
| 2272 | QualifierCollector QC; |
| 2273 | const Type *NonQualTy = QC.strip(NativeParamType); |
| 2274 | QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType(); |
| 2275 | unsigned NativePointeeAddrSpace = |
| 2276 | NativePointeeTy.getQualifiers().getAddressSpace(); |
| 2277 | QualType TargetPointeeTy = TargetParam->getType()->getPointeeType(); |
| 2278 | llvm::Value *TargetAddr = CGF.EmitLoadOfScalar( |
| 2279 | LocalAddr, /*Volatile=*/false, TargetPointeeTy, SourceLocation()); |
| 2280 | // First cast to generic. |
| 2281 | TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( |
| 2282 | TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo( |
| 2283 | /*AddrSpace=*/0)); |
| 2284 | // Cast from generic to native address space. |
| 2285 | TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( |
| 2286 | TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo( |
| 2287 | NativePointeeAddrSpace)); |
| 2288 | Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType); |
| 2289 | CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false, |
| 2290 | NativeParam->getType()); |
| 2291 | return NativeParamAddr; |
| 2292 | } |
| 2293 | |
| 2294 | void CGOpenMPRuntimeNVPTX::emitOutlinedFunctionCall( |
Alexey Bataev | 3c595a6 | 2017-08-14 15:01:03 +0000 | [diff] [blame] | 2295 | CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn, |
Alexey Bataev | 3b8d558 | 2017-08-08 18:04:06 +0000 | [diff] [blame] | 2296 | ArrayRef<llvm::Value *> Args) const { |
| 2297 | SmallVector<llvm::Value *, 4> TargetArgs; |
Alexey Bataev | 07ed94a | 2017-08-15 14:34:04 +0000 | [diff] [blame^] | 2298 | TargetArgs.reserve(Args.size()); |
Alexey Bataev | 3b8d558 | 2017-08-08 18:04:06 +0000 | [diff] [blame] | 2299 | auto *FnType = |
| 2300 | cast<llvm::FunctionType>(OutlinedFn->getType()->getPointerElementType()); |
| 2301 | for (unsigned I = 0, E = Args.size(); I < E; ++I) { |
Alexey Bataev | 07ed94a | 2017-08-15 14:34:04 +0000 | [diff] [blame^] | 2302 | if (FnType->isVarArg() && FnType->getNumParams() <= I) { |
| 2303 | TargetArgs.append(std::next(Args.begin(), I), Args.end()); |
| 2304 | break; |
| 2305 | } |
Alexey Bataev | 3b8d558 | 2017-08-08 18:04:06 +0000 | [diff] [blame] | 2306 | llvm::Type *TargetType = FnType->getParamType(I); |
| 2307 | llvm::Value *NativeArg = Args[I]; |
| 2308 | if (!TargetType->isPointerTy()) { |
| 2309 | TargetArgs.emplace_back(NativeArg); |
| 2310 | continue; |
| 2311 | } |
| 2312 | llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( |
| 2313 | NativeArg, NativeArg->getType()->getPointerElementType()->getPointerTo( |
| 2314 | /*AddrSpace=*/0)); |
| 2315 | TargetArgs.emplace_back( |
| 2316 | CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType)); |
| 2317 | } |
Alexey Bataev | 3c595a6 | 2017-08-14 15:01:03 +0000 | [diff] [blame] | 2318 | CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs); |
Alexey Bataev | 3b8d558 | 2017-08-08 18:04:06 +0000 | [diff] [blame] | 2319 | } |