blob: 6c0f00d10ca37de92765a66dda9b3044d35ab8c6 [file] [log] [blame]
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001//===---- 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 Bataevc5b1d322016-03-04 09:22:22 +000016#include "clang/AST/DeclOpenMP.h"
Carlo Bertollic6872252016-04-04 15:55:02 +000017#include "CodeGenFunction.h"
18#include "clang/AST/StmtOpenMP.h"
Samuel Antao45bfe4c2016-02-08 15:59:20 +000019
20using namespace clang;
21using namespace CodeGen;
22
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +000023namespace {
24enum OpenMPRTLFunctionNVPTX {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +000025 /// \brief Call to void __kmpc_kernel_init(kmp_int32 thread_limit,
26 /// int16_t RequiresOMPRuntime);
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +000027 OMPRTL_NVPTX__kmpc_kernel_init,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +000028 /// \brief Call to void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +000029 OMPRTL_NVPTX__kmpc_kernel_deinit,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +000030 /// \brief Call to void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +000031 /// int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +000032 OMPRTL_NVPTX__kmpc_spmd_kernel_init,
33 /// \brief Call to void __kmpc_spmd_kernel_deinit();
34 OMPRTL_NVPTX__kmpc_spmd_kernel_deinit,
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000035 /// \brief Call to void __kmpc_kernel_prepare_parallel(void
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +000036 /// *outlined_function, void ***args, kmp_int32 nArgs, int16_t
37 /// IsOMPRuntimeInitialized);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000038 OMPRTL_NVPTX__kmpc_kernel_prepare_parallel,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +000039 /// \brief Call to bool __kmpc_kernel_parallel(void **outlined_function, void
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +000040 /// ***args, int16_t IsOMPRuntimeInitialized);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000041 OMPRTL_NVPTX__kmpc_kernel_parallel,
42 /// \brief Call to void __kmpc_kernel_end_parallel();
43 OMPRTL_NVPTX__kmpc_kernel_end_parallel,
44 /// Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
45 /// global_tid);
46 OMPRTL_NVPTX__kmpc_serialized_parallel,
47 /// Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
48 /// global_tid);
49 OMPRTL_NVPTX__kmpc_end_serialized_parallel,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000050 /// \brief Call to int32_t __kmpc_shuffle_int32(int32_t element,
51 /// int16_t lane_offset, int16_t warp_size);
52 OMPRTL_NVPTX__kmpc_shuffle_int32,
53 /// \brief Call to int64_t __kmpc_shuffle_int64(int64_t element,
54 /// int16_t lane_offset, int16_t warp_size);
55 OMPRTL_NVPTX__kmpc_shuffle_int64,
56 /// \brief Call to __kmpc_nvptx_parallel_reduce_nowait(kmp_int32
57 /// global_tid, kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
58 /// void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
59 /// lane_offset, int16_t shortCircuit),
60 /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num));
61 OMPRTL_NVPTX__kmpc_parallel_reduce_nowait,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +000062 /// \brief Call to __kmpc_nvptx_teams_reduce_nowait(int32_t global_tid,
63 /// int32_t num_vars, size_t reduce_size, void *reduce_data,
64 /// void (*kmp_ShuffleReductFctPtr)(void *rhs, int16_t lane_id, int16_t
65 /// lane_offset, int16_t shortCircuit),
66 /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num),
67 /// void (*kmp_CopyToScratchpadFctPtr)(void *reduce_data, void * scratchpad,
68 /// int32_t index, int32_t width),
69 /// void (*kmp_LoadReduceFctPtr)(void *reduce_data, void * scratchpad, int32_t
70 /// index, int32_t width, int32_t reduce))
71 OMPRTL_NVPTX__kmpc_teams_reduce_nowait,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000072 /// \brief Call to __kmpc_nvptx_end_reduce_nowait(int32_t global_tid);
73 OMPRTL_NVPTX__kmpc_end_reduce_nowait
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +000074};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000075
76/// Pre(post)-action for different OpenMP constructs specialized for NVPTX.
77class NVPTXActionTy final : public PrePostActionTy {
78 llvm::Value *EnterCallee;
79 ArrayRef<llvm::Value *> EnterArgs;
80 llvm::Value *ExitCallee;
81 ArrayRef<llvm::Value *> ExitArgs;
82 bool Conditional;
83 llvm::BasicBlock *ContBlock = nullptr;
84
85public:
86 NVPTXActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
87 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
88 bool Conditional = false)
89 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
90 ExitArgs(ExitArgs), Conditional(Conditional) {}
91 void Enter(CodeGenFunction &CGF) override {
92 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
93 if (Conditional) {
94 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
95 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
96 ContBlock = CGF.createBasicBlock("omp_if.end");
97 // Generate the branch (If-stmt)
98 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
99 CGF.EmitBlock(ThenBlock);
100 }
101 }
102 void Done(CodeGenFunction &CGF) {
103 // Emit the rest of blocks/branches
104 CGF.EmitBranch(ContBlock);
105 CGF.EmitBlock(ContBlock, true);
106 }
107 void Exit(CodeGenFunction &CGF) override {
108 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
109 }
110};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000111
112// A class to track the execution mode when codegening directives within
113// a target region. The appropriate mode (generic/spmd) is set on entry
114// to the target region and used by containing directives such as 'parallel'
115// to emit optimized code.
116class ExecutionModeRAII {
117private:
118 CGOpenMPRuntimeNVPTX::ExecutionMode SavedMode;
119 CGOpenMPRuntimeNVPTX::ExecutionMode &Mode;
120
121public:
122 ExecutionModeRAII(CGOpenMPRuntimeNVPTX::ExecutionMode &Mode,
123 CGOpenMPRuntimeNVPTX::ExecutionMode NewMode)
124 : Mode(Mode) {
125 SavedMode = Mode;
126 Mode = NewMode;
127 }
128 ~ExecutionModeRAII() { Mode = SavedMode; }
129};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000130
131/// GPU Configuration: This information can be derived from cuda registers,
132/// however, providing compile time constants helps generate more efficient
133/// code. For all practical purposes this is fine because the configuration
134/// is the same for all known NVPTX architectures.
135enum MachineConfiguration : unsigned {
136 WarpSize = 32,
137 /// Number of bits required to represent a lane identifier, which is
138 /// computed as log_2(WarpSize).
139 LaneIDBits = 5,
140 LaneIDMask = WarpSize - 1,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +0000141
142 /// Global memory alignment for performance.
143 GlobalMemoryAlignment = 256,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000144};
145
146enum NamedBarrier : unsigned {
147 /// Synchronize on this barrier #ID using a named barrier primitive.
148 /// Only the subset of active threads in a parallel region arrive at the
149 /// barrier.
150 NB_Parallel = 1,
151};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000152} // anonymous namespace
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000153
154/// Get the GPU warp size.
155static llvm::Value *getNVPTXWarpSize(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000156 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000157 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000158 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_warpsize),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000159 "nvptx_warp_size");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000160}
161
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000162/// Get the id of the current thread on the GPU.
163static llvm::Value *getNVPTXThreadID(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000164 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000165 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000166 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_tid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000167 "nvptx_tid");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000168}
169
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000170/// Get the id of the warp in the block.
171/// We assume that the warp size is 32, which is always the case
172/// on the NVPTX device, to generate more efficient code.
173static llvm::Value *getNVPTXWarpID(CodeGenFunction &CGF) {
174 CGBuilderTy &Bld = CGF.Builder;
175 return Bld.CreateAShr(getNVPTXThreadID(CGF), LaneIDBits, "nvptx_warp_id");
176}
177
178/// Get the id of the current lane in the Warp.
179/// We assume that the warp size is 32, which is always the case
180/// on the NVPTX device, to generate more efficient code.
181static llvm::Value *getNVPTXLaneID(CodeGenFunction &CGF) {
182 CGBuilderTy &Bld = CGF.Builder;
183 return Bld.CreateAnd(getNVPTXThreadID(CGF), Bld.getInt32(LaneIDMask),
184 "nvptx_lane_id");
185}
186
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000187/// Get the maximum number of threads in a block of the GPU.
188static llvm::Value *getNVPTXNumThreads(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000189 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000190 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000191 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_ntid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000192 "nvptx_num_threads");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000193}
194
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000195/// Get barrier to synchronize all threads in a block.
196static void getNVPTXCTABarrier(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000197 CGF.EmitRuntimeCall(llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000198 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_barrier0));
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000199}
200
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000201/// Get barrier #ID to synchronize selected (multiple of warp size) threads in
202/// a CTA.
203static void getNVPTXBarrier(CodeGenFunction &CGF, int ID,
204 llvm::Value *NumThreads) {
205 CGBuilderTy &Bld = CGF.Builder;
206 llvm::Value *Args[] = {Bld.getInt32(ID), NumThreads};
Alexey Bataev3c595a62017-08-14 15:01:03 +0000207 CGF.EmitRuntimeCall(llvm::Intrinsic::getDeclaration(
208 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_barrier),
209 Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000210}
211
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000212/// Synchronize all GPU threads in a block.
213static void syncCTAThreads(CodeGenFunction &CGF) { getNVPTXCTABarrier(CGF); }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000214
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000215/// Synchronize worker threads in a parallel region.
216static void syncParallelThreads(CodeGenFunction &CGF, llvm::Value *NumThreads) {
217 return getNVPTXBarrier(CGF, NB_Parallel, NumThreads);
218}
219
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000220/// Get the value of the thread_limit clause in the teams directive.
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000221/// For the 'generic' execution mode, the runtime encodes thread_limit in
222/// the launch parameters, always starting thread_limit+warpSize threads per
223/// CTA. The threads in the last warp are reserved for master execution.
224/// For the 'spmd' execution mode, all threads in a CTA are part of the team.
225static llvm::Value *getThreadLimit(CodeGenFunction &CGF,
226 bool IsInSpmdExecutionMode = false) {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000227 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000228 return IsInSpmdExecutionMode
229 ? getNVPTXNumThreads(CGF)
230 : Bld.CreateSub(getNVPTXNumThreads(CGF), getNVPTXWarpSize(CGF),
231 "thread_limit");
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000232}
233
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000234/// Get the thread id of the OMP master thread.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000235/// The master thread id is the first thread (lane) of the last warp in the
236/// GPU block. Warp size is assumed to be some power of 2.
237/// Thread id is 0 indexed.
238/// E.g: If NumThreads is 33, master id is 32.
239/// If NumThreads is 64, master id is 32.
240/// If NumThreads is 1024, master id is 992.
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000241static llvm::Value *getMasterThreadID(CodeGenFunction &CGF) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000242 CGBuilderTy &Bld = CGF.Builder;
243 llvm::Value *NumThreads = getNVPTXNumThreads(CGF);
244
245 // We assume that the warp size is a power of 2.
246 llvm::Value *Mask = Bld.CreateSub(getNVPTXWarpSize(CGF), Bld.getInt32(1));
247
248 return Bld.CreateAnd(Bld.CreateSub(NumThreads, Bld.getInt32(1)),
249 Bld.CreateNot(Mask), "master_tid");
250}
251
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000252CGOpenMPRuntimeNVPTX::WorkerFunctionState::WorkerFunctionState(
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000253 CodeGenModule &CGM, SourceLocation Loc)
254 : WorkerFn(nullptr), CGFI(nullptr), Loc(Loc) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000255 createWorkerFunction(CGM);
Vasileios Kalintirise5c09592016-03-22 10:41:20 +0000256}
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000257
258void CGOpenMPRuntimeNVPTX::WorkerFunctionState::createWorkerFunction(
259 CodeGenModule &CGM) {
260 // Create an worker function with no arguments.
261 CGFI = &CGM.getTypes().arrangeNullaryFunction();
262
263 WorkerFn = llvm::Function::Create(
264 CGM.getTypes().GetFunctionType(*CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataevaee93892018-01-08 20:09:47 +0000265 /*placeholder=*/"_worker", &CGM.getModule());
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000266 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, WorkerFn, *CGFI);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000267}
268
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000269bool CGOpenMPRuntimeNVPTX::isInSpmdExecutionMode() const {
270 return CurrentExecutionMode == CGOpenMPRuntimeNVPTX::ExecutionMode::Spmd;
271}
272
273static CGOpenMPRuntimeNVPTX::ExecutionMode
274getExecutionModeForDirective(CodeGenModule &CGM,
275 const OMPExecutableDirective &D) {
276 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
277 switch (DirectiveKind) {
278 case OMPD_target:
Arpith Chacko Jacobcca61a32017-01-26 15:43:27 +0000279 case OMPD_target_teams:
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000280 return CGOpenMPRuntimeNVPTX::ExecutionMode::Generic;
281 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +0000282 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +0000283 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000284 return CGOpenMPRuntimeNVPTX::ExecutionMode::Spmd;
285 default:
286 llvm_unreachable("Unsupported directive on NVPTX device.");
287 }
288 llvm_unreachable("Unsupported directive on NVPTX device.");
289}
290
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000291void CGOpenMPRuntimeNVPTX::emitGenericKernel(const OMPExecutableDirective &D,
292 StringRef ParentName,
293 llvm::Function *&OutlinedFn,
294 llvm::Constant *&OutlinedFnID,
295 bool IsOffloadEntry,
296 const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000297 ExecutionModeRAII ModeRAII(CurrentExecutionMode,
298 CGOpenMPRuntimeNVPTX::ExecutionMode::Generic);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000299 EntryFunctionState EST;
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000300 WorkerFunctionState WST(CGM, D.getLocStart());
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000301 Work.clear();
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +0000302 WrapperFunctionsMap.clear();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000303
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000304 // Emit target region as a standalone region.
305 class NVPTXPrePostActionTy : public PrePostActionTy {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000306 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
307 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000308
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000309 public:
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000310 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000311 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST)
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000312 : EST(EST), WST(WST) {}
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000313 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000314 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
315 .emitGenericEntryHeader(CGF, EST, WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000316 }
317 void Exit(CodeGenFunction &CGF) override {
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000318 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
319 .emitGenericEntryFooter(CGF, EST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000320 }
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000321 } Action(EST, WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000322 CodeGen.setAction(Action);
323 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
324 IsOffloadEntry, CodeGen);
325
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000326 // Now change the name of the worker function to correspond to this target
327 // region's entry function.
328 WST.WorkerFn->setName(OutlinedFn->getName() + "_worker");
Alexey Bataevaee93892018-01-08 20:09:47 +0000329
330 // Create the worker function
331 emitWorkerFunction(WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000332}
333
334// Setup NVPTX threads for master-worker OpenMP scheme.
335void CGOpenMPRuntimeNVPTX::emitGenericEntryHeader(CodeGenFunction &CGF,
336 EntryFunctionState &EST,
337 WorkerFunctionState &WST) {
338 CGBuilderTy &Bld = CGF.Builder;
339
340 llvm::BasicBlock *WorkerBB = CGF.createBasicBlock(".worker");
341 llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
342 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
343 EST.ExitBB = CGF.createBasicBlock(".exit");
344
345 auto *IsWorker =
346 Bld.CreateICmpULT(getNVPTXThreadID(CGF), getThreadLimit(CGF));
347 Bld.CreateCondBr(IsWorker, WorkerBB, MasterCheckBB);
348
349 CGF.EmitBlock(WorkerBB);
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000350 emitOutlinedFunctionCall(CGF, WST.Loc, WST.WorkerFn);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000351 CGF.EmitBranch(EST.ExitBB);
352
353 CGF.EmitBlock(MasterCheckBB);
354 auto *IsMaster =
355 Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
356 Bld.CreateCondBr(IsMaster, MasterBB, EST.ExitBB);
357
358 CGF.EmitBlock(MasterBB);
359 // First action in sequential region:
360 // Initialize the state of the OpenMP runtime library on the GPU.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +0000361 // TODO: Optimize runtime initialization and pass in correct value.
362 llvm::Value *Args[] = {getThreadLimit(CGF),
363 Bld.getInt16(/*RequiresOMPRuntime=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000364 CGF.EmitRuntimeCall(
365 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_init), Args);
366}
367
368void CGOpenMPRuntimeNVPTX::emitGenericEntryFooter(CodeGenFunction &CGF,
369 EntryFunctionState &EST) {
370 if (!EST.ExitBB)
371 EST.ExitBB = CGF.createBasicBlock(".exit");
372
373 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".termination.notifier");
374 CGF.EmitBranch(TerminateBB);
375
376 CGF.EmitBlock(TerminateBB);
377 // Signal termination condition.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +0000378 // TODO: Optimize runtime initialization and pass in correct value.
379 llvm::Value *Args[] = {CGF.Builder.getInt16(/*IsOMPRuntimeInitialized=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000380 CGF.EmitRuntimeCall(
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +0000381 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_deinit), Args);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000382 // Barrier to terminate worker threads.
383 syncCTAThreads(CGF);
384 // Master thread jumps to exit point.
385 CGF.EmitBranch(EST.ExitBB);
386
387 CGF.EmitBlock(EST.ExitBB);
388 EST.ExitBB = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000389}
390
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000391void CGOpenMPRuntimeNVPTX::emitSpmdKernel(const OMPExecutableDirective &D,
392 StringRef ParentName,
393 llvm::Function *&OutlinedFn,
394 llvm::Constant *&OutlinedFnID,
395 bool IsOffloadEntry,
396 const RegionCodeGenTy &CodeGen) {
397 ExecutionModeRAII ModeRAII(CurrentExecutionMode,
398 CGOpenMPRuntimeNVPTX::ExecutionMode::Spmd);
399 EntryFunctionState EST;
400
401 // Emit target region as a standalone region.
402 class NVPTXPrePostActionTy : public PrePostActionTy {
403 CGOpenMPRuntimeNVPTX &RT;
404 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
405 const OMPExecutableDirective &D;
406
407 public:
408 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT,
409 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
410 const OMPExecutableDirective &D)
411 : RT(RT), EST(EST), D(D) {}
412 void Enter(CodeGenFunction &CGF) override {
413 RT.emitSpmdEntryHeader(CGF, EST, D);
414 }
415 void Exit(CodeGenFunction &CGF) override {
416 RT.emitSpmdEntryFooter(CGF, EST);
417 }
418 } Action(*this, EST, D);
419 CodeGen.setAction(Action);
420 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
421 IsOffloadEntry, CodeGen);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000422}
423
424void CGOpenMPRuntimeNVPTX::emitSpmdEntryHeader(
425 CodeGenFunction &CGF, EntryFunctionState &EST,
426 const OMPExecutableDirective &D) {
427 auto &Bld = CGF.Builder;
428
429 // Setup BBs in entry function.
430 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute");
431 EST.ExitBB = CGF.createBasicBlock(".exit");
432
433 // Initialize the OMP state in the runtime; called by all active threads.
434 // TODO: Set RequiresOMPRuntime and RequiresDataSharing parameters
435 // based on code analysis of the target region.
436 llvm::Value *Args[] = {getThreadLimit(CGF, /*IsInSpmdExecutionMode=*/true),
437 /*RequiresOMPRuntime=*/Bld.getInt16(1),
438 /*RequiresDataSharing=*/Bld.getInt16(1)};
439 CGF.EmitRuntimeCall(
440 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_init), Args);
441 CGF.EmitBranch(ExecuteBB);
442
443 CGF.EmitBlock(ExecuteBB);
444}
445
446void CGOpenMPRuntimeNVPTX::emitSpmdEntryFooter(CodeGenFunction &CGF,
447 EntryFunctionState &EST) {
448 if (!EST.ExitBB)
449 EST.ExitBB = CGF.createBasicBlock(".exit");
450
451 llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit");
452 CGF.EmitBranch(OMPDeInitBB);
453
454 CGF.EmitBlock(OMPDeInitBB);
455 // DeInitialize the OMP state in the runtime; called by all active threads.
456 CGF.EmitRuntimeCall(
457 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_deinit), None);
458 CGF.EmitBranch(EST.ExitBB);
459
460 CGF.EmitBlock(EST.ExitBB);
461 EST.ExitBB = nullptr;
462}
463
464// Create a unique global variable to indicate the execution mode of this target
465// region. The execution mode is either 'generic', or 'spmd' depending on the
466// target directive. This variable is picked up by the offload library to setup
467// the device appropriately before kernel launch. If the execution mode is
468// 'generic', the runtime reserves one warp for the master, otherwise, all
469// warps participate in parallel work.
470static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
471 CGOpenMPRuntimeNVPTX::ExecutionMode Mode) {
472 (void)new llvm::GlobalVariable(
473 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
474 llvm::GlobalValue::WeakAnyLinkage,
475 llvm::ConstantInt::get(CGM.Int8Ty, Mode), Name + Twine("_exec_mode"));
476}
477
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000478void CGOpenMPRuntimeNVPTX::emitWorkerFunction(WorkerFunctionState &WST) {
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +0000479 ASTContext &Ctx = CGM.getContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000480
481 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000482 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, *WST.CGFI, {},
483 WST.Loc, WST.Loc);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000484 emitWorkerLoop(CGF, WST);
485 CGF.FinishFunction();
486}
487
488void CGOpenMPRuntimeNVPTX::emitWorkerLoop(CodeGenFunction &CGF,
489 WorkerFunctionState &WST) {
490 //
491 // The workers enter this loop and wait for parallel work from the master.
492 // When the master encounters a parallel region it sets up the work + variable
493 // arguments, and wakes up the workers. The workers first check to see if
494 // they are required for the parallel region, i.e., within the # of requested
495 // parallel threads. The activated workers load the variable arguments and
496 // execute the parallel work.
497 //
498
499 CGBuilderTy &Bld = CGF.Builder;
500
501 llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work");
502 llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers");
503 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel");
504 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel");
505 llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel");
506 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
507
508 CGF.EmitBranch(AwaitBB);
509
510 // Workers wait for work from master.
511 CGF.EmitBlock(AwaitBB);
512 // Wait for parallel work
513 syncCTAThreads(CGF);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000514
515 Address WorkFn =
516 CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn");
517 Address ExecStatus =
518 CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status");
519 CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0));
520 CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy));
521
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +0000522 // Set up shared arguments
523 Address SharedArgs =
524 CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrPtrTy, "shared_args");
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +0000525 // TODO: Optimize runtime initialization and pass in correct value.
526 llvm::Value *Args[] = {WorkFn.getPointer(), SharedArgs.getPointer(),
527 /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000528 llvm::Value *Ret = CGF.EmitRuntimeCall(
529 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args);
530 Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000531
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000532 // On termination condition (workid == 0), exit loop.
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000533 llvm::Value *ShouldTerminate =
534 Bld.CreateIsNull(Bld.CreateLoad(WorkFn), "should_terminate");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000535 Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB);
536
537 // Activate requested workers.
538 CGF.EmitBlock(SelectWorkersBB);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000539 llvm::Value *IsActive =
540 Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active");
541 Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000542
543 // Signal start of parallel region.
544 CGF.EmitBlock(ExecuteBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000545
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +0000546 // Current context
547 ASTContext &Ctx = CGF.getContext();
548
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000549 // Process work items: outlined parallel functions.
550 for (auto *W : Work) {
551 // Try to match this outlined function.
552 auto *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy);
553
554 llvm::Value *WorkFnMatch =
555 Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match");
556
557 llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn");
558 llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next");
559 Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB);
560
561 // Execute this outlined function.
562 CGF.EmitBlock(ExecuteFNBB);
563
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +0000564 // Insert call to work function via shared wrapper. The shared
565 // wrapper takes exactly three arguments:
566 // - the parallelism level;
567 // - the master thread ID;
568 // - the list of references to shared arguments.
569 //
570 // TODO: Assert that the function is a wrapper function.s
571 Address Capture = CGF.EmitLoadOfPointer(SharedArgs,
572 Ctx.getPointerType(
573 Ctx.getPointerType(Ctx.VoidPtrTy)).castAs<PointerType>());
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000574 emitOutlinedFunctionCall(CGF, WST.Loc, W,
575 {Bld.getInt16(/*ParallelLevel=*/0),
576 getMasterThreadID(CGF), Capture.getPointer()});
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000577
578 // Go to end of parallel region.
579 CGF.EmitBranch(TerminateBB);
580
581 CGF.EmitBlock(CheckNextBB);
582 }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000583
584 // Signal end of parallel region.
585 CGF.EmitBlock(TerminateBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000586 CGF.EmitRuntimeCall(
587 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_end_parallel),
588 llvm::None);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000589 CGF.EmitBranch(BarrierBB);
590
591 // All active and inactive workers wait at a barrier after parallel region.
592 CGF.EmitBlock(BarrierBB);
593 // Barrier after parallel region.
594 syncCTAThreads(CGF);
595 CGF.EmitBranch(AwaitBB);
596
597 // Exit target region.
598 CGF.EmitBlock(ExitBB);
599}
600
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000601/// \brief Returns specified OpenMP runtime function for the current OpenMP
602/// implementation. Specialized for the NVPTX device.
603/// \param Function OpenMP runtime function.
604/// \return Specified function.
605llvm::Constant *
606CGOpenMPRuntimeNVPTX::createNVPTXRuntimeFunction(unsigned Function) {
607 llvm::Constant *RTLFn = nullptr;
608 switch (static_cast<OpenMPRTLFunctionNVPTX>(Function)) {
609 case OMPRTL_NVPTX__kmpc_kernel_init: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +0000610 // Build void __kmpc_kernel_init(kmp_int32 thread_limit, int16_t
611 // RequiresOMPRuntime);
612 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty};
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000613 llvm::FunctionType *FnTy =
614 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
615 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_init");
616 break;
617 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000618 case OMPRTL_NVPTX__kmpc_kernel_deinit: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +0000619 // Build void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
620 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000621 llvm::FunctionType *FnTy =
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +0000622 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000623 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_deinit");
624 break;
625 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000626 case OMPRTL_NVPTX__kmpc_spmd_kernel_init: {
627 // Build void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +0000628 // int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000629 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
630 llvm::FunctionType *FnTy =
631 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
632 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_init");
633 break;
634 }
635 case OMPRTL_NVPTX__kmpc_spmd_kernel_deinit: {
636 // Build void __kmpc_spmd_kernel_deinit();
637 llvm::FunctionType *FnTy =
638 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
639 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_deinit");
640 break;
641 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000642 case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: {
643 /// Build void __kmpc_kernel_prepare_parallel(
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +0000644 /// void *outlined_function, void ***args, kmp_int32 nArgs, int16_t
645 /// IsOMPRuntimeInitialized);
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +0000646 llvm::Type *TypeParams[] = {CGM.Int8PtrTy,
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +0000647 CGM.Int8PtrPtrTy->getPointerTo(0), CGM.Int32Ty,
648 CGM.Int16Ty};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000649 llvm::FunctionType *FnTy =
650 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
651 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_prepare_parallel");
652 break;
653 }
654 case OMPRTL_NVPTX__kmpc_kernel_parallel: {
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +0000655 /// Build bool __kmpc_kernel_parallel(void **outlined_function, void
656 /// ***args, int16_t IsOMPRuntimeInitialized);
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +0000657 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy,
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +0000658 CGM.Int8PtrPtrTy->getPointerTo(0), CGM.Int16Ty};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000659 llvm::Type *RetTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
660 llvm::FunctionType *FnTy =
661 llvm::FunctionType::get(RetTy, TypeParams, /*isVarArg*/ false);
662 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_parallel");
663 break;
664 }
665 case OMPRTL_NVPTX__kmpc_kernel_end_parallel: {
666 /// Build void __kmpc_kernel_end_parallel();
667 llvm::FunctionType *FnTy =
668 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
669 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_end_parallel");
670 break;
671 }
672 case OMPRTL_NVPTX__kmpc_serialized_parallel: {
673 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
674 // global_tid);
675 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
676 llvm::FunctionType *FnTy =
677 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
678 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
679 break;
680 }
681 case OMPRTL_NVPTX__kmpc_end_serialized_parallel: {
682 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
683 // global_tid);
684 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
685 llvm::FunctionType *FnTy =
686 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
687 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
688 break;
689 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000690 case OMPRTL_NVPTX__kmpc_shuffle_int32: {
691 // Build int32_t __kmpc_shuffle_int32(int32_t element,
692 // int16_t lane_offset, int16_t warp_size);
693 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
694 llvm::FunctionType *FnTy =
695 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
696 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int32");
697 break;
698 }
699 case OMPRTL_NVPTX__kmpc_shuffle_int64: {
700 // Build int64_t __kmpc_shuffle_int64(int64_t element,
701 // int16_t lane_offset, int16_t warp_size);
702 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int16Ty, CGM.Int16Ty};
703 llvm::FunctionType *FnTy =
704 llvm::FunctionType::get(CGM.Int64Ty, TypeParams, /*isVarArg*/ false);
705 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int64");
706 break;
707 }
708 case OMPRTL_NVPTX__kmpc_parallel_reduce_nowait: {
709 // Build int32_t kmpc_nvptx_parallel_reduce_nowait(kmp_int32 global_tid,
710 // kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
711 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
712 // lane_offset, int16_t Algorithm Version),
713 // void (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
714 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
715 CGM.Int16Ty, CGM.Int16Ty};
716 auto *ShuffleReduceFnTy =
717 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
718 /*isVarArg=*/false);
719 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
720 auto *InterWarpCopyFnTy =
721 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
722 /*isVarArg=*/false);
723 llvm::Type *TypeParams[] = {CGM.Int32Ty,
724 CGM.Int32Ty,
725 CGM.SizeTy,
726 CGM.VoidPtrTy,
727 ShuffleReduceFnTy->getPointerTo(),
728 InterWarpCopyFnTy->getPointerTo()};
729 llvm::FunctionType *FnTy =
730 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
731 RTLFn = CGM.CreateRuntimeFunction(
732 FnTy, /*Name=*/"__kmpc_nvptx_parallel_reduce_nowait");
733 break;
734 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +0000735 case OMPRTL_NVPTX__kmpc_teams_reduce_nowait: {
736 // Build int32_t __kmpc_nvptx_teams_reduce_nowait(int32_t global_tid,
737 // int32_t num_vars, size_t reduce_size, void *reduce_data,
738 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
739 // lane_offset, int16_t shortCircuit),
740 // void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num),
741 // void (*kmp_CopyToScratchpadFctPtr)(void *reduce_data, void * scratchpad,
742 // int32_t index, int32_t width),
743 // void (*kmp_LoadReduceFctPtr)(void *reduce_data, void * scratchpad,
744 // int32_t index, int32_t width, int32_t reduce))
745 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
746 CGM.Int16Ty, CGM.Int16Ty};
747 auto *ShuffleReduceFnTy =
748 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
749 /*isVarArg=*/false);
750 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
751 auto *InterWarpCopyFnTy =
752 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
753 /*isVarArg=*/false);
754 llvm::Type *CopyToScratchpadTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy,
755 CGM.Int32Ty, CGM.Int32Ty};
756 auto *CopyToScratchpadFnTy =
757 llvm::FunctionType::get(CGM.VoidTy, CopyToScratchpadTypeParams,
758 /*isVarArg=*/false);
759 llvm::Type *LoadReduceTypeParams[] = {
760 CGM.VoidPtrTy, CGM.VoidPtrTy, CGM.Int32Ty, CGM.Int32Ty, CGM.Int32Ty};
761 auto *LoadReduceFnTy =
762 llvm::FunctionType::get(CGM.VoidTy, LoadReduceTypeParams,
763 /*isVarArg=*/false);
764 llvm::Type *TypeParams[] = {CGM.Int32Ty,
765 CGM.Int32Ty,
766 CGM.SizeTy,
767 CGM.VoidPtrTy,
768 ShuffleReduceFnTy->getPointerTo(),
769 InterWarpCopyFnTy->getPointerTo(),
770 CopyToScratchpadFnTy->getPointerTo(),
771 LoadReduceFnTy->getPointerTo()};
772 llvm::FunctionType *FnTy =
773 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
774 RTLFn = CGM.CreateRuntimeFunction(
775 FnTy, /*Name=*/"__kmpc_nvptx_teams_reduce_nowait");
776 break;
777 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000778 case OMPRTL_NVPTX__kmpc_end_reduce_nowait: {
779 // Build __kmpc_end_reduce_nowait(kmp_int32 global_tid);
780 llvm::Type *TypeParams[] = {CGM.Int32Ty};
781 llvm::FunctionType *FnTy =
782 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
783 RTLFn = CGM.CreateRuntimeFunction(
784 FnTy, /*Name=*/"__kmpc_nvptx_end_reduce_nowait");
785 break;
786 }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000787 }
788 return RTLFn;
789}
790
791void CGOpenMPRuntimeNVPTX::createOffloadEntry(llvm::Constant *ID,
792 llvm::Constant *Addr,
Samuel Antaof83efdb2017-01-05 16:02:49 +0000793 uint64_t Size, int32_t) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000794 auto *F = dyn_cast<llvm::Function>(Addr);
795 // TODO: Add support for global variables on the device after declare target
796 // support.
797 if (!F)
798 return;
799 llvm::Module *M = F->getParent();
800 llvm::LLVMContext &Ctx = M->getContext();
801
802 // Get "nvvm.annotations" metadata node
803 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
804
805 llvm::Metadata *MDVals[] = {
806 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, "kernel"),
807 llvm::ConstantAsMetadata::get(
808 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))};
809 // Append metadata to nvvm.annotations
810 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
811}
812
813void CGOpenMPRuntimeNVPTX::emitTargetOutlinedFunction(
814 const OMPExecutableDirective &D, StringRef ParentName,
815 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000816 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000817 if (!IsOffloadEntry) // Nothing to do.
818 return;
819
820 assert(!ParentName.empty() && "Invalid target region parent name!");
821
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000822 CGOpenMPRuntimeNVPTX::ExecutionMode Mode =
823 getExecutionModeForDirective(CGM, D);
824 switch (Mode) {
825 case CGOpenMPRuntimeNVPTX::ExecutionMode::Generic:
826 emitGenericKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
827 CodeGen);
828 break;
829 case CGOpenMPRuntimeNVPTX::ExecutionMode::Spmd:
830 emitSpmdKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
831 CodeGen);
832 break;
833 case CGOpenMPRuntimeNVPTX::ExecutionMode::Unknown:
834 llvm_unreachable(
835 "Unknown programming model for OpenMP directive on NVPTX target.");
836 }
837
838 setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000839}
840
Samuel Antao45bfe4c2016-02-08 15:59:20 +0000841CGOpenMPRuntimeNVPTX::CGOpenMPRuntimeNVPTX(CodeGenModule &CGM)
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000842 : CGOpenMPRuntime(CGM), CurrentExecutionMode(ExecutionMode::Unknown) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000843 if (!CGM.getLangOpts().OpenMPIsDevice)
844 llvm_unreachable("OpenMP NVPTX can only handle device code.");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000845}
Carlo Bertollic6872252016-04-04 15:55:02 +0000846
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +0000847void CGOpenMPRuntimeNVPTX::emitProcBindClause(CodeGenFunction &CGF,
848 OpenMPProcBindClauseKind ProcBind,
849 SourceLocation Loc) {
850 // Do nothing in case of Spmd mode and L0 parallel.
851 // TODO: If in Spmd mode and L1 parallel emit the clause.
852 if (isInSpmdExecutionMode())
853 return;
854
855 CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc);
856}
857
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +0000858void CGOpenMPRuntimeNVPTX::emitNumThreadsClause(CodeGenFunction &CGF,
859 llvm::Value *NumThreads,
860 SourceLocation Loc) {
861 // Do nothing in case of Spmd mode and L0 parallel.
862 // TODO: If in Spmd mode and L1 parallel emit the clause.
863 if (isInSpmdExecutionMode())
864 return;
865
866 CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc);
867}
868
Carlo Bertollic6872252016-04-04 15:55:02 +0000869void CGOpenMPRuntimeNVPTX::emitNumTeamsClause(CodeGenFunction &CGF,
870 const Expr *NumTeams,
871 const Expr *ThreadLimit,
872 SourceLocation Loc) {}
873
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +0000874llvm::Value *CGOpenMPRuntimeNVPTX::emitParallelOutlinedFunction(
875 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
876 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +0000877
878 auto *OutlinedFun = cast<llvm::Function>(
879 CGOpenMPRuntime::emitParallelOutlinedFunction(
880 D, ThreadIDVar, InnermostKind, CodeGen));
881 if (!isInSpmdExecutionMode()) {
882 llvm::Function *WrapperFun =
883 createDataSharingWrapper(OutlinedFun, D);
884 WrapperFunctionsMap[OutlinedFun] = WrapperFun;
885 }
886
887 return OutlinedFun;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +0000888}
889
890llvm::Value *CGOpenMPRuntimeNVPTX::emitTeamsOutlinedFunction(
Carlo Bertollic6872252016-04-04 15:55:02 +0000891 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
892 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
893
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +0000894 llvm::Value *OutlinedFunVal = CGOpenMPRuntime::emitTeamsOutlinedFunction(
895 D, ThreadIDVar, InnermostKind, CodeGen);
896 llvm::Function *OutlinedFun = cast<llvm::Function>(OutlinedFunVal);
897 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +0000898 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +0000899 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
Carlo Bertollic6872252016-04-04 15:55:02 +0000900
901 return OutlinedFun;
902}
903
904void CGOpenMPRuntimeNVPTX::emitTeamsCall(CodeGenFunction &CGF,
905 const OMPExecutableDirective &D,
906 SourceLocation Loc,
907 llvm::Value *OutlinedFn,
908 ArrayRef<llvm::Value *> CapturedVars) {
909 if (!CGF.HaveInsertPoint())
910 return;
911
912 Address ZeroAddr =
913 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
914 /*Name*/ ".zero.addr");
915 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
916 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
917 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
918 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
919 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +0000920 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Carlo Bertollic6872252016-04-04 15:55:02 +0000921}
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000922
923void CGOpenMPRuntimeNVPTX::emitParallelCall(
924 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
925 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
926 if (!CGF.HaveInsertPoint())
927 return;
928
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000929 if (isInSpmdExecutionMode())
930 emitSpmdParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
931 else
932 emitGenericParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000933}
934
935void CGOpenMPRuntimeNVPTX::emitGenericParallelCall(
936 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
937 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
938 llvm::Function *Fn = cast<llvm::Function>(OutlinedFn);
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +0000939 llvm::Function *WFn = WrapperFunctionsMap[Fn];
940 assert(WFn && "Wrapper function does not exist!");
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000941
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +0000942 // Force inline this outlined function at its call site.
943 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
944
945 auto &&L0ParallelGen = [this, WFn, &CapturedVars](CodeGenFunction &CGF,
946 PrePostActionTy &) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000947 CGBuilderTy &Bld = CGF.Builder;
948
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +0000949 llvm::Value *ID = Bld.CreateBitOrPointerCast(WFn, CGM.Int8PtrTy);
950
951 if (!CapturedVars.empty()) {
Gheorghe-Teodor Berceab4c74c62017-12-12 21:38:43 +0000952 // There's somehting to share, add the attribute
953 CGF.CurFn->addFnAttr("has-nvptx-shared-depot");
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +0000954 // Prepare for parallel region. Indicate the outlined function.
955 Address SharedArgs =
956 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy,
957 "shared_args");
958 llvm::Value *SharedArgsPtr = SharedArgs.getPointer();
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +0000959 // TODO: Optimize runtime initialization and pass in correct value.
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +0000960 llvm::Value *Args[] = {ID, SharedArgsPtr,
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +0000961 Bld.getInt32(CapturedVars.size()),
962 /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +0000963
964 CGF.EmitRuntimeCall(
965 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_prepare_parallel),
966 Args);
967
968 unsigned Idx = 0;
969 ASTContext &Ctx = CGF.getContext();
970 for (llvm::Value *V : CapturedVars) {
971 Address Dst = Bld.CreateConstInBoundsGEP(
972 CGF.EmitLoadOfPointer(SharedArgs,
973 Ctx.getPointerType(
974 Ctx.getPointerType(Ctx.VoidPtrTy)).castAs<PointerType>()),
975 Idx, CGF.getPointerSize());
976 llvm::Value *PtrV = Bld.CreateBitCast(V, CGF.VoidPtrTy);
977 CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
978 Ctx.getPointerType(Ctx.VoidPtrTy));
979 Idx++;
980 }
981 } else {
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +0000982 // TODO: Optimize runtime initialization and pass in correct value.
983 llvm::Value *Args[] = {
984 ID, llvm::ConstantPointerNull::get(CGF.VoidPtrPtrTy->getPointerTo(0)),
985 /*nArgs=*/Bld.getInt32(0), /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +0000986 CGF.EmitRuntimeCall(
987 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_prepare_parallel),
988 Args);
989 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000990
991 // Activate workers. This barrier is used by the master to signal
992 // work for the workers.
993 syncCTAThreads(CGF);
994
995 // OpenMP [2.5, Parallel Construct, p.49]
996 // There is an implied barrier at the end of a parallel region. After the
997 // end of a parallel region, only the master thread of the team resumes
998 // execution of the enclosing task region.
999 //
1000 // The master waits at this barrier until all workers are done.
1001 syncCTAThreads(CGF);
1002
1003 // Remember for post-processing in worker loop.
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +00001004 Work.emplace_back(WFn);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001005 };
1006
1007 auto *RTLoc = emitUpdateLocation(CGF, Loc);
1008 auto *ThreadID = getThreadID(CGF, Loc);
1009 llvm::Value *Args[] = {RTLoc, ThreadID};
1010
Alexey Bataev3c595a62017-08-14 15:01:03 +00001011 auto &&SeqGen = [this, Fn, &CapturedVars, &Args, Loc](CodeGenFunction &CGF,
1012 PrePostActionTy &) {
1013 auto &&CodeGen = [this, Fn, &CapturedVars, Loc](CodeGenFunction &CGF,
1014 PrePostActionTy &Action) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001015 Action.Enter(CGF);
1016
1017 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
1018 OutlinedFnArgs.push_back(
1019 llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo()));
1020 OutlinedFnArgs.push_back(
1021 llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo()));
1022 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00001023 emitOutlinedFunctionCall(CGF, Loc, Fn, OutlinedFnArgs);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001024 };
1025
1026 RegionCodeGenTy RCG(CodeGen);
1027 NVPTXActionTy Action(
1028 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
1029 Args,
1030 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
1031 Args);
1032 RCG.setAction(Action);
1033 RCG(CGF);
1034 };
1035
1036 if (IfCond)
1037 emitOMPIfClause(CGF, IfCond, L0ParallelGen, SeqGen);
1038 else {
1039 CodeGenFunction::RunCleanupsScope Scope(CGF);
1040 RegionCodeGenTy ThenRCG(L0ParallelGen);
1041 ThenRCG(CGF);
1042 }
1043}
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001044
1045void CGOpenMPRuntimeNVPTX::emitSpmdParallelCall(
1046 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
1047 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
1048 // Just call the outlined function to execute the parallel region.
1049 // OutlinedFn(&GTid, &zero, CapturedStruct);
1050 //
1051 // TODO: Do something with IfCond when support for the 'if' clause
1052 // is added on Spmd target directives.
1053 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
1054 OutlinedFnArgs.push_back(
1055 llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo()));
1056 OutlinedFnArgs.push_back(
1057 llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo()));
1058 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00001059 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001060}
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001061
Alexey Bataevb2575932018-01-04 20:18:55 +00001062/// Cast value to the specified type.
1063static llvm::Value *
1064castValueToType(CodeGenFunction &CGF, llvm::Value *Val, llvm::Type *CastTy,
1065 llvm::Optional<bool> IsSigned = llvm::None) {
1066 if (Val->getType() == CastTy)
1067 return Val;
1068 if (Val->getType()->getPrimitiveSizeInBits() > 0 &&
1069 CastTy->getPrimitiveSizeInBits() > 0 &&
1070 Val->getType()->getPrimitiveSizeInBits() ==
1071 CastTy->getPrimitiveSizeInBits())
1072 return CGF.Builder.CreateBitCast(Val, CastTy);
1073 if (IsSigned.hasValue() && CastTy->isIntegerTy() &&
1074 Val->getType()->isIntegerTy())
1075 return CGF.Builder.CreateIntCast(Val, CastTy, *IsSigned);
1076 Address CastItem = CGF.CreateTempAlloca(
1077 CastTy,
1078 CharUnits::fromQuantity(
1079 CGF.CGM.getDataLayout().getPrefTypeAlignment(Val->getType())));
1080 Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1081 CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
1082 CGF.Builder.CreateStore(Val, ValCastItem);
1083 return CGF.Builder.CreateLoad(CastItem);
1084}
1085
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001086/// This function creates calls to one of two shuffle functions to copy
1087/// variables between lanes in a warp.
1088static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001089 llvm::Value *Elem,
1090 llvm::Value *Offset) {
1091 auto &CGM = CGF.CGM;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001092 auto &Bld = CGF.Builder;
1093 CGOpenMPRuntimeNVPTX &RT =
1094 *(static_cast<CGOpenMPRuntimeNVPTX *>(&CGM.getOpenMPRuntime()));
1095
Alexey Bataevb2575932018-01-04 20:18:55 +00001096 unsigned Size = CGM.getDataLayout().getTypeStoreSize(Elem->getType());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001097 assert(Size <= 8 && "Unsupported bitwidth in shuffle instruction.");
1098
1099 OpenMPRTLFunctionNVPTX ShuffleFn = Size <= 4
1100 ? OMPRTL_NVPTX__kmpc_shuffle_int32
1101 : OMPRTL_NVPTX__kmpc_shuffle_int64;
1102
1103 // Cast all types to 32- or 64-bit values before calling shuffle routines.
Alexey Bataevb2575932018-01-04 20:18:55 +00001104 llvm::Type *CastTy = Size <= 4 ? CGM.Int32Ty : CGM.Int64Ty;
1105 llvm::Value *ElemCast = castValueToType(CGF, Elem, CastTy, /*isSigned=*/true);
1106 auto *WarpSize =
1107 Bld.CreateIntCast(getNVPTXWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001108
1109 auto *ShuffledVal =
1110 CGF.EmitRuntimeCall(RT.createNVPTXRuntimeFunction(ShuffleFn),
1111 {ElemCast, Offset, WarpSize});
1112
Alexey Bataevb2575932018-01-04 20:18:55 +00001113 return castValueToType(CGF, ShuffledVal, Elem->getType(), /*isSigned=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001114}
1115
1116namespace {
1117enum CopyAction : unsigned {
1118 // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
1119 // the warp using shuffle instructions.
1120 RemoteLaneToThread,
1121 // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
1122 ThreadCopy,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001123 // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
1124 ThreadToScratchpad,
1125 // ScratchpadToThread: Copy from a scratchpad array in global memory
1126 // containing team-reduced data to a thread's stack.
1127 ScratchpadToThread,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001128};
1129} // namespace
1130
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001131struct CopyOptionsTy {
1132 llvm::Value *RemoteLaneOffset;
1133 llvm::Value *ScratchpadIndex;
1134 llvm::Value *ScratchpadWidth;
1135};
1136
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001137/// Emit instructions to copy a Reduce list, which contains partially
1138/// aggregated values, in the specified direction.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001139static void emitReductionListCopy(
1140 CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
1141 ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
1142 CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001143
1144 auto &CGM = CGF.CGM;
1145 auto &C = CGM.getContext();
1146 auto &Bld = CGF.Builder;
1147
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001148 auto *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
1149 auto *ScratchpadIndex = CopyOptions.ScratchpadIndex;
1150 auto *ScratchpadWidth = CopyOptions.ScratchpadWidth;
1151
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001152 // Iterates, element-by-element, through the source Reduce list and
1153 // make a copy.
1154 unsigned Idx = 0;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001155 unsigned Size = Privates.size();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001156 for (auto &Private : Privates) {
1157 Address SrcElementAddr = Address::invalid();
1158 Address DestElementAddr = Address::invalid();
1159 Address DestElementPtrAddr = Address::invalid();
1160 // Should we shuffle in an element from a remote lane?
1161 bool ShuffleInElement = false;
1162 // Set to true to update the pointer in the dest Reduce list to a
1163 // newly created element.
1164 bool UpdateDestListPtr = false;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001165 // Increment the src or dest pointer to the scratchpad, for each
1166 // new element.
1167 bool IncrScratchpadSrc = false;
1168 bool IncrScratchpadDest = false;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001169
1170 switch (Action) {
1171 case RemoteLaneToThread: {
1172 // Step 1.1: Get the address for the src element in the Reduce list.
1173 Address SrcElementPtrAddr =
1174 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00001175 SrcElementAddr = CGF.EmitLoadOfPointer(
1176 SrcElementPtrAddr,
1177 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001178
1179 // Step 1.2: Create a temporary to store the element in the destination
1180 // Reduce list.
1181 DestElementPtrAddr =
1182 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
1183 DestElementAddr =
1184 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
1185 ShuffleInElement = true;
1186 UpdateDestListPtr = true;
1187 break;
1188 }
1189 case ThreadCopy: {
1190 // Step 1.1: Get the address for the src element in the Reduce list.
1191 Address SrcElementPtrAddr =
1192 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00001193 SrcElementAddr = CGF.EmitLoadOfPointer(
1194 SrcElementPtrAddr,
1195 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001196
1197 // Step 1.2: Get the address for dest element. The destination
1198 // element has already been created on the thread's stack.
1199 DestElementPtrAddr =
1200 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00001201 DestElementAddr = CGF.EmitLoadOfPointer(
1202 DestElementPtrAddr,
1203 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001204 break;
1205 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001206 case ThreadToScratchpad: {
1207 // Step 1.1: Get the address for the src element in the Reduce list.
1208 Address SrcElementPtrAddr =
1209 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00001210 SrcElementAddr = CGF.EmitLoadOfPointer(
1211 SrcElementPtrAddr,
1212 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001213
1214 // Step 1.2: Get the address for dest element:
1215 // address = base + index * ElementSizeInChars.
1216 unsigned ElementSizeInChars =
1217 C.getTypeSizeInChars(Private->getType()).getQuantity();
1218 auto *CurrentOffset =
1219 Bld.CreateMul(llvm::ConstantInt::get(CGM.SizeTy, ElementSizeInChars),
1220 ScratchpadIndex);
1221 auto *ScratchPadElemAbsolutePtrVal =
1222 Bld.CreateAdd(DestBase.getPointer(), CurrentOffset);
1223 ScratchPadElemAbsolutePtrVal =
1224 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00001225 DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
1226 C.getTypeAlignInChars(Private->getType()));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001227 IncrScratchpadDest = true;
1228 break;
1229 }
1230 case ScratchpadToThread: {
1231 // Step 1.1: Get the address for the src element in the scratchpad.
1232 // address = base + index * ElementSizeInChars.
1233 unsigned ElementSizeInChars =
1234 C.getTypeSizeInChars(Private->getType()).getQuantity();
1235 auto *CurrentOffset =
1236 Bld.CreateMul(llvm::ConstantInt::get(CGM.SizeTy, ElementSizeInChars),
1237 ScratchpadIndex);
1238 auto *ScratchPadElemAbsolutePtrVal =
1239 Bld.CreateAdd(SrcBase.getPointer(), CurrentOffset);
1240 ScratchPadElemAbsolutePtrVal =
1241 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
1242 SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
1243 C.getTypeAlignInChars(Private->getType()));
1244 IncrScratchpadSrc = true;
1245
1246 // Step 1.2: Create a temporary to store the element in the destination
1247 // Reduce list.
1248 DestElementPtrAddr =
1249 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
1250 DestElementAddr =
1251 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
1252 UpdateDestListPtr = true;
1253 break;
1254 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001255 }
1256
1257 // Regardless of src and dest of copy, we emit the load of src
1258 // element as this is required in all directions
1259 SrcElementAddr = Bld.CreateElementBitCast(
1260 SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
1261 llvm::Value *Elem =
1262 CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false,
1263 Private->getType(), SourceLocation());
1264
1265 // Now that all active lanes have read the element in the
1266 // Reduce list, shuffle over the value from the remote lane.
Alexey Bataevb2575932018-01-04 20:18:55 +00001267 if (ShuffleInElement)
1268 Elem = createRuntimeShuffleFunction(CGF, Elem, RemoteLaneOffset);
1269
1270 DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
1271 SrcElementAddr.getElementType());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001272
1273 // Store the source element value to the dest element address.
1274 CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false,
1275 Private->getType());
1276
1277 // Step 3.1: Modify reference in dest Reduce list as needed.
1278 // Modifying the reference in Reduce list to point to the newly
1279 // created element. The element is live in the current function
1280 // scope and that of functions it invokes (i.e., reduce_function).
1281 // RemoteReduceData[i] = (void*)&RemoteElem
1282 if (UpdateDestListPtr) {
1283 CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
1284 DestElementAddr.getPointer(), CGF.VoidPtrTy),
1285 DestElementPtrAddr, /*Volatile=*/false,
1286 C.VoidPtrTy);
1287 }
1288
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001289 // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
1290 // address of the next element in scratchpad memory, unless we're currently
1291 // processing the last one. Memory alignment is also taken care of here.
1292 if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
1293 llvm::Value *ScratchpadBasePtr =
1294 IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
1295 unsigned ElementSizeInChars =
1296 C.getTypeSizeInChars(Private->getType()).getQuantity();
1297 ScratchpadBasePtr = Bld.CreateAdd(
1298 ScratchpadBasePtr,
1299 Bld.CreateMul(ScratchpadWidth, llvm::ConstantInt::get(
1300 CGM.SizeTy, ElementSizeInChars)));
1301
1302 // Take care of global memory alignment for performance
1303 ScratchpadBasePtr = Bld.CreateSub(ScratchpadBasePtr,
1304 llvm::ConstantInt::get(CGM.SizeTy, 1));
1305 ScratchpadBasePtr = Bld.CreateSDiv(
1306 ScratchpadBasePtr,
1307 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
1308 ScratchpadBasePtr = Bld.CreateAdd(ScratchpadBasePtr,
1309 llvm::ConstantInt::get(CGM.SizeTy, 1));
1310 ScratchpadBasePtr = Bld.CreateMul(
1311 ScratchpadBasePtr,
1312 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
1313
1314 if (IncrScratchpadDest)
1315 DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
1316 else /* IncrScratchpadSrc = true */
1317 SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
1318 }
1319
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001320 Idx++;
1321 }
1322}
1323
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001324/// This function emits a helper that loads data from the scratchpad array
1325/// and (optionally) reduces it with the input operand.
1326///
1327/// load_and_reduce(local, scratchpad, index, width, should_reduce)
1328/// reduce_data remote;
1329/// for elem in remote:
1330/// remote.elem = Scratchpad[elem_id][index]
1331/// if (should_reduce)
1332/// local = local @ remote
1333/// else
1334/// local = remote
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001335static llvm::Value *emitReduceScratchpadFunction(
1336 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
1337 QualType ReductionArrayTy, llvm::Value *ReduceFn, SourceLocation Loc) {
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001338 auto &C = CGM.getContext();
1339 auto Int32Ty = C.getIntTypeForBitwidth(32, /* Signed */ true);
1340
1341 // Destination of the copy.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001342 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
1343 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001344 // Base address of the scratchpad array, with each element storing a
1345 // Reduce list per team.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001346 ImplicitParamDecl ScratchPadArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
1347 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001348 // A source index into the scratchpad array.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001349 ImplicitParamDecl IndexArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
1350 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001351 // Row width of an element in the scratchpad array, typically
1352 // the number of teams.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001353 ImplicitParamDecl WidthArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
1354 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001355 // If should_reduce == 1, then it's load AND reduce,
1356 // If should_reduce == 0 (or otherwise), then it only loads (+ copy).
1357 // The latter case is used for initialization.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001358 ImplicitParamDecl ShouldReduceArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
1359 Int32Ty, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001360
1361 FunctionArgList Args;
1362 Args.push_back(&ReduceListArg);
1363 Args.push_back(&ScratchPadArg);
1364 Args.push_back(&IndexArg);
1365 Args.push_back(&WidthArg);
1366 Args.push_back(&ShouldReduceArg);
1367
1368 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
1369 auto *Fn = llvm::Function::Create(
1370 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
1371 "_omp_reduction_load_and_reduce", &CGM.getModule());
1372 CGM.SetInternalFunctionAttributes(/*DC=*/nullptr, Fn, CGFI);
1373 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001374 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001375
1376 auto &Bld = CGF.Builder;
1377
1378 // Get local Reduce list pointer.
1379 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
1380 Address ReduceListAddr(
1381 Bld.CreatePointerBitCastOrAddrSpaceCast(
1382 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
1383 C.VoidPtrTy, SourceLocation()),
1384 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
1385 CGF.getPointerAlign());
1386
1387 Address AddrScratchPadArg = CGF.GetAddrOfLocalVar(&ScratchPadArg);
1388 llvm::Value *ScratchPadBase = CGF.EmitLoadOfScalar(
1389 AddrScratchPadArg, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
1390
1391 Address AddrIndexArg = CGF.GetAddrOfLocalVar(&IndexArg);
1392 llvm::Value *IndexVal =
1393 Bld.CreateIntCast(CGF.EmitLoadOfScalar(AddrIndexArg, /*Volatile=*/false,
1394 Int32Ty, SourceLocation()),
1395 CGM.SizeTy, /*isSigned=*/true);
1396
1397 Address AddrWidthArg = CGF.GetAddrOfLocalVar(&WidthArg);
1398 llvm::Value *WidthVal =
1399 Bld.CreateIntCast(CGF.EmitLoadOfScalar(AddrWidthArg, /*Volatile=*/false,
1400 Int32Ty, SourceLocation()),
1401 CGM.SizeTy, /*isSigned=*/true);
1402
1403 Address AddrShouldReduceArg = CGF.GetAddrOfLocalVar(&ShouldReduceArg);
1404 llvm::Value *ShouldReduceVal = CGF.EmitLoadOfScalar(
1405 AddrShouldReduceArg, /*Volatile=*/false, Int32Ty, SourceLocation());
1406
1407 // The absolute ptr address to the base addr of the next element to copy.
1408 llvm::Value *CumulativeElemBasePtr =
1409 Bld.CreatePtrToInt(ScratchPadBase, CGM.SizeTy);
1410 Address SrcDataAddr(CumulativeElemBasePtr, CGF.getPointerAlign());
1411
1412 // Create a Remote Reduce list to store the elements read from the
1413 // scratchpad array.
1414 Address RemoteReduceList =
1415 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_red_list");
1416
1417 // Assemble remote Reduce list from scratchpad array.
1418 emitReductionListCopy(ScratchpadToThread, CGF, ReductionArrayTy, Privates,
1419 SrcDataAddr, RemoteReduceList,
1420 {/*RemoteLaneOffset=*/nullptr,
1421 /*ScratchpadIndex=*/IndexVal,
1422 /*ScratchpadWidth=*/WidthVal});
1423
1424 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
1425 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
1426 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
1427
1428 auto CondReduce = Bld.CreateICmpEQ(ShouldReduceVal, Bld.getInt32(1));
1429 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
1430
1431 CGF.EmitBlock(ThenBB);
1432 // We should reduce with the local Reduce list.
1433 // reduce_function(LocalReduceList, RemoteReduceList)
1434 llvm::Value *LocalDataPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
1435 ReduceListAddr.getPointer(), CGF.VoidPtrTy);
1436 llvm::Value *RemoteDataPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
1437 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001438 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
1439 CGF, Loc, ReduceFn, {LocalDataPtr, RemoteDataPtr});
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001440 Bld.CreateBr(MergeBB);
1441
1442 CGF.EmitBlock(ElseBB);
1443 // No reduction; just copy:
1444 // Local Reduce list = Remote Reduce list.
1445 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
1446 RemoteReduceList, ReduceListAddr);
1447 Bld.CreateBr(MergeBB);
1448
1449 CGF.EmitBlock(MergeBB);
1450
1451 CGF.FinishFunction();
1452 return Fn;
1453}
1454
1455/// This function emits a helper that stores reduced data from the team
1456/// master to a scratchpad array in global memory.
1457///
1458/// for elem in Reduce List:
1459/// scratchpad[elem_id][index] = elem
1460///
Benjamin Kramer674d5792017-05-26 20:08:24 +00001461static llvm::Value *emitCopyToScratchpad(CodeGenModule &CGM,
1462 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001463 QualType ReductionArrayTy,
1464 SourceLocation Loc) {
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001465
1466 auto &C = CGM.getContext();
1467 auto Int32Ty = C.getIntTypeForBitwidth(32, /* Signed */ true);
1468
1469 // Source of the copy.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001470 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
1471 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001472 // Base address of the scratchpad array, with each element storing a
1473 // Reduce list per team.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001474 ImplicitParamDecl ScratchPadArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
1475 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001476 // A destination index into the scratchpad array, typically the team
1477 // identifier.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001478 ImplicitParamDecl IndexArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
1479 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001480 // Row width of an element in the scratchpad array, typically
1481 // the number of teams.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001482 ImplicitParamDecl WidthArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
1483 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001484
1485 FunctionArgList Args;
1486 Args.push_back(&ReduceListArg);
1487 Args.push_back(&ScratchPadArg);
1488 Args.push_back(&IndexArg);
1489 Args.push_back(&WidthArg);
1490
1491 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
1492 auto *Fn = llvm::Function::Create(
1493 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
1494 "_omp_reduction_copy_to_scratchpad", &CGM.getModule());
1495 CGM.SetInternalFunctionAttributes(/*DC=*/nullptr, Fn, CGFI);
1496 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001497 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001498
1499 auto &Bld = CGF.Builder;
1500
1501 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
1502 Address SrcDataAddr(
1503 Bld.CreatePointerBitCastOrAddrSpaceCast(
1504 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
1505 C.VoidPtrTy, SourceLocation()),
1506 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
1507 CGF.getPointerAlign());
1508
1509 Address AddrScratchPadArg = CGF.GetAddrOfLocalVar(&ScratchPadArg);
1510 llvm::Value *ScratchPadBase = CGF.EmitLoadOfScalar(
1511 AddrScratchPadArg, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
1512
1513 Address AddrIndexArg = CGF.GetAddrOfLocalVar(&IndexArg);
1514 llvm::Value *IndexVal =
1515 Bld.CreateIntCast(CGF.EmitLoadOfScalar(AddrIndexArg, /*Volatile=*/false,
1516 Int32Ty, SourceLocation()),
1517 CGF.SizeTy, /*isSigned=*/true);
1518
1519 Address AddrWidthArg = CGF.GetAddrOfLocalVar(&WidthArg);
1520 llvm::Value *WidthVal =
1521 Bld.CreateIntCast(CGF.EmitLoadOfScalar(AddrWidthArg, /*Volatile=*/false,
1522 Int32Ty, SourceLocation()),
1523 CGF.SizeTy, /*isSigned=*/true);
1524
1525 // The absolute ptr address to the base addr of the next element to copy.
1526 llvm::Value *CumulativeElemBasePtr =
1527 Bld.CreatePtrToInt(ScratchPadBase, CGM.SizeTy);
1528 Address DestDataAddr(CumulativeElemBasePtr, CGF.getPointerAlign());
1529
1530 emitReductionListCopy(ThreadToScratchpad, CGF, ReductionArrayTy, Privates,
1531 SrcDataAddr, DestDataAddr,
1532 {/*RemoteLaneOffset=*/nullptr,
1533 /*ScratchpadIndex=*/IndexVal,
1534 /*ScratchpadWidth=*/WidthVal});
1535
1536 CGF.FinishFunction();
1537 return Fn;
1538}
1539
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001540/// This function emits a helper that gathers Reduce lists from the first
1541/// lane of every active warp to lanes in the first warp.
1542///
1543/// void inter_warp_copy_func(void* reduce_data, num_warps)
1544/// shared smem[warp_size];
1545/// For all data entries D in reduce_data:
1546/// If (I am the first lane in each warp)
1547/// Copy my local D to smem[warp_id]
1548/// sync
1549/// if (I am the first warp)
1550/// Copy smem[thread_id] to my local D
1551/// sync
1552static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
1553 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001554 QualType ReductionArrayTy,
1555 SourceLocation Loc) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001556 auto &C = CGM.getContext();
1557 auto &M = CGM.getModule();
1558
1559 // ReduceList: thread local Reduce list.
1560 // At the stage of the computation when this function is called, partially
1561 // aggregated values reside in the first lane of every active warp.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001562 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
1563 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001564 // NumWarps: number of warps active in the parallel region. This could
1565 // be smaller than 32 (max warps in a CTA) for partial block reduction.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001566 ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00001567 C.getIntTypeForBitwidth(32, /* Signed */ true),
1568 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001569 FunctionArgList Args;
1570 Args.push_back(&ReduceListArg);
1571 Args.push_back(&NumWarpsArg);
1572
1573 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
1574 auto *Fn = llvm::Function::Create(
1575 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
1576 "_omp_reduction_inter_warp_copy_func", &CGM.getModule());
1577 CGM.SetInternalFunctionAttributes(/*DC=*/nullptr, Fn, CGFI);
1578 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001579 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001580
1581 auto &Bld = CGF.Builder;
1582
1583 // This array is used as a medium to transfer, one reduce element at a time,
1584 // the data from the first lane of every warp to lanes in the first warp
1585 // in order to perform the final step of a reduction in a parallel region
1586 // (reduction across warps). The array is placed in NVPTX __shared__ memory
1587 // for reduced latency, as well as to have a distinct copy for concurrently
1588 // executing target regions. The array is declared with common linkage so
1589 // as to be shared across compilation units.
1590 const char *TransferMediumName =
1591 "__openmp_nvptx_data_transfer_temporary_storage";
1592 llvm::GlobalVariable *TransferMedium =
1593 M.getGlobalVariable(TransferMediumName);
1594 if (!TransferMedium) {
1595 auto *Ty = llvm::ArrayType::get(CGM.Int64Ty, WarpSize);
1596 unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
1597 TransferMedium = new llvm::GlobalVariable(
1598 M, Ty,
1599 /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage,
1600 llvm::Constant::getNullValue(Ty), TransferMediumName,
1601 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
1602 SharedAddressSpace);
1603 }
1604
1605 // Get the CUDA thread id of the current OpenMP thread on the GPU.
1606 auto *ThreadID = getNVPTXThreadID(CGF);
1607 // nvptx_lane_id = nvptx_id % warpsize
1608 auto *LaneID = getNVPTXLaneID(CGF);
1609 // nvptx_warp_id = nvptx_id / warpsize
1610 auto *WarpID = getNVPTXWarpID(CGF);
1611
1612 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
1613 Address LocalReduceList(
1614 Bld.CreatePointerBitCastOrAddrSpaceCast(
1615 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
1616 C.VoidPtrTy, SourceLocation()),
1617 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
1618 CGF.getPointerAlign());
1619
1620 unsigned Idx = 0;
1621 for (auto &Private : Privates) {
1622 //
1623 // Warp master copies reduce element to transfer medium in __shared__
1624 // memory.
1625 //
1626 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
1627 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
1628 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
1629
1630 // if (lane_id == 0)
1631 auto IsWarpMaster =
1632 Bld.CreateICmpEQ(LaneID, Bld.getInt32(0), "warp_master");
1633 Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
1634 CGF.EmitBlock(ThenBB);
1635
1636 // Reduce element = LocalReduceList[i]
1637 Address ElemPtrPtrAddr =
1638 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
1639 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
1640 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
1641 // elemptr = (type[i]*)(elemptrptr)
1642 Address ElemPtr =
1643 Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
1644 ElemPtr = Bld.CreateElementBitCast(
1645 ElemPtr, CGF.ConvertTypeForMem(Private->getType()));
1646 // elem = *elemptr
1647 llvm::Value *Elem = CGF.EmitLoadOfScalar(
1648 ElemPtr, /*Volatile=*/false, Private->getType(), SourceLocation());
1649
1650 // Get pointer to location in transfer medium.
1651 // MediumPtr = &medium[warp_id]
1652 llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
1653 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
1654 Address MediumPtr(MediumPtrVal, C.getTypeAlignInChars(Private->getType()));
1655 // Casting to actual data type.
1656 // MediumPtr = (type[i]*)MediumPtrAddr;
1657 MediumPtr = Bld.CreateElementBitCast(
1658 MediumPtr, CGF.ConvertTypeForMem(Private->getType()));
1659
1660 //*MediumPtr = elem
1661 Bld.CreateStore(Elem, MediumPtr);
1662
1663 Bld.CreateBr(MergeBB);
1664
1665 CGF.EmitBlock(ElseBB);
1666 Bld.CreateBr(MergeBB);
1667
1668 CGF.EmitBlock(MergeBB);
1669
1670 Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
1671 llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
1672 AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, SourceLocation());
1673
1674 auto *NumActiveThreads = Bld.CreateNSWMul(
1675 NumWarpsVal, getNVPTXWarpSize(CGF), "num_active_threads");
1676 // named_barrier_sync(ParallelBarrierID, num_active_threads)
1677 syncParallelThreads(CGF, NumActiveThreads);
1678
1679 //
1680 // Warp 0 copies reduce element from transfer medium.
1681 //
1682 llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
1683 llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
1684 llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
1685
1686 // Up to 32 threads in warp 0 are active.
1687 auto IsActiveThread =
1688 Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
1689 Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
1690
1691 CGF.EmitBlock(W0ThenBB);
1692
1693 // SrcMediumPtr = &medium[tid]
1694 llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
1695 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
1696 Address SrcMediumPtr(SrcMediumPtrVal,
1697 C.getTypeAlignInChars(Private->getType()));
1698 // SrcMediumVal = *SrcMediumPtr;
1699 SrcMediumPtr = Bld.CreateElementBitCast(
1700 SrcMediumPtr, CGF.ConvertTypeForMem(Private->getType()));
1701 llvm::Value *SrcMediumValue = CGF.EmitLoadOfScalar(
1702 SrcMediumPtr, /*Volatile=*/false, Private->getType(), SourceLocation());
1703
1704 // TargetElemPtr = (type[i]*)(SrcDataAddr[i])
1705 Address TargetElemPtrPtr =
1706 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
1707 llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
1708 TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
1709 Address TargetElemPtr =
1710 Address(TargetElemPtrVal, C.getTypeAlignInChars(Private->getType()));
1711 TargetElemPtr = Bld.CreateElementBitCast(
1712 TargetElemPtr, CGF.ConvertTypeForMem(Private->getType()));
1713
1714 // *TargetElemPtr = SrcMediumVal;
1715 CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
1716 Private->getType());
1717 Bld.CreateBr(W0MergeBB);
1718
1719 CGF.EmitBlock(W0ElseBB);
1720 Bld.CreateBr(W0MergeBB);
1721
1722 CGF.EmitBlock(W0MergeBB);
1723
1724 // While warp 0 copies values from transfer medium, all other warps must
1725 // wait.
1726 syncParallelThreads(CGF, NumActiveThreads);
1727 Idx++;
1728 }
1729
1730 CGF.FinishFunction();
1731 return Fn;
1732}
1733
1734/// Emit a helper that reduces data across two OpenMP threads (lanes)
1735/// in the same warp. It uses shuffle instructions to copy over data from
1736/// a remote lane's stack. The reduction algorithm performed is specified
1737/// by the fourth parameter.
1738///
1739/// Algorithm Versions.
1740/// Full Warp Reduce (argument value 0):
1741/// This algorithm assumes that all 32 lanes are active and gathers
1742/// data from these 32 lanes, producing a single resultant value.
1743/// Contiguous Partial Warp Reduce (argument value 1):
1744/// This algorithm assumes that only a *contiguous* subset of lanes
1745/// are active. This happens for the last warp in a parallel region
1746/// when the user specified num_threads is not an integer multiple of
1747/// 32. This contiguous subset always starts with the zeroth lane.
1748/// Partial Warp Reduce (argument value 2):
1749/// This algorithm gathers data from any number of lanes at any position.
1750/// All reduced values are stored in the lowest possible lane. The set
1751/// of problems every algorithm addresses is a super set of those
1752/// addressable by algorithms with a lower version number. Overhead
1753/// increases as algorithm version increases.
1754///
1755/// Terminology
1756/// Reduce element:
1757/// Reduce element refers to the individual data field with primitive
1758/// data types to be combined and reduced across threads.
1759/// Reduce list:
1760/// Reduce list refers to a collection of local, thread-private
1761/// reduce elements.
1762/// Remote Reduce list:
1763/// Remote Reduce list refers to a collection of remote (relative to
1764/// the current thread) reduce elements.
1765///
1766/// We distinguish between three states of threads that are important to
1767/// the implementation of this function.
1768/// Alive threads:
1769/// Threads in a warp executing the SIMT instruction, as distinguished from
1770/// threads that are inactive due to divergent control flow.
1771/// Active threads:
1772/// The minimal set of threads that has to be alive upon entry to this
1773/// function. The computation is correct iff active threads are alive.
1774/// Some threads are alive but they are not active because they do not
1775/// contribute to the computation in any useful manner. Turning them off
1776/// may introduce control flow overheads without any tangible benefits.
1777/// Effective threads:
1778/// In order to comply with the argument requirements of the shuffle
1779/// function, we must keep all lanes holding data alive. But at most
1780/// half of them perform value aggregation; we refer to this half of
1781/// threads as effective. The other half is simply handing off their
1782/// data.
1783///
1784/// Procedure
1785/// Value shuffle:
1786/// In this step active threads transfer data from higher lane positions
1787/// in the warp to lower lane positions, creating Remote Reduce list.
1788/// Value aggregation:
1789/// In this step, effective threads combine their thread local Reduce list
1790/// with Remote Reduce list and store the result in the thread local
1791/// Reduce list.
1792/// Value copy:
1793/// In this step, we deal with the assumption made by algorithm 2
1794/// (i.e. contiguity assumption). When we have an odd number of lanes
1795/// active, say 2k+1, only k threads will be effective and therefore k
1796/// new values will be produced. However, the Reduce list owned by the
1797/// (2k+1)th thread is ignored in the value aggregation. Therefore
1798/// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
1799/// that the contiguity assumption still holds.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001800static llvm::Value *emitShuffleAndReduceFunction(
1801 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
1802 QualType ReductionArrayTy, llvm::Value *ReduceFn, SourceLocation Loc) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001803 auto &C = CGM.getContext();
1804
1805 // Thread local Reduce list used to host the values of data to be reduced.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001806 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
1807 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001808 // Current lane id; could be logical.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001809 ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
1810 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001811 // Offset of the remote source lane relative to the current lane.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001812 ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
1813 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001814 // Algorithm version. This is expected to be known at compile time.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001815 ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
1816 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001817 FunctionArgList Args;
1818 Args.push_back(&ReduceListArg);
1819 Args.push_back(&LaneIDArg);
1820 Args.push_back(&RemoteLaneOffsetArg);
1821 Args.push_back(&AlgoVerArg);
1822
1823 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
1824 auto *Fn = llvm::Function::Create(
1825 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
1826 "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
1827 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
1828 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001829 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001830
1831 auto &Bld = CGF.Builder;
1832
1833 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
1834 Address LocalReduceList(
1835 Bld.CreatePointerBitCastOrAddrSpaceCast(
1836 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
1837 C.VoidPtrTy, SourceLocation()),
1838 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
1839 CGF.getPointerAlign());
1840
1841 Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
1842 llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
1843 AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
1844
1845 Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
1846 llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
1847 AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
1848
1849 Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
1850 llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
1851 AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
1852
1853 // Create a local thread-private variable to host the Reduce list
1854 // from a remote lane.
1855 Address RemoteReduceList =
1856 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
1857
1858 // This loop iterates through the list of reduce elements and copies,
1859 // element by element, from a remote lane in the warp to RemoteReduceList,
1860 // hosted on the thread's stack.
1861 emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
1862 LocalReduceList, RemoteReduceList,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001863 {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
1864 /*ScratchpadIndex=*/nullptr,
1865 /*ScratchpadWidth=*/nullptr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001866
1867 // The actions to be performed on the Remote Reduce list is dependent
1868 // on the algorithm version.
1869 //
1870 // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
1871 // LaneId % 2 == 0 && Offset > 0):
1872 // do the reduction value aggregation
1873 //
1874 // The thread local variable Reduce list is mutated in place to host the
1875 // reduced data, which is the aggregated value produced from local and
1876 // remote lanes.
1877 //
1878 // Note that AlgoVer is expected to be a constant integer known at compile
1879 // time.
1880 // When AlgoVer==0, the first conjunction evaluates to true, making
1881 // the entire predicate true during compile time.
1882 // When AlgoVer==1, the second conjunction has only the second part to be
1883 // evaluated during runtime. Other conjunctions evaluates to false
1884 // during compile time.
1885 // When AlgoVer==2, the third conjunction has only the second part to be
1886 // evaluated during runtime. Other conjunctions evaluates to false
1887 // during compile time.
1888 auto CondAlgo0 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(0));
1889
1890 auto Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
1891 auto CondAlgo1 = Bld.CreateAnd(
1892 Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
1893
1894 auto Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
1895 auto CondAlgo2 = Bld.CreateAnd(
1896 Algo2,
1897 Bld.CreateICmpEQ(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1)),
1898 Bld.getInt16(0)));
1899 CondAlgo2 = Bld.CreateAnd(
1900 CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
1901
1902 auto CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
1903 CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
1904
1905 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
1906 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
1907 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
1908 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
1909
1910 CGF.EmitBlock(ThenBB);
1911 // reduce_function(LocalReduceList, RemoteReduceList)
1912 llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
1913 LocalReduceList.getPointer(), CGF.VoidPtrTy);
1914 llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
1915 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001916 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
1917 CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001918 Bld.CreateBr(MergeBB);
1919
1920 CGF.EmitBlock(ElseBB);
1921 Bld.CreateBr(MergeBB);
1922
1923 CGF.EmitBlock(MergeBB);
1924
1925 // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
1926 // Reduce list.
1927 Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
1928 auto CondCopy = Bld.CreateAnd(
1929 Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
1930
1931 llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
1932 llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
1933 llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
1934 Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
1935
1936 CGF.EmitBlock(CpyThenBB);
1937 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
1938 RemoteReduceList, LocalReduceList);
1939 Bld.CreateBr(CpyMergeBB);
1940
1941 CGF.EmitBlock(CpyElseBB);
1942 Bld.CreateBr(CpyMergeBB);
1943
1944 CGF.EmitBlock(CpyMergeBB);
1945
1946 CGF.FinishFunction();
1947 return Fn;
1948}
1949
1950///
1951/// Design of OpenMP reductions on the GPU
1952///
1953/// Consider a typical OpenMP program with one or more reduction
1954/// clauses:
1955///
1956/// float foo;
1957/// double bar;
1958/// #pragma omp target teams distribute parallel for \
1959/// reduction(+:foo) reduction(*:bar)
1960/// for (int i = 0; i < N; i++) {
1961/// foo += A[i]; bar *= B[i];
1962/// }
1963///
1964/// where 'foo' and 'bar' are reduced across all OpenMP threads in
1965/// all teams. In our OpenMP implementation on the NVPTX device an
1966/// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
1967/// within a team are mapped to CUDA threads within a threadblock.
1968/// Our goal is to efficiently aggregate values across all OpenMP
1969/// threads such that:
1970///
1971/// - the compiler and runtime are logically concise, and
1972/// - the reduction is performed efficiently in a hierarchical
1973/// manner as follows: within OpenMP threads in the same warp,
1974/// across warps in a threadblock, and finally across teams on
1975/// the NVPTX device.
1976///
1977/// Introduction to Decoupling
1978///
1979/// We would like to decouple the compiler and the runtime so that the
1980/// latter is ignorant of the reduction variables (number, data types)
1981/// and the reduction operators. This allows a simpler interface
1982/// and implementation while still attaining good performance.
1983///
1984/// Pseudocode for the aforementioned OpenMP program generated by the
1985/// compiler is as follows:
1986///
1987/// 1. Create private copies of reduction variables on each OpenMP
1988/// thread: 'foo_private', 'bar_private'
1989/// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
1990/// to it and writes the result in 'foo_private' and 'bar_private'
1991/// respectively.
1992/// 3. Call the OpenMP runtime on the GPU to reduce within a team
1993/// and store the result on the team master:
1994///
1995/// __kmpc_nvptx_parallel_reduce_nowait(...,
1996/// reduceData, shuffleReduceFn, interWarpCpyFn)
1997///
1998/// where:
1999/// struct ReduceData {
2000/// double *foo;
2001/// double *bar;
2002/// } reduceData
2003/// reduceData.foo = &foo_private
2004/// reduceData.bar = &bar_private
2005///
2006/// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
2007/// auxiliary functions generated by the compiler that operate on
2008/// variables of type 'ReduceData'. They aid the runtime perform
2009/// algorithmic steps in a data agnostic manner.
2010///
2011/// 'shuffleReduceFn' is a pointer to a function that reduces data
2012/// of type 'ReduceData' across two OpenMP threads (lanes) in the
2013/// same warp. It takes the following arguments as input:
2014///
2015/// a. variable of type 'ReduceData' on the calling lane,
2016/// b. its lane_id,
2017/// c. an offset relative to the current lane_id to generate a
2018/// remote_lane_id. The remote lane contains the second
2019/// variable of type 'ReduceData' that is to be reduced.
2020/// d. an algorithm version parameter determining which reduction
2021/// algorithm to use.
2022///
2023/// 'shuffleReduceFn' retrieves data from the remote lane using
2024/// efficient GPU shuffle intrinsics and reduces, using the
2025/// algorithm specified by the 4th parameter, the two operands
2026/// element-wise. The result is written to the first operand.
2027///
2028/// Different reduction algorithms are implemented in different
2029/// runtime functions, all calling 'shuffleReduceFn' to perform
2030/// the essential reduction step. Therefore, based on the 4th
2031/// parameter, this function behaves slightly differently to
2032/// cooperate with the runtime to ensure correctness under
2033/// different circumstances.
2034///
2035/// 'InterWarpCpyFn' is a pointer to a function that transfers
2036/// reduced variables across warps. It tunnels, through CUDA
2037/// shared memory, the thread-private data of type 'ReduceData'
2038/// from lane 0 of each warp to a lane in the first warp.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002039/// 4. Call the OpenMP runtime on the GPU to reduce across teams.
2040/// The last team writes the global reduced value to memory.
2041///
2042/// ret = __kmpc_nvptx_teams_reduce_nowait(...,
2043/// reduceData, shuffleReduceFn, interWarpCpyFn,
2044/// scratchpadCopyFn, loadAndReduceFn)
2045///
2046/// 'scratchpadCopyFn' is a helper that stores reduced
2047/// data from the team master to a scratchpad array in
2048/// global memory.
2049///
2050/// 'loadAndReduceFn' is a helper that loads data from
2051/// the scratchpad array and reduces it with the input
2052/// operand.
2053///
2054/// These compiler generated functions hide address
2055/// calculation and alignment information from the runtime.
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002056/// 5. if ret == 1:
2057/// The team master of the last team stores the reduced
2058/// result to the globals in memory.
2059/// foo += reduceData.foo; bar *= reduceData.bar
2060///
2061///
2062/// Warp Reduction Algorithms
2063///
2064/// On the warp level, we have three algorithms implemented in the
2065/// OpenMP runtime depending on the number of active lanes:
2066///
2067/// Full Warp Reduction
2068///
2069/// The reduce algorithm within a warp where all lanes are active
2070/// is implemented in the runtime as follows:
2071///
2072/// full_warp_reduce(void *reduce_data,
2073/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
2074/// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
2075/// ShuffleReduceFn(reduce_data, 0, offset, 0);
2076/// }
2077///
2078/// The algorithm completes in log(2, WARPSIZE) steps.
2079///
2080/// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
2081/// not used therefore we save instructions by not retrieving lane_id
2082/// from the corresponding special registers. The 4th parameter, which
2083/// represents the version of the algorithm being used, is set to 0 to
2084/// signify full warp reduction.
2085///
2086/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
2087///
2088/// #reduce_elem refers to an element in the local lane's data structure
2089/// #remote_elem is retrieved from a remote lane
2090/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
2091/// reduce_elem = reduce_elem REDUCE_OP remote_elem;
2092///
2093/// Contiguous Partial Warp Reduction
2094///
2095/// This reduce algorithm is used within a warp where only the first
2096/// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
2097/// number of OpenMP threads in a parallel region is not a multiple of
2098/// WARPSIZE. The algorithm is implemented in the runtime as follows:
2099///
2100/// void
2101/// contiguous_partial_reduce(void *reduce_data,
2102/// kmp_ShuffleReductFctPtr ShuffleReduceFn,
2103/// int size, int lane_id) {
2104/// int curr_size;
2105/// int offset;
2106/// curr_size = size;
2107/// mask = curr_size/2;
2108/// while (offset>0) {
2109/// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
2110/// curr_size = (curr_size+1)/2;
2111/// offset = curr_size/2;
2112/// }
2113/// }
2114///
2115/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
2116///
2117/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
2118/// if (lane_id < offset)
2119/// reduce_elem = reduce_elem REDUCE_OP remote_elem
2120/// else
2121/// reduce_elem = remote_elem
2122///
2123/// This algorithm assumes that the data to be reduced are located in a
2124/// contiguous subset of lanes starting from the first. When there is
2125/// an odd number of active lanes, the data in the last lane is not
2126/// aggregated with any other lane's dat but is instead copied over.
2127///
2128/// Dispersed Partial Warp Reduction
2129///
2130/// This algorithm is used within a warp when any discontiguous subset of
2131/// lanes are active. It is used to implement the reduction operation
2132/// across lanes in an OpenMP simd region or in a nested parallel region.
2133///
2134/// void
2135/// dispersed_partial_reduce(void *reduce_data,
2136/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
2137/// int size, remote_id;
2138/// int logical_lane_id = number_of_active_lanes_before_me() * 2;
2139/// do {
2140/// remote_id = next_active_lane_id_right_after_me();
2141/// # the above function returns 0 of no active lane
2142/// # is present right after the current lane.
2143/// size = number_of_active_lanes_in_this_warp();
2144/// logical_lane_id /= 2;
2145/// ShuffleReduceFn(reduce_data, logical_lane_id,
2146/// remote_id-1-threadIdx.x, 2);
2147/// } while (logical_lane_id % 2 == 0 && size > 1);
2148/// }
2149///
2150/// There is no assumption made about the initial state of the reduction.
2151/// Any number of lanes (>=1) could be active at any position. The reduction
2152/// result is returned in the first active lane.
2153///
2154/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
2155///
2156/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
2157/// if (lane_id % 2 == 0 && offset > 0)
2158/// reduce_elem = reduce_elem REDUCE_OP remote_elem
2159/// else
2160/// reduce_elem = remote_elem
2161///
2162///
2163/// Intra-Team Reduction
2164///
2165/// This function, as implemented in the runtime call
2166/// '__kmpc_nvptx_parallel_reduce_nowait', aggregates data across OpenMP
2167/// threads in a team. It first reduces within a warp using the
2168/// aforementioned algorithms. We then proceed to gather all such
2169/// reduced values at the first warp.
2170///
2171/// The runtime makes use of the function 'InterWarpCpyFn', which copies
2172/// data from each of the "warp master" (zeroth lane of each warp, where
2173/// warp-reduced data is held) to the zeroth warp. This step reduces (in
2174/// a mathematical sense) the problem of reduction across warp masters in
2175/// a block to the problem of warp reduction.
2176///
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002177///
2178/// Inter-Team Reduction
2179///
2180/// Once a team has reduced its data to a single value, it is stored in
2181/// a global scratchpad array. Since each team has a distinct slot, this
2182/// can be done without locking.
2183///
2184/// The last team to write to the scratchpad array proceeds to reduce the
2185/// scratchpad array. One or more workers in the last team use the helper
2186/// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
2187/// the k'th worker reduces every k'th element.
2188///
2189/// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait' to
2190/// reduce across workers and compute a globally reduced value.
2191///
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002192void CGOpenMPRuntimeNVPTX::emitReduction(
2193 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
2194 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
2195 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
2196 if (!CGF.HaveInsertPoint())
2197 return;
2198
2199 bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002200 bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
2201 // FIXME: Add support for simd reduction.
2202 assert((TeamsReduction || ParallelReduction) &&
2203 "Invalid reduction selection in emitReduction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002204
2205 auto &C = CGM.getContext();
2206
2207 // 1. Build a list of reduction variables.
2208 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
2209 auto Size = RHSExprs.size();
2210 for (auto *E : Privates) {
2211 if (E->getType()->isVariablyModifiedType())
2212 // Reserve place for array size.
2213 ++Size;
2214 }
2215 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
2216 QualType ReductionArrayTy =
2217 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2218 /*IndexTypeQuals=*/0);
2219 Address ReductionList =
2220 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
2221 auto IPriv = Privates.begin();
2222 unsigned Idx = 0;
2223 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
2224 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
2225 CGF.getPointerSize());
2226 CGF.Builder.CreateStore(
2227 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2228 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
2229 Elem);
2230 if ((*IPriv)->getType()->isVariablyModifiedType()) {
2231 // Store array size.
2232 ++Idx;
2233 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
2234 CGF.getPointerSize());
2235 llvm::Value *Size = CGF.Builder.CreateIntCast(
2236 CGF.getVLASize(
2237 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
2238 .first,
2239 CGF.SizeTy, /*isSigned=*/false);
2240 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
2241 Elem);
2242 }
2243 }
2244
2245 // 2. Emit reduce_func().
2246 auto *ReductionFn = emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002247 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
2248 Privates, LHSExprs, RHSExprs, ReductionOps);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002249
2250 // 4. Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
2251 // RedList, shuffle_reduce_func, interwarp_copy_func);
2252 auto *ThreadId = getThreadID(CGF, Loc);
2253 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
2254 auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2255 ReductionList.getPointer(), CGF.VoidPtrTy);
2256
2257 auto *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002258 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002259 auto *InterWarpCopyFn =
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002260 emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002261
2262 llvm::Value *Res = nullptr;
2263 if (ParallelReduction) {
2264 llvm::Value *Args[] = {ThreadId,
2265 CGF.Builder.getInt32(RHSExprs.size()),
2266 ReductionArrayTySize,
2267 RL,
2268 ShuffleAndReduceFn,
2269 InterWarpCopyFn};
2270
2271 Res = CGF.EmitRuntimeCall(
2272 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_reduce_nowait),
2273 Args);
2274 }
2275
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002276 if (TeamsReduction) {
2277 auto *ScratchPadCopyFn =
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002278 emitCopyToScratchpad(CGM, Privates, ReductionArrayTy, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002279 auto *LoadAndReduceFn = emitReduceScratchpadFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002280 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002281
2282 llvm::Value *Args[] = {ThreadId,
2283 CGF.Builder.getInt32(RHSExprs.size()),
2284 ReductionArrayTySize,
2285 RL,
2286 ShuffleAndReduceFn,
2287 InterWarpCopyFn,
2288 ScratchPadCopyFn,
2289 LoadAndReduceFn};
2290 Res = CGF.EmitRuntimeCall(
2291 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_teams_reduce_nowait),
2292 Args);
2293 }
2294
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002295 // 5. Build switch(res)
2296 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
2297 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/1);
2298
2299 // 6. Build case 1: where we have reduced values in the master
2300 // thread in each team.
2301 // __kmpc_end_reduce{_nowait}(<gtid>);
2302 // break;
2303 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
2304 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
2305 CGF.EmitBlock(Case1BB);
2306
2307 // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
2308 llvm::Value *EndArgs[] = {ThreadId};
2309 auto &&CodeGen = [&Privates, &LHSExprs, &RHSExprs, &ReductionOps,
2310 this](CodeGenFunction &CGF, PrePostActionTy &Action) {
2311 auto IPriv = Privates.begin();
2312 auto ILHS = LHSExprs.begin();
2313 auto IRHS = RHSExprs.begin();
2314 for (auto *E : ReductionOps) {
2315 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
2316 cast<DeclRefExpr>(*IRHS));
2317 ++IPriv;
2318 ++ILHS;
2319 ++IRHS;
2320 }
2321 };
2322 RegionCodeGenTy RCG(CodeGen);
2323 NVPTXActionTy Action(
2324 nullptr, llvm::None,
2325 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_reduce_nowait),
2326 EndArgs);
2327 RCG.setAction(Action);
2328 RCG(CGF);
2329 CGF.EmitBranch(DefaultBB);
2330 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
2331}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002332
2333const VarDecl *
2334CGOpenMPRuntimeNVPTX::translateParameter(const FieldDecl *FD,
2335 const VarDecl *NativeParam) const {
2336 if (!NativeParam->getType()->isReferenceType())
2337 return NativeParam;
2338 QualType ArgType = NativeParam->getType();
2339 QualifierCollector QC;
2340 const Type *NonQualTy = QC.strip(ArgType);
2341 QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
2342 if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
2343 if (Attr->getCaptureKind() == OMPC_map) {
2344 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
2345 LangAS::opencl_global);
2346 }
2347 }
2348 ArgType = CGM.getContext().getPointerType(PointeeTy);
2349 QC.addRestrict();
2350 enum { NVPTX_local_addr = 5 };
Alexander Richardson6d989432017-10-15 18:48:14 +00002351 QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002352 ArgType = QC.apply(CGM.getContext(), ArgType);
Alexey Bataevb45d43c2017-11-22 16:02:03 +00002353 if (isa<ImplicitParamDecl>(NativeParam)) {
2354 return ImplicitParamDecl::Create(
2355 CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
2356 NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
2357 }
2358 return ParmVarDecl::Create(
2359 CGM.getContext(),
2360 const_cast<DeclContext *>(NativeParam->getDeclContext()),
2361 NativeParam->getLocStart(), NativeParam->getLocation(),
2362 NativeParam->getIdentifier(), ArgType,
2363 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002364}
2365
2366Address
2367CGOpenMPRuntimeNVPTX::getParameterAddress(CodeGenFunction &CGF,
2368 const VarDecl *NativeParam,
2369 const VarDecl *TargetParam) const {
2370 assert(NativeParam != TargetParam &&
2371 NativeParam->getType()->isReferenceType() &&
2372 "Native arg must not be the same as target arg.");
2373 Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
2374 QualType NativeParamType = NativeParam->getType();
2375 QualifierCollector QC;
2376 const Type *NonQualTy = QC.strip(NativeParamType);
2377 QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
2378 unsigned NativePointeeAddrSpace =
Alexander Richardson6d989432017-10-15 18:48:14 +00002379 CGF.getContext().getTargetAddressSpace(NativePointeeTy);
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00002380 QualType TargetTy = TargetParam->getType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002381 llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00002382 LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002383 // First cast to generic.
2384 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2385 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
2386 /*AddrSpace=*/0));
2387 // Cast from generic to native address space.
2388 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2389 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
2390 NativePointeeAddrSpace));
2391 Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
2392 CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00002393 NativeParamType);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002394 return NativeParamAddr;
2395}
2396
2397void CGOpenMPRuntimeNVPTX::emitOutlinedFunctionCall(
Alexey Bataev3c595a62017-08-14 15:01:03 +00002398 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002399 ArrayRef<llvm::Value *> Args) const {
2400 SmallVector<llvm::Value *, 4> TargetArgs;
Alexey Bataev07ed94a2017-08-15 14:34:04 +00002401 TargetArgs.reserve(Args.size());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002402 auto *FnType =
2403 cast<llvm::FunctionType>(OutlinedFn->getType()->getPointerElementType());
2404 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
Alexey Bataev07ed94a2017-08-15 14:34:04 +00002405 if (FnType->isVarArg() && FnType->getNumParams() <= I) {
2406 TargetArgs.append(std::next(Args.begin(), I), Args.end());
2407 break;
2408 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002409 llvm::Type *TargetType = FnType->getParamType(I);
2410 llvm::Value *NativeArg = Args[I];
2411 if (!TargetType->isPointerTy()) {
2412 TargetArgs.emplace_back(NativeArg);
2413 continue;
2414 }
2415 llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2416 NativeArg, NativeArg->getType()->getPointerElementType()->getPointerTo(
2417 /*AddrSpace=*/0));
2418 TargetArgs.emplace_back(
2419 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
2420 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00002421 CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002422}
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +00002423
2424/// Emit function which wraps the outline parallel region
2425/// and controls the arguments which are passed to this function.
2426/// The wrapper ensures that the outlined function is called
2427/// with the correct arguments when data is shared.
2428llvm::Function *CGOpenMPRuntimeNVPTX::createDataSharingWrapper(
2429 llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
2430 ASTContext &Ctx = CGM.getContext();
Alexey Bataev475a7442018-01-12 19:39:11 +00002431 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_parallel);
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +00002432
2433 // Create a function that takes as argument the source thread.
2434 FunctionArgList WrapperArgs;
2435 QualType Int16QTy =
2436 Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
2437 QualType Int32QTy =
2438 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
2439 QualType Int32PtrQTy = Ctx.getPointerType(Int32QTy);
2440 QualType VoidPtrPtrQTy = Ctx.getPointerType(Ctx.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002441 ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getLocStart(),
2442 /*Id=*/nullptr, Int16QTy,
2443 ImplicitParamDecl::Other);
2444 ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getLocStart(),
2445 /*Id=*/nullptr, Int32QTy,
2446 ImplicitParamDecl::Other);
2447 ImplicitParamDecl SharedArgsList(Ctx, /*DC=*/nullptr, D.getLocStart(),
2448 /*Id=*/nullptr, VoidPtrPtrQTy,
2449 ImplicitParamDecl::Other);
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +00002450 WrapperArgs.emplace_back(&ParallelLevelArg);
2451 WrapperArgs.emplace_back(&WrapperArg);
2452 WrapperArgs.emplace_back(&SharedArgsList);
2453
2454 auto &CGFI =
2455 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
2456
2457 auto *Fn = llvm::Function::Create(
2458 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2459 OutlinedParallelFn->getName() + "_wrapper", &CGM.getModule());
2460 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
2461 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
2462
2463 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002464 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
2465 D.getLocStart(), D.getLocStart());
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +00002466
2467 const auto *RD = CS.getCapturedRecordDecl();
2468 auto CurField = RD->field_begin();
2469
2470 // Get the array of arguments.
2471 SmallVector<llvm::Value *, 8> Args;
2472
2473 // TODO: suppport SIMD and pass actual values
2474 Args.emplace_back(llvm::ConstantPointerNull::get(
2475 CGM.Int32Ty->getPointerTo()));
2476 Args.emplace_back(llvm::ConstantPointerNull::get(
2477 CGM.Int32Ty->getPointerTo()));
2478
2479 CGBuilderTy &Bld = CGF.Builder;
2480 auto CI = CS.capture_begin();
2481
2482 // Load the start of the array
2483 auto SharedArgs =
2484 CGF.EmitLoadOfPointer(CGF.GetAddrOfLocalVar(&SharedArgsList),
2485 VoidPtrPtrQTy->castAs<PointerType>());
2486
2487 // For each captured variable
2488 for (unsigned I = 0; I < CS.capture_size(); ++I, ++CI, ++CurField) {
2489 // Name of captured variable
2490 StringRef Name;
2491 if (CI->capturesThis())
2492 Name = "this";
2493 else
2494 Name = CI->getCapturedVar()->getName();
2495
2496 // We retrieve the CLANG type of the argument. We use it to create
2497 // an alloca which will give us the LLVM type.
2498 QualType ElemTy = CurField->getType();
2499 // If this is a capture by copy the element type has to be the pointer to
2500 // the data.
2501 if (CI->capturesVariableByCopy())
2502 ElemTy = Ctx.getPointerType(ElemTy);
2503
2504 // Get shared address of the captured variable.
2505 Address ArgAddress = Bld.CreateConstInBoundsGEP(
2506 SharedArgs, I, CGF.getPointerSize());
2507 Address TypedArgAddress = Bld.CreateBitCast(
2508 ArgAddress, CGF.ConvertTypeForMem(Ctx.getPointerType(ElemTy)));
2509 llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedArgAddress,
2510 /*Volatile=*/false, Int32PtrQTy, SourceLocation());
2511 Args.emplace_back(Arg);
2512 }
2513
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002514 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedParallelFn, Args);
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +00002515 CGF.FinishFunction();
2516 return Fn;
2517}