blob: ba23c493d87713774887c8028030c51e525ff99e [file] [log] [blame]
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001//===---- CGOpenMPRuntimeNVPTX.cpp - Interface to OpenMP NVPTX Runtimes ---===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Samuel Antao45bfe4c2016-02-08 15:59:20 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This provides a class for OpenMP runtime code generation specialized to NVPTX
10// targets.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGOpenMPRuntimeNVPTX.h"
Carlo Bertollic6872252016-04-04 15:55:02 +000015#include "CodeGenFunction.h"
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000016#include "clang/AST/DeclOpenMP.h"
Carlo Bertollic6872252016-04-04 15:55:02 +000017#include "clang/AST/StmtOpenMP.h"
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000018#include "clang/AST/StmtVisitor.h"
Alexey Bataeve4090182018-11-02 14:54:07 +000019#include "clang/Basic/Cuda.h"
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000020#include "llvm/ADT/SmallPtrSet.h"
Samuel Antao45bfe4c2016-02-08 15:59:20 +000021
22using namespace clang;
23using namespace CodeGen;
24
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +000025namespace {
26enum OpenMPRTLFunctionNVPTX {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000027 /// Call to void __kmpc_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +000028 /// int16_t RequiresOMPRuntime);
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +000029 OMPRTL_NVPTX__kmpc_kernel_init,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000030 /// Call to void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +000031 OMPRTL_NVPTX__kmpc_kernel_deinit,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000032 /// Call to void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +000033 /// int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +000034 OMPRTL_NVPTX__kmpc_spmd_kernel_init,
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +000035 /// Call to void __kmpc_spmd_kernel_deinit_v2(int16_t RequiresOMPRuntime);
36 OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000037 /// Call to void __kmpc_kernel_prepare_parallel(void
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +000038 /// *outlined_function, int16_t
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +000039 /// IsOMPRuntimeInitialized);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000040 OMPRTL_NVPTX__kmpc_kernel_prepare_parallel,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000041 /// Call to bool __kmpc_kernel_parallel(void **outlined_function,
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +000042 /// int16_t IsOMPRuntimeInitialized);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000043 OMPRTL_NVPTX__kmpc_kernel_parallel,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000044 /// Call to void __kmpc_kernel_end_parallel();
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000045 OMPRTL_NVPTX__kmpc_kernel_end_parallel,
46 /// Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
47 /// global_tid);
48 OMPRTL_NVPTX__kmpc_serialized_parallel,
49 /// Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
50 /// global_tid);
51 OMPRTL_NVPTX__kmpc_end_serialized_parallel,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000052 /// Call to int32_t __kmpc_shuffle_int32(int32_t element,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000053 /// int16_t lane_offset, int16_t warp_size);
54 OMPRTL_NVPTX__kmpc_shuffle_int32,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000055 /// Call to int64_t __kmpc_shuffle_int64(int64_t element,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000056 /// int16_t lane_offset, int16_t warp_size);
57 OMPRTL_NVPTX__kmpc_shuffle_int64,
Alexey Bataev8e009032019-01-04 17:25:09 +000058 /// Call to __kmpc_nvptx_parallel_reduce_nowait_v2(ident_t *loc, kmp_int32
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000059 /// global_tid, kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
60 /// void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
61 /// lane_offset, int16_t shortCircuit),
62 /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num));
Alexey Bataev8061acd2019-02-20 16:36:22 +000063 OMPRTL_NVPTX__kmpc_nvptx_parallel_reduce_nowait_v2,
64 /// Call to __kmpc_nvptx_teams_reduce_nowait_v2(ident_t *loc, kmp_int32
65 /// global_tid, void *global_buffer, int32_t num_of_records, void*
66 /// reduce_data,
67 /// void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
68 /// lane_offset, int16_t shortCircuit),
69 /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num), void
70 /// (*kmp_ListToGlobalCpyFctPtr)(void *buffer, int idx, void *reduce_data),
71 /// void (*kmp_GlobalToListCpyFctPtr)(void *buffer, int idx,
72 /// void *reduce_data), void (*kmp_GlobalToListCpyPtrsFctPtr)(void *buffer,
73 /// int idx, void *reduce_data), void (*kmp_GlobalToListRedFctPtr)(void
74 /// *buffer, int idx, void *reduce_data));
75 OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_v2,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000076 /// Call to __kmpc_nvptx_end_reduce_nowait(int32_t global_tid);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000077 OMPRTL_NVPTX__kmpc_end_reduce_nowait,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000078 /// Call to void __kmpc_data_sharing_init_stack();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000079 OMPRTL_NVPTX__kmpc_data_sharing_init_stack,
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +000080 /// Call to void __kmpc_data_sharing_init_stack_spmd();
81 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd,
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +000082 /// Call to void* __kmpc_data_sharing_coalesced_push_stack(size_t size,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000083 /// int16_t UseSharedMemory);
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +000084 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000085 /// Call to void __kmpc_data_sharing_pop_stack(void *a);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000086 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000087 /// Call to void __kmpc_begin_sharing_variables(void ***args,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000088 /// size_t n_args);
89 OMPRTL_NVPTX__kmpc_begin_sharing_variables,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000090 /// Call to void __kmpc_end_sharing_variables();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000091 OMPRTL_NVPTX__kmpc_end_sharing_variables,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000092 /// Call to void __kmpc_get_shared_variables(void ***GlobalArgs)
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000093 OMPRTL_NVPTX__kmpc_get_shared_variables,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +000094 /// Call to uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32
95 /// global_tid);
96 OMPRTL_NVPTX__kmpc_parallel_level,
Alexey Bataev673110d2018-05-16 13:36:30 +000097 /// Call to int8_t __kmpc_is_spmd_exec_mode();
98 OMPRTL_NVPTX__kmpc_is_spmd_exec_mode,
Alexey Bataev8e009032019-01-04 17:25:09 +000099 /// Call to void __kmpc_get_team_static_memory(int16_t isSPMDExecutionMode,
100 /// const void *buf, size_t size, int16_t is_shared, const void **res);
Alexey Bataeve4090182018-11-02 14:54:07 +0000101 OMPRTL_NVPTX__kmpc_get_team_static_memory,
Alexey Bataev8e009032019-01-04 17:25:09 +0000102 /// Call to void __kmpc_restore_team_static_memory(int16_t
103 /// isSPMDExecutionMode, int16_t is_shared);
Alexey Bataeve4090182018-11-02 14:54:07 +0000104 OMPRTL_NVPTX__kmpc_restore_team_static_memory,
Alexey Bataeva3924b52019-01-03 16:25:35 +0000105 /// Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataevc3028ca2018-12-04 15:03:25 +0000106 OMPRTL__kmpc_barrier,
Alexey Bataeva3924b52019-01-03 16:25:35 +0000107 /// Call to void __kmpc_barrier_simple_spmd(ident_t *loc, kmp_int32
108 /// global_tid);
109 OMPRTL__kmpc_barrier_simple_spmd,
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000110};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000111
112/// Pre(post)-action for different OpenMP constructs specialized for NVPTX.
113class NVPTXActionTy final : public PrePostActionTy {
James Y Knight9871db02019-02-05 16:42:33 +0000114 llvm::FunctionCallee EnterCallee = nullptr;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000115 ArrayRef<llvm::Value *> EnterArgs;
James Y Knight9871db02019-02-05 16:42:33 +0000116 llvm::FunctionCallee ExitCallee = nullptr;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000117 ArrayRef<llvm::Value *> ExitArgs;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000118 bool Conditional = false;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000119 llvm::BasicBlock *ContBlock = nullptr;
120
121public:
James Y Knight9871db02019-02-05 16:42:33 +0000122 NVPTXActionTy(llvm::FunctionCallee EnterCallee,
123 ArrayRef<llvm::Value *> EnterArgs,
124 llvm::FunctionCallee ExitCallee,
125 ArrayRef<llvm::Value *> ExitArgs, bool Conditional = false)
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000126 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
127 ExitArgs(ExitArgs), Conditional(Conditional) {}
128 void Enter(CodeGenFunction &CGF) override {
129 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
130 if (Conditional) {
131 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
132 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
133 ContBlock = CGF.createBasicBlock("omp_if.end");
134 // Generate the branch (If-stmt)
135 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
136 CGF.EmitBlock(ThenBlock);
137 }
138 }
139 void Done(CodeGenFunction &CGF) {
140 // Emit the rest of blocks/branches
141 CGF.EmitBranch(ContBlock);
142 CGF.EmitBlock(ContBlock, true);
143 }
144 void Exit(CodeGenFunction &CGF) override {
145 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
146 }
147};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000148
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000149/// A class to track the execution mode when codegening directives within
150/// a target region. The appropriate mode (SPMD|NON-SPMD) is set on entry
151/// to the target region and used by containing directives such as 'parallel'
152/// to emit optimized code.
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000153class ExecutionRuntimeModesRAII {
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000154private:
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000155 CGOpenMPRuntimeNVPTX::ExecutionMode SavedExecMode =
156 CGOpenMPRuntimeNVPTX::EM_Unknown;
157 CGOpenMPRuntimeNVPTX::ExecutionMode &ExecMode;
158 bool SavedRuntimeMode = false;
159 bool *RuntimeMode = nullptr;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000160
161public:
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000162 /// Constructor for Non-SPMD mode.
163 ExecutionRuntimeModesRAII(CGOpenMPRuntimeNVPTX::ExecutionMode &ExecMode)
164 : ExecMode(ExecMode) {
165 SavedExecMode = ExecMode;
166 ExecMode = CGOpenMPRuntimeNVPTX::EM_NonSPMD;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000167 }
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000168 /// Constructor for SPMD mode.
169 ExecutionRuntimeModesRAII(CGOpenMPRuntimeNVPTX::ExecutionMode &ExecMode,
170 bool &RuntimeMode, bool FullRuntimeMode)
171 : ExecMode(ExecMode), RuntimeMode(&RuntimeMode) {
172 SavedExecMode = ExecMode;
173 SavedRuntimeMode = RuntimeMode;
174 ExecMode = CGOpenMPRuntimeNVPTX::EM_SPMD;
175 RuntimeMode = FullRuntimeMode;
176 }
177 ~ExecutionRuntimeModesRAII() {
178 ExecMode = SavedExecMode;
179 if (RuntimeMode)
180 *RuntimeMode = SavedRuntimeMode;
181 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000182};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000183
184/// GPU Configuration: This information can be derived from cuda registers,
185/// however, providing compile time constants helps generate more efficient
186/// code. For all practical purposes this is fine because the configuration
187/// is the same for all known NVPTX architectures.
188enum MachineConfiguration : unsigned {
189 WarpSize = 32,
190 /// Number of bits required to represent a lane identifier, which is
191 /// computed as log_2(WarpSize).
192 LaneIDBits = 5,
193 LaneIDMask = WarpSize - 1,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +0000194
195 /// Global memory alignment for performance.
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000196 GlobalMemoryAlignment = 128,
Alexey Bataev09c9eea2018-11-09 16:18:04 +0000197
198 /// Maximal size of the shared memory buffer.
199 SharedMemorySize = 128,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000200};
201
Alexey Bataevf2f39be2018-11-16 19:38:21 +0000202static const ValueDecl *getPrivateItem(const Expr *RefExpr) {
203 RefExpr = RefExpr->IgnoreParens();
204 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr)) {
205 const Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
206 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
207 Base = TempASE->getBase()->IgnoreParenImpCasts();
208 RefExpr = Base;
209 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr)) {
210 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
211 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
212 Base = TempOASE->getBase()->IgnoreParenImpCasts();
213 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
214 Base = TempASE->getBase()->IgnoreParenImpCasts();
215 RefExpr = Base;
216 }
217 RefExpr = RefExpr->IgnoreParenImpCasts();
218 if (const auto *DE = dyn_cast<DeclRefExpr>(RefExpr))
219 return cast<ValueDecl>(DE->getDecl()->getCanonicalDecl());
220 const auto *ME = cast<MemberExpr>(RefExpr);
221 return cast<ValueDecl>(ME->getMemberDecl()->getCanonicalDecl());
222}
223
Alexey Bataev2adecff2018-09-21 14:22:53 +0000224typedef std::pair<CharUnits /*Align*/, const ValueDecl *> VarsDataTy;
225static bool stable_sort_comparator(const VarsDataTy P1, const VarsDataTy P2) {
226 return P1.first > P2.first;
227}
228
229static RecordDecl *buildRecordForGlobalizedVars(
230 ASTContext &C, ArrayRef<const ValueDecl *> EscapedDecls,
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000231 ArrayRef<const ValueDecl *> EscapedDeclsForTeams,
Alexey Bataev2adecff2018-09-21 14:22:53 +0000232 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
Alexey Bataev8061acd2019-02-20 16:36:22 +0000233 &MappedDeclsFields, int BufSize) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000234 if (EscapedDecls.empty() && EscapedDeclsForTeams.empty())
Alexey Bataev2adecff2018-09-21 14:22:53 +0000235 return nullptr;
236 SmallVector<VarsDataTy, 4> GlobalizedVars;
237 for (const ValueDecl *D : EscapedDecls)
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000238 GlobalizedVars.emplace_back(
239 CharUnits::fromQuantity(std::max(
240 C.getDeclAlign(D).getQuantity(),
241 static_cast<CharUnits::QuantityType>(GlobalMemoryAlignment))),
242 D);
243 for (const ValueDecl *D : EscapedDeclsForTeams)
Alexey Bataev2adecff2018-09-21 14:22:53 +0000244 GlobalizedVars.emplace_back(C.getDeclAlign(D), D);
245 std::stable_sort(GlobalizedVars.begin(), GlobalizedVars.end(),
246 stable_sort_comparator);
247 // Build struct _globalized_locals_ty {
Alexey Bataevff23bb62018-10-11 18:30:31 +0000248 // /* globalized vars */[WarSize] align (max(decl_align,
249 // GlobalMemoryAlignment))
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000250 // /* globalized vars */ for EscapedDeclsForTeams
Alexey Bataev2adecff2018-09-21 14:22:53 +0000251 // };
252 RecordDecl *GlobalizedRD = C.buildImplicitRecord("_globalized_locals_ty");
253 GlobalizedRD->startDefinition();
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000254 llvm::SmallPtrSet<const ValueDecl *, 16> SingleEscaped(
255 EscapedDeclsForTeams.begin(), EscapedDeclsForTeams.end());
Alexey Bataev2adecff2018-09-21 14:22:53 +0000256 for (const auto &Pair : GlobalizedVars) {
257 const ValueDecl *VD = Pair.second;
258 QualType Type = VD->getType();
259 if (Type->isLValueReferenceType())
260 Type = C.getPointerType(Type.getNonReferenceType());
261 else
262 Type = Type.getNonReferenceType();
263 SourceLocation Loc = VD->getLocation();
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000264 FieldDecl *Field;
265 if (SingleEscaped.count(VD)) {
266 Field = FieldDecl::Create(
267 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
268 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
269 /*BW=*/nullptr, /*Mutable=*/false,
270 /*InitStyle=*/ICIS_NoInit);
271 Field->setAccess(AS_public);
272 if (VD->hasAttrs()) {
273 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
274 E(VD->getAttrs().end());
275 I != E; ++I)
276 Field->addAttr(*I);
277 }
278 } else {
Alexey Bataev8061acd2019-02-20 16:36:22 +0000279 llvm::APInt ArraySize(32, BufSize);
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000280 Type = C.getConstantArrayType(Type, ArraySize, ArrayType::Normal, 0);
281 Field = FieldDecl::Create(
282 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
283 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
284 /*BW=*/nullptr, /*Mutable=*/false,
285 /*InitStyle=*/ICIS_NoInit);
286 Field->setAccess(AS_public);
287 llvm::APInt Align(32, std::max(C.getDeclAlign(VD).getQuantity(),
288 static_cast<CharUnits::QuantityType>(
289 GlobalMemoryAlignment)));
290 Field->addAttr(AlignedAttr::CreateImplicit(
291 C, AlignedAttr::GNU_aligned, /*IsAlignmentExpr=*/true,
292 IntegerLiteral::Create(C, Align,
293 C.getIntTypeForBitwidth(32, /*Signed=*/0),
294 SourceLocation())));
Alexey Bataev2adecff2018-09-21 14:22:53 +0000295 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000296 GlobalizedRD->addDecl(Field);
Alexey Bataev2adecff2018-09-21 14:22:53 +0000297 MappedDeclsFields.try_emplace(VD, Field);
298 }
299 GlobalizedRD->completeDefinition();
300 return GlobalizedRD;
301}
302
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000303/// Get the list of variables that can escape their declaration context.
304class CheckVarsEscapingDeclContext final
305 : public ConstStmtVisitor<CheckVarsEscapingDeclContext> {
306 CodeGenFunction &CGF;
307 llvm::SetVector<const ValueDecl *> EscapedDecls;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000308 llvm::SetVector<const ValueDecl *> EscapedVariableLengthDecls;
Alexey Bataevc99042b2018-03-15 18:10:54 +0000309 llvm::SmallPtrSet<const Decl *, 4> EscapedParameters;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000310 RecordDecl *GlobalizedRD = nullptr;
311 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000312 bool AllEscaped = false;
Alexey Bataev91433f62018-06-26 17:24:03 +0000313 bool IsForCombinedParallelRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000314
315 void markAsEscaped(const ValueDecl *VD) {
Alexey Bataev03f270c2018-03-30 18:31:07 +0000316 // Do not globalize declare target variables.
Alexey Bataev97b72212018-08-14 18:31:20 +0000317 if (!isa<VarDecl>(VD) ||
318 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataev03f270c2018-03-30 18:31:07 +0000319 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000320 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataevc99042b2018-03-15 18:10:54 +0000321 // Variables captured by value must be globalized.
322 if (auto *CSI = CGF.CapturedStmtInfo) {
Mikael Holmen9f373a32018-03-16 07:27:57 +0000323 if (const FieldDecl *FD = CSI->lookup(cast<VarDecl>(VD))) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000324 // Check if need to capture the variable that was already captured by
325 // value in the outer region.
Alexey Bataev91433f62018-06-26 17:24:03 +0000326 if (!IsForCombinedParallelRegion) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000327 if (!FD->hasAttrs())
328 return;
329 const auto *Attr = FD->getAttr<OMPCaptureKindAttr>();
330 if (!Attr)
331 return;
Alexey Bataev6393eb72018-12-06 15:35:13 +0000332 if (((Attr->getCaptureKind() != OMPC_map) &&
333 !isOpenMPPrivate(
334 static_cast<OpenMPClauseKind>(Attr->getCaptureKind()))) ||
335 ((Attr->getCaptureKind() == OMPC_map) &&
336 !FD->getType()->isAnyPointerType()))
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000337 return;
338 }
339 if (!FD->getType()->isReferenceType()) {
340 assert(!VD->getType()->isVariablyModifiedType() &&
341 "Parameter captured by value with variably modified type");
342 EscapedParameters.insert(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000343 } else if (!IsForCombinedParallelRegion) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000344 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000345 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000346 }
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000347 }
348 if ((!CGF.CapturedStmtInfo ||
Alexey Bataev91433f62018-06-26 17:24:03 +0000349 (IsForCombinedParallelRegion && CGF.CapturedStmtInfo)) &&
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000350 VD->getType()->isReferenceType())
351 // Do not globalize variables with reference type.
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000352 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000353 if (VD->getType()->isVariablyModifiedType())
354 EscapedVariableLengthDecls.insert(VD);
355 else
356 EscapedDecls.insert(VD);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000357 }
358
359 void VisitValueDecl(const ValueDecl *VD) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000360 if (VD->getType()->isLValueReferenceType())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000361 markAsEscaped(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000362 if (const auto *VarD = dyn_cast<VarDecl>(VD)) {
363 if (!isa<ParmVarDecl>(VarD) && VarD->hasInit()) {
364 const bool SavedAllEscaped = AllEscaped;
365 AllEscaped = VD->getType()->isLValueReferenceType();
366 Visit(VarD->getInit());
367 AllEscaped = SavedAllEscaped;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000368 }
369 }
370 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000371 void VisitOpenMPCapturedStmt(const CapturedStmt *S,
372 ArrayRef<OMPClause *> Clauses,
373 bool IsCombinedParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000374 if (!S)
375 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000376 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000377 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
378 const ValueDecl *VD = C.getCapturedVar();
Alexey Bataev91433f62018-06-26 17:24:03 +0000379 bool SavedIsForCombinedParallelRegion = IsForCombinedParallelRegion;
380 if (IsCombinedParallelRegion) {
381 // Check if the variable is privatized in the combined construct and
382 // those private copies must be shared in the inner parallel
383 // directive.
384 IsForCombinedParallelRegion = false;
385 for (const OMPClause *C : Clauses) {
386 if (!isOpenMPPrivate(C->getClauseKind()) ||
387 C->getClauseKind() == OMPC_reduction ||
388 C->getClauseKind() == OMPC_linear ||
389 C->getClauseKind() == OMPC_private)
390 continue;
391 ArrayRef<const Expr *> Vars;
392 if (const auto *PC = dyn_cast<OMPFirstprivateClause>(C))
393 Vars = PC->getVarRefs();
394 else if (const auto *PC = dyn_cast<OMPLastprivateClause>(C))
395 Vars = PC->getVarRefs();
396 else
397 llvm_unreachable("Unexpected clause.");
398 for (const auto *E : Vars) {
399 const Decl *D =
400 cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
401 if (D == VD->getCanonicalDecl()) {
402 IsForCombinedParallelRegion = true;
403 break;
404 }
405 }
406 if (IsForCombinedParallelRegion)
407 break;
408 }
409 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000410 markAsEscaped(VD);
411 if (isa<OMPCapturedExprDecl>(VD))
412 VisitValueDecl(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000413 IsForCombinedParallelRegion = SavedIsForCombinedParallelRegion;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000414 }
415 }
416 }
417
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000418 void buildRecordForGlobalizedVars(bool IsInTTDRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000419 assert(!GlobalizedRD &&
420 "Record for globalized variables is built already.");
Alexey Bataevff23bb62018-10-11 18:30:31 +0000421 ArrayRef<const ValueDecl *> EscapedDeclsForParallel, EscapedDeclsForTeams;
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000422 if (IsInTTDRegion)
Alexey Bataevff23bb62018-10-11 18:30:31 +0000423 EscapedDeclsForTeams = EscapedDecls.getArrayRef();
424 else
425 EscapedDeclsForParallel = EscapedDecls.getArrayRef();
Alexey Bataev2adecff2018-09-21 14:22:53 +0000426 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataevff23bb62018-10-11 18:30:31 +0000427 CGF.getContext(), EscapedDeclsForParallel, EscapedDeclsForTeams,
Alexey Bataev8061acd2019-02-20 16:36:22 +0000428 MappedDeclsFields, WarpSize);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000429 }
430
431public:
Alexey Bataevf2f39be2018-11-16 19:38:21 +0000432 CheckVarsEscapingDeclContext(CodeGenFunction &CGF,
433 ArrayRef<const ValueDecl *> TeamsReductions)
434 : CGF(CGF), EscapedDecls(TeamsReductions.begin(), TeamsReductions.end()) {
435 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000436 virtual ~CheckVarsEscapingDeclContext() = default;
437 void VisitDeclStmt(const DeclStmt *S) {
438 if (!S)
439 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000440 for (const Decl *D : S->decls())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000441 if (const auto *VD = dyn_cast_or_null<ValueDecl>(D))
442 VisitValueDecl(VD);
443 }
444 void VisitOMPExecutableDirective(const OMPExecutableDirective *D) {
445 if (!D)
446 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000447 if (!D->hasAssociatedStmt())
448 return;
449 if (const auto *S =
450 dyn_cast_or_null<CapturedStmt>(D->getAssociatedStmt())) {
451 // Do not analyze directives that do not actually require capturing,
452 // like `omp for` or `omp simd` directives.
453 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
454 getOpenMPCaptureRegions(CaptureRegions, D->getDirectiveKind());
455 if (CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown) {
456 VisitStmt(S->getCapturedStmt());
457 return;
Alexey Bataev673110d2018-05-16 13:36:30 +0000458 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000459 VisitOpenMPCapturedStmt(
460 S, D->clauses(),
461 CaptureRegions.back() == OMPD_parallel &&
462 isOpenMPDistributeDirective(D->getDirectiveKind()));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000463 }
464 }
465 void VisitCapturedStmt(const CapturedStmt *S) {
466 if (!S)
467 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000468 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000469 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
470 const ValueDecl *VD = C.getCapturedVar();
471 markAsEscaped(VD);
472 if (isa<OMPCapturedExprDecl>(VD))
473 VisitValueDecl(VD);
474 }
475 }
476 }
477 void VisitLambdaExpr(const LambdaExpr *E) {
478 if (!E)
479 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000480 for (const LambdaCapture &C : E->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000481 if (C.capturesVariable()) {
482 if (C.getCaptureKind() == LCK_ByRef) {
483 const ValueDecl *VD = C.getCapturedVar();
484 markAsEscaped(VD);
485 if (E->isInitCapture(&C) || isa<OMPCapturedExprDecl>(VD))
486 VisitValueDecl(VD);
487 }
488 }
489 }
490 }
491 void VisitBlockExpr(const BlockExpr *E) {
492 if (!E)
493 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000494 for (const BlockDecl::Capture &C : E->getBlockDecl()->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000495 if (C.isByRef()) {
496 const VarDecl *VD = C.getVariable();
497 markAsEscaped(VD);
498 if (isa<OMPCapturedExprDecl>(VD) || VD->isInitCapture())
499 VisitValueDecl(VD);
500 }
501 }
502 }
503 void VisitCallExpr(const CallExpr *E) {
504 if (!E)
505 return;
506 for (const Expr *Arg : E->arguments()) {
507 if (!Arg)
508 continue;
509 if (Arg->isLValue()) {
510 const bool SavedAllEscaped = AllEscaped;
511 AllEscaped = true;
512 Visit(Arg);
513 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000514 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000515 Visit(Arg);
Alexey Bataev9ff80832018-04-16 20:16:21 +0000516 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000517 }
518 Visit(E->getCallee());
519 }
520 void VisitDeclRefExpr(const DeclRefExpr *E) {
521 if (!E)
522 return;
523 const ValueDecl *VD = E->getDecl();
524 if (AllEscaped)
525 markAsEscaped(VD);
526 if (isa<OMPCapturedExprDecl>(VD))
527 VisitValueDecl(VD);
528 else if (const auto *VarD = dyn_cast<VarDecl>(VD))
529 if (VarD->isInitCapture())
530 VisitValueDecl(VD);
531 }
532 void VisitUnaryOperator(const UnaryOperator *E) {
533 if (!E)
534 return;
535 if (E->getOpcode() == UO_AddrOf) {
536 const bool SavedAllEscaped = AllEscaped;
537 AllEscaped = true;
538 Visit(E->getSubExpr());
539 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000540 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000541 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000542 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000543 }
544 void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
545 if (!E)
546 return;
547 if (E->getCastKind() == CK_ArrayToPointerDecay) {
548 const bool SavedAllEscaped = AllEscaped;
549 AllEscaped = true;
550 Visit(E->getSubExpr());
551 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000552 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000553 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000554 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000555 }
556 void VisitExpr(const Expr *E) {
557 if (!E)
558 return;
559 bool SavedAllEscaped = AllEscaped;
560 if (!E->isLValue())
561 AllEscaped = false;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000562 for (const Stmt *Child : E->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000563 if (Child)
564 Visit(Child);
565 AllEscaped = SavedAllEscaped;
566 }
567 void VisitStmt(const Stmt *S) {
568 if (!S)
569 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000570 for (const Stmt *Child : S->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000571 if (Child)
572 Visit(Child);
573 }
574
Alexey Bataevc99042b2018-03-15 18:10:54 +0000575 /// Returns the record that handles all the escaped local variables and used
576 /// instead of their original storage.
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000577 const RecordDecl *getGlobalizedRecord(bool IsInTTDRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000578 if (!GlobalizedRD)
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000579 buildRecordForGlobalizedVars(IsInTTDRegion);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000580 return GlobalizedRD;
581 }
582
Alexey Bataevc99042b2018-03-15 18:10:54 +0000583 /// Returns the field in the globalized record for the escaped variable.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000584 const FieldDecl *getFieldForGlobalizedVar(const ValueDecl *VD) const {
585 assert(GlobalizedRD &&
586 "Record for globalized variables must be generated already.");
587 auto I = MappedDeclsFields.find(VD);
588 if (I == MappedDeclsFields.end())
589 return nullptr;
590 return I->getSecond();
591 }
592
Alexey Bataevc99042b2018-03-15 18:10:54 +0000593 /// Returns the list of the escaped local variables/parameters.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000594 ArrayRef<const ValueDecl *> getEscapedDecls() const {
595 return EscapedDecls.getArrayRef();
596 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000597
598 /// Checks if the escaped local variable is actually a parameter passed by
599 /// value.
600 const llvm::SmallPtrSetImpl<const Decl *> &getEscapedParameters() const {
601 return EscapedParameters;
602 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000603
604 /// Returns the list of the escaped variables with the variably modified
605 /// types.
606 ArrayRef<const ValueDecl *> getEscapedVariableLengthDecls() const {
607 return EscapedVariableLengthDecls.getArrayRef();
608 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000609};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000610} // anonymous namespace
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000611
612/// Get the GPU warp size.
613static llvm::Value *getNVPTXWarpSize(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000614 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000615 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000616 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_warpsize),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000617 "nvptx_warp_size");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000618}
619
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000620/// Get the id of the current thread on the GPU.
621static llvm::Value *getNVPTXThreadID(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000622 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000623 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000624 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_tid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000625 "nvptx_tid");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000626}
627
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000628/// Get the id of the warp in the block.
629/// We assume that the warp size is 32, which is always the case
630/// on the NVPTX device, to generate more efficient code.
631static llvm::Value *getNVPTXWarpID(CodeGenFunction &CGF) {
632 CGBuilderTy &Bld = CGF.Builder;
633 return Bld.CreateAShr(getNVPTXThreadID(CGF), LaneIDBits, "nvptx_warp_id");
634}
635
636/// Get the id of the current lane in the Warp.
637/// We assume that the warp size is 32, which is always the case
638/// on the NVPTX device, to generate more efficient code.
639static llvm::Value *getNVPTXLaneID(CodeGenFunction &CGF) {
640 CGBuilderTy &Bld = CGF.Builder;
641 return Bld.CreateAnd(getNVPTXThreadID(CGF), Bld.getInt32(LaneIDMask),
642 "nvptx_lane_id");
643}
644
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000645/// Get the maximum number of threads in a block of the GPU.
646static llvm::Value *getNVPTXNumThreads(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000647 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000648 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000649 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_ntid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000650 "nvptx_num_threads");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000651}
652
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000653/// Get the value of the thread_limit clause in the teams directive.
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000654/// For the 'generic' execution mode, the runtime encodes thread_limit in
655/// the launch parameters, always starting thread_limit+warpSize threads per
656/// CTA. The threads in the last warp are reserved for master execution.
657/// For the 'spmd' execution mode, all threads in a CTA are part of the team.
658static llvm::Value *getThreadLimit(CodeGenFunction &CGF,
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000659 bool IsInSPMDExecutionMode = false) {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000660 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000661 return IsInSPMDExecutionMode
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000662 ? getNVPTXNumThreads(CGF)
Alexey Bataeve290ec02018-04-06 16:03:36 +0000663 : Bld.CreateNUWSub(getNVPTXNumThreads(CGF), getNVPTXWarpSize(CGF),
664 "thread_limit");
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000665}
666
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000667/// Get the thread id of the OMP master thread.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000668/// The master thread id is the first thread (lane) of the last warp in the
669/// GPU block. Warp size is assumed to be some power of 2.
670/// Thread id is 0 indexed.
671/// E.g: If NumThreads is 33, master id is 32.
672/// If NumThreads is 64, master id is 32.
673/// If NumThreads is 1024, master id is 992.
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000674static llvm::Value *getMasterThreadID(CodeGenFunction &CGF) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000675 CGBuilderTy &Bld = CGF.Builder;
676 llvm::Value *NumThreads = getNVPTXNumThreads(CGF);
677
678 // We assume that the warp size is a power of 2.
Alexey Bataeve290ec02018-04-06 16:03:36 +0000679 llvm::Value *Mask = Bld.CreateNUWSub(getNVPTXWarpSize(CGF), Bld.getInt32(1));
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000680
Alexey Bataeve290ec02018-04-06 16:03:36 +0000681 return Bld.CreateAnd(Bld.CreateNUWSub(NumThreads, Bld.getInt32(1)),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000682 Bld.CreateNot(Mask), "master_tid");
683}
684
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000685CGOpenMPRuntimeNVPTX::WorkerFunctionState::WorkerFunctionState(
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000686 CodeGenModule &CGM, SourceLocation Loc)
Alexey Bataev9ff80832018-04-16 20:16:21 +0000687 : WorkerFn(nullptr), CGFI(CGM.getTypes().arrangeNullaryFunction()),
688 Loc(Loc) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000689 createWorkerFunction(CGM);
Vasileios Kalintirise5c09592016-03-22 10:41:20 +0000690}
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000691
692void CGOpenMPRuntimeNVPTX::WorkerFunctionState::createWorkerFunction(
693 CodeGenModule &CGM) {
694 // Create an worker function with no arguments.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000695
696 WorkerFn = llvm::Function::Create(
Alexey Bataev9ff80832018-04-16 20:16:21 +0000697 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataevaee93892018-01-08 20:09:47 +0000698 /*placeholder=*/"_worker", &CGM.getModule());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000699 CGM.SetInternalFunctionAttributes(GlobalDecl(), WorkerFn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +0000700 WorkerFn->setDoesNotRecurse();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000701}
702
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000703CGOpenMPRuntimeNVPTX::ExecutionMode
704CGOpenMPRuntimeNVPTX::getExecutionMode() const {
705 return CurrentExecutionMode;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000706}
707
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000708static CGOpenMPRuntimeNVPTX::DataSharingMode
709getDataSharingMode(CodeGenModule &CGM) {
710 return CGM.getLangOpts().OpenMPCUDAMode ? CGOpenMPRuntimeNVPTX::CUDA
711 : CGOpenMPRuntimeNVPTX::Generic;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000712}
713
Alexey Bataev7bb33532019-01-07 21:30:43 +0000714/// Checks if the expression is constant or does not have non-trivial function
715/// calls.
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000716static bool isTrivial(ASTContext &Ctx, const Expr * E) {
717 // We can skip constant expressions.
718 // We can skip expressions with trivial calls or simple expressions.
719 return (E->isEvaluatable(Ctx, Expr::SE_AllowUndefinedBehavior) ||
720 !E->hasNonTrivialCall(Ctx)) &&
721 !E->HasSideEffects(Ctx, /*IncludePossibleEffects=*/true);
722}
723
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000724/// Checks if the \p Body is the \a CompoundStmt and returns its child statement
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000725/// iff there is only one that is not evaluatable at the compile time.
726static const Stmt *getSingleCompoundChild(ASTContext &Ctx, const Stmt *Body) {
727 if (const auto *C = dyn_cast<CompoundStmt>(Body)) {
728 const Stmt *Child = nullptr;
729 for (const Stmt *S : C->body()) {
730 if (const auto *E = dyn_cast<Expr>(S)) {
731 if (isTrivial(Ctx, E))
732 continue;
733 }
734 // Some of the statements can be ignored.
735 if (isa<AsmStmt>(S) || isa<NullStmt>(S) || isa<OMPFlushDirective>(S) ||
736 isa<OMPBarrierDirective>(S) || isa<OMPTaskyieldDirective>(S))
737 continue;
738 // Analyze declarations.
739 if (const auto *DS = dyn_cast<DeclStmt>(S)) {
740 if (llvm::all_of(DS->decls(), [&Ctx](const Decl *D) {
741 if (isa<EmptyDecl>(D) || isa<DeclContext>(D) ||
742 isa<TypeDecl>(D) || isa<PragmaCommentDecl>(D) ||
743 isa<PragmaDetectMismatchDecl>(D) || isa<UsingDecl>(D) ||
744 isa<UsingDirectiveDecl>(D) ||
745 isa<OMPDeclareReductionDecl>(D) ||
Alexey Bataev25ed0c02019-03-07 17:54:44 +0000746 isa<OMPThreadPrivateDecl>(D) || isa<OMPAllocateDecl>(D))
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000747 return true;
748 const auto *VD = dyn_cast<VarDecl>(D);
749 if (!VD)
750 return false;
751 return VD->isConstexpr() ||
752 ((VD->getType().isTrivialType(Ctx) ||
753 VD->getType()->isReferenceType()) &&
754 (!VD->hasInit() || isTrivial(Ctx, VD->getInit())));
755 }))
756 continue;
757 }
758 // Found multiple children - cannot get the one child only.
759 if (Child)
760 return Body;
761 Child = S;
762 }
763 if (Child)
764 return Child;
765 }
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000766 return Body;
767}
768
769/// Check if the parallel directive has an 'if' clause with non-constant or
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000770/// false condition. Also, check if the number of threads is strictly specified
771/// and run those directives in non-SPMD mode.
772static bool hasParallelIfNumThreadsClause(ASTContext &Ctx,
773 const OMPExecutableDirective &D) {
774 if (D.hasClausesOfKind<OMPNumThreadsClause>())
775 return true;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000776 for (const auto *C : D.getClausesOfKind<OMPIfClause>()) {
777 OpenMPDirectiveKind NameModifier = C->getNameModifier();
778 if (NameModifier != OMPD_parallel && NameModifier != OMPD_unknown)
779 continue;
780 const Expr *Cond = C->getCondition();
781 bool Result;
782 if (!Cond->EvaluateAsBooleanCondition(Result, Ctx) || !Result)
783 return true;
784 }
785 return false;
786}
787
788/// Check for inner (nested) SPMD construct, if any
789static bool hasNestedSPMDDirective(ASTContext &Ctx,
790 const OMPExecutableDirective &D) {
791 const auto *CS = D.getInnermostCapturedStmt();
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000792 const auto *Body =
793 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000794 const Stmt *ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000795
796 if (const auto *NestedDir = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
797 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000798 switch (D.getDirectiveKind()) {
799 case OMPD_target:
Alexey Bataevdf093e72018-05-11 19:45:14 +0000800 if (isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000801 !hasParallelIfNumThreadsClause(Ctx, *NestedDir))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000802 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000803 if (DKind == OMPD_teams) {
804 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
805 /*IgnoreCaptured=*/true);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000806 if (!Body)
807 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000808 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000809 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
810 DKind = NND->getDirectiveKind();
Alexey Bataevdf093e72018-05-11 19:45:14 +0000811 if (isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000812 !hasParallelIfNumThreadsClause(Ctx, *NND))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000813 return true;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000814 }
815 }
816 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000817 case OMPD_target_teams:
Alexey Bataevdf093e72018-05-11 19:45:14 +0000818 return isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000819 !hasParallelIfNumThreadsClause(Ctx, *NestedDir);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000820 case OMPD_target_simd:
821 case OMPD_target_parallel:
822 case OMPD_target_parallel_for:
823 case OMPD_target_parallel_for_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000824 case OMPD_target_teams_distribute:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000825 case OMPD_target_teams_distribute_simd:
826 case OMPD_target_teams_distribute_parallel_for:
827 case OMPD_target_teams_distribute_parallel_for_simd:
828 case OMPD_parallel:
829 case OMPD_for:
830 case OMPD_parallel_for:
831 case OMPD_parallel_sections:
832 case OMPD_for_simd:
833 case OMPD_parallel_for_simd:
834 case OMPD_cancel:
835 case OMPD_cancellation_point:
836 case OMPD_ordered:
837 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +0000838 case OMPD_allocate:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000839 case OMPD_task:
840 case OMPD_simd:
841 case OMPD_sections:
842 case OMPD_section:
843 case OMPD_single:
844 case OMPD_master:
845 case OMPD_critical:
846 case OMPD_taskyield:
847 case OMPD_barrier:
848 case OMPD_taskwait:
849 case OMPD_taskgroup:
850 case OMPD_atomic:
851 case OMPD_flush:
852 case OMPD_teams:
853 case OMPD_target_data:
854 case OMPD_target_exit_data:
855 case OMPD_target_enter_data:
856 case OMPD_distribute:
857 case OMPD_distribute_simd:
858 case OMPD_distribute_parallel_for:
859 case OMPD_distribute_parallel_for_simd:
860 case OMPD_teams_distribute:
861 case OMPD_teams_distribute_simd:
862 case OMPD_teams_distribute_parallel_for:
863 case OMPD_teams_distribute_parallel_for_simd:
864 case OMPD_target_update:
865 case OMPD_declare_simd:
866 case OMPD_declare_target:
867 case OMPD_end_declare_target:
868 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +0000869 case OMPD_declare_mapper:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000870 case OMPD_taskloop:
871 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000872 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000873 case OMPD_unknown:
874 llvm_unreachable("Unexpected directive.");
875 }
876 }
877
878 return false;
879}
880
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000881static bool supportsSPMDExecutionMode(ASTContext &Ctx,
882 const OMPExecutableDirective &D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000883 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
884 switch (DirectiveKind) {
885 case OMPD_target:
886 case OMPD_target_teams:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000887 return hasNestedSPMDDirective(Ctx, D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000888 case OMPD_target_parallel:
889 case OMPD_target_parallel_for:
890 case OMPD_target_parallel_for_simd:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000891 case OMPD_target_teams_distribute_parallel_for:
892 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev2adecff2018-09-21 14:22:53 +0000893 return !hasParallelIfNumThreadsClause(Ctx, D);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000894 case OMPD_target_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000895 case OMPD_target_teams_distribute:
896 case OMPD_target_teams_distribute_simd:
897 return false;
898 case OMPD_parallel:
899 case OMPD_for:
900 case OMPD_parallel_for:
901 case OMPD_parallel_sections:
902 case OMPD_for_simd:
903 case OMPD_parallel_for_simd:
904 case OMPD_cancel:
905 case OMPD_cancellation_point:
906 case OMPD_ordered:
907 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +0000908 case OMPD_allocate:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000909 case OMPD_task:
910 case OMPD_simd:
911 case OMPD_sections:
912 case OMPD_section:
913 case OMPD_single:
914 case OMPD_master:
915 case OMPD_critical:
916 case OMPD_taskyield:
917 case OMPD_barrier:
918 case OMPD_taskwait:
919 case OMPD_taskgroup:
920 case OMPD_atomic:
921 case OMPD_flush:
922 case OMPD_teams:
923 case OMPD_target_data:
924 case OMPD_target_exit_data:
925 case OMPD_target_enter_data:
926 case OMPD_distribute:
927 case OMPD_distribute_simd:
928 case OMPD_distribute_parallel_for:
929 case OMPD_distribute_parallel_for_simd:
930 case OMPD_teams_distribute:
931 case OMPD_teams_distribute_simd:
932 case OMPD_teams_distribute_parallel_for:
933 case OMPD_teams_distribute_parallel_for_simd:
934 case OMPD_target_update:
935 case OMPD_declare_simd:
936 case OMPD_declare_target:
937 case OMPD_end_declare_target:
938 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +0000939 case OMPD_declare_mapper:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000940 case OMPD_taskloop:
941 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000942 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000943 case OMPD_unknown:
944 break;
945 }
946 llvm_unreachable(
947 "Unknown programming model for OpenMP directive on NVPTX target.");
948}
949
950/// Check if the directive is loops based and has schedule clause at all or has
951/// static scheduling.
952static bool hasStaticScheduling(const OMPExecutableDirective &D) {
953 assert(isOpenMPWorksharingDirective(D.getDirectiveKind()) &&
954 isOpenMPLoopDirective(D.getDirectiveKind()) &&
955 "Expected loop-based directive.");
956 return !D.hasClausesOfKind<OMPOrderedClause>() &&
957 (!D.hasClausesOfKind<OMPScheduleClause>() ||
958 llvm::any_of(D.getClausesOfKind<OMPScheduleClause>(),
959 [](const OMPScheduleClause *C) {
960 return C->getScheduleKind() == OMPC_SCHEDULE_static;
961 }));
962}
963
964/// Check for inner (nested) lightweight runtime construct, if any
965static bool hasNestedLightweightDirective(ASTContext &Ctx,
966 const OMPExecutableDirective &D) {
967 assert(supportsSPMDExecutionMode(Ctx, D) && "Expected SPMD mode directive.");
968 const auto *CS = D.getInnermostCapturedStmt();
969 const auto *Body =
970 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000971 const Stmt *ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000972
973 if (const auto *NestedDir = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
974 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
975 switch (D.getDirectiveKind()) {
976 case OMPD_target:
977 if (isOpenMPParallelDirective(DKind) &&
978 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
979 hasStaticScheduling(*NestedDir))
980 return true;
981 if (DKind == OMPD_parallel) {
982 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
983 /*IgnoreCaptured=*/true);
984 if (!Body)
985 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000986 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000987 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
988 DKind = NND->getDirectiveKind();
989 if (isOpenMPWorksharingDirective(DKind) &&
990 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
991 return true;
992 }
993 } else if (DKind == OMPD_teams) {
994 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
995 /*IgnoreCaptured=*/true);
996 if (!Body)
997 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000998 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000999 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
1000 DKind = NND->getDirectiveKind();
1001 if (isOpenMPParallelDirective(DKind) &&
1002 isOpenMPWorksharingDirective(DKind) &&
1003 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
1004 return true;
1005 if (DKind == OMPD_parallel) {
1006 Body = NND->getInnermostCapturedStmt()->IgnoreContainers(
1007 /*IgnoreCaptured=*/true);
1008 if (!Body)
1009 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001010 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001011 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
1012 DKind = NND->getDirectiveKind();
1013 if (isOpenMPWorksharingDirective(DKind) &&
1014 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
1015 return true;
1016 }
1017 }
1018 }
1019 }
1020 return false;
1021 case OMPD_target_teams:
1022 if (isOpenMPParallelDirective(DKind) &&
1023 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
1024 hasStaticScheduling(*NestedDir))
1025 return true;
1026 if (DKind == OMPD_parallel) {
1027 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
1028 /*IgnoreCaptured=*/true);
1029 if (!Body)
1030 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001031 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001032 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
1033 DKind = NND->getDirectiveKind();
1034 if (isOpenMPWorksharingDirective(DKind) &&
1035 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
1036 return true;
1037 }
1038 }
1039 return false;
1040 case OMPD_target_parallel:
1041 return isOpenMPWorksharingDirective(DKind) &&
1042 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NestedDir);
1043 case OMPD_target_teams_distribute:
1044 case OMPD_target_simd:
1045 case OMPD_target_parallel_for:
1046 case OMPD_target_parallel_for_simd:
1047 case OMPD_target_teams_distribute_simd:
1048 case OMPD_target_teams_distribute_parallel_for:
1049 case OMPD_target_teams_distribute_parallel_for_simd:
1050 case OMPD_parallel:
1051 case OMPD_for:
1052 case OMPD_parallel_for:
1053 case OMPD_parallel_sections:
1054 case OMPD_for_simd:
1055 case OMPD_parallel_for_simd:
1056 case OMPD_cancel:
1057 case OMPD_cancellation_point:
1058 case OMPD_ordered:
1059 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00001060 case OMPD_allocate:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001061 case OMPD_task:
1062 case OMPD_simd:
1063 case OMPD_sections:
1064 case OMPD_section:
1065 case OMPD_single:
1066 case OMPD_master:
1067 case OMPD_critical:
1068 case OMPD_taskyield:
1069 case OMPD_barrier:
1070 case OMPD_taskwait:
1071 case OMPD_taskgroup:
1072 case OMPD_atomic:
1073 case OMPD_flush:
1074 case OMPD_teams:
1075 case OMPD_target_data:
1076 case OMPD_target_exit_data:
1077 case OMPD_target_enter_data:
1078 case OMPD_distribute:
1079 case OMPD_distribute_simd:
1080 case OMPD_distribute_parallel_for:
1081 case OMPD_distribute_parallel_for_simd:
1082 case OMPD_teams_distribute:
1083 case OMPD_teams_distribute_simd:
1084 case OMPD_teams_distribute_parallel_for:
1085 case OMPD_teams_distribute_parallel_for_simd:
1086 case OMPD_target_update:
1087 case OMPD_declare_simd:
1088 case OMPD_declare_target:
1089 case OMPD_end_declare_target:
1090 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00001091 case OMPD_declare_mapper:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001092 case OMPD_taskloop:
1093 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001094 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001095 case OMPD_unknown:
1096 llvm_unreachable("Unexpected directive.");
1097 }
1098 }
1099
1100 return false;
1101}
1102
1103/// Checks if the construct supports lightweight runtime. It must be SPMD
1104/// construct + inner loop-based construct with static scheduling.
1105static bool supportsLightweightRuntime(ASTContext &Ctx,
1106 const OMPExecutableDirective &D) {
1107 if (!supportsSPMDExecutionMode(Ctx, D))
1108 return false;
1109 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
1110 switch (DirectiveKind) {
1111 case OMPD_target:
1112 case OMPD_target_teams:
1113 case OMPD_target_parallel:
1114 return hasNestedLightweightDirective(Ctx, D);
1115 case OMPD_target_parallel_for:
1116 case OMPD_target_parallel_for_simd:
1117 case OMPD_target_teams_distribute_parallel_for:
1118 case OMPD_target_teams_distribute_parallel_for_simd:
1119 // (Last|First)-privates must be shared in parallel region.
1120 return hasStaticScheduling(D);
1121 case OMPD_target_simd:
1122 case OMPD_target_teams_distribute:
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001123 case OMPD_target_teams_distribute_simd:
Alexey Bataevdf093e72018-05-11 19:45:14 +00001124 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001125 case OMPD_parallel:
1126 case OMPD_for:
1127 case OMPD_parallel_for:
1128 case OMPD_parallel_sections:
1129 case OMPD_for_simd:
1130 case OMPD_parallel_for_simd:
1131 case OMPD_cancel:
1132 case OMPD_cancellation_point:
1133 case OMPD_ordered:
1134 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00001135 case OMPD_allocate:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001136 case OMPD_task:
1137 case OMPD_simd:
1138 case OMPD_sections:
1139 case OMPD_section:
1140 case OMPD_single:
1141 case OMPD_master:
1142 case OMPD_critical:
1143 case OMPD_taskyield:
1144 case OMPD_barrier:
1145 case OMPD_taskwait:
1146 case OMPD_taskgroup:
1147 case OMPD_atomic:
1148 case OMPD_flush:
1149 case OMPD_teams:
1150 case OMPD_target_data:
1151 case OMPD_target_exit_data:
1152 case OMPD_target_enter_data:
1153 case OMPD_distribute:
1154 case OMPD_distribute_simd:
1155 case OMPD_distribute_parallel_for:
1156 case OMPD_distribute_parallel_for_simd:
1157 case OMPD_teams_distribute:
1158 case OMPD_teams_distribute_simd:
1159 case OMPD_teams_distribute_parallel_for:
1160 case OMPD_teams_distribute_parallel_for_simd:
1161 case OMPD_target_update:
1162 case OMPD_declare_simd:
1163 case OMPD_declare_target:
1164 case OMPD_end_declare_target:
1165 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00001166 case OMPD_declare_mapper:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001167 case OMPD_taskloop:
1168 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001169 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001170 case OMPD_unknown:
1171 break;
1172 }
1173 llvm_unreachable(
1174 "Unknown programming model for OpenMP directive on NVPTX target.");
1175}
1176
1177void CGOpenMPRuntimeNVPTX::emitNonSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001178 StringRef ParentName,
1179 llvm::Function *&OutlinedFn,
1180 llvm::Constant *&OutlinedFnID,
1181 bool IsOffloadEntry,
1182 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001183 ExecutionRuntimeModesRAII ModeRAII(CurrentExecutionMode);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001184 EntryFunctionState EST;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001185 WorkerFunctionState WST(CGM, D.getBeginLoc());
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001186 Work.clear();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001187 WrapperFunctionsMap.clear();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001188
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001189 // Emit target region as a standalone region.
1190 class NVPTXPrePostActionTy : public PrePostActionTy {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001191 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1192 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001193
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001194 public:
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001195 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001196 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST)
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001197 : EST(EST), WST(WST) {}
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001198 void Enter(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001199 auto &RT =
1200 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001201 RT.emitNonSPMDEntryHeader(CGF, EST, WST);
1202 // Skip target region initialization.
1203 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001204 }
1205 void Exit(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001206 auto &RT =
1207 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001208 RT.clearLocThreadIdInsertPt(CGF);
1209 RT.emitNonSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001210 }
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001211 } Action(EST, WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001212 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001213 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001214 // Reserve place for the globalized memory.
1215 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001216 if (!KernelStaticGlobalized) {
1217 KernelStaticGlobalized = new llvm::GlobalVariable(
1218 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1219 llvm::GlobalValue::InternalLinkage,
1220 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1221 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1222 llvm::GlobalValue::NotThreadLocal,
1223 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1224 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001225 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1226 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001227 IsInTTDRegion = false;
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001228
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001229 // Now change the name of the worker function to correspond to this target
1230 // region's entry function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001231 WST.WorkerFn->setName(Twine(OutlinedFn->getName(), "_worker"));
Alexey Bataevaee93892018-01-08 20:09:47 +00001232
1233 // Create the worker function
1234 emitWorkerFunction(WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001235}
1236
1237// Setup NVPTX threads for master-worker OpenMP scheme.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001238void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryHeader(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001239 EntryFunctionState &EST,
1240 WorkerFunctionState &WST) {
1241 CGBuilderTy &Bld = CGF.Builder;
1242
1243 llvm::BasicBlock *WorkerBB = CGF.createBasicBlock(".worker");
1244 llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
1245 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
1246 EST.ExitBB = CGF.createBasicBlock(".exit");
1247
Alexey Bataev9ff80832018-04-16 20:16:21 +00001248 llvm::Value *IsWorker =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001249 Bld.CreateICmpULT(getNVPTXThreadID(CGF), getThreadLimit(CGF));
1250 Bld.CreateCondBr(IsWorker, WorkerBB, MasterCheckBB);
1251
1252 CGF.EmitBlock(WorkerBB);
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001253 emitCall(CGF, WST.Loc, WST.WorkerFn);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001254 CGF.EmitBranch(EST.ExitBB);
1255
1256 CGF.EmitBlock(MasterCheckBB);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001257 llvm::Value *IsMaster =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001258 Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
1259 Bld.CreateCondBr(IsMaster, MasterBB, EST.ExitBB);
1260
1261 CGF.EmitBlock(MasterBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001262 IsInTargetMasterThreadRegion = true;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001263 // SEQUENTIAL (MASTER) REGION START
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001264 // First action in sequential region:
1265 // Initialize the state of the OpenMP runtime library on the GPU.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001266 // TODO: Optimize runtime initialization and pass in correct value.
1267 llvm::Value *Args[] = {getThreadLimit(CGF),
1268 Bld.getInt16(/*RequiresOMPRuntime=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001269 CGF.EmitRuntimeCall(
1270 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_init), Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001271
1272 // For data sharing, we need to initialize the stack.
1273 CGF.EmitRuntimeCall(
1274 createNVPTXRuntimeFunction(
1275 OMPRTL_NVPTX__kmpc_data_sharing_init_stack));
1276
Alexey Bataevc99042b2018-03-15 18:10:54 +00001277 emitGenericVarsProlog(CGF, WST.Loc);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001278}
1279
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001280void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001281 EntryFunctionState &EST) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001282 IsInTargetMasterThreadRegion = false;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001283 if (!CGF.HaveInsertPoint())
1284 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001285
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001286 emitGenericVarsEpilog(CGF);
1287
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001288 if (!EST.ExitBB)
1289 EST.ExitBB = CGF.createBasicBlock(".exit");
1290
1291 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".termination.notifier");
1292 CGF.EmitBranch(TerminateBB);
1293
1294 CGF.EmitBlock(TerminateBB);
1295 // Signal termination condition.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001296 // TODO: Optimize runtime initialization and pass in correct value.
1297 llvm::Value *Args[] = {CGF.Builder.getInt16(/*IsOMPRuntimeInitialized=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001298 CGF.EmitRuntimeCall(
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001299 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_deinit), Args);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001300 // Barrier to terminate worker threads.
1301 syncCTAThreads(CGF);
1302 // Master thread jumps to exit point.
1303 CGF.EmitBranch(EST.ExitBB);
1304
1305 CGF.EmitBlock(EST.ExitBB);
1306 EST.ExitBB = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001307}
1308
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001309void CGOpenMPRuntimeNVPTX::emitSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001310 StringRef ParentName,
1311 llvm::Function *&OutlinedFn,
1312 llvm::Constant *&OutlinedFnID,
1313 bool IsOffloadEntry,
1314 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001315 ExecutionRuntimeModesRAII ModeRAII(
1316 CurrentExecutionMode, RequiresFullRuntime,
1317 CGM.getLangOpts().OpenMPCUDAForceFullRuntime ||
1318 !supportsLightweightRuntime(CGM.getContext(), D));
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001319 EntryFunctionState EST;
1320
1321 // Emit target region as a standalone region.
1322 class NVPTXPrePostActionTy : public PrePostActionTy {
1323 CGOpenMPRuntimeNVPTX &RT;
1324 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1325 const OMPExecutableDirective &D;
1326
1327 public:
1328 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT,
1329 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
1330 const OMPExecutableDirective &D)
1331 : RT(RT), EST(EST), D(D) {}
1332 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001333 RT.emitSPMDEntryHeader(CGF, EST, D);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001334 // Skip target region initialization.
1335 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001336 }
1337 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevfd006c42018-10-05 15:08:53 +00001338 RT.clearLocThreadIdInsertPt(CGF);
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001339 RT.emitSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001340 }
1341 } Action(*this, EST, D);
1342 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001343 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001344 // Reserve place for the globalized memory.
1345 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001346 if (!KernelStaticGlobalized) {
1347 KernelStaticGlobalized = new llvm::GlobalVariable(
1348 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1349 llvm::GlobalValue::InternalLinkage,
1350 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1351 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1352 llvm::GlobalValue::NotThreadLocal,
1353 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1354 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001355 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1356 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001357 IsInTTDRegion = false;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001358}
1359
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001360void CGOpenMPRuntimeNVPTX::emitSPMDEntryHeader(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001361 CodeGenFunction &CGF, EntryFunctionState &EST,
1362 const OMPExecutableDirective &D) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001363 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001364
1365 // Setup BBs in entry function.
1366 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute");
1367 EST.ExitBB = CGF.createBasicBlock(".exit");
1368
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001369 llvm::Value *Args[] = {getThreadLimit(CGF, /*IsInSPMDExecutionMode=*/true),
1370 /*RequiresOMPRuntime=*/
1371 Bld.getInt16(RequiresFullRuntime ? 1 : 0),
1372 /*RequiresDataSharing=*/Bld.getInt16(0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001373 CGF.EmitRuntimeCall(
1374 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_init), Args);
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001375
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001376 if (RequiresFullRuntime) {
1377 // For data sharing, we need to initialize the stack.
1378 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1379 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd));
1380 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001381
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001382 CGF.EmitBranch(ExecuteBB);
1383
1384 CGF.EmitBlock(ExecuteBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001385
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001386 IsInTargetMasterThreadRegion = true;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001387}
1388
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001389void CGOpenMPRuntimeNVPTX::emitSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001390 EntryFunctionState &EST) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001391 IsInTargetMasterThreadRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001392 if (!CGF.HaveInsertPoint())
1393 return;
1394
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001395 if (!EST.ExitBB)
1396 EST.ExitBB = CGF.createBasicBlock(".exit");
1397
1398 llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit");
1399 CGF.EmitBranch(OMPDeInitBB);
1400
1401 CGF.EmitBlock(OMPDeInitBB);
1402 // DeInitialize the OMP state in the runtime; called by all active threads.
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001403 llvm::Value *Args[] = {/*RequiresOMPRuntime=*/
1404 CGF.Builder.getInt16(RequiresFullRuntime ? 1 : 0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001405 CGF.EmitRuntimeCall(
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001406 createNVPTXRuntimeFunction(
1407 OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2), Args);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001408 CGF.EmitBranch(EST.ExitBB);
1409
1410 CGF.EmitBlock(EST.ExitBB);
1411 EST.ExitBB = nullptr;
1412}
1413
1414// Create a unique global variable to indicate the execution mode of this target
1415// region. The execution mode is either 'generic', or 'spmd' depending on the
1416// target directive. This variable is picked up by the offload library to setup
1417// the device appropriately before kernel launch. If the execution mode is
1418// 'generic', the runtime reserves one warp for the master, otherwise, all
1419// warps participate in parallel work.
1420static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001421 bool Mode) {
1422 auto *GVMode =
1423 new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
1424 llvm::GlobalValue::WeakAnyLinkage,
1425 llvm::ConstantInt::get(CGM.Int8Ty, Mode ? 0 : 1),
1426 Twine(Name, "_exec_mode"));
Alexey Bataev9ff80832018-04-16 20:16:21 +00001427 CGM.addCompilerUsedGlobal(GVMode);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001428}
1429
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001430void CGOpenMPRuntimeNVPTX::emitWorkerFunction(WorkerFunctionState &WST) {
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +00001431 ASTContext &Ctx = CGM.getContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001432
1433 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001434 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, WST.CGFI, {},
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001435 WST.Loc, WST.Loc);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001436 emitWorkerLoop(CGF, WST);
1437 CGF.FinishFunction();
1438}
1439
1440void CGOpenMPRuntimeNVPTX::emitWorkerLoop(CodeGenFunction &CGF,
1441 WorkerFunctionState &WST) {
1442 //
1443 // The workers enter this loop and wait for parallel work from the master.
1444 // When the master encounters a parallel region it sets up the work + variable
1445 // arguments, and wakes up the workers. The workers first check to see if
1446 // they are required for the parallel region, i.e., within the # of requested
1447 // parallel threads. The activated workers load the variable arguments and
1448 // execute the parallel work.
1449 //
1450
1451 CGBuilderTy &Bld = CGF.Builder;
1452
1453 llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work");
1454 llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers");
1455 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel");
1456 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel");
1457 llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel");
1458 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1459
1460 CGF.EmitBranch(AwaitBB);
1461
1462 // Workers wait for work from master.
1463 CGF.EmitBlock(AwaitBB);
1464 // Wait for parallel work
1465 syncCTAThreads(CGF);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001466
1467 Address WorkFn =
1468 CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn");
1469 Address ExecStatus =
1470 CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status");
1471 CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0));
1472 CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy));
1473
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001474 // TODO: Optimize runtime initialization and pass in correct value.
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001475 llvm::Value *Args[] = {WorkFn.getPointer(),
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001476 /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001477 llvm::Value *Ret = CGF.EmitRuntimeCall(
1478 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args);
1479 Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001480
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001481 // On termination condition (workid == 0), exit loop.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001482 llvm::Value *WorkID = Bld.CreateLoad(WorkFn);
1483 llvm::Value *ShouldTerminate = Bld.CreateIsNull(WorkID, "should_terminate");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001484 Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB);
1485
1486 // Activate requested workers.
1487 CGF.EmitBlock(SelectWorkersBB);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001488 llvm::Value *IsActive =
1489 Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active");
1490 Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001491
1492 // Signal start of parallel region.
1493 CGF.EmitBlock(ExecuteBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001494 // Skip initialization.
1495 setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001496
1497 // Process work items: outlined parallel functions.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001498 for (llvm::Function *W : Work) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001499 // Try to match this outlined function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001500 llvm::Value *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001501
1502 llvm::Value *WorkFnMatch =
1503 Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match");
1504
1505 llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn");
1506 llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next");
1507 Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB);
1508
1509 // Execute this outlined function.
1510 CGF.EmitBlock(ExecuteFNBB);
1511
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001512 // Insert call to work function via shared wrapper. The shared
1513 // wrapper takes two arguments:
1514 // - the parallelism level;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001515 // - the thread ID;
1516 emitCall(CGF, WST.Loc, W,
1517 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001518
1519 // Go to end of parallel region.
1520 CGF.EmitBranch(TerminateBB);
1521
1522 CGF.EmitBlock(CheckNextBB);
1523 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001524 // Default case: call to outlined function through pointer if the target
1525 // region makes a declare target call that may contain an orphaned parallel
1526 // directive.
1527 auto *ParallelFnTy =
1528 llvm::FunctionType::get(CGM.VoidTy, {CGM.Int16Ty, CGM.Int32Ty},
James Y Knight9871db02019-02-05 16:42:33 +00001529 /*isVarArg=*/false);
1530 llvm::Value *WorkFnCast =
1531 Bld.CreateBitCast(WorkID, ParallelFnTy->getPointerTo());
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001532 // Insert call to work function via shared wrapper. The shared
1533 // wrapper takes two arguments:
1534 // - the parallelism level;
1535 // - the thread ID;
James Y Knight9871db02019-02-05 16:42:33 +00001536 emitCall(CGF, WST.Loc, {ParallelFnTy, WorkFnCast},
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001537 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
1538 // Go to end of parallel region.
1539 CGF.EmitBranch(TerminateBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001540
1541 // Signal end of parallel region.
1542 CGF.EmitBlock(TerminateBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001543 CGF.EmitRuntimeCall(
1544 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_end_parallel),
1545 llvm::None);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001546 CGF.EmitBranch(BarrierBB);
1547
1548 // All active and inactive workers wait at a barrier after parallel region.
1549 CGF.EmitBlock(BarrierBB);
1550 // Barrier after parallel region.
1551 syncCTAThreads(CGF);
1552 CGF.EmitBranch(AwaitBB);
1553
1554 // Exit target region.
1555 CGF.EmitBlock(ExitBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001556 // Skip initialization.
1557 clearLocThreadIdInsertPt(CGF);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001558}
1559
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001560/// Returns specified OpenMP runtime function for the current OpenMP
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001561/// implementation. Specialized for the NVPTX device.
1562/// \param Function OpenMP runtime function.
1563/// \return Specified function.
James Y Knight9871db02019-02-05 16:42:33 +00001564llvm::FunctionCallee
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001565CGOpenMPRuntimeNVPTX::createNVPTXRuntimeFunction(unsigned Function) {
James Y Knight9871db02019-02-05 16:42:33 +00001566 llvm::FunctionCallee RTLFn = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001567 switch (static_cast<OpenMPRTLFunctionNVPTX>(Function)) {
1568 case OMPRTL_NVPTX__kmpc_kernel_init: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001569 // Build void __kmpc_kernel_init(kmp_int32 thread_limit, int16_t
1570 // RequiresOMPRuntime);
1571 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001572 auto *FnTy =
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001573 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1574 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_init");
1575 break;
1576 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001577 case OMPRTL_NVPTX__kmpc_kernel_deinit: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001578 // Build void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
1579 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001580 auto *FnTy =
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001581 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001582 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_deinit");
1583 break;
1584 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001585 case OMPRTL_NVPTX__kmpc_spmd_kernel_init: {
1586 // Build void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001587 // int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001588 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001589 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001590 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1591 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_init");
1592 break;
1593 }
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001594 case OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2: {
1595 // Build void __kmpc_spmd_kernel_deinit_v2(int16_t RequiresOMPRuntime);
1596 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001597 auto *FnTy =
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001598 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1599 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_deinit_v2");
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001600 break;
1601 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001602 case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: {
1603 /// Build void __kmpc_kernel_prepare_parallel(
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001604 /// void *outlined_function, int16_t IsOMPRuntimeInitialized);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001605 llvm::Type *TypeParams[] = {CGM.Int8PtrTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001606 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001607 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1608 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_prepare_parallel");
1609 break;
1610 }
1611 case OMPRTL_NVPTX__kmpc_kernel_parallel: {
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001612 /// Build bool __kmpc_kernel_parallel(void **outlined_function,
1613 /// int16_t IsOMPRuntimeInitialized);
1614 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy, CGM.Int16Ty};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001615 llvm::Type *RetTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001616 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001617 llvm::FunctionType::get(RetTy, TypeParams, /*isVarArg*/ false);
1618 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_parallel");
1619 break;
1620 }
1621 case OMPRTL_NVPTX__kmpc_kernel_end_parallel: {
1622 /// Build void __kmpc_kernel_end_parallel();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001623 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001624 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1625 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_end_parallel");
1626 break;
1627 }
1628 case OMPRTL_NVPTX__kmpc_serialized_parallel: {
1629 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1630 // global_tid);
1631 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001632 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001633 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1634 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1635 break;
1636 }
1637 case OMPRTL_NVPTX__kmpc_end_serialized_parallel: {
1638 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1639 // global_tid);
1640 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001641 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001642 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1643 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1644 break;
1645 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001646 case OMPRTL_NVPTX__kmpc_shuffle_int32: {
1647 // Build int32_t __kmpc_shuffle_int32(int32_t element,
1648 // int16_t lane_offset, int16_t warp_size);
1649 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001650 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001651 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1652 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int32");
1653 break;
1654 }
1655 case OMPRTL_NVPTX__kmpc_shuffle_int64: {
1656 // Build int64_t __kmpc_shuffle_int64(int64_t element,
1657 // int16_t lane_offset, int16_t warp_size);
1658 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001659 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001660 llvm::FunctionType::get(CGM.Int64Ty, TypeParams, /*isVarArg*/ false);
1661 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int64");
1662 break;
1663 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00001664 case OMPRTL_NVPTX__kmpc_nvptx_parallel_reduce_nowait_v2: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001665 // Build int32_t kmpc_nvptx_parallel_reduce_nowait_v2(ident_t *loc,
1666 // kmp_int32 global_tid, kmp_int32 num_vars, size_t reduce_size, void*
1667 // reduce_data, void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t
1668 // lane_id, int16_t lane_offset, int16_t Algorithm Version), void
1669 // (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001670 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1671 CGM.Int16Ty, CGM.Int16Ty};
1672 auto *ShuffleReduceFnTy =
1673 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1674 /*isVarArg=*/false);
1675 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1676 auto *InterWarpCopyFnTy =
1677 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1678 /*isVarArg=*/false);
Alexey Bataev8e009032019-01-04 17:25:09 +00001679 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1680 CGM.Int32Ty,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001681 CGM.Int32Ty,
1682 CGM.SizeTy,
1683 CGM.VoidPtrTy,
1684 ShuffleReduceFnTy->getPointerTo(),
1685 InterWarpCopyFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001686 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001687 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1688 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev8e009032019-01-04 17:25:09 +00001689 FnTy, /*Name=*/"__kmpc_nvptx_parallel_reduce_nowait_v2");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001690 break;
1691 }
1692 case OMPRTL_NVPTX__kmpc_end_reduce_nowait: {
1693 // Build __kmpc_end_reduce_nowait(kmp_int32 global_tid);
1694 llvm::Type *TypeParams[] = {CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001695 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001696 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1697 RTLFn = CGM.CreateRuntimeFunction(
1698 FnTy, /*Name=*/"__kmpc_nvptx_end_reduce_nowait");
1699 break;
1700 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00001701 case OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_v2: {
1702 // Build int32_t __kmpc_nvptx_teams_reduce_nowait_v2(ident_t *loc, kmp_int32
1703 // global_tid, void *global_buffer, int32_t num_of_records, void*
1704 // reduce_data,
1705 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1706 // lane_offset, int16_t shortCircuit),
1707 // void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num), void
1708 // (*kmp_ListToGlobalCpyFctPtr)(void *buffer, int idx, void *reduce_data),
1709 // void (*kmp_GlobalToListCpyFctPtr)(void *buffer, int idx,
1710 // void *reduce_data), void (*kmp_GlobalToListCpyPtrsFctPtr)(void *buffer,
1711 // int idx, void *reduce_data), void (*kmp_GlobalToListRedFctPtr)(void
1712 // *buffer, int idx, void *reduce_data));
1713 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1714 CGM.Int16Ty, CGM.Int16Ty};
1715 auto *ShuffleReduceFnTy =
1716 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1717 /*isVarArg=*/false);
1718 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1719 auto *InterWarpCopyFnTy =
1720 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1721 /*isVarArg=*/false);
1722 llvm::Type *GlobalListTypeParams[] = {CGM.VoidPtrTy, CGM.IntTy,
1723 CGM.VoidPtrTy};
1724 auto *GlobalListFnTy =
1725 llvm::FunctionType::get(CGM.VoidTy, GlobalListTypeParams,
1726 /*isVarArg=*/false);
1727 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1728 CGM.Int32Ty,
1729 CGM.VoidPtrTy,
1730 CGM.Int32Ty,
1731 CGM.VoidPtrTy,
1732 ShuffleReduceFnTy->getPointerTo(),
1733 InterWarpCopyFnTy->getPointerTo(),
1734 GlobalListFnTy->getPointerTo(),
1735 GlobalListFnTy->getPointerTo(),
1736 GlobalListFnTy->getPointerTo(),
1737 GlobalListFnTy->getPointerTo()};
Alexey Bataeva1166022018-11-27 21:24:54 +00001738 auto *FnTy =
1739 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1740 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev8061acd2019-02-20 16:36:22 +00001741 FnTy, /*Name=*/"__kmpc_nvptx_teams_reduce_nowait_v2");
Alexey Bataeva1166022018-11-27 21:24:54 +00001742 break;
1743 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001744 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack: {
1745 /// Build void __kmpc_data_sharing_init_stack();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001746 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001747 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1748 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack");
1749 break;
1750 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001751 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd: {
1752 /// Build void __kmpc_data_sharing_init_stack_spmd();
1753 auto *FnTy =
1754 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001755 RTLFn =
1756 CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack_spmd");
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001757 break;
1758 }
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001759 case OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack: {
1760 // Build void *__kmpc_data_sharing_coalesced_push_stack(size_t size,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001761 // int16_t UseSharedMemory);
1762 llvm::Type *TypeParams[] = {CGM.SizeTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001763 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001764 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1765 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001766 FnTy, /*Name=*/"__kmpc_data_sharing_coalesced_push_stack");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001767 break;
1768 }
1769 case OMPRTL_NVPTX__kmpc_data_sharing_pop_stack: {
1770 // Build void __kmpc_data_sharing_pop_stack(void *a);
1771 llvm::Type *TypeParams[] = {CGM.VoidPtrTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001772 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001773 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1774 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1775 /*Name=*/"__kmpc_data_sharing_pop_stack");
1776 break;
1777 }
1778 case OMPRTL_NVPTX__kmpc_begin_sharing_variables: {
1779 /// Build void __kmpc_begin_sharing_variables(void ***args,
1780 /// size_t n_args);
1781 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo(), CGM.SizeTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001782 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001783 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1784 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_begin_sharing_variables");
1785 break;
1786 }
1787 case OMPRTL_NVPTX__kmpc_end_sharing_variables: {
1788 /// Build void __kmpc_end_sharing_variables();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001789 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001790 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1791 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_sharing_variables");
1792 break;
1793 }
1794 case OMPRTL_NVPTX__kmpc_get_shared_variables: {
1795 /// Build void __kmpc_get_shared_variables(void ***GlobalArgs);
1796 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001797 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001798 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1799 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_shared_variables");
1800 break;
1801 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001802 case OMPRTL_NVPTX__kmpc_parallel_level: {
1803 // Build uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32 global_tid);
1804 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1805 auto *FnTy =
1806 llvm::FunctionType::get(CGM.Int16Ty, TypeParams, /*isVarArg*/ false);
1807 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_parallel_level");
1808 break;
1809 }
Alexey Bataev673110d2018-05-16 13:36:30 +00001810 case OMPRTL_NVPTX__kmpc_is_spmd_exec_mode: {
1811 // Build int8_t __kmpc_is_spmd_exec_mode();
1812 auto *FnTy = llvm::FunctionType::get(CGM.Int8Ty, /*isVarArg=*/false);
1813 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_is_spmd_exec_mode");
1814 break;
1815 }
Alexey Bataeve4090182018-11-02 14:54:07 +00001816 case OMPRTL_NVPTX__kmpc_get_team_static_memory: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001817 // Build void __kmpc_get_team_static_memory(int16_t isSPMDExecutionMode,
1818 // const void *buf, size_t size, int16_t is_shared, const void **res);
1819 llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.VoidPtrTy, CGM.SizeTy,
1820 CGM.Int16Ty, CGM.VoidPtrPtrTy};
Alexey Bataeve4090182018-11-02 14:54:07 +00001821 auto *FnTy =
1822 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1823 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_team_static_memory");
1824 break;
1825 }
1826 case OMPRTL_NVPTX__kmpc_restore_team_static_memory: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001827 // Build void __kmpc_restore_team_static_memory(int16_t isSPMDExecutionMode,
1828 // int16_t is_shared);
1829 llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataeve4090182018-11-02 14:54:07 +00001830 auto *FnTy =
Alexey Bataev8e009032019-01-04 17:25:09 +00001831 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
Alexey Bataeve4090182018-11-02 14:54:07 +00001832 RTLFn =
1833 CGM.CreateRuntimeFunction(FnTy, "__kmpc_restore_team_static_memory");
1834 break;
1835 }
Alexey Bataevc3028ca2018-12-04 15:03:25 +00001836 case OMPRTL__kmpc_barrier: {
1837 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
1838 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1839 auto *FnTy =
1840 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1841 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
James Y Knight9871db02019-02-05 16:42:33 +00001842 cast<llvm::Function>(RTLFn.getCallee())
1843 ->addFnAttr(llvm::Attribute::Convergent);
Alexey Bataevc3028ca2018-12-04 15:03:25 +00001844 break;
1845 }
Alexey Bataeva3924b52019-01-03 16:25:35 +00001846 case OMPRTL__kmpc_barrier_simple_spmd: {
1847 // Build void __kmpc_barrier_simple_spmd(ident_t *loc, kmp_int32
1848 // global_tid);
1849 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1850 auto *FnTy =
1851 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1852 RTLFn =
1853 CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier_simple_spmd");
James Y Knight9871db02019-02-05 16:42:33 +00001854 cast<llvm::Function>(RTLFn.getCallee())
1855 ->addFnAttr(llvm::Attribute::Convergent);
Alexey Bataeva3924b52019-01-03 16:25:35 +00001856 break;
1857 }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001858 }
1859 return RTLFn;
1860}
1861
1862void CGOpenMPRuntimeNVPTX::createOffloadEntry(llvm::Constant *ID,
1863 llvm::Constant *Addr,
Alexey Bataev03f270c2018-03-30 18:31:07 +00001864 uint64_t Size, int32_t,
1865 llvm::GlobalValue::LinkageTypes) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001866 // TODO: Add support for global variables on the device after declare target
1867 // support.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001868 if (!isa<llvm::Function>(Addr))
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001869 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +00001870 llvm::Module &M = CGM.getModule();
1871 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001872
1873 // Get "nvvm.annotations" metadata node
Alexey Bataev9ff80832018-04-16 20:16:21 +00001874 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001875
1876 llvm::Metadata *MDVals[] = {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001877 llvm::ConstantAsMetadata::get(Addr), llvm::MDString::get(Ctx, "kernel"),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001878 llvm::ConstantAsMetadata::get(
1879 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))};
1880 // Append metadata to nvvm.annotations
1881 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
1882}
1883
1884void CGOpenMPRuntimeNVPTX::emitTargetOutlinedFunction(
1885 const OMPExecutableDirective &D, StringRef ParentName,
1886 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001887 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001888 if (!IsOffloadEntry) // Nothing to do.
1889 return;
1890
1891 assert(!ParentName.empty() && "Invalid target region parent name!");
1892
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001893 bool Mode = supportsSPMDExecutionMode(CGM.getContext(), D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001894 if (Mode)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001895 emitSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001896 CodeGen);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001897 else
1898 emitNonSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1899 CodeGen);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001900
1901 setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001902}
1903
Alexey Bataevceeaa482018-11-21 21:04:34 +00001904namespace {
1905LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
1906/// Enum for accesseing the reserved_2 field of the ident_t struct.
1907enum ModeFlagsTy : unsigned {
1908 /// Bit set to 1 when in SPMD mode.
1909 KMP_IDENT_SPMD_MODE = 0x01,
1910 /// Bit set to 1 when a simplified runtime is used.
1911 KMP_IDENT_SIMPLE_RT_MODE = 0x02,
1912 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/KMP_IDENT_SIMPLE_RT_MODE)
1913};
1914
1915/// Special mode Undefined. Is the combination of Non-SPMD mode + SimpleRuntime.
1916static const ModeFlagsTy UndefinedMode =
1917 (~KMP_IDENT_SPMD_MODE) & KMP_IDENT_SIMPLE_RT_MODE;
1918} // anonymous namespace
1919
1920unsigned CGOpenMPRuntimeNVPTX::getDefaultLocationReserved2Flags() const {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001921 switch (getExecutionMode()) {
1922 case EM_SPMD:
1923 if (requiresFullRuntime())
1924 return KMP_IDENT_SPMD_MODE & (~KMP_IDENT_SIMPLE_RT_MODE);
1925 return KMP_IDENT_SPMD_MODE | KMP_IDENT_SIMPLE_RT_MODE;
1926 case EM_NonSPMD:
1927 assert(requiresFullRuntime() && "Expected full runtime.");
1928 return (~KMP_IDENT_SPMD_MODE) & (~KMP_IDENT_SIMPLE_RT_MODE);
1929 case EM_Unknown:
1930 return UndefinedMode;
1931 }
1932 llvm_unreachable("Unknown flags are requested.");
Alexey Bataevceeaa482018-11-21 21:04:34 +00001933}
1934
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001935CGOpenMPRuntimeNVPTX::CGOpenMPRuntimeNVPTX(CodeGenModule &CGM)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001936 : CGOpenMPRuntime(CGM, "_", "$") {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001937 if (!CGM.getLangOpts().OpenMPIsDevice)
1938 llvm_unreachable("OpenMP NVPTX can only handle device code.");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001939}
Carlo Bertollic6872252016-04-04 15:55:02 +00001940
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001941void CGOpenMPRuntimeNVPTX::emitProcBindClause(CodeGenFunction &CGF,
1942 OpenMPProcBindClauseKind ProcBind,
1943 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001944 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001945 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001946 return;
1947
1948 CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc);
1949}
1950
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001951void CGOpenMPRuntimeNVPTX::emitNumThreadsClause(CodeGenFunction &CGF,
1952 llvm::Value *NumThreads,
1953 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001954 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001955 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001956 return;
1957
1958 CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc);
1959}
1960
Carlo Bertollic6872252016-04-04 15:55:02 +00001961void CGOpenMPRuntimeNVPTX::emitNumTeamsClause(CodeGenFunction &CGF,
1962 const Expr *NumTeams,
1963 const Expr *ThreadLimit,
1964 SourceLocation Loc) {}
1965
James Y Knight9871db02019-02-05 16:42:33 +00001966llvm::Function *CGOpenMPRuntimeNVPTX::emitParallelOutlinedFunction(
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001967 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1968 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00001969 // Emit target region as a standalone region.
1970 class NVPTXPrePostActionTy : public PrePostActionTy {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001971 bool &IsInParallelRegion;
1972 bool PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001973
1974 public:
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001975 NVPTXPrePostActionTy(bool &IsInParallelRegion)
1976 : IsInParallelRegion(IsInParallelRegion) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00001977 void Enter(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001978 PrevIsInParallelRegion = IsInParallelRegion;
1979 IsInParallelRegion = true;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001980 }
1981 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001982 IsInParallelRegion = PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001983 }
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001984 } Action(IsInParallelRegion);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001985 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001986 bool PrevIsInTTDRegion = IsInTTDRegion;
1987 IsInTTDRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001988 bool PrevIsInTargetMasterThreadRegion = IsInTargetMasterThreadRegion;
1989 IsInTargetMasterThreadRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001990 auto *OutlinedFun =
1991 cast<llvm::Function>(CGOpenMPRuntime::emitParallelOutlinedFunction(
1992 D, ThreadIDVar, InnermostKind, CodeGen));
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001993 IsInTargetMasterThreadRegion = PrevIsInTargetMasterThreadRegion;
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001994 IsInTTDRegion = PrevIsInTTDRegion;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001995 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD &&
1996 !IsInParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001997 llvm::Function *WrapperFun =
1998 createParallelDataSharingWrapper(OutlinedFun, D);
1999 WrapperFunctionsMap[OutlinedFun] = WrapperFun;
2000 }
2001
2002 return OutlinedFun;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002003}
2004
Alexey Bataev2adecff2018-09-21 14:22:53 +00002005/// Get list of lastprivate variables from the teams distribute ... or
2006/// teams {distribute ...} directives.
2007static void
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00002008getDistributeLastprivateVars(ASTContext &Ctx, const OMPExecutableDirective &D,
Alexey Bataev2adecff2018-09-21 14:22:53 +00002009 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
2010 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
2011 "expected teams directive.");
2012 const OMPExecutableDirective *Dir = &D;
2013 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
2014 if (const Stmt *S = getSingleCompoundChild(
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00002015 Ctx,
Alexey Bataev2adecff2018-09-21 14:22:53 +00002016 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
2017 /*IgnoreCaptured=*/true))) {
2018 Dir = dyn_cast<OMPExecutableDirective>(S);
2019 if (Dir && !isOpenMPDistributeDirective(Dir->getDirectiveKind()))
2020 Dir = nullptr;
2021 }
2022 }
2023 if (!Dir)
2024 return;
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002025 for (const auto *C : Dir->getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002026 for (const Expr *E : C->getVarRefs())
2027 Vars.push_back(getPrivateItem(E));
2028 }
2029}
2030
2031/// Get list of reduction variables from the teams ... directives.
2032static void
2033getTeamsReductionVars(ASTContext &Ctx, const OMPExecutableDirective &D,
2034 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
2035 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
2036 "expected teams directive.");
2037 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
2038 for (const Expr *E : C->privates())
2039 Vars.push_back(getPrivateItem(E));
Alexey Bataev2adecff2018-09-21 14:22:53 +00002040 }
2041}
2042
James Y Knight9871db02019-02-05 16:42:33 +00002043llvm::Function *CGOpenMPRuntimeNVPTX::emitTeamsOutlinedFunction(
Carlo Bertollic6872252016-04-04 15:55:02 +00002044 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
2045 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002046 SourceLocation Loc = D.getBeginLoc();
Carlo Bertollic6872252016-04-04 15:55:02 +00002047
Alexey Bataev2adecff2018-09-21 14:22:53 +00002048 const RecordDecl *GlobalizedRD = nullptr;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002049 llvm::SmallVector<const ValueDecl *, 4> LastPrivatesReductions;
Alexey Bataev2adecff2018-09-21 14:22:53 +00002050 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002051 // Globalize team reductions variable unconditionally in all modes.
Alexey Bataev8061acd2019-02-20 16:36:22 +00002052 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
2053 getTeamsReductionVars(CGM.getContext(), D, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002054 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002055 getDistributeLastprivateVars(CGM.getContext(), D, LastPrivatesReductions);
2056 if (!LastPrivatesReductions.empty()) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002057 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002058 CGM.getContext(), llvm::None, LastPrivatesReductions,
Alexey Bataev8061acd2019-02-20 16:36:22 +00002059 MappedDeclsFields, WarpSize);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002060 }
2061 } else if (!LastPrivatesReductions.empty()) {
2062 assert(!TeamAndReductions.first &&
2063 "Previous team declaration is not expected.");
2064 TeamAndReductions.first = D.getCapturedStmt(OMPD_teams)->getCapturedDecl();
2065 std::swap(TeamAndReductions.second, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002066 }
2067
Alexey Bataevc99042b2018-03-15 18:10:54 +00002068 // Emit target region as a standalone region.
2069 class NVPTXPrePostActionTy : public PrePostActionTy {
2070 SourceLocation &Loc;
Alexey Bataev2adecff2018-09-21 14:22:53 +00002071 const RecordDecl *GlobalizedRD;
2072 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2073 &MappedDeclsFields;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002074
2075 public:
Alexey Bataev2adecff2018-09-21 14:22:53 +00002076 NVPTXPrePostActionTy(
2077 SourceLocation &Loc, const RecordDecl *GlobalizedRD,
2078 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2079 &MappedDeclsFields)
2080 : Loc(Loc), GlobalizedRD(GlobalizedRD),
2081 MappedDeclsFields(MappedDeclsFields) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00002082 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002083 auto &Rt =
2084 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
2085 if (GlobalizedRD) {
2086 auto I = Rt.FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
2087 I->getSecond().GlobalRecord = GlobalizedRD;
2088 I->getSecond().MappedParams =
2089 llvm::make_unique<CodeGenFunction::OMPMapVars>();
2090 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
2091 for (const auto &Pair : MappedDeclsFields) {
2092 assert(Pair.getFirst()->isCanonicalDecl() &&
2093 "Expected canonical declaration");
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002094 Data.insert(std::make_pair(Pair.getFirst(),
2095 MappedVarData(Pair.getSecond(),
2096 /*IsOnePerTeam=*/true)));
Alexey Bataev2adecff2018-09-21 14:22:53 +00002097 }
2098 }
2099 Rt.emitGenericVarsProlog(CGF, Loc);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002100 }
2101 void Exit(CodeGenFunction &CGF) override {
2102 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
2103 .emitGenericVarsEpilog(CGF);
2104 }
Alexey Bataev2adecff2018-09-21 14:22:53 +00002105 } Action(Loc, GlobalizedRD, MappedDeclsFields);
2106 CodeGen.setAction(Action);
James Y Knight9871db02019-02-05 16:42:33 +00002107 llvm::Function *OutlinedFun = CGOpenMPRuntime::emitTeamsOutlinedFunction(
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002108 D, ThreadIDVar, InnermostKind, CodeGen);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002109 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00002110 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002111 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
Carlo Bertollic6872252016-04-04 15:55:02 +00002112
2113 return OutlinedFun;
2114}
2115
Alexey Bataevc99042b2018-03-15 18:10:54 +00002116void CGOpenMPRuntimeNVPTX::emitGenericVarsProlog(CodeGenFunction &CGF,
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002117 SourceLocation Loc,
2118 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002119 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2120 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002121 return;
2122
Alexey Bataevc99042b2018-03-15 18:10:54 +00002123 CGBuilderTy &Bld = CGF.Builder;
2124
2125 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
2126 if (I == FunctionGlobalizedDecls.end())
2127 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002128 if (const RecordDecl *GlobalizedVarsRecord = I->getSecond().GlobalRecord) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002129 QualType GlobalRecTy = CGM.getContext().getRecordType(GlobalizedVarsRecord);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002130 QualType SecGlobalRecTy;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002131
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002132 // Recover pointer to this function's global record. The runtime will
2133 // handle the specifics of the allocation of the memory.
2134 // Use actual memory size of the record including the padding
2135 // for alignment purposes.
2136 unsigned Alignment =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002137 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002138 unsigned GlobalRecordSize =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002139 CGM.getContext().getTypeSizeInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002140 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002141
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002142 llvm::PointerType *GlobalRecPtrTy =
2143 CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo();
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002144 llvm::Value *GlobalRecCastAddr;
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002145 llvm::Value *IsTTD = nullptr;
Alexey Bataeve4090182018-11-02 14:54:07 +00002146 if (!IsInTTDRegion &&
2147 (WithSPMDCheck ||
2148 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002149 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2150 llvm::BasicBlock *SPMDBB = CGF.createBasicBlock(".spmd");
2151 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002152 if (I->getSecond().SecondaryGlobalRecord.hasValue()) {
2153 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2154 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2155 llvm::Value *PL = CGF.EmitRuntimeCall(
2156 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2157 {RTLoc, ThreadID});
2158 IsTTD = Bld.CreateIsNull(PL);
2159 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002160 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2161 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
2162 Bld.CreateCondBr(IsSPMD, SPMDBB, NonSPMDBB);
2163 // There is no need to emit line number for unconditional branch.
2164 (void)ApplyDebugLocation::CreateEmpty(CGF);
2165 CGF.EmitBlock(SPMDBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002166 Address RecPtr = Address(llvm::ConstantPointerNull::get(GlobalRecPtrTy),
2167 CharUnits::fromQuantity(Alignment));
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002168 CGF.EmitBranch(ExitBB);
2169 // There is no need to emit line number for unconditional branch.
2170 (void)ApplyDebugLocation::CreateEmpty(CGF);
2171 CGF.EmitBlock(NonSPMDBB);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002172 llvm::Value *Size = llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize);
2173 if (const RecordDecl *SecGlobalizedVarsRecord =
2174 I->getSecond().SecondaryGlobalRecord.getValueOr(nullptr)) {
2175 SecGlobalRecTy =
2176 CGM.getContext().getRecordType(SecGlobalizedVarsRecord);
2177
2178 // Recover pointer to this function's global record. The runtime will
2179 // handle the specifics of the allocation of the memory.
2180 // Use actual memory size of the record including the padding
2181 // for alignment purposes.
2182 unsigned Alignment =
2183 CGM.getContext().getTypeAlignInChars(SecGlobalRecTy).getQuantity();
2184 unsigned GlobalRecordSize =
2185 CGM.getContext().getTypeSizeInChars(SecGlobalRecTy).getQuantity();
2186 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
2187 Size = Bld.CreateSelect(
2188 IsTTD, llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize), Size);
2189 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002190 // TODO: allow the usage of shared memory to be controlled by
2191 // the user, for now, default to global.
2192 llvm::Value *GlobalRecordSizeArg[] = {
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002193 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002194 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2195 createNVPTXRuntimeFunction(
2196 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2197 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002198 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002199 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002200 CGF.EmitBlock(ExitBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002201 auto *Phi = Bld.CreatePHI(GlobalRecPtrTy,
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002202 /*NumReservedValues=*/2, "_select_stack");
2203 Phi->addIncoming(RecPtr.getPointer(), SPMDBB);
2204 Phi->addIncoming(GlobalRecCastAddr, NonSPMDBB);
2205 GlobalRecCastAddr = Phi;
2206 I->getSecond().GlobalRecordAddr = Phi;
2207 I->getSecond().IsInSPMDModeFlag = IsSPMD;
Alexey Bataeve4090182018-11-02 14:54:07 +00002208 } else if (IsInTTDRegion) {
2209 assert(GlobalizedRecords.back().Records.size() < 2 &&
2210 "Expected less than 2 globalized records: one for target and one "
2211 "for teams.");
2212 unsigned Offset = 0;
2213 for (const RecordDecl *RD : GlobalizedRecords.back().Records) {
2214 QualType RDTy = CGM.getContext().getRecordType(RD);
2215 unsigned Alignment =
2216 CGM.getContext().getTypeAlignInChars(RDTy).getQuantity();
2217 unsigned Size = CGM.getContext().getTypeSizeInChars(RDTy).getQuantity();
2218 Offset =
2219 llvm::alignTo(llvm::alignTo(Offset, Alignment) + Size, Alignment);
2220 }
2221 unsigned Alignment =
2222 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
2223 Offset = llvm::alignTo(Offset, Alignment);
2224 GlobalizedRecords.back().Records.push_back(GlobalizedVarsRecord);
2225 ++GlobalizedRecords.back().RegionCounter;
2226 if (GlobalizedRecords.back().Records.size() == 1) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002227 assert(KernelStaticGlobalized &&
2228 "Kernel static pointer must be initialized already.");
2229 auto *UseSharedMemory = new llvm::GlobalVariable(
2230 CGM.getModule(), CGM.Int16Ty, /*isConstant=*/true,
2231 llvm::GlobalValue::InternalLinkage, nullptr,
2232 "_openmp_static_kernel$is_shared");
2233 UseSharedMemory->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2234 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2235 /*DestWidth=*/16, /*Signed=*/0);
2236 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2237 Address(UseSharedMemory,
2238 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2239 /*Volatile=*/false, Int16Ty, Loc);
2240 auto *StaticGlobalized = new llvm::GlobalVariable(
2241 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002242 llvm::GlobalValue::CommonLinkage, nullptr);
Alexey Bataeve4090182018-11-02 14:54:07 +00002243 auto *RecSize = new llvm::GlobalVariable(
2244 CGM.getModule(), CGM.SizeTy, /*isConstant=*/true,
2245 llvm::GlobalValue::InternalLinkage, nullptr,
2246 "_openmp_static_kernel$size");
2247 RecSize->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2248 llvm::Value *Ld = CGF.EmitLoadOfScalar(
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002249 Address(RecSize, CGM.getSizeAlign()), /*Volatile=*/false,
Alexey Bataeve4090182018-11-02 14:54:07 +00002250 CGM.getContext().getSizeType(), Loc);
2251 llvm::Value *ResAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2252 KernelStaticGlobalized, CGM.VoidPtrPtrTy);
Alexey Bataev8e009032019-01-04 17:25:09 +00002253 llvm::Value *GlobalRecordSizeArg[] = {
2254 llvm::ConstantInt::get(
2255 CGM.Int16Ty,
2256 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD ? 1 : 0),
2257 StaticGlobalized, Ld, IsInSharedMemory, ResAddr};
Alexey Bataeve4090182018-11-02 14:54:07 +00002258 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2259 OMPRTL_NVPTX__kmpc_get_team_static_memory),
2260 GlobalRecordSizeArg);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002261 GlobalizedRecords.back().Buffer = StaticGlobalized;
Alexey Bataeve4090182018-11-02 14:54:07 +00002262 GlobalizedRecords.back().RecSize = RecSize;
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002263 GlobalizedRecords.back().UseSharedMemory = UseSharedMemory;
2264 GlobalizedRecords.back().Loc = Loc;
Alexey Bataeve4090182018-11-02 14:54:07 +00002265 }
2266 assert(KernelStaticGlobalized && "Global address must be set already.");
2267 Address FrameAddr = CGF.EmitLoadOfPointer(
2268 Address(KernelStaticGlobalized, CGM.getPointerAlign()),
2269 CGM.getContext()
2270 .getPointerType(CGM.getContext().VoidPtrTy)
2271 .castAs<PointerType>());
2272 llvm::Value *GlobalRecValue =
James Y Knight751fe282019-02-09 22:22:28 +00002273 Bld.CreateConstInBoundsGEP(FrameAddr, Offset).getPointer();
Alexey Bataeve4090182018-11-02 14:54:07 +00002274 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2275 I->getSecond().IsInSPMDModeFlag = nullptr;
2276 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2277 GlobalRecValue, CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo());
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002278 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002279 // TODO: allow the usage of shared memory to be controlled by
2280 // the user, for now, default to global.
2281 llvm::Value *GlobalRecordSizeArg[] = {
2282 llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize),
2283 CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002284 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2285 createNVPTXRuntimeFunction(
2286 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2287 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002288 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002289 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002290 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2291 I->getSecond().IsInSPMDModeFlag = nullptr;
2292 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002293 LValue Base =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002294 CGF.MakeNaturalAlignPointeeAddrLValue(GlobalRecCastAddr, GlobalRecTy);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002295
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002296 // Emit the "global alloca" which is a GEP from the global declaration
2297 // record using the pointer returned by the runtime.
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002298 LValue SecBase;
2299 decltype(I->getSecond().LocalVarData)::const_iterator SecIt;
2300 if (IsTTD) {
2301 SecIt = I->getSecond().SecondaryLocalVarData->begin();
2302 llvm::PointerType *SecGlobalRecPtrTy =
2303 CGF.ConvertTypeForMem(SecGlobalRecTy)->getPointerTo();
2304 SecBase = CGF.MakeNaturalAlignPointeeAddrLValue(
2305 Bld.CreatePointerBitCastOrAddrSpaceCast(
2306 I->getSecond().GlobalRecordAddr, SecGlobalRecPtrTy),
2307 SecGlobalRecTy);
2308 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002309 for (auto &Rec : I->getSecond().LocalVarData) {
2310 bool EscapedParam = I->getSecond().EscapedParameters.count(Rec.first);
2311 llvm::Value *ParValue;
2312 if (EscapedParam) {
2313 const auto *VD = cast<VarDecl>(Rec.first);
2314 LValue ParLVal =
2315 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
2316 ParValue = CGF.EmitLoadOfScalar(ParLVal, Loc);
2317 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002318 LValue VarAddr = CGF.EmitLValueForField(Base, Rec.second.FD);
2319 // Emit VarAddr basing on lane-id if required.
2320 QualType VarTy;
2321 if (Rec.second.IsOnePerTeam) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002322 VarTy = Rec.second.FD->getType();
2323 } else {
2324 llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(
2325 VarAddr.getAddress().getPointer(),
2326 {Bld.getInt32(0), getNVPTXLaneID(CGF)});
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002327 VarTy =
2328 Rec.second.FD->getType()->castAsArrayTypeUnsafe()->getElementType();
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002329 VarAddr = CGF.MakeAddrLValue(
2330 Address(Ptr, CGM.getContext().getDeclAlign(Rec.first)), VarTy,
2331 AlignmentSource::Decl);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002332 }
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002333 Rec.second.PrivateAddr = VarAddr.getAddress();
Alexey Bataeve4090182018-11-02 14:54:07 +00002334 if (!IsInTTDRegion &&
2335 (WithSPMDCheck ||
2336 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002337 assert(I->getSecond().IsInSPMDModeFlag &&
2338 "Expected unknown execution mode or required SPMD check.");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002339 if (IsTTD) {
2340 assert(SecIt->second.IsOnePerTeam &&
2341 "Secondary glob data must be one per team.");
2342 LValue SecVarAddr = CGF.EmitLValueForField(SecBase, SecIt->second.FD);
2343 VarAddr.setAddress(
2344 Address(Bld.CreateSelect(IsTTD, SecVarAddr.getPointer(),
2345 VarAddr.getPointer()),
2346 VarAddr.getAlignment()));
2347 Rec.second.PrivateAddr = VarAddr.getAddress();
2348 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002349 Address GlobalPtr = Rec.second.PrivateAddr;
2350 Address LocalAddr = CGF.CreateMemTemp(VarTy, Rec.second.FD->getName());
2351 Rec.second.PrivateAddr = Address(
2352 Bld.CreateSelect(I->getSecond().IsInSPMDModeFlag,
2353 LocalAddr.getPointer(), GlobalPtr.getPointer()),
2354 LocalAddr.getAlignment());
2355 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002356 if (EscapedParam) {
2357 const auto *VD = cast<VarDecl>(Rec.first);
2358 CGF.EmitStoreOfScalar(ParValue, VarAddr);
2359 I->getSecond().MappedParams->setVarAddr(CGF, VD, VarAddr.getAddress());
2360 }
Alexey Bataev93a38d62018-10-16 00:09:06 +00002361 if (IsTTD)
2362 ++SecIt;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002363 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002364 }
2365 for (const ValueDecl *VD : I->getSecond().EscapedVariableLengthDecls) {
2366 // Recover pointer to this function's global record. The runtime will
2367 // handle the specifics of the allocation of the memory.
2368 // Use actual memory size of the record including the padding
2369 // for alignment purposes.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002370 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002371 llvm::Value *Size = CGF.getTypeSize(VD->getType());
2372 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2373 Size = Bld.CreateNUWAdd(
2374 Size, llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity() - 1));
2375 llvm::Value *AlignVal =
2376 llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity());
2377 Size = Bld.CreateUDiv(Size, AlignVal);
2378 Size = Bld.CreateNUWMul(Size, AlignVal);
2379 // TODO: allow the usage of shared memory to be controlled by
2380 // the user, for now, default to global.
2381 llvm::Value *GlobalRecordSizeArg[] = {
2382 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
2383 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002384 createNVPTXRuntimeFunction(
2385 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002386 GlobalRecordSizeArg);
2387 llvm::Value *GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2388 GlobalRecValue, CGF.ConvertTypeForMem(VD->getType())->getPointerTo());
2389 LValue Base = CGF.MakeAddrLValue(GlobalRecCastAddr, VD->getType(),
2390 CGM.getContext().getDeclAlign(VD),
2391 AlignmentSource::Decl);
2392 I->getSecond().MappedParams->setVarAddr(CGF, cast<VarDecl>(VD),
2393 Base.getAddress());
2394 I->getSecond().EscapedVariableLengthDeclsAddrs.emplace_back(GlobalRecValue);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002395 }
2396 I->getSecond().MappedParams->apply(CGF);
2397}
2398
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002399void CGOpenMPRuntimeNVPTX::emitGenericVarsEpilog(CodeGenFunction &CGF,
2400 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002401 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2402 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002403 return;
2404
Alexey Bataevc99042b2018-03-15 18:10:54 +00002405 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002406 if (I != FunctionGlobalizedDecls.end()) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00002407 I->getSecond().MappedParams->restore(CGF);
2408 if (!CGF.HaveInsertPoint())
2409 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002410 for (llvm::Value *Addr :
2411 llvm::reverse(I->getSecond().EscapedVariableLengthDeclsAddrs)) {
2412 CGF.EmitRuntimeCall(
2413 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2414 Addr);
2415 }
2416 if (I->getSecond().GlobalRecordAddr) {
Alexey Bataeve4090182018-11-02 14:54:07 +00002417 if (!IsInTTDRegion &&
2418 (WithSPMDCheck ||
2419 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002420 CGBuilderTy &Bld = CGF.Builder;
2421 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2422 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
2423 Bld.CreateCondBr(I->getSecond().IsInSPMDModeFlag, ExitBB, NonSPMDBB);
2424 // There is no need to emit line number for unconditional branch.
2425 (void)ApplyDebugLocation::CreateEmpty(CGF);
2426 CGF.EmitBlock(NonSPMDBB);
2427 CGF.EmitRuntimeCall(
2428 createNVPTXRuntimeFunction(
2429 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2430 CGF.EmitCastToVoidPtr(I->getSecond().GlobalRecordAddr));
2431 CGF.EmitBlock(ExitBB);
Alexey Bataeve4090182018-11-02 14:54:07 +00002432 } else if (IsInTTDRegion) {
2433 assert(GlobalizedRecords.back().RegionCounter > 0 &&
2434 "region counter must be > 0.");
2435 --GlobalizedRecords.back().RegionCounter;
2436 // Emit the restore function only in the target region.
2437 if (GlobalizedRecords.back().RegionCounter == 0) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002438 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2439 /*DestWidth=*/16, /*Signed=*/0);
2440 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2441 Address(GlobalizedRecords.back().UseSharedMemory,
2442 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2443 /*Volatile=*/false, Int16Ty, GlobalizedRecords.back().Loc);
Alexey Bataev8e009032019-01-04 17:25:09 +00002444 llvm::Value *Args[] = {
2445 llvm::ConstantInt::get(
2446 CGM.Int16Ty,
2447 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD ? 1 : 0),
2448 IsInSharedMemory};
Alexey Bataeve4090182018-11-02 14:54:07 +00002449 CGF.EmitRuntimeCall(
2450 createNVPTXRuntimeFunction(
2451 OMPRTL_NVPTX__kmpc_restore_team_static_memory),
Alexey Bataev8e009032019-01-04 17:25:09 +00002452 Args);
Alexey Bataeve4090182018-11-02 14:54:07 +00002453 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002454 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002455 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2456 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2457 I->getSecond().GlobalRecordAddr);
2458 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002459 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00002460 }
2461}
2462
Carlo Bertollic6872252016-04-04 15:55:02 +00002463void CGOpenMPRuntimeNVPTX::emitTeamsCall(CodeGenFunction &CGF,
2464 const OMPExecutableDirective &D,
2465 SourceLocation Loc,
James Y Knight9871db02019-02-05 16:42:33 +00002466 llvm::Function *OutlinedFn,
Carlo Bertollic6872252016-04-04 15:55:02 +00002467 ArrayRef<llvm::Value *> CapturedVars) {
2468 if (!CGF.HaveInsertPoint())
2469 return;
2470
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002471 Address ZeroAddr = CGF.CreateMemTemp(
2472 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2473 /*Name*/ ".zero.addr");
Carlo Bertollic6872252016-04-04 15:55:02 +00002474 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2475 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002476 OutlinedFnArgs.push_back(emitThreadIDAddress(CGF, Loc).getPointer());
Carlo Bertollic6872252016-04-04 15:55:02 +00002477 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2478 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002479 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Carlo Bertollic6872252016-04-04 15:55:02 +00002480}
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002481
2482void CGOpenMPRuntimeNVPTX::emitParallelCall(
James Y Knight9871db02019-02-05 16:42:33 +00002483 CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002484 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2485 if (!CGF.HaveInsertPoint())
2486 return;
2487
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002488 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002489 emitSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002490 else
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002491 emitNonSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002492}
2493
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002494void CGOpenMPRuntimeNVPTX::emitNonSPMDParallelCall(
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002495 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2496 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2497 llvm::Function *Fn = cast<llvm::Function>(OutlinedFn);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002498
2499 // Force inline this outlined function at its call site.
2500 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
2501
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002502 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2503 /*DestWidth=*/32, /*Signed=*/1),
2504 ".zero.addr");
2505 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002506 // ThreadId for serialized parallels is 0.
2507 Address ThreadIDAddr = ZeroAddr;
2508 auto &&CodeGen = [this, Fn, CapturedVars, Loc, ZeroAddr, &ThreadIDAddr](
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002509 CodeGenFunction &CGF, PrePostActionTy &Action) {
2510 Action.Enter(CGF);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002511
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002512 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2513 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2514 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2515 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2516 emitOutlinedFunctionCall(CGF, Loc, Fn, OutlinedFnArgs);
2517 };
2518 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2519 PrePostActionTy &) {
2520
2521 RegionCodeGenTy RCG(CodeGen);
2522 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2523 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2524 llvm::Value *Args[] = {RTLoc, ThreadID};
2525
2526 NVPTXActionTy Action(
2527 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2528 Args,
2529 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2530 Args);
2531 RCG.setAction(Action);
2532 RCG(CGF);
2533 };
2534
2535 auto &&L0ParallelGen = [this, CapturedVars, Fn](CodeGenFunction &CGF,
2536 PrePostActionTy &Action) {
2537 CGBuilderTy &Bld = CGF.Builder;
2538 llvm::Function *WFn = WrapperFunctionsMap[Fn];
2539 assert(WFn && "Wrapper function does not exist!");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002540 llvm::Value *ID = Bld.CreateBitOrPointerCast(WFn, CGM.Int8PtrTy);
2541
2542 // Prepare for parallel region. Indicate the outlined function.
2543 llvm::Value *Args[] = {ID, /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002544 CGF.EmitRuntimeCall(
2545 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_prepare_parallel),
2546 Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002547
2548 // Create a private scope that will globalize the arguments
2549 // passed from the outside of the target region.
2550 CodeGenFunction::OMPPrivateScope PrivateArgScope(CGF);
2551
Raphael Isemannb23ccec2018-12-10 12:37:46 +00002552 // There's something to share.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002553 if (!CapturedVars.empty()) {
2554 // Prepare for parallel region. Indicate the outlined function.
2555 Address SharedArgs =
2556 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "shared_arg_refs");
2557 llvm::Value *SharedArgsPtr = SharedArgs.getPointer();
2558
2559 llvm::Value *DataSharingArgs[] = {
2560 SharedArgsPtr,
2561 llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size())};
2562 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2563 OMPRTL_NVPTX__kmpc_begin_sharing_variables),
2564 DataSharingArgs);
2565
2566 // Store variable address in a list of references to pass to workers.
2567 unsigned Idx = 0;
2568 ASTContext &Ctx = CGF.getContext();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002569 Address SharedArgListAddress = CGF.EmitLoadOfPointer(
2570 SharedArgs, Ctx.getPointerType(Ctx.getPointerType(Ctx.VoidPtrTy))
2571 .castAs<PointerType>());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002572 for (llvm::Value *V : CapturedVars) {
James Y Knight751fe282019-02-09 22:22:28 +00002573 Address Dst = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002574 llvm::Value *PtrV;
Alexey Bataev17314212018-03-20 15:41:05 +00002575 if (V->getType()->isIntegerTy())
2576 PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
2577 else
2578 PtrV = Bld.CreatePointerBitCastOrAddrSpaceCast(V, CGF.VoidPtrTy);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002579 CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
2580 Ctx.getPointerType(Ctx.VoidPtrTy));
Alexey Bataevc99042b2018-03-15 18:10:54 +00002581 ++Idx;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002582 }
2583 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002584
2585 // Activate workers. This barrier is used by the master to signal
2586 // work for the workers.
2587 syncCTAThreads(CGF);
2588
2589 // OpenMP [2.5, Parallel Construct, p.49]
2590 // There is an implied barrier at the end of a parallel region. After the
2591 // end of a parallel region, only the master thread of the team resumes
2592 // execution of the enclosing task region.
2593 //
2594 // The master waits at this barrier until all workers are done.
2595 syncCTAThreads(CGF);
2596
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002597 if (!CapturedVars.empty())
2598 CGF.EmitRuntimeCall(
2599 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_sharing_variables));
2600
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002601 // Remember for post-processing in worker loop.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002602 Work.emplace_back(WFn);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002603 };
2604
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002605 auto &&LNParallelGen = [this, Loc, &SeqGen, &L0ParallelGen](
2606 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002607 if (IsInParallelRegion) {
2608 SeqGen(CGF, Action);
2609 } else if (IsInTargetMasterThreadRegion) {
2610 L0ParallelGen(CGF, Action);
2611 } else {
2612 // Check for master and then parallelism:
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002613 // if (__kmpc_is_spmd_exec_mode() || __kmpc_parallel_level(loc, gtid)) {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002614 // Serialized execution.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002615 // } else {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002616 // Worker call.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002617 // }
2618 CGBuilderTy &Bld = CGF.Builder;
2619 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002620 llvm::BasicBlock *SeqBB = CGF.createBasicBlock(".sequential");
2621 llvm::BasicBlock *ParallelCheckBB = CGF.createBasicBlock(".parcheck");
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002622 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
Alexey Bataev673110d2018-05-16 13:36:30 +00002623 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2624 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002625 Bld.CreateCondBr(IsSPMD, SeqBB, ParallelCheckBB);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002626 // There is no need to emit line number for unconditional branch.
2627 (void)ApplyDebugLocation::CreateEmpty(CGF);
2628 CGF.EmitBlock(ParallelCheckBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002629 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2630 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2631 llvm::Value *PL = CGF.EmitRuntimeCall(
2632 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2633 {RTLoc, ThreadID});
2634 llvm::Value *Res = Bld.CreateIsNotNull(PL);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002635 Bld.CreateCondBr(Res, SeqBB, MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002636 CGF.EmitBlock(SeqBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002637 SeqGen(CGF, Action);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002638 CGF.EmitBranch(ExitBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002639 // There is no need to emit line number for unconditional branch.
2640 (void)ApplyDebugLocation::CreateEmpty(CGF);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002641 CGF.EmitBlock(MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002642 L0ParallelGen(CGF, Action);
2643 CGF.EmitBranch(ExitBB);
2644 // There is no need to emit line number for unconditional branch.
2645 (void)ApplyDebugLocation::CreateEmpty(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002646 // Emit the continuation block for code after the if.
2647 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2648 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002649 };
2650
Alexey Bataev9ff80832018-04-16 20:16:21 +00002651 if (IfCond) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002652 emitOMPIfClause(CGF, IfCond, LNParallelGen, SeqGen);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002653 } else {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002654 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002655 RegionCodeGenTy ThenRCG(LNParallelGen);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002656 ThenRCG(CGF);
2657 }
2658}
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002659
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002660void CGOpenMPRuntimeNVPTX::emitSPMDParallelCall(
James Y Knight9871db02019-02-05 16:42:33 +00002661 CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002662 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2663 // Just call the outlined function to execute the parallel region.
2664 // OutlinedFn(&GTid, &zero, CapturedStruct);
2665 //
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002666 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Carlo Bertolli79712092018-02-28 20:48:35 +00002667
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002668 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2669 /*DestWidth=*/32, /*Signed=*/1),
2670 ".zero.addr");
Carlo Bertolli79712092018-02-28 20:48:35 +00002671 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002672 // ThreadId for serialized parallels is 0.
2673 Address ThreadIDAddr = ZeroAddr;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002674 auto &&CodeGen = [this, OutlinedFn, CapturedVars, Loc, ZeroAddr,
Alexey Bataev8521ff62018-07-25 20:03:01 +00002675 &ThreadIDAddr](CodeGenFunction &CGF,
2676 PrePostActionTy &Action) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002677 Action.Enter(CGF);
2678
2679 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2680 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2681 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2682 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2683 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2684 };
2685 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2686 PrePostActionTy &) {
2687
2688 RegionCodeGenTy RCG(CodeGen);
2689 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2690 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2691 llvm::Value *Args[] = {RTLoc, ThreadID};
2692
2693 NVPTXActionTy Action(
2694 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2695 Args,
2696 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2697 Args);
2698 RCG.setAction(Action);
2699 RCG(CGF);
2700 };
2701
2702 if (IsInTargetMasterThreadRegion) {
Alexey Bataev8521ff62018-07-25 20:03:01 +00002703 // In the worker need to use the real thread id.
2704 ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002705 RegionCodeGenTy RCG(CodeGen);
2706 RCG(CGF);
2707 } else {
2708 // If we are not in the target region, it is definitely L2 parallelism or
2709 // more, because for SPMD mode we always has L1 parallel level, sowe don't
2710 // need to check for orphaned directives.
2711 RegionCodeGenTy RCG(SeqGen);
2712 RCG(CGF);
2713 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002714}
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002715
Alexey Bataeva3924b52019-01-03 16:25:35 +00002716void CGOpenMPRuntimeNVPTX::syncCTAThreads(CodeGenFunction &CGF) {
2717 // Always emit simple barriers!
2718 if (!CGF.HaveInsertPoint())
2719 return;
2720 // Build call __kmpc_barrier_simple_spmd(nullptr, 0);
2721 // This function does not use parameters, so we can emit just default values.
2722 llvm::Value *Args[] = {
2723 llvm::ConstantPointerNull::get(
2724 cast<llvm::PointerType>(getIdentTyPointerTy())),
2725 llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/0, /*isSigned=*/true)};
2726 CGF.EmitRuntimeCall(
2727 createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier_simple_spmd), Args);
2728}
2729
Alexey Bataevc3028ca2018-12-04 15:03:25 +00002730void CGOpenMPRuntimeNVPTX::emitBarrierCall(CodeGenFunction &CGF,
2731 SourceLocation Loc,
2732 OpenMPDirectiveKind Kind, bool,
2733 bool) {
2734 // Always emit simple barriers!
2735 if (!CGF.HaveInsertPoint())
2736 return;
2737 // Build call __kmpc_cancel_barrier(loc, thread_id);
2738 unsigned Flags = getDefaultFlagsForBarriers(Kind);
2739 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2740 getThreadID(CGF, Loc)};
2741 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier), Args);
2742}
2743
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002744void CGOpenMPRuntimeNVPTX::emitCriticalRegion(
2745 CodeGenFunction &CGF, StringRef CriticalName,
2746 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
2747 const Expr *Hint) {
2748 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
2749 llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
2750 llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
2751 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
2752 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
2753
2754 // Fetch team-local id of the thread.
2755 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
2756
2757 // Get the width of the team.
2758 llvm::Value *TeamWidth = getNVPTXNumThreads(CGF);
2759
2760 // Initialize the counter variable for the loop.
2761 QualType Int32Ty =
2762 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
2763 Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
2764 LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
2765 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
2766 /*isInit=*/true);
2767
2768 // Block checks if loop counter exceeds upper bound.
2769 CGF.EmitBlock(LoopBB);
2770 llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2771 llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
2772 CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
2773
2774 // Block tests which single thread should execute region, and which threads
2775 // should go straight to synchronisation point.
2776 CGF.EmitBlock(TestBB);
2777 CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2778 llvm::Value *CmpThreadToCounter =
2779 CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
2780 CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
2781
2782 // Block emits the body of the critical region.
2783 CGF.EmitBlock(BodyBB);
2784
2785 // Output the critical statement.
Alexey Bataev2c1ff9d2018-12-04 15:25:01 +00002786 CGOpenMPRuntime::emitCriticalRegion(CGF, CriticalName, CriticalOpGen, Loc,
2787 Hint);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002788
2789 // After the body surrounded by the critical region, the single executing
2790 // thread will jump to the synchronisation point.
2791 // Block waits for all threads in current team to finish then increments the
2792 // counter variable and returns to the loop.
2793 CGF.EmitBlock(SyncBB);
Alexey Bataev2c1ff9d2018-12-04 15:25:01 +00002794 emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false,
2795 /*ForceSimpleCall=*/true);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002796
2797 llvm::Value *IncCounterVal =
2798 CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
2799 CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
2800 CGF.EmitBranch(LoopBB);
2801
2802 // Block that is reached when all threads in the team complete the region.
2803 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2804}
2805
Alexey Bataevb2575932018-01-04 20:18:55 +00002806/// Cast value to the specified type.
Alexey Bataeva453f362018-03-19 17:53:56 +00002807static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
2808 QualType ValTy, QualType CastTy,
2809 SourceLocation Loc) {
2810 assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
2811 "Cast type must sized.");
2812 assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
2813 "Val type must sized.");
2814 llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
2815 if (ValTy == CastTy)
Alexey Bataevb2575932018-01-04 20:18:55 +00002816 return Val;
Alexey Bataeva453f362018-03-19 17:53:56 +00002817 if (CGF.getContext().getTypeSizeInChars(ValTy) ==
2818 CGF.getContext().getTypeSizeInChars(CastTy))
2819 return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
2820 if (CastTy->isIntegerType() && ValTy->isIntegerType())
2821 return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
2822 CastTy->hasSignedIntegerRepresentation());
2823 Address CastItem = CGF.CreateMemTemp(CastTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002824 Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2825 CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
Alexey Bataeva453f362018-03-19 17:53:56 +00002826 CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy);
2827 return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc);
Alexey Bataevb2575932018-01-04 20:18:55 +00002828}
2829
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002830/// This function creates calls to one of two shuffle functions to copy
2831/// variables between lanes in a warp.
2832static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002833 llvm::Value *Elem,
Alexey Bataeva453f362018-03-19 17:53:56 +00002834 QualType ElemType,
2835 llvm::Value *Offset,
2836 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002837 CodeGenModule &CGM = CGF.CGM;
2838 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002839 CGOpenMPRuntimeNVPTX &RT =
2840 *(static_cast<CGOpenMPRuntimeNVPTX *>(&CGM.getOpenMPRuntime()));
2841
Alexey Bataeva453f362018-03-19 17:53:56 +00002842 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2843 assert(Size.getQuantity() <= 8 &&
2844 "Unsupported bitwidth in shuffle instruction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002845
Alexey Bataeva453f362018-03-19 17:53:56 +00002846 OpenMPRTLFunctionNVPTX ShuffleFn = Size.getQuantity() <= 4
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002847 ? OMPRTL_NVPTX__kmpc_shuffle_int32
2848 : OMPRTL_NVPTX__kmpc_shuffle_int64;
2849
2850 // Cast all types to 32- or 64-bit values before calling shuffle routines.
Alexey Bataeva453f362018-03-19 17:53:56 +00002851 QualType CastTy = CGF.getContext().getIntTypeForBitwidth(
2852 Size.getQuantity() <= 4 ? 32 : 64, /*Signed=*/1);
2853 llvm::Value *ElemCast = castValueToType(CGF, Elem, ElemType, CastTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002854 llvm::Value *WarpSize =
Alexey Bataevb2575932018-01-04 20:18:55 +00002855 Bld.CreateIntCast(getNVPTXWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002856
Alexey Bataev9ff80832018-04-16 20:16:21 +00002857 llvm::Value *ShuffledVal = CGF.EmitRuntimeCall(
2858 RT.createNVPTXRuntimeFunction(ShuffleFn), {ElemCast, Offset, WarpSize});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002859
Alexey Bataeva453f362018-03-19 17:53:56 +00002860 return castValueToType(CGF, ShuffledVal, CastTy, ElemType, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002861}
2862
Alexey Bataev12c62902018-06-22 19:10:38 +00002863static void shuffleAndStore(CodeGenFunction &CGF, Address SrcAddr,
2864 Address DestAddr, QualType ElemType,
2865 llvm::Value *Offset, SourceLocation Loc) {
2866 CGBuilderTy &Bld = CGF.Builder;
2867
2868 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2869 // Create the loop over the big sized data.
2870 // ptr = (void*)Elem;
2871 // ptrEnd = (void*) Elem + 1;
2872 // Step = 8;
2873 // while (ptr + Step < ptrEnd)
2874 // shuffle((int64_t)*ptr);
2875 // Step = 4;
2876 // while (ptr + Step < ptrEnd)
2877 // shuffle((int32_t)*ptr);
2878 // ...
2879 Address ElemPtr = DestAddr;
2880 Address Ptr = SrcAddr;
2881 Address PtrEnd = Bld.CreatePointerBitCastOrAddrSpaceCast(
James Y Knight751fe282019-02-09 22:22:28 +00002882 Bld.CreateConstGEP(SrcAddr, 1), CGF.VoidPtrTy);
Alexey Bataev12c62902018-06-22 19:10:38 +00002883 for (int IntSize = 8; IntSize >= 1; IntSize /= 2) {
2884 if (Size < CharUnits::fromQuantity(IntSize))
2885 continue;
2886 QualType IntType = CGF.getContext().getIntTypeForBitwidth(
2887 CGF.getContext().toBits(CharUnits::fromQuantity(IntSize)),
2888 /*Signed=*/1);
2889 llvm::Type *IntTy = CGF.ConvertTypeForMem(IntType);
2890 Ptr = Bld.CreatePointerBitCastOrAddrSpaceCast(Ptr, IntTy->getPointerTo());
2891 ElemPtr =
2892 Bld.CreatePointerBitCastOrAddrSpaceCast(ElemPtr, IntTy->getPointerTo());
2893 if (Size.getQuantity() / IntSize > 1) {
2894 llvm::BasicBlock *PreCondBB = CGF.createBasicBlock(".shuffle.pre_cond");
2895 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".shuffle.then");
2896 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".shuffle.exit");
2897 llvm::BasicBlock *CurrentBB = Bld.GetInsertBlock();
2898 CGF.EmitBlock(PreCondBB);
2899 llvm::PHINode *PhiSrc =
2900 Bld.CreatePHI(Ptr.getType(), /*NumReservedValues=*/2);
2901 PhiSrc->addIncoming(Ptr.getPointer(), CurrentBB);
2902 llvm::PHINode *PhiDest =
2903 Bld.CreatePHI(ElemPtr.getType(), /*NumReservedValues=*/2);
2904 PhiDest->addIncoming(ElemPtr.getPointer(), CurrentBB);
2905 Ptr = Address(PhiSrc, Ptr.getAlignment());
2906 ElemPtr = Address(PhiDest, ElemPtr.getAlignment());
2907 llvm::Value *PtrDiff = Bld.CreatePtrDiff(
2908 PtrEnd.getPointer(), Bld.CreatePointerBitCastOrAddrSpaceCast(
2909 Ptr.getPointer(), CGF.VoidPtrTy));
2910 Bld.CreateCondBr(Bld.CreateICmpSGT(PtrDiff, Bld.getInt64(IntSize - 1)),
2911 ThenBB, ExitBB);
2912 CGF.EmitBlock(ThenBB);
2913 llvm::Value *Res = createRuntimeShuffleFunction(
2914 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2915 IntType, Offset, Loc);
2916 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
James Y Knight751fe282019-02-09 22:22:28 +00002917 Address LocalPtr = Bld.CreateConstGEP(Ptr, 1);
2918 Address LocalElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002919 PhiSrc->addIncoming(LocalPtr.getPointer(), ThenBB);
2920 PhiDest->addIncoming(LocalElemPtr.getPointer(), ThenBB);
Alexey Bataev12c62902018-06-22 19:10:38 +00002921 CGF.EmitBranch(PreCondBB);
2922 CGF.EmitBlock(ExitBB);
2923 } else {
2924 llvm::Value *Res = createRuntimeShuffleFunction(
2925 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2926 IntType, Offset, Loc);
2927 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
James Y Knight751fe282019-02-09 22:22:28 +00002928 Ptr = Bld.CreateConstGEP(Ptr, 1);
2929 ElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
Alexey Bataev12c62902018-06-22 19:10:38 +00002930 }
2931 Size = Size % IntSize;
2932 }
2933}
2934
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002935namespace {
2936enum CopyAction : unsigned {
2937 // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
2938 // the warp using shuffle instructions.
2939 RemoteLaneToThread,
2940 // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
2941 ThreadCopy,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002942 // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
2943 ThreadToScratchpad,
2944 // ScratchpadToThread: Copy from a scratchpad array in global memory
2945 // containing team-reduced data to a thread's stack.
2946 ScratchpadToThread,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002947};
2948} // namespace
2949
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002950struct CopyOptionsTy {
2951 llvm::Value *RemoteLaneOffset;
2952 llvm::Value *ScratchpadIndex;
2953 llvm::Value *ScratchpadWidth;
2954};
2955
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002956/// Emit instructions to copy a Reduce list, which contains partially
2957/// aggregated values, in the specified direction.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002958static void emitReductionListCopy(
2959 CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
2960 ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
2961 CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002962
Alexey Bataev9ff80832018-04-16 20:16:21 +00002963 CodeGenModule &CGM = CGF.CGM;
2964 ASTContext &C = CGM.getContext();
2965 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002966
Alexey Bataev9ff80832018-04-16 20:16:21 +00002967 llvm::Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
2968 llvm::Value *ScratchpadIndex = CopyOptions.ScratchpadIndex;
2969 llvm::Value *ScratchpadWidth = CopyOptions.ScratchpadWidth;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002970
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002971 // Iterates, element-by-element, through the source Reduce list and
2972 // make a copy.
2973 unsigned Idx = 0;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002974 unsigned Size = Privates.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00002975 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002976 Address SrcElementAddr = Address::invalid();
2977 Address DestElementAddr = Address::invalid();
2978 Address DestElementPtrAddr = Address::invalid();
2979 // Should we shuffle in an element from a remote lane?
2980 bool ShuffleInElement = false;
2981 // Set to true to update the pointer in the dest Reduce list to a
2982 // newly created element.
2983 bool UpdateDestListPtr = false;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002984 // Increment the src or dest pointer to the scratchpad, for each
2985 // new element.
2986 bool IncrScratchpadSrc = false;
2987 bool IncrScratchpadDest = false;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002988
2989 switch (Action) {
2990 case RemoteLaneToThread: {
2991 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002992 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00002993 SrcElementAddr = CGF.EmitLoadOfPointer(
2994 SrcElementPtrAddr,
2995 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002996
2997 // Step 1.2: Create a temporary to store the element in the destination
2998 // Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002999 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003000 DestElementAddr =
3001 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
3002 ShuffleInElement = true;
3003 UpdateDestListPtr = true;
3004 break;
3005 }
3006 case ThreadCopy: {
3007 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00003008 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00003009 SrcElementAddr = CGF.EmitLoadOfPointer(
3010 SrcElementPtrAddr,
3011 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003012
3013 // Step 1.2: Get the address for dest element. The destination
3014 // element has already been created on the thread's stack.
James Y Knight751fe282019-02-09 22:22:28 +00003015 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00003016 DestElementAddr = CGF.EmitLoadOfPointer(
3017 DestElementPtrAddr,
3018 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003019 break;
3020 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003021 case ThreadToScratchpad: {
3022 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00003023 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00003024 SrcElementAddr = CGF.EmitLoadOfPointer(
3025 SrcElementPtrAddr,
3026 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003027
3028 // Step 1.2: Get the address for dest element:
3029 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00003030 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00003031 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003032 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003033 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003034 Bld.CreateNUWAdd(DestBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003035 ScratchPadElemAbsolutePtrVal =
3036 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00003037 DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
3038 C.getTypeAlignInChars(Private->getType()));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003039 IncrScratchpadDest = true;
3040 break;
3041 }
3042 case ScratchpadToThread: {
3043 // Step 1.1: Get the address for the src element in the scratchpad.
3044 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00003045 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00003046 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003047 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003048 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003049 Bld.CreateNUWAdd(SrcBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003050 ScratchPadElemAbsolutePtrVal =
3051 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
3052 SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
3053 C.getTypeAlignInChars(Private->getType()));
3054 IncrScratchpadSrc = true;
3055
3056 // Step 1.2: Create a temporary to store the element in the destination
3057 // Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00003058 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003059 DestElementAddr =
3060 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
3061 UpdateDestListPtr = true;
3062 break;
3063 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003064 }
3065
3066 // Regardless of src and dest of copy, we emit the load of src
3067 // element as this is required in all directions
3068 SrcElementAddr = Bld.CreateElementBitCast(
3069 SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
Alexey Bataev12c62902018-06-22 19:10:38 +00003070 DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
3071 SrcElementAddr.getElementType());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003072
3073 // Now that all active lanes have read the element in the
3074 // Reduce list, shuffle over the value from the remote lane.
Alexey Bataeva453f362018-03-19 17:53:56 +00003075 if (ShuffleInElement) {
Alexey Bataev12c62902018-06-22 19:10:38 +00003076 shuffleAndStore(CGF, SrcElementAddr, DestElementAddr, Private->getType(),
3077 RemoteLaneOffset, Private->getExprLoc());
3078 } else {
Alexey Bataev8061acd2019-02-20 16:36:22 +00003079 switch (CGF.getEvaluationKind(Private->getType())) {
3080 case TEK_Scalar: {
Alexey Bataev12c62902018-06-22 19:10:38 +00003081 llvm::Value *Elem =
3082 CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false,
3083 Private->getType(), Private->getExprLoc());
3084 // Store the source element value to the dest element address.
3085 CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false,
3086 Private->getType());
Alexey Bataev8061acd2019-02-20 16:36:22 +00003087 break;
3088 }
3089 case TEK_Complex: {
3090 CodeGenFunction::ComplexPairTy Elem = CGF.EmitLoadOfComplex(
3091 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3092 Private->getExprLoc());
3093 CGF.EmitStoreOfComplex(
3094 Elem, CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3095 /*isInit=*/false);
3096 break;
3097 }
3098 case TEK_Aggregate:
Alexey Bataev12c62902018-06-22 19:10:38 +00003099 CGF.EmitAggregateCopy(
3100 CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3101 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3102 Private->getType(), AggValueSlot::DoesNotOverlap);
Alexey Bataev8061acd2019-02-20 16:36:22 +00003103 break;
Alexey Bataev12c62902018-06-22 19:10:38 +00003104 }
Alexey Bataeva453f362018-03-19 17:53:56 +00003105 }
Alexey Bataevb2575932018-01-04 20:18:55 +00003106
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003107 // Step 3.1: Modify reference in dest Reduce list as needed.
3108 // Modifying the reference in Reduce list to point to the newly
3109 // created element. The element is live in the current function
3110 // scope and that of functions it invokes (i.e., reduce_function).
3111 // RemoteReduceData[i] = (void*)&RemoteElem
3112 if (UpdateDestListPtr) {
3113 CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
3114 DestElementAddr.getPointer(), CGF.VoidPtrTy),
3115 DestElementPtrAddr, /*Volatile=*/false,
3116 C.VoidPtrTy);
3117 }
3118
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003119 // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
3120 // address of the next element in scratchpad memory, unless we're currently
3121 // processing the last one. Memory alignment is also taken care of here.
3122 if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
3123 llvm::Value *ScratchpadBasePtr =
3124 IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
Alexey Bataeve290ec02018-04-06 16:03:36 +00003125 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
3126 ScratchpadBasePtr = Bld.CreateNUWAdd(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003127 ScratchpadBasePtr,
Alexey Bataeve290ec02018-04-06 16:03:36 +00003128 Bld.CreateNUWMul(ScratchpadWidth, ElementSizeInChars));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003129
3130 // Take care of global memory alignment for performance
Alexey Bataeve290ec02018-04-06 16:03:36 +00003131 ScratchpadBasePtr = Bld.CreateNUWSub(
3132 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3133 ScratchpadBasePtr = Bld.CreateUDiv(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003134 ScratchpadBasePtr,
3135 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
Alexey Bataeve290ec02018-04-06 16:03:36 +00003136 ScratchpadBasePtr = Bld.CreateNUWAdd(
3137 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3138 ScratchpadBasePtr = Bld.CreateNUWMul(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003139 ScratchpadBasePtr,
3140 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
3141
3142 if (IncrScratchpadDest)
3143 DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3144 else /* IncrScratchpadSrc = true */
3145 SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3146 }
3147
Alexey Bataev9ff80832018-04-16 20:16:21 +00003148 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003149 }
3150}
3151
3152/// This function emits a helper that gathers Reduce lists from the first
3153/// lane of every active warp to lanes in the first warp.
3154///
3155/// void inter_warp_copy_func(void* reduce_data, num_warps)
3156/// shared smem[warp_size];
3157/// For all data entries D in reduce_data:
Alexey Bataev29d47fc2018-12-18 19:20:15 +00003158/// sync
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003159/// If (I am the first lane in each warp)
3160/// Copy my local D to smem[warp_id]
3161/// sync
3162/// if (I am the first warp)
3163/// Copy smem[thread_id] to my local D
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003164static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
3165 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003166 QualType ReductionArrayTy,
3167 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003168 ASTContext &C = CGM.getContext();
3169 llvm::Module &M = CGM.getModule();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003170
3171 // ReduceList: thread local Reduce list.
3172 // At the stage of the computation when this function is called, partially
3173 // aggregated values reside in the first lane of every active warp.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003174 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3175 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003176 // NumWarps: number of warps active in the parallel region. This could
3177 // be smaller than 32 (max warps in a CTA) for partial block reduction.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003178 ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00003179 C.getIntTypeForBitwidth(32, /* Signed */ true),
3180 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003181 FunctionArgList Args;
3182 Args.push_back(&ReduceListArg);
3183 Args.push_back(&NumWarpsArg);
3184
Alexey Bataev9ff80832018-04-16 20:16:21 +00003185 const CGFunctionInfo &CGFI =
3186 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev8061acd2019-02-20 16:36:22 +00003187 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
3188 llvm::GlobalValue::InternalLinkage,
3189 "_omp_reduction_inter_warp_copy_func", &M);
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003190 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003191 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003192 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003193 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003194
Alexey Bataev9ff80832018-04-16 20:16:21 +00003195 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003196
3197 // This array is used as a medium to transfer, one reduce element at a time,
3198 // the data from the first lane of every warp to lanes in the first warp
3199 // in order to perform the final step of a reduction in a parallel region
3200 // (reduction across warps). The array is placed in NVPTX __shared__ memory
3201 // for reduced latency, as well as to have a distinct copy for concurrently
3202 // executing target regions. The array is declared with common linkage so
3203 // as to be shared across compilation units.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003204 StringRef TransferMediumName =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003205 "__openmp_nvptx_data_transfer_temporary_storage";
3206 llvm::GlobalVariable *TransferMedium =
3207 M.getGlobalVariable(TransferMediumName);
3208 if (!TransferMedium) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003209 auto *Ty = llvm::ArrayType::get(CGM.Int32Ty, WarpSize);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003210 unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
3211 TransferMedium = new llvm::GlobalVariable(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003212 M, Ty, /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003213 llvm::Constant::getNullValue(Ty), TransferMediumName,
3214 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3215 SharedAddressSpace);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003216 CGM.addCompilerUsedGlobal(TransferMedium);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003217 }
3218
3219 // Get the CUDA thread id of the current OpenMP thread on the GPU.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003220 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003221 // nvptx_lane_id = nvptx_id % warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003222 llvm::Value *LaneID = getNVPTXLaneID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003223 // nvptx_warp_id = nvptx_id / warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003224 llvm::Value *WarpID = getNVPTXWarpID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003225
3226 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3227 Address LocalReduceList(
3228 Bld.CreatePointerBitCastOrAddrSpaceCast(
3229 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003230 C.VoidPtrTy, Loc),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003231 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3232 CGF.getPointerAlign());
3233
3234 unsigned Idx = 0;
Alexey Bataev9ff80832018-04-16 20:16:21 +00003235 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003236 //
3237 // Warp master copies reduce element to transfer medium in __shared__
3238 // memory.
3239 //
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003240 unsigned RealTySize =
3241 C.getTypeSizeInChars(Private->getType())
3242 .alignTo(C.getTypeAlignInChars(Private->getType()))
3243 .getQuantity();
3244 for (unsigned TySize = 4; TySize > 0 && RealTySize > 0; TySize /=2) {
3245 unsigned NumIters = RealTySize / TySize;
3246 if (NumIters == 0)
3247 continue;
3248 QualType CType = C.getIntTypeForBitwidth(
3249 C.toBits(CharUnits::fromQuantity(TySize)), /*Signed=*/1);
3250 llvm::Type *CopyType = CGF.ConvertTypeForMem(CType);
3251 CharUnits Align = CharUnits::fromQuantity(TySize);
3252 llvm::Value *Cnt = nullptr;
3253 Address CntAddr = Address::invalid();
3254 llvm::BasicBlock *PrecondBB = nullptr;
3255 llvm::BasicBlock *ExitBB = nullptr;
3256 if (NumIters > 1) {
3257 CntAddr = CGF.CreateMemTemp(C.IntTy, ".cnt.addr");
3258 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.IntTy), CntAddr,
3259 /*Volatile=*/false, C.IntTy);
3260 PrecondBB = CGF.createBasicBlock("precond");
3261 ExitBB = CGF.createBasicBlock("exit");
3262 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("body");
3263 // There is no need to emit line number for unconditional branch.
3264 (void)ApplyDebugLocation::CreateEmpty(CGF);
3265 CGF.EmitBlock(PrecondBB);
3266 Cnt = CGF.EmitLoadOfScalar(CntAddr, /*Volatile=*/false, C.IntTy, Loc);
3267 llvm::Value *Cmp =
3268 Bld.CreateICmpULT(Cnt, llvm::ConstantInt::get(CGM.IntTy, NumIters));
3269 Bld.CreateCondBr(Cmp, BodyBB, ExitBB);
3270 CGF.EmitBlock(BodyBB);
3271 }
Alexey Bataev29d47fc2018-12-18 19:20:15 +00003272 // kmpc_barrier.
3273 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3274 /*EmitChecks=*/false,
3275 /*ForceSimpleCall=*/true);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003276 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3277 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3278 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003279
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003280 // if (lane_id == 0)
3281 llvm::Value *IsWarpMaster = Bld.CreateIsNull(LaneID, "warp_master");
3282 Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
3283 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003284
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003285 // Reduce element = LocalReduceList[i]
James Y Knight751fe282019-02-09 22:22:28 +00003286 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003287 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3288 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3289 // elemptr = ((CopyType*)(elemptrptr)) + I
3290 Address ElemPtr = Address(ElemPtrPtr, Align);
3291 ElemPtr = Bld.CreateElementBitCast(ElemPtr, CopyType);
3292 if (NumIters > 1) {
3293 ElemPtr = Address(Bld.CreateGEP(ElemPtr.getPointer(), Cnt),
3294 ElemPtr.getAlignment());
3295 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003296
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003297 // Get pointer to location in transfer medium.
3298 // MediumPtr = &medium[warp_id]
3299 llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
3300 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
3301 Address MediumPtr(MediumPtrVal, Align);
3302 // Casting to actual data type.
3303 // MediumPtr = (CopyType*)MediumPtrAddr;
3304 MediumPtr = Bld.CreateElementBitCast(MediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003305
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003306 // elem = *elemptr
3307 //*MediumPtr = elem
3308 llvm::Value *Elem =
3309 CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003310 // Store the source element value to the dest element address.
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003311 CGF.EmitStoreOfScalar(Elem, MediumPtr, /*Volatile=*/true, CType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003312
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003313 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003314
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003315 CGF.EmitBlock(ElseBB);
3316 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003317
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003318 CGF.EmitBlock(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003319
Alexey Bataevae51b962018-12-14 21:00:58 +00003320 // kmpc_barrier.
3321 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3322 /*EmitChecks=*/false,
3323 /*ForceSimpleCall=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003324
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003325 //
3326 // Warp 0 copies reduce element from transfer medium.
3327 //
3328 llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
3329 llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
3330 llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003331
Alexey Bataevae51b962018-12-14 21:00:58 +00003332 Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
3333 llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
3334 AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, Loc);
3335
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003336 // Up to 32 threads in warp 0 are active.
3337 llvm::Value *IsActiveThread =
3338 Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
3339 Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003340
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003341 CGF.EmitBlock(W0ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003342
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003343 // SrcMediumPtr = &medium[tid]
3344 llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
3345 TransferMedium,
3346 {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
3347 Address SrcMediumPtr(SrcMediumPtrVal, Align);
3348 // SrcMediumVal = *SrcMediumPtr;
3349 SrcMediumPtr = Bld.CreateElementBitCast(SrcMediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003350
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003351 // TargetElemPtr = (CopyType*)(SrcDataAddr[i]) + I
James Y Knight751fe282019-02-09 22:22:28 +00003352 Address TargetElemPtrPtr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003353 llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
3354 TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, Loc);
3355 Address TargetElemPtr = Address(TargetElemPtrVal, Align);
3356 TargetElemPtr = Bld.CreateElementBitCast(TargetElemPtr, CopyType);
3357 if (NumIters > 1) {
3358 TargetElemPtr = Address(Bld.CreateGEP(TargetElemPtr.getPointer(), Cnt),
3359 TargetElemPtr.getAlignment());
3360 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003361
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003362 // *TargetElemPtr = SrcMediumVal;
3363 llvm::Value *SrcMediumValue =
3364 CGF.EmitLoadOfScalar(SrcMediumPtr, /*Volatile=*/true, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003365 CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003366 CType);
3367 Bld.CreateBr(W0MergeBB);
3368
3369 CGF.EmitBlock(W0ElseBB);
3370 Bld.CreateBr(W0MergeBB);
3371
3372 CGF.EmitBlock(W0MergeBB);
3373
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003374 if (NumIters > 1) {
3375 Cnt = Bld.CreateNSWAdd(Cnt, llvm::ConstantInt::get(CGM.IntTy, /*V=*/1));
3376 CGF.EmitStoreOfScalar(Cnt, CntAddr, /*Volatile=*/false, C.IntTy);
3377 CGF.EmitBranch(PrecondBB);
3378 (void)ApplyDebugLocation::CreateEmpty(CGF);
3379 CGF.EmitBlock(ExitBB);
3380 }
3381 RealTySize %= TySize;
Alexey Bataev12c62902018-06-22 19:10:38 +00003382 }
Alexey Bataev9ff80832018-04-16 20:16:21 +00003383 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003384 }
3385
3386 CGF.FinishFunction();
3387 return Fn;
3388}
3389
3390/// Emit a helper that reduces data across two OpenMP threads (lanes)
3391/// in the same warp. It uses shuffle instructions to copy over data from
3392/// a remote lane's stack. The reduction algorithm performed is specified
3393/// by the fourth parameter.
3394///
3395/// Algorithm Versions.
3396/// Full Warp Reduce (argument value 0):
3397/// This algorithm assumes that all 32 lanes are active and gathers
3398/// data from these 32 lanes, producing a single resultant value.
3399/// Contiguous Partial Warp Reduce (argument value 1):
3400/// This algorithm assumes that only a *contiguous* subset of lanes
3401/// are active. This happens for the last warp in a parallel region
3402/// when the user specified num_threads is not an integer multiple of
3403/// 32. This contiguous subset always starts with the zeroth lane.
3404/// Partial Warp Reduce (argument value 2):
3405/// This algorithm gathers data from any number of lanes at any position.
3406/// All reduced values are stored in the lowest possible lane. The set
3407/// of problems every algorithm addresses is a super set of those
3408/// addressable by algorithms with a lower version number. Overhead
3409/// increases as algorithm version increases.
3410///
3411/// Terminology
3412/// Reduce element:
3413/// Reduce element refers to the individual data field with primitive
3414/// data types to be combined and reduced across threads.
3415/// Reduce list:
3416/// Reduce list refers to a collection of local, thread-private
3417/// reduce elements.
3418/// Remote Reduce list:
3419/// Remote Reduce list refers to a collection of remote (relative to
3420/// the current thread) reduce elements.
3421///
3422/// We distinguish between three states of threads that are important to
3423/// the implementation of this function.
3424/// Alive threads:
3425/// Threads in a warp executing the SIMT instruction, as distinguished from
3426/// threads that are inactive due to divergent control flow.
3427/// Active threads:
3428/// The minimal set of threads that has to be alive upon entry to this
3429/// function. The computation is correct iff active threads are alive.
3430/// Some threads are alive but they are not active because they do not
3431/// contribute to the computation in any useful manner. Turning them off
3432/// may introduce control flow overheads without any tangible benefits.
3433/// Effective threads:
3434/// In order to comply with the argument requirements of the shuffle
3435/// function, we must keep all lanes holding data alive. But at most
3436/// half of them perform value aggregation; we refer to this half of
3437/// threads as effective. The other half is simply handing off their
3438/// data.
3439///
3440/// Procedure
3441/// Value shuffle:
3442/// In this step active threads transfer data from higher lane positions
3443/// in the warp to lower lane positions, creating Remote Reduce list.
3444/// Value aggregation:
3445/// In this step, effective threads combine their thread local Reduce list
3446/// with Remote Reduce list and store the result in the thread local
3447/// Reduce list.
3448/// Value copy:
3449/// In this step, we deal with the assumption made by algorithm 2
3450/// (i.e. contiguity assumption). When we have an odd number of lanes
3451/// active, say 2k+1, only k threads will be effective and therefore k
3452/// new values will be produced. However, the Reduce list owned by the
3453/// (2k+1)th thread is ignored in the value aggregation. Therefore
3454/// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
3455/// that the contiguity assumption still holds.
James Y Knight9871db02019-02-05 16:42:33 +00003456static llvm::Function *emitShuffleAndReduceFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003457 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
James Y Knight9871db02019-02-05 16:42:33 +00003458 QualType ReductionArrayTy, llvm::Function *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003459 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003460
3461 // Thread local Reduce list used to host the values of data to be reduced.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003462 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3463 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003464 // Current lane id; could be logical.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003465 ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
3466 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003467 // Offset of the remote source lane relative to the current lane.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003468 ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3469 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003470 // Algorithm version. This is expected to be known at compile time.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003471 ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3472 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003473 FunctionArgList Args;
3474 Args.push_back(&ReduceListArg);
3475 Args.push_back(&LaneIDArg);
3476 Args.push_back(&RemoteLaneOffsetArg);
3477 Args.push_back(&AlgoVerArg);
3478
Alexey Bataev9ff80832018-04-16 20:16:21 +00003479 const CGFunctionInfo &CGFI =
3480 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003481 auto *Fn = llvm::Function::Create(
3482 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3483 "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003484 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003485 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003486 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003487 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003488
Alexey Bataev9ff80832018-04-16 20:16:21 +00003489 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003490
3491 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3492 Address LocalReduceList(
3493 Bld.CreatePointerBitCastOrAddrSpaceCast(
3494 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3495 C.VoidPtrTy, SourceLocation()),
3496 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3497 CGF.getPointerAlign());
3498
3499 Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
3500 llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
3501 AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3502
3503 Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
3504 llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
3505 AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3506
3507 Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
3508 llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
3509 AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3510
3511 // Create a local thread-private variable to host the Reduce list
3512 // from a remote lane.
3513 Address RemoteReduceList =
3514 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
3515
3516 // This loop iterates through the list of reduce elements and copies,
3517 // element by element, from a remote lane in the warp to RemoteReduceList,
3518 // hosted on the thread's stack.
3519 emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
3520 LocalReduceList, RemoteReduceList,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003521 {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
3522 /*ScratchpadIndex=*/nullptr,
3523 /*ScratchpadWidth=*/nullptr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003524
3525 // The actions to be performed on the Remote Reduce list is dependent
3526 // on the algorithm version.
3527 //
3528 // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
3529 // LaneId % 2 == 0 && Offset > 0):
3530 // do the reduction value aggregation
3531 //
3532 // The thread local variable Reduce list is mutated in place to host the
3533 // reduced data, which is the aggregated value produced from local and
3534 // remote lanes.
3535 //
3536 // Note that AlgoVer is expected to be a constant integer known at compile
3537 // time.
3538 // When AlgoVer==0, the first conjunction evaluates to true, making
3539 // the entire predicate true during compile time.
3540 // When AlgoVer==1, the second conjunction has only the second part to be
3541 // evaluated during runtime. Other conjunctions evaluates to false
3542 // during compile time.
3543 // When AlgoVer==2, the third conjunction has only the second part to be
3544 // evaluated during runtime. Other conjunctions evaluates to false
3545 // during compile time.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003546 llvm::Value *CondAlgo0 = Bld.CreateIsNull(AlgoVerArgVal);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003547
Alexey Bataev9ff80832018-04-16 20:16:21 +00003548 llvm::Value *Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
3549 llvm::Value *CondAlgo1 = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003550 Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
3551
Alexey Bataev9ff80832018-04-16 20:16:21 +00003552 llvm::Value *Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
3553 llvm::Value *CondAlgo2 = Bld.CreateAnd(
3554 Algo2, Bld.CreateIsNull(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1))));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003555 CondAlgo2 = Bld.CreateAnd(
3556 CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
3557
Alexey Bataev9ff80832018-04-16 20:16:21 +00003558 llvm::Value *CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003559 CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
3560
3561 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3562 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3563 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
3564 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
3565
3566 CGF.EmitBlock(ThenBB);
3567 // reduce_function(LocalReduceList, RemoteReduceList)
3568 llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3569 LocalReduceList.getPointer(), CGF.VoidPtrTy);
3570 llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3571 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003572 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3573 CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003574 Bld.CreateBr(MergeBB);
3575
3576 CGF.EmitBlock(ElseBB);
3577 Bld.CreateBr(MergeBB);
3578
3579 CGF.EmitBlock(MergeBB);
3580
3581 // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
3582 // Reduce list.
3583 Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
Alexey Bataev9ff80832018-04-16 20:16:21 +00003584 llvm::Value *CondCopy = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003585 Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
3586
3587 llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
3588 llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
3589 llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
3590 Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
3591
3592 CGF.EmitBlock(CpyThenBB);
3593 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
3594 RemoteReduceList, LocalReduceList);
3595 Bld.CreateBr(CpyMergeBB);
3596
3597 CGF.EmitBlock(CpyElseBB);
3598 Bld.CreateBr(CpyMergeBB);
3599
3600 CGF.EmitBlock(CpyMergeBB);
3601
3602 CGF.FinishFunction();
3603 return Fn;
3604}
3605
Alexey Bataev8061acd2019-02-20 16:36:22 +00003606/// This function emits a helper that copies all the reduction variables from
3607/// the team into the provided global buffer for the reduction variables.
3608///
3609/// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
3610/// For all data entries D in reduce_data:
3611/// Copy local D to buffer.D[Idx]
3612static llvm::Value *emitListToGlobalCopyFunction(
3613 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3614 QualType ReductionArrayTy, SourceLocation Loc,
3615 const RecordDecl *TeamReductionRec,
3616 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3617 &VarFieldMap) {
3618 ASTContext &C = CGM.getContext();
3619
3620 // Buffer: global reduction buffer.
3621 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3622 C.VoidPtrTy, ImplicitParamDecl::Other);
3623 // Idx: index of the buffer.
3624 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3625 ImplicitParamDecl::Other);
3626 // ReduceList: thread local Reduce list.
3627 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3628 C.VoidPtrTy, ImplicitParamDecl::Other);
3629 FunctionArgList Args;
3630 Args.push_back(&BufferArg);
3631 Args.push_back(&IdxArg);
3632 Args.push_back(&ReduceListArg);
3633
3634 const CGFunctionInfo &CGFI =
3635 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3636 auto *Fn = llvm::Function::Create(
3637 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3638 "_omp_reduction_list_to_global_copy_func", &CGM.getModule());
3639 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3640 Fn->setDoesNotRecurse();
3641 CodeGenFunction CGF(CGM);
3642 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3643
3644 CGBuilderTy &Bld = CGF.Builder;
3645
3646 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3647 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3648 Address LocalReduceList(
3649 Bld.CreatePointerBitCastOrAddrSpaceCast(
3650 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3651 C.VoidPtrTy, Loc),
3652 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3653 CGF.getPointerAlign());
3654 QualType StaticTy = C.getRecordType(TeamReductionRec);
3655 llvm::Type *LLVMReductionsBufferTy =
3656 CGM.getTypes().ConvertTypeForMem(StaticTy);
3657 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3658 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3659 LLVMReductionsBufferTy->getPointerTo());
3660 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3661 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3662 /*Volatile=*/false, C.IntTy,
3663 Loc)};
3664 unsigned Idx = 0;
3665 for (const Expr *Private : Privates) {
3666 // Reduce element = LocalReduceList[i]
3667 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
3668 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3669 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3670 // elemptr = ((CopyType*)(elemptrptr)) + I
3671 ElemPtrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3672 ElemPtrPtr, CGF.ConvertTypeForMem(Private->getType())->getPointerTo());
3673 Address ElemPtr =
3674 Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
3675 const ValueDecl *VD = cast<DeclRefExpr>(Private)->getDecl();
3676 // Global = Buffer.VD[Idx];
3677 const FieldDecl *FD = VarFieldMap.lookup(VD);
3678 LValue GlobLVal = CGF.EmitLValueForField(
3679 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3680 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3681 GlobLVal.setAddress(Address(BufferPtr, GlobLVal.getAlignment()));
3682 switch (CGF.getEvaluationKind(Private->getType())) {
3683 case TEK_Scalar: {
3684 llvm::Value *V = CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false,
3685 Private->getType(), Loc);
3686 CGF.EmitStoreOfScalar(V, GlobLVal);
3687 break;
3688 }
3689 case TEK_Complex: {
3690 CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(
3691 CGF.MakeAddrLValue(ElemPtr, Private->getType()), Loc);
3692 CGF.EmitStoreOfComplex(V, GlobLVal, /*isInit=*/false);
3693 break;
3694 }
3695 case TEK_Aggregate:
3696 CGF.EmitAggregateCopy(GlobLVal,
3697 CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3698 Private->getType(), AggValueSlot::DoesNotOverlap);
3699 break;
3700 }
3701 ++Idx;
3702 }
3703
3704 CGF.FinishFunction();
3705 return Fn;
3706}
3707
3708/// This function emits a helper that reduces all the reduction variables from
3709/// the team into the provided global buffer for the reduction variables.
3710///
3711/// void list_to_global_reduce_func(void *buffer, int Idx, void *reduce_data)
3712/// void *GlobPtrs[];
3713/// GlobPtrs[0] = (void*)&buffer.D0[Idx];
3714/// ...
3715/// GlobPtrs[N] = (void*)&buffer.DN[Idx];
3716/// reduce_function(GlobPtrs, reduce_data);
3717static llvm::Value *emitListToGlobalReduceFunction(
3718 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3719 QualType ReductionArrayTy, SourceLocation Loc,
3720 const RecordDecl *TeamReductionRec,
3721 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3722 &VarFieldMap,
3723 llvm::Function *ReduceFn) {
3724 ASTContext &C = CGM.getContext();
3725
3726 // Buffer: global reduction buffer.
3727 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3728 C.VoidPtrTy, ImplicitParamDecl::Other);
3729 // Idx: index of the buffer.
3730 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3731 ImplicitParamDecl::Other);
3732 // ReduceList: thread local Reduce list.
3733 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3734 C.VoidPtrTy, ImplicitParamDecl::Other);
3735 FunctionArgList Args;
3736 Args.push_back(&BufferArg);
3737 Args.push_back(&IdxArg);
3738 Args.push_back(&ReduceListArg);
3739
3740 const CGFunctionInfo &CGFI =
3741 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3742 auto *Fn = llvm::Function::Create(
3743 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3744 "_omp_reduction_list_to_global_reduce_func", &CGM.getModule());
3745 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3746 Fn->setDoesNotRecurse();
3747 CodeGenFunction CGF(CGM);
3748 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3749
3750 CGBuilderTy &Bld = CGF.Builder;
3751
3752 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3753 QualType StaticTy = C.getRecordType(TeamReductionRec);
3754 llvm::Type *LLVMReductionsBufferTy =
3755 CGM.getTypes().ConvertTypeForMem(StaticTy);
3756 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3757 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3758 LLVMReductionsBufferTy->getPointerTo());
3759
3760 // 1. Build a list of reduction variables.
3761 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3762 Address ReductionList =
3763 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3764 auto IPriv = Privates.begin();
3765 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3766 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3767 /*Volatile=*/false, C.IntTy,
3768 Loc)};
3769 unsigned Idx = 0;
3770 for (unsigned I = 0, E = Privates.size(); I < E; ++I, ++IPriv, ++Idx) {
3771 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3772 // Global = Buffer.VD[Idx];
3773 const ValueDecl *VD = cast<DeclRefExpr>(*IPriv)->getDecl();
3774 const FieldDecl *FD = VarFieldMap.lookup(VD);
3775 LValue GlobLVal = CGF.EmitLValueForField(
3776 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3777 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3778 llvm::Value *Ptr = CGF.EmitCastToVoidPtr(BufferPtr);
3779 CGF.EmitStoreOfScalar(Ptr, Elem, /*Volatile=*/false, C.VoidPtrTy);
3780 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3781 // Store array size.
3782 ++Idx;
3783 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3784 llvm::Value *Size = CGF.Builder.CreateIntCast(
3785 CGF.getVLASize(
3786 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3787 .NumElts,
3788 CGF.SizeTy, /*isSigned=*/false);
3789 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3790 Elem);
3791 }
3792 }
3793
3794 // Call reduce_function(GlobalReduceList, ReduceList)
3795 llvm::Value *GlobalReduceList =
3796 CGF.EmitCastToVoidPtr(ReductionList.getPointer());
3797 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3798 llvm::Value *ReducedPtr = CGF.EmitLoadOfScalar(
3799 AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
3800 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3801 CGF, Loc, ReduceFn, {GlobalReduceList, ReducedPtr});
3802 CGF.FinishFunction();
3803 return Fn;
3804}
3805
3806/// This function emits a helper that copies all the reduction variables from
3807/// the team into the provided global buffer for the reduction variables.
3808///
3809/// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
3810/// For all data entries D in reduce_data:
3811/// Copy buffer.D[Idx] to local D;
3812static llvm::Value *emitGlobalToListCopyFunction(
3813 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3814 QualType ReductionArrayTy, SourceLocation Loc,
3815 const RecordDecl *TeamReductionRec,
3816 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3817 &VarFieldMap) {
3818 ASTContext &C = CGM.getContext();
3819
3820 // Buffer: global reduction buffer.
3821 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3822 C.VoidPtrTy, ImplicitParamDecl::Other);
3823 // Idx: index of the buffer.
3824 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3825 ImplicitParamDecl::Other);
3826 // ReduceList: thread local Reduce list.
3827 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3828 C.VoidPtrTy, ImplicitParamDecl::Other);
3829 FunctionArgList Args;
3830 Args.push_back(&BufferArg);
3831 Args.push_back(&IdxArg);
3832 Args.push_back(&ReduceListArg);
3833
3834 const CGFunctionInfo &CGFI =
3835 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3836 auto *Fn = llvm::Function::Create(
3837 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3838 "_omp_reduction_global_to_list_copy_func", &CGM.getModule());
3839 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3840 Fn->setDoesNotRecurse();
3841 CodeGenFunction CGF(CGM);
3842 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3843
3844 CGBuilderTy &Bld = CGF.Builder;
3845
3846 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3847 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3848 Address LocalReduceList(
3849 Bld.CreatePointerBitCastOrAddrSpaceCast(
3850 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3851 C.VoidPtrTy, Loc),
3852 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3853 CGF.getPointerAlign());
3854 QualType StaticTy = C.getRecordType(TeamReductionRec);
3855 llvm::Type *LLVMReductionsBufferTy =
3856 CGM.getTypes().ConvertTypeForMem(StaticTy);
3857 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3858 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3859 LLVMReductionsBufferTy->getPointerTo());
3860
3861 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3862 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3863 /*Volatile=*/false, C.IntTy,
3864 Loc)};
3865 unsigned Idx = 0;
3866 for (const Expr *Private : Privates) {
3867 // Reduce element = LocalReduceList[i]
3868 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
3869 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3870 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3871 // elemptr = ((CopyType*)(elemptrptr)) + I
3872 ElemPtrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3873 ElemPtrPtr, CGF.ConvertTypeForMem(Private->getType())->getPointerTo());
3874 Address ElemPtr =
3875 Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
3876 const ValueDecl *VD = cast<DeclRefExpr>(Private)->getDecl();
3877 // Global = Buffer.VD[Idx];
3878 const FieldDecl *FD = VarFieldMap.lookup(VD);
3879 LValue GlobLVal = CGF.EmitLValueForField(
3880 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3881 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3882 GlobLVal.setAddress(Address(BufferPtr, GlobLVal.getAlignment()));
3883 switch (CGF.getEvaluationKind(Private->getType())) {
3884 case TEK_Scalar: {
3885 llvm::Value *V = CGF.EmitLoadOfScalar(GlobLVal, Loc);
3886 CGF.EmitStoreOfScalar(V, ElemPtr, /*Volatile=*/false, Private->getType());
3887 break;
3888 }
3889 case TEK_Complex: {
3890 CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(GlobLVal, Loc);
3891 CGF.EmitStoreOfComplex(V, CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3892 /*isInit=*/false);
3893 break;
3894 }
3895 case TEK_Aggregate:
3896 CGF.EmitAggregateCopy(CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3897 GlobLVal, Private->getType(),
3898 AggValueSlot::DoesNotOverlap);
3899 break;
3900 }
3901 ++Idx;
3902 }
3903
3904 CGF.FinishFunction();
3905 return Fn;
3906}
3907
3908/// This function emits a helper that reduces all the reduction variables from
3909/// the team into the provided global buffer for the reduction variables.
3910///
3911/// void global_to_list_reduce_func(void *buffer, int Idx, void *reduce_data)
3912/// void *GlobPtrs[];
3913/// GlobPtrs[0] = (void*)&buffer.D0[Idx];
3914/// ...
3915/// GlobPtrs[N] = (void*)&buffer.DN[Idx];
3916/// reduce_function(reduce_data, GlobPtrs);
3917static llvm::Value *emitGlobalToListReduceFunction(
3918 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3919 QualType ReductionArrayTy, SourceLocation Loc,
3920 const RecordDecl *TeamReductionRec,
3921 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3922 &VarFieldMap,
3923 llvm::Function *ReduceFn) {
3924 ASTContext &C = CGM.getContext();
3925
3926 // Buffer: global reduction buffer.
3927 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3928 C.VoidPtrTy, ImplicitParamDecl::Other);
3929 // Idx: index of the buffer.
3930 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3931 ImplicitParamDecl::Other);
3932 // ReduceList: thread local Reduce list.
3933 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3934 C.VoidPtrTy, ImplicitParamDecl::Other);
3935 FunctionArgList Args;
3936 Args.push_back(&BufferArg);
3937 Args.push_back(&IdxArg);
3938 Args.push_back(&ReduceListArg);
3939
3940 const CGFunctionInfo &CGFI =
3941 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3942 auto *Fn = llvm::Function::Create(
3943 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3944 "_omp_reduction_global_to_list_reduce_func", &CGM.getModule());
3945 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3946 Fn->setDoesNotRecurse();
3947 CodeGenFunction CGF(CGM);
3948 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3949
3950 CGBuilderTy &Bld = CGF.Builder;
3951
3952 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3953 QualType StaticTy = C.getRecordType(TeamReductionRec);
3954 llvm::Type *LLVMReductionsBufferTy =
3955 CGM.getTypes().ConvertTypeForMem(StaticTy);
3956 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3957 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3958 LLVMReductionsBufferTy->getPointerTo());
3959
3960 // 1. Build a list of reduction variables.
3961 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3962 Address ReductionList =
3963 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3964 auto IPriv = Privates.begin();
3965 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3966 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3967 /*Volatile=*/false, C.IntTy,
3968 Loc)};
3969 unsigned Idx = 0;
3970 for (unsigned I = 0, E = Privates.size(); I < E; ++I, ++IPriv, ++Idx) {
3971 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3972 // Global = Buffer.VD[Idx];
3973 const ValueDecl *VD = cast<DeclRefExpr>(*IPriv)->getDecl();
3974 const FieldDecl *FD = VarFieldMap.lookup(VD);
3975 LValue GlobLVal = CGF.EmitLValueForField(
3976 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3977 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3978 llvm::Value *Ptr = CGF.EmitCastToVoidPtr(BufferPtr);
3979 CGF.EmitStoreOfScalar(Ptr, Elem, /*Volatile=*/false, C.VoidPtrTy);
3980 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3981 // Store array size.
3982 ++Idx;
3983 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3984 llvm::Value *Size = CGF.Builder.CreateIntCast(
3985 CGF.getVLASize(
3986 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3987 .NumElts,
3988 CGF.SizeTy, /*isSigned=*/false);
3989 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3990 Elem);
3991 }
3992 }
3993
3994 // Call reduce_function(ReduceList, GlobalReduceList)
3995 llvm::Value *GlobalReduceList =
3996 CGF.EmitCastToVoidPtr(ReductionList.getPointer());
3997 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3998 llvm::Value *ReducedPtr = CGF.EmitLoadOfScalar(
3999 AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
4000 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
4001 CGF, Loc, ReduceFn, {ReducedPtr, GlobalReduceList});
4002 CGF.FinishFunction();
4003 return Fn;
4004}
4005
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004006///
4007/// Design of OpenMP reductions on the GPU
4008///
4009/// Consider a typical OpenMP program with one or more reduction
4010/// clauses:
4011///
4012/// float foo;
4013/// double bar;
4014/// #pragma omp target teams distribute parallel for \
4015/// reduction(+:foo) reduction(*:bar)
4016/// for (int i = 0; i < N; i++) {
4017/// foo += A[i]; bar *= B[i];
4018/// }
4019///
4020/// where 'foo' and 'bar' are reduced across all OpenMP threads in
4021/// all teams. In our OpenMP implementation on the NVPTX device an
4022/// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
4023/// within a team are mapped to CUDA threads within a threadblock.
4024/// Our goal is to efficiently aggregate values across all OpenMP
4025/// threads such that:
4026///
4027/// - the compiler and runtime are logically concise, and
4028/// - the reduction is performed efficiently in a hierarchical
4029/// manner as follows: within OpenMP threads in the same warp,
4030/// across warps in a threadblock, and finally across teams on
4031/// the NVPTX device.
4032///
4033/// Introduction to Decoupling
4034///
4035/// We would like to decouple the compiler and the runtime so that the
4036/// latter is ignorant of the reduction variables (number, data types)
4037/// and the reduction operators. This allows a simpler interface
4038/// and implementation while still attaining good performance.
4039///
4040/// Pseudocode for the aforementioned OpenMP program generated by the
4041/// compiler is as follows:
4042///
4043/// 1. Create private copies of reduction variables on each OpenMP
4044/// thread: 'foo_private', 'bar_private'
4045/// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
4046/// to it and writes the result in 'foo_private' and 'bar_private'
4047/// respectively.
4048/// 3. Call the OpenMP runtime on the GPU to reduce within a team
4049/// and store the result on the team master:
4050///
Alexey Bataev8e009032019-01-04 17:25:09 +00004051/// __kmpc_nvptx_parallel_reduce_nowait_v2(...,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004052/// reduceData, shuffleReduceFn, interWarpCpyFn)
4053///
4054/// where:
4055/// struct ReduceData {
4056/// double *foo;
4057/// double *bar;
4058/// } reduceData
4059/// reduceData.foo = &foo_private
4060/// reduceData.bar = &bar_private
4061///
4062/// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
4063/// auxiliary functions generated by the compiler that operate on
4064/// variables of type 'ReduceData'. They aid the runtime perform
4065/// algorithmic steps in a data agnostic manner.
4066///
4067/// 'shuffleReduceFn' is a pointer to a function that reduces data
4068/// of type 'ReduceData' across two OpenMP threads (lanes) in the
4069/// same warp. It takes the following arguments as input:
4070///
4071/// a. variable of type 'ReduceData' on the calling lane,
4072/// b. its lane_id,
4073/// c. an offset relative to the current lane_id to generate a
4074/// remote_lane_id. The remote lane contains the second
4075/// variable of type 'ReduceData' that is to be reduced.
4076/// d. an algorithm version parameter determining which reduction
4077/// algorithm to use.
4078///
4079/// 'shuffleReduceFn' retrieves data from the remote lane using
4080/// efficient GPU shuffle intrinsics and reduces, using the
4081/// algorithm specified by the 4th parameter, the two operands
4082/// element-wise. The result is written to the first operand.
4083///
4084/// Different reduction algorithms are implemented in different
4085/// runtime functions, all calling 'shuffleReduceFn' to perform
4086/// the essential reduction step. Therefore, based on the 4th
4087/// parameter, this function behaves slightly differently to
4088/// cooperate with the runtime to ensure correctness under
4089/// different circumstances.
4090///
4091/// 'InterWarpCpyFn' is a pointer to a function that transfers
4092/// reduced variables across warps. It tunnels, through CUDA
4093/// shared memory, the thread-private data of type 'ReduceData'
4094/// from lane 0 of each warp to a lane in the first warp.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004095/// 4. Call the OpenMP runtime on the GPU to reduce across teams.
4096/// The last team writes the global reduced value to memory.
4097///
4098/// ret = __kmpc_nvptx_teams_reduce_nowait(...,
4099/// reduceData, shuffleReduceFn, interWarpCpyFn,
4100/// scratchpadCopyFn, loadAndReduceFn)
4101///
4102/// 'scratchpadCopyFn' is a helper that stores reduced
4103/// data from the team master to a scratchpad array in
4104/// global memory.
4105///
4106/// 'loadAndReduceFn' is a helper that loads data from
4107/// the scratchpad array and reduces it with the input
4108/// operand.
4109///
4110/// These compiler generated functions hide address
4111/// calculation and alignment information from the runtime.
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004112/// 5. if ret == 1:
4113/// The team master of the last team stores the reduced
4114/// result to the globals in memory.
4115/// foo += reduceData.foo; bar *= reduceData.bar
4116///
4117///
4118/// Warp Reduction Algorithms
4119///
4120/// On the warp level, we have three algorithms implemented in the
4121/// OpenMP runtime depending on the number of active lanes:
4122///
4123/// Full Warp Reduction
4124///
4125/// The reduce algorithm within a warp where all lanes are active
4126/// is implemented in the runtime as follows:
4127///
4128/// full_warp_reduce(void *reduce_data,
4129/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
4130/// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
4131/// ShuffleReduceFn(reduce_data, 0, offset, 0);
4132/// }
4133///
4134/// The algorithm completes in log(2, WARPSIZE) steps.
4135///
4136/// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
4137/// not used therefore we save instructions by not retrieving lane_id
4138/// from the corresponding special registers. The 4th parameter, which
4139/// represents the version of the algorithm being used, is set to 0 to
4140/// signify full warp reduction.
4141///
4142/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4143///
4144/// #reduce_elem refers to an element in the local lane's data structure
4145/// #remote_elem is retrieved from a remote lane
4146/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4147/// reduce_elem = reduce_elem REDUCE_OP remote_elem;
4148///
4149/// Contiguous Partial Warp Reduction
4150///
4151/// This reduce algorithm is used within a warp where only the first
4152/// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
4153/// number of OpenMP threads in a parallel region is not a multiple of
4154/// WARPSIZE. The algorithm is implemented in the runtime as follows:
4155///
4156/// void
4157/// contiguous_partial_reduce(void *reduce_data,
4158/// kmp_ShuffleReductFctPtr ShuffleReduceFn,
4159/// int size, int lane_id) {
4160/// int curr_size;
4161/// int offset;
4162/// curr_size = size;
4163/// mask = curr_size/2;
4164/// while (offset>0) {
4165/// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
4166/// curr_size = (curr_size+1)/2;
4167/// offset = curr_size/2;
4168/// }
4169/// }
4170///
4171/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4172///
4173/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4174/// if (lane_id < offset)
4175/// reduce_elem = reduce_elem REDUCE_OP remote_elem
4176/// else
4177/// reduce_elem = remote_elem
4178///
4179/// This algorithm assumes that the data to be reduced are located in a
4180/// contiguous subset of lanes starting from the first. When there is
4181/// an odd number of active lanes, the data in the last lane is not
4182/// aggregated with any other lane's dat but is instead copied over.
4183///
4184/// Dispersed Partial Warp Reduction
4185///
4186/// This algorithm is used within a warp when any discontiguous subset of
4187/// lanes are active. It is used to implement the reduction operation
4188/// across lanes in an OpenMP simd region or in a nested parallel region.
4189///
4190/// void
4191/// dispersed_partial_reduce(void *reduce_data,
4192/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
4193/// int size, remote_id;
4194/// int logical_lane_id = number_of_active_lanes_before_me() * 2;
4195/// do {
4196/// remote_id = next_active_lane_id_right_after_me();
4197/// # the above function returns 0 of no active lane
4198/// # is present right after the current lane.
4199/// size = number_of_active_lanes_in_this_warp();
4200/// logical_lane_id /= 2;
4201/// ShuffleReduceFn(reduce_data, logical_lane_id,
4202/// remote_id-1-threadIdx.x, 2);
4203/// } while (logical_lane_id % 2 == 0 && size > 1);
4204/// }
4205///
4206/// There is no assumption made about the initial state of the reduction.
4207/// Any number of lanes (>=1) could be active at any position. The reduction
4208/// result is returned in the first active lane.
4209///
4210/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4211///
4212/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4213/// if (lane_id % 2 == 0 && offset > 0)
4214/// reduce_elem = reduce_elem REDUCE_OP remote_elem
4215/// else
4216/// reduce_elem = remote_elem
4217///
4218///
4219/// Intra-Team Reduction
4220///
4221/// This function, as implemented in the runtime call
Alexey Bataev8e009032019-01-04 17:25:09 +00004222/// '__kmpc_nvptx_parallel_reduce_nowait_v2', aggregates data across OpenMP
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004223/// threads in a team. It first reduces within a warp using the
4224/// aforementioned algorithms. We then proceed to gather all such
4225/// reduced values at the first warp.
4226///
4227/// The runtime makes use of the function 'InterWarpCpyFn', which copies
4228/// data from each of the "warp master" (zeroth lane of each warp, where
4229/// warp-reduced data is held) to the zeroth warp. This step reduces (in
4230/// a mathematical sense) the problem of reduction across warp masters in
4231/// a block to the problem of warp reduction.
4232///
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004233///
4234/// Inter-Team Reduction
4235///
4236/// Once a team has reduced its data to a single value, it is stored in
4237/// a global scratchpad array. Since each team has a distinct slot, this
4238/// can be done without locking.
4239///
4240/// The last team to write to the scratchpad array proceeds to reduce the
4241/// scratchpad array. One or more workers in the last team use the helper
4242/// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
4243/// the k'th worker reduces every k'th element.
4244///
Alexey Bataev8e009032019-01-04 17:25:09 +00004245/// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait_v2' to
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004246/// reduce across workers and compute a globally reduced value.
4247///
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004248void CGOpenMPRuntimeNVPTX::emitReduction(
4249 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
4250 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
4251 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
4252 if (!CGF.HaveInsertPoint())
4253 return;
4254
4255 bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00004256#ifndef NDEBUG
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004257 bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00004258#endif
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004259
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00004260 if (Options.SimpleReduction) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004261 assert(!TeamsReduction && !ParallelReduction &&
4262 "Invalid reduction selection in emitReduction.");
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00004263 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
4264 ReductionOps, Options);
4265 return;
4266 }
4267
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004268 assert((TeamsReduction || ParallelReduction) &&
4269 "Invalid reduction selection in emitReduction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004270
Alexey Bataeva1166022018-11-27 21:24:54 +00004271 // Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004272 // RedList, shuffle_reduce_func, interwarp_copy_func);
Alexey Bataeva1166022018-11-27 21:24:54 +00004273 // or
4274 // Build res = __kmpc_reduce_teams_nowait_simple(<loc>, <gtid>, <lck>);
Alexey Bataev8e009032019-01-04 17:25:09 +00004275 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004276 llvm::Value *ThreadId = getThreadID(CGF, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004277
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004278 llvm::Value *Res;
Alexey Bataev8061acd2019-02-20 16:36:22 +00004279 ASTContext &C = CGM.getContext();
4280 // 1. Build a list of reduction variables.
4281 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
4282 auto Size = RHSExprs.size();
4283 for (const Expr *E : Privates) {
4284 if (E->getType()->isVariablyModifiedType())
4285 // Reserve place for array size.
4286 ++Size;
4287 }
4288 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
4289 QualType ReductionArrayTy =
4290 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
4291 /*IndexTypeQuals=*/0);
4292 Address ReductionList =
4293 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
4294 auto IPriv = Privates.begin();
4295 unsigned Idx = 0;
4296 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
4297 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
4298 CGF.Builder.CreateStore(
4299 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4300 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
4301 Elem);
4302 if ((*IPriv)->getType()->isVariablyModifiedType()) {
4303 // Store array size.
4304 ++Idx;
4305 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
4306 llvm::Value *Size = CGF.Builder.CreateIntCast(
4307 CGF.getVLASize(
4308 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
4309 .NumElts,
4310 CGF.SizeTy, /*isSigned=*/false);
4311 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
4312 Elem);
4313 }
4314 }
4315
4316 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4317 ReductionList.getPointer(), CGF.VoidPtrTy);
4318 llvm::Function *ReductionFn = emitReductionFunction(
4319 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
4320 Privates, LHSExprs, RHSExprs, ReductionOps);
4321 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
4322 llvm::Function *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
4323 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
4324 llvm::Value *InterWarpCopyFn =
4325 emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
4326
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004327 if (ParallelReduction) {
Alexey Bataev8e009032019-01-04 17:25:09 +00004328 llvm::Value *Args[] = {RTLoc,
4329 ThreadId,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004330 CGF.Builder.getInt32(RHSExprs.size()),
4331 ReductionArrayTySize,
4332 RL,
4333 ShuffleAndReduceFn,
4334 InterWarpCopyFn};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004335
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004336 Res = CGF.EmitRuntimeCall(
Alexey Bataeva1166022018-11-27 21:24:54 +00004337 createNVPTXRuntimeFunction(
Alexey Bataev8061acd2019-02-20 16:36:22 +00004338 OMPRTL_NVPTX__kmpc_nvptx_parallel_reduce_nowait_v2),
4339 Args);
4340 } else {
4341 assert(TeamsReduction && "expected teams reduction.");
4342 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> VarFieldMap;
4343 llvm::SmallVector<const ValueDecl *, 4> PrivatesReductions(Privates.size());
4344 int Cnt = 0;
4345 for (const Expr *DRE : Privates) {
4346 PrivatesReductions[Cnt] = cast<DeclRefExpr>(DRE)->getDecl();
4347 ++Cnt;
4348 }
4349 const RecordDecl *TeamReductionRec = ::buildRecordForGlobalizedVars(
4350 CGM.getContext(), PrivatesReductions, llvm::None, VarFieldMap,
4351 C.getLangOpts().OpenMPCUDAReductionBufNum);
4352 TeamsReductions.push_back(TeamReductionRec);
4353 if (!KernelTeamsReductionPtr) {
4354 KernelTeamsReductionPtr = new llvm::GlobalVariable(
4355 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/true,
4356 llvm::GlobalValue::InternalLinkage, nullptr,
4357 "_openmp_teams_reductions_buffer_$_$ptr");
4358 }
4359 llvm::Value *GlobalBufferPtr = CGF.EmitLoadOfScalar(
4360 Address(KernelTeamsReductionPtr, CGM.getPointerAlign()),
4361 /*Volatile=*/false, C.getPointerType(C.VoidPtrTy), Loc);
4362 llvm::Value *GlobalToBufferCpyFn = ::emitListToGlobalCopyFunction(
4363 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
4364 llvm::Value *GlobalToBufferRedFn = ::emitListToGlobalReduceFunction(
4365 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap,
4366 ReductionFn);
4367 llvm::Value *BufferToGlobalCpyFn = ::emitGlobalToListCopyFunction(
4368 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
4369 llvm::Value *BufferToGlobalRedFn = ::emitGlobalToListReduceFunction(
4370 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap,
4371 ReductionFn);
4372
4373 llvm::Value *Args[] = {
4374 RTLoc,
4375 ThreadId,
4376 GlobalBufferPtr,
4377 CGF.Builder.getInt32(C.getLangOpts().OpenMPCUDAReductionBufNum),
4378 RL,
4379 ShuffleAndReduceFn,
4380 InterWarpCopyFn,
4381 GlobalToBufferCpyFn,
4382 GlobalToBufferRedFn,
4383 BufferToGlobalCpyFn,
4384 BufferToGlobalRedFn};
4385
4386 Res = CGF.EmitRuntimeCall(
4387 createNVPTXRuntimeFunction(
4388 OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_v2),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004389 Args);
4390 }
4391
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004392 // 5. Build if (res == 1)
4393 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.reduction.done");
4394 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.then");
4395 llvm::Value *Cond = CGF.Builder.CreateICmpEQ(
4396 Res, llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1));
4397 CGF.Builder.CreateCondBr(Cond, ThenBB, ExitBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004398
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004399 // 6. Build then branch: where we have reduced values in the master
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004400 // thread in each team.
4401 // __kmpc_end_reduce{_nowait}(<gtid>);
4402 // break;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004403 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004404
4405 // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004406 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004407 this](CodeGenFunction &CGF, PrePostActionTy &Action) {
4408 auto IPriv = Privates.begin();
4409 auto ILHS = LHSExprs.begin();
4410 auto IRHS = RHSExprs.begin();
Alexey Bataev9ff80832018-04-16 20:16:21 +00004411 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004412 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4413 cast<DeclRefExpr>(*IRHS));
4414 ++IPriv;
4415 ++ILHS;
4416 ++IRHS;
4417 }
4418 };
Alexey Bataev8061acd2019-02-20 16:36:22 +00004419 llvm::Value *EndArgs[] = {ThreadId};
4420 RegionCodeGenTy RCG(CodeGen);
4421 NVPTXActionTy Action(
4422 nullptr, llvm::None,
4423 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_reduce_nowait),
4424 EndArgs);
4425 RCG.setAction(Action);
4426 RCG(CGF);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004427 // There is no need to emit line number for unconditional branch.
4428 (void)ApplyDebugLocation::CreateEmpty(CGF);
4429 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004430}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004431
4432const VarDecl *
4433CGOpenMPRuntimeNVPTX::translateParameter(const FieldDecl *FD,
4434 const VarDecl *NativeParam) const {
4435 if (!NativeParam->getType()->isReferenceType())
4436 return NativeParam;
4437 QualType ArgType = NativeParam->getType();
4438 QualifierCollector QC;
4439 const Type *NonQualTy = QC.strip(ArgType);
4440 QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4441 if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
4442 if (Attr->getCaptureKind() == OMPC_map) {
4443 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
4444 LangAS::opencl_global);
Alexey Bataev1af5bd52019-03-05 17:47:18 +00004445 } else if (Attr->getCaptureKind() == OMPC_firstprivate &&
4446 PointeeTy.isConstant(CGM.getContext())) {
4447 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
4448 LangAS::opencl_generic);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004449 }
4450 }
4451 ArgType = CGM.getContext().getPointerType(PointeeTy);
4452 QC.addRestrict();
4453 enum { NVPTX_local_addr = 5 };
Alexander Richardson6d989432017-10-15 18:48:14 +00004454 QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004455 ArgType = QC.apply(CGM.getContext(), ArgType);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004456 if (isa<ImplicitParamDecl>(NativeParam))
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004457 return ImplicitParamDecl::Create(
4458 CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
4459 NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004460 return ParmVarDecl::Create(
4461 CGM.getContext(),
4462 const_cast<DeclContext *>(NativeParam->getDeclContext()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004463 NativeParam->getBeginLoc(), NativeParam->getLocation(),
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004464 NativeParam->getIdentifier(), ArgType,
4465 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004466}
4467
4468Address
4469CGOpenMPRuntimeNVPTX::getParameterAddress(CodeGenFunction &CGF,
4470 const VarDecl *NativeParam,
4471 const VarDecl *TargetParam) const {
4472 assert(NativeParam != TargetParam &&
4473 NativeParam->getType()->isReferenceType() &&
4474 "Native arg must not be the same as target arg.");
4475 Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
4476 QualType NativeParamType = NativeParam->getType();
4477 QualifierCollector QC;
4478 const Type *NonQualTy = QC.strip(NativeParamType);
4479 QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4480 unsigned NativePointeeAddrSpace =
Alexander Richardson6d989432017-10-15 18:48:14 +00004481 CGF.getContext().getTargetAddressSpace(NativePointeeTy);
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004482 QualType TargetTy = TargetParam->getType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004483 llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004484 LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004485 // First cast to generic.
4486 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4487 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4488 /*AddrSpace=*/0));
4489 // Cast from generic to native address space.
4490 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4491 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4492 NativePointeeAddrSpace));
4493 Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
4494 CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004495 NativeParamType);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004496 return NativeParamAddr;
4497}
4498
4499void CGOpenMPRuntimeNVPTX::emitOutlinedFunctionCall(
James Y Knight9871db02019-02-05 16:42:33 +00004500 CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn,
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004501 ArrayRef<llvm::Value *> Args) const {
4502 SmallVector<llvm::Value *, 4> TargetArgs;
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004503 TargetArgs.reserve(Args.size());
James Y Knight9871db02019-02-05 16:42:33 +00004504 auto *FnType = OutlinedFn.getFunctionType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004505 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004506 if (FnType->isVarArg() && FnType->getNumParams() <= I) {
4507 TargetArgs.append(std::next(Args.begin(), I), Args.end());
4508 break;
4509 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004510 llvm::Type *TargetType = FnType->getParamType(I);
4511 llvm::Value *NativeArg = Args[I];
4512 if (!TargetType->isPointerTy()) {
4513 TargetArgs.emplace_back(NativeArg);
4514 continue;
4515 }
4516 llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataevc99042b2018-03-15 18:10:54 +00004517 NativeArg,
4518 NativeArg->getType()->getPointerElementType()->getPointerTo());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004519 TargetArgs.emplace_back(
4520 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
4521 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00004522 CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004523}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004524
4525/// Emit function which wraps the outline parallel region
4526/// and controls the arguments which are passed to this function.
4527/// The wrapper ensures that the outlined function is called
4528/// with the correct arguments when data is shared.
4529llvm::Function *CGOpenMPRuntimeNVPTX::createParallelDataSharingWrapper(
4530 llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
4531 ASTContext &Ctx = CGM.getContext();
4532 const auto &CS = *D.getCapturedStmt(OMPD_parallel);
4533
4534 // Create a function that takes as argument the source thread.
4535 FunctionArgList WrapperArgs;
4536 QualType Int16QTy =
4537 Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
4538 QualType Int32QTy =
4539 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004540 ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004541 /*Id=*/nullptr, Int16QTy,
4542 ImplicitParamDecl::Other);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004543 ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004544 /*Id=*/nullptr, Int32QTy,
4545 ImplicitParamDecl::Other);
4546 WrapperArgs.emplace_back(&ParallelLevelArg);
4547 WrapperArgs.emplace_back(&WrapperArg);
4548
Alexey Bataev9ff80832018-04-16 20:16:21 +00004549 const CGFunctionInfo &CGFI =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004550 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
4551
4552 auto *Fn = llvm::Function::Create(
4553 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataev9ff80832018-04-16 20:16:21 +00004554 Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004555 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004556 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004557 Fn->setDoesNotRecurse();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004558
4559 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
4560 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004561 D.getBeginLoc(), D.getBeginLoc());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004562
4563 const auto *RD = CS.getCapturedRecordDecl();
4564 auto CurField = RD->field_begin();
4565
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004566 Address ZeroAddr = CGF.CreateMemTemp(
4567 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
4568 /*Name*/ ".zero.addr");
4569 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004570 // Get the array of arguments.
4571 SmallVector<llvm::Value *, 8> Args;
4572
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004573 Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).getPointer());
4574 Args.emplace_back(ZeroAddr.getPointer());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004575
4576 CGBuilderTy &Bld = CGF.Builder;
4577 auto CI = CS.capture_begin();
4578
4579 // Use global memory for data sharing.
4580 // Handle passing of global args to workers.
4581 Address GlobalArgs =
4582 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
4583 llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
4584 llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
4585 CGF.EmitRuntimeCall(
4586 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_get_shared_variables),
4587 DataSharingArgs);
4588
4589 // Retrieve the shared variables from the list of references returned
4590 // by the runtime. Pass the variables to the outlined function.
Alexey Bataev17314212018-03-20 15:41:05 +00004591 Address SharedArgListAddress = Address::invalid();
4592 if (CS.capture_size() > 0 ||
4593 isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4594 SharedArgListAddress = CGF.EmitLoadOfPointer(
4595 GlobalArgs, CGF.getContext()
4596 .getPointerType(CGF.getContext().getPointerType(
4597 CGF.getContext().VoidPtrTy))
4598 .castAs<PointerType>());
4599 }
4600 unsigned Idx = 0;
4601 if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
James Y Knight751fe282019-02-09 22:22:28 +00004602 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004603 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4604 Src, CGF.SizeTy->getPointerTo());
4605 llvm::Value *LB = CGF.EmitLoadOfScalar(
4606 TypedAddress,
4607 /*Volatile=*/false,
4608 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4609 cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
4610 Args.emplace_back(LB);
4611 ++Idx;
James Y Knight751fe282019-02-09 22:22:28 +00004612 Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004613 TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4614 Src, CGF.SizeTy->getPointerTo());
4615 llvm::Value *UB = CGF.EmitLoadOfScalar(
4616 TypedAddress,
4617 /*Volatile=*/false,
4618 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4619 cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
4620 Args.emplace_back(UB);
4621 ++Idx;
4622 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004623 if (CS.capture_size() > 0) {
4624 ASTContext &CGFContext = CGF.getContext();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004625 for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
4626 QualType ElemTy = CurField->getType();
James Y Knight751fe282019-02-09 22:22:28 +00004627 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004628 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004629 Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)));
4630 llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
4631 /*Volatile=*/false,
4632 CGFContext.getPointerType(ElemTy),
4633 CI->getLocation());
Alexey Bataev2091ca62018-04-23 17:33:41 +00004634 if (CI->capturesVariableByCopy() &&
4635 !CI->getCapturedVar()->getType()->isAnyPointerType()) {
Alexey Bataev17314212018-03-20 15:41:05 +00004636 Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
4637 CI->getLocation());
4638 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004639 Args.emplace_back(Arg);
4640 }
4641 }
4642
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004643 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedParallelFn, Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004644 CGF.FinishFunction();
4645 return Fn;
4646}
4647
4648void CGOpenMPRuntimeNVPTX::emitFunctionProlog(CodeGenFunction &CGF,
4649 const Decl *D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004650 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4651 return;
4652
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004653 assert(D && "Expected function or captured|block decl.");
4654 assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
4655 "Function is registered already.");
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004656 assert((!TeamAndReductions.first || TeamAndReductions.first == D) &&
4657 "Team is set but not processed.");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004658 const Stmt *Body = nullptr;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004659 bool NeedToDelayGlobalization = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004660 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4661 Body = FD->getBody();
4662 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
4663 Body = BD->getBody();
4664 } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
4665 Body = CD->getBody();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004666 NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
Alexey Bataev2adecff2018-09-21 14:22:53 +00004667 if (NeedToDelayGlobalization &&
4668 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
4669 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004670 }
4671 if (!Body)
4672 return;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004673 CheckVarsEscapingDeclContext VarChecker(CGF, TeamAndReductions.second);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004674 VarChecker.Visit(Body);
Alexey Bataevff23bb62018-10-11 18:30:31 +00004675 const RecordDecl *GlobalizedVarsRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004676 VarChecker.getGlobalizedRecord(IsInTTDRegion);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004677 TeamAndReductions.first = nullptr;
4678 TeamAndReductions.second.clear();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004679 ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
4680 VarChecker.getEscapedVariableLengthDecls();
4681 if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004682 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004683 auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
4684 I->getSecond().MappedParams =
4685 llvm::make_unique<CodeGenFunction::OMPMapVars>();
4686 I->getSecond().GlobalRecord = GlobalizedVarsRecord;
4687 I->getSecond().EscapedParameters.insert(
4688 VarChecker.getEscapedParameters().begin(),
4689 VarChecker.getEscapedParameters().end());
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004690 I->getSecond().EscapedVariableLengthDecls.append(
4691 EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004692 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004693 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004694 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004695 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004696 Data.insert(std::make_pair(VD, MappedVarData(FD, IsInTTDRegion)));
Alexey Bataevc99042b2018-03-15 18:10:54 +00004697 }
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004698 if (!IsInTTDRegion && !NeedToDelayGlobalization && !IsInParallelRegion) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004699 CheckVarsEscapingDeclContext VarChecker(CGF, llvm::None);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004700 VarChecker.Visit(Body);
4701 I->getSecond().SecondaryGlobalRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004702 VarChecker.getGlobalizedRecord(/*IsInTTDRegion=*/true);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004703 I->getSecond().SecondaryLocalVarData.emplace();
4704 DeclToAddrMapTy &Data = I->getSecond().SecondaryLocalVarData.getValue();
4705 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
4706 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
4707 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004708 Data.insert(
4709 std::make_pair(VD, MappedVarData(FD, /*IsInTTDRegion=*/true)));
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004710 }
4711 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00004712 if (!NeedToDelayGlobalization) {
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004713 emitGenericVarsProlog(CGF, D->getBeginLoc(), /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004714 struct GlobalizationScope final : EHScopeStack::Cleanup {
4715 GlobalizationScope() = default;
4716
4717 void Emit(CodeGenFunction &CGF, Flags flags) override {
4718 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004719 .emitGenericVarsEpilog(CGF, /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004720 }
4721 };
4722 CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004723 }
4724}
4725
4726Address CGOpenMPRuntimeNVPTX::getAddressOfLocalVariable(CodeGenFunction &CGF,
4727 const VarDecl *VD) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004728 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4729 return Address::invalid();
4730
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004731 VD = VD->getCanonicalDecl();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004732 auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
4733 if (I == FunctionGlobalizedDecls.end())
4734 return Address::invalid();
Alexey Bataevc99042b2018-03-15 18:10:54 +00004735 auto VDI = I->getSecond().LocalVarData.find(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004736 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004737 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004738 if (VD->hasAttrs()) {
4739 for (specific_attr_iterator<OMPReferencedVarAttr> IT(VD->attr_begin()),
4740 E(VD->attr_end());
4741 IT != E; ++IT) {
4742 auto VDI = I->getSecond().LocalVarData.find(
4743 cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
4744 ->getCanonicalDecl());
4745 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004746 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004747 }
4748 }
4749 return Address::invalid();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004750}
4751
4752void CGOpenMPRuntimeNVPTX::functionFinished(CodeGenFunction &CGF) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004753 FunctionGlobalizedDecls.erase(CGF.CurFn);
4754 CGOpenMPRuntime::functionFinished(CGF);
4755}
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004756
4757void CGOpenMPRuntimeNVPTX::getDefaultDistScheduleAndChunk(
4758 CodeGenFunction &CGF, const OMPLoopDirective &S,
4759 OpenMPDistScheduleClauseKind &ScheduleKind,
4760 llvm::Value *&Chunk) const {
4761 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
4762 ScheduleKind = OMPC_DIST_SCHEDULE_static;
4763 Chunk = CGF.EmitScalarConversion(getNVPTXNumThreads(CGF),
4764 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4765 S.getIterationVariable()->getType(), S.getBeginLoc());
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004766 return;
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004767 }
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004768 CGOpenMPRuntime::getDefaultDistScheduleAndChunk(
4769 CGF, S, ScheduleKind, Chunk);
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004770}
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004771
4772void CGOpenMPRuntimeNVPTX::getDefaultScheduleAndChunk(
4773 CodeGenFunction &CGF, const OMPLoopDirective &S,
4774 OpenMPScheduleClauseKind &ScheduleKind,
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004775 const Expr *&ChunkExpr) const {
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004776 ScheduleKind = OMPC_SCHEDULE_static;
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004777 // Chunk size is 1 in this case.
4778 llvm::APInt ChunkSize(32, 1);
4779 ChunkExpr = IntegerLiteral::Create(CGF.getContext(), ChunkSize,
4780 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4781 SourceLocation());
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004782}
Alexey Bataev60705422018-10-30 15:50:12 +00004783
4784void CGOpenMPRuntimeNVPTX::adjustTargetSpecificDataForLambdas(
4785 CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
4786 assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
4787 " Expected target-based directive.");
4788 const CapturedStmt *CS = D.getCapturedStmt(OMPD_target);
4789 for (const CapturedStmt::Capture &C : CS->captures()) {
4790 // Capture variables captured by reference in lambdas for target-based
4791 // directives.
4792 if (!C.capturesVariable())
4793 continue;
4794 const VarDecl *VD = C.getCapturedVar();
4795 const auto *RD = VD->getType()
4796 .getCanonicalType()
4797 .getNonReferenceType()
4798 ->getAsCXXRecordDecl();
4799 if (!RD || !RD->isLambda())
4800 continue;
4801 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4802 LValue VDLVal;
4803 if (VD->getType().getCanonicalType()->isReferenceType())
4804 VDLVal = CGF.EmitLoadOfReferenceLValue(VDAddr, VD->getType());
4805 else
4806 VDLVal = CGF.MakeAddrLValue(
4807 VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
4808 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4809 FieldDecl *ThisCapture = nullptr;
4810 RD->getCaptureFields(Captures, ThisCapture);
4811 if (ThisCapture && CGF.CapturedStmtInfo->isCXXThisExprCaptured()) {
4812 LValue ThisLVal =
4813 CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
4814 llvm::Value *CXXThis = CGF.LoadCXXThis();
4815 CGF.EmitStoreOfScalar(CXXThis, ThisLVal);
4816 }
4817 for (const LambdaCapture &LC : RD->captures()) {
4818 if (LC.getCaptureKind() != LCK_ByRef)
4819 continue;
4820 const VarDecl *VD = LC.getCapturedVar();
4821 if (!CS->capturesVariable(VD))
4822 continue;
4823 auto It = Captures.find(VD);
4824 assert(It != Captures.end() && "Found lambda capture without field.");
4825 LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
4826 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4827 if (VD->getType().getCanonicalType()->isReferenceType())
4828 VDAddr = CGF.EmitLoadOfReferenceLValue(VDAddr,
4829 VD->getType().getCanonicalType())
4830 .getAddress();
4831 CGF.EmitStoreOfScalar(VDAddr.getPointer(), VarLVal);
4832 }
4833 }
4834}
4835
Alexey Bataev1af5bd52019-03-05 17:47:18 +00004836unsigned CGOpenMPRuntimeNVPTX::getDefaultFirstprivateAddressSpace() const {
4837 return CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant);
4838}
4839
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004840// Get current CudaArch and ignore any unknown values
4841static CudaArch getCudaArch(CodeGenModule &CGM) {
4842 if (!CGM.getTarget().hasFeature("ptx"))
4843 return CudaArch::UNKNOWN;
4844 llvm::StringMap<bool> Features;
4845 CGM.getTarget().initFeatureMap(Features, CGM.getDiags(),
4846 CGM.getTarget().getTargetOpts().CPU,
4847 CGM.getTarget().getTargetOpts().Features);
4848 for (const auto &Feature : Features) {
4849 if (Feature.getValue()) {
4850 CudaArch Arch = StringToCudaArch(Feature.getKey());
4851 if (Arch != CudaArch::UNKNOWN)
4852 return Arch;
4853 }
4854 }
4855 return CudaArch::UNKNOWN;
4856}
4857
4858/// Check to see if target architecture supports unified addressing which is
4859/// a restriction for OpenMP requires clause "unified_shared_memory".
4860void CGOpenMPRuntimeNVPTX::checkArchForUnifiedAddressing(
4861 CodeGenModule &CGM, const OMPRequiresDecl *D) const {
4862 for (const OMPClause *Clause : D->clauselists()) {
4863 if (Clause->getClauseKind() == OMPC_unified_shared_memory) {
4864 switch (getCudaArch(CGM)) {
4865 case CudaArch::SM_20:
4866 case CudaArch::SM_21:
4867 case CudaArch::SM_30:
4868 case CudaArch::SM_32:
4869 case CudaArch::SM_35:
4870 case CudaArch::SM_37:
4871 case CudaArch::SM_50:
4872 case CudaArch::SM_52:
4873 case CudaArch::SM_53:
4874 case CudaArch::SM_60:
4875 case CudaArch::SM_61:
4876 case CudaArch::SM_62:
4877 CGM.Error(Clause->getBeginLoc(),
4878 "Target architecture does not support unified addressing");
4879 return;
4880 case CudaArch::SM_70:
4881 case CudaArch::SM_72:
4882 case CudaArch::SM_75:
4883 case CudaArch::GFX600:
4884 case CudaArch::GFX601:
4885 case CudaArch::GFX700:
4886 case CudaArch::GFX701:
4887 case CudaArch::GFX702:
4888 case CudaArch::GFX703:
4889 case CudaArch::GFX704:
4890 case CudaArch::GFX801:
4891 case CudaArch::GFX802:
4892 case CudaArch::GFX803:
4893 case CudaArch::GFX810:
4894 case CudaArch::GFX900:
4895 case CudaArch::GFX902:
4896 case CudaArch::GFX904:
4897 case CudaArch::GFX906:
4898 case CudaArch::GFX909:
4899 case CudaArch::UNKNOWN:
4900 break;
4901 case CudaArch::LAST:
4902 llvm_unreachable("Unexpected Cuda arch.");
4903 }
4904 }
4905 }
4906}
4907
Alexey Bataeve4090182018-11-02 14:54:07 +00004908/// Get number of SMs and number of blocks per SM.
4909static std::pair<unsigned, unsigned> getSMsBlocksPerSM(CodeGenModule &CGM) {
4910 std::pair<unsigned, unsigned> Data;
4911 if (CGM.getLangOpts().OpenMPCUDANumSMs)
4912 Data.first = CGM.getLangOpts().OpenMPCUDANumSMs;
4913 if (CGM.getLangOpts().OpenMPCUDABlocksPerSM)
4914 Data.second = CGM.getLangOpts().OpenMPCUDABlocksPerSM;
4915 if (Data.first && Data.second)
4916 return Data;
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004917 switch (getCudaArch(CGM)) {
4918 case CudaArch::SM_20:
4919 case CudaArch::SM_21:
4920 case CudaArch::SM_30:
4921 case CudaArch::SM_32:
4922 case CudaArch::SM_35:
4923 case CudaArch::SM_37:
4924 case CudaArch::SM_50:
4925 case CudaArch::SM_52:
4926 case CudaArch::SM_53:
4927 return {16, 16};
4928 case CudaArch::SM_60:
4929 case CudaArch::SM_61:
4930 case CudaArch::SM_62:
4931 return {56, 32};
4932 case CudaArch::SM_70:
4933 case CudaArch::SM_72:
4934 case CudaArch::SM_75:
4935 return {84, 32};
4936 case CudaArch::GFX600:
4937 case CudaArch::GFX601:
4938 case CudaArch::GFX700:
4939 case CudaArch::GFX701:
4940 case CudaArch::GFX702:
4941 case CudaArch::GFX703:
4942 case CudaArch::GFX704:
4943 case CudaArch::GFX801:
4944 case CudaArch::GFX802:
4945 case CudaArch::GFX803:
4946 case CudaArch::GFX810:
4947 case CudaArch::GFX900:
4948 case CudaArch::GFX902:
4949 case CudaArch::GFX904:
4950 case CudaArch::GFX906:
4951 case CudaArch::GFX909:
4952 case CudaArch::UNKNOWN:
4953 break;
4954 case CudaArch::LAST:
4955 llvm_unreachable("Unexpected Cuda arch.");
Alexey Bataeve4090182018-11-02 14:54:07 +00004956 }
4957 llvm_unreachable("Unexpected NVPTX target without ptx feature.");
4958}
4959
4960void CGOpenMPRuntimeNVPTX::clear() {
4961 if (!GlobalizedRecords.empty()) {
4962 ASTContext &C = CGM.getContext();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004963 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> GlobalRecs;
4964 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> SharedRecs;
Alexey Bataeve4090182018-11-02 14:54:07 +00004965 RecordDecl *StaticRD = C.buildImplicitRecord(
4966 "_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
4967 StaticRD->startDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004968 RecordDecl *SharedStaticRD = C.buildImplicitRecord(
4969 "_shared_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
4970 SharedStaticRD->startDefinition();
Alexey Bataeve4090182018-11-02 14:54:07 +00004971 for (const GlobalPtrSizeRecsTy &Records : GlobalizedRecords) {
4972 if (Records.Records.empty())
4973 continue;
4974 unsigned Size = 0;
4975 unsigned RecAlignment = 0;
4976 for (const RecordDecl *RD : Records.Records) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004977 QualType RDTy = C.getRecordType(RD);
4978 unsigned Alignment = C.getTypeAlignInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00004979 RecAlignment = std::max(RecAlignment, Alignment);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004980 unsigned RecSize = C.getTypeSizeInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00004981 Size =
4982 llvm::alignTo(llvm::alignTo(Size, Alignment) + RecSize, Alignment);
4983 }
4984 Size = llvm::alignTo(Size, RecAlignment);
4985 llvm::APInt ArySize(/*numBits=*/64, Size);
4986 QualType SubTy = C.getConstantArrayType(
4987 C.CharTy, ArySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004988 const bool UseSharedMemory = Size <= SharedMemorySize;
4989 auto *Field =
4990 FieldDecl::Create(C, UseSharedMemory ? SharedStaticRD : StaticRD,
4991 SourceLocation(), SourceLocation(), nullptr, SubTy,
4992 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
4993 /*BW=*/nullptr, /*Mutable=*/false,
4994 /*InitStyle=*/ICIS_NoInit);
Alexey Bataeve4090182018-11-02 14:54:07 +00004995 Field->setAccess(AS_public);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004996 if (UseSharedMemory) {
4997 SharedStaticRD->addDecl(Field);
4998 SharedRecs.push_back(&Records);
4999 } else {
5000 StaticRD->addDecl(Field);
5001 GlobalRecs.push_back(&Records);
5002 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005003 Records.RecSize->setInitializer(llvm::ConstantInt::get(CGM.SizeTy, Size));
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005004 Records.UseSharedMemory->setInitializer(
5005 llvm::ConstantInt::get(CGM.Int16Ty, UseSharedMemory ? 1 : 0));
5006 }
Alexey Bataev6a1b06b2018-12-18 21:01:42 +00005007 // Allocate SharedMemorySize buffer for the shared memory.
5008 // FIXME: nvlink does not handle weak linkage correctly (object with the
5009 // different size are reported as erroneous).
5010 // Restore this code as sson as nvlink is fixed.
5011 if (!SharedStaticRD->field_empty()) {
5012 llvm::APInt ArySize(/*numBits=*/64, SharedMemorySize);
5013 QualType SubTy = C.getConstantArrayType(
5014 C.CharTy, ArySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
5015 auto *Field = FieldDecl::Create(
5016 C, SharedStaticRD, SourceLocation(), SourceLocation(), nullptr, SubTy,
5017 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
5018 /*BW=*/nullptr, /*Mutable=*/false,
5019 /*InitStyle=*/ICIS_NoInit);
5020 Field->setAccess(AS_public);
5021 SharedStaticRD->addDecl(Field);
5022 }
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005023 SharedStaticRD->completeDefinition();
5024 if (!SharedStaticRD->field_empty()) {
5025 QualType StaticTy = C.getRecordType(SharedStaticRD);
5026 llvm::Type *LLVMStaticTy = CGM.getTypes().ConvertTypeForMem(StaticTy);
5027 auto *GV = new llvm::GlobalVariable(
5028 CGM.getModule(), LLVMStaticTy,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00005029 /*isConstant=*/false, llvm::GlobalValue::CommonLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005030 llvm::Constant::getNullValue(LLVMStaticTy),
5031 "_openmp_shared_static_glob_rd_$_", /*InsertBefore=*/nullptr,
5032 llvm::GlobalValue::NotThreadLocal,
5033 C.getTargetAddressSpace(LangAS::cuda_shared));
5034 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
5035 GV, CGM.VoidPtrTy);
5036 for (const GlobalPtrSizeRecsTy *Rec : SharedRecs) {
5037 Rec->Buffer->replaceAllUsesWith(Replacement);
5038 Rec->Buffer->eraseFromParent();
5039 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005040 }
5041 StaticRD->completeDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005042 if (!StaticRD->field_empty()) {
5043 QualType StaticTy = C.getRecordType(StaticRD);
5044 std::pair<unsigned, unsigned> SMsBlockPerSM = getSMsBlocksPerSM(CGM);
5045 llvm::APInt Size1(32, SMsBlockPerSM.second);
5046 QualType Arr1Ty =
5047 C.getConstantArrayType(StaticTy, Size1, ArrayType::Normal,
5048 /*IndexTypeQuals=*/0);
5049 llvm::APInt Size2(32, SMsBlockPerSM.first);
5050 QualType Arr2Ty = C.getConstantArrayType(Arr1Ty, Size2, ArrayType::Normal,
5051 /*IndexTypeQuals=*/0);
5052 llvm::Type *LLVMArr2Ty = CGM.getTypes().ConvertTypeForMem(Arr2Ty);
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005053 // FIXME: nvlink does not handle weak linkage correctly (object with the
5054 // different size are reported as erroneous).
5055 // Restore CommonLinkage as soon as nvlink is fixed.
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005056 auto *GV = new llvm::GlobalVariable(
5057 CGM.getModule(), LLVMArr2Ty,
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005058 /*isConstant=*/false, llvm::GlobalValue::InternalLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005059 llvm::Constant::getNullValue(LLVMArr2Ty),
5060 "_openmp_static_glob_rd_$_");
5061 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
5062 GV, CGM.VoidPtrTy);
5063 for (const GlobalPtrSizeRecsTy *Rec : GlobalRecs) {
5064 Rec->Buffer->replaceAllUsesWith(Replacement);
5065 Rec->Buffer->eraseFromParent();
5066 }
5067 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005068 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00005069 if (!TeamsReductions.empty()) {
5070 ASTContext &C = CGM.getContext();
5071 RecordDecl *StaticRD = C.buildImplicitRecord(
5072 "_openmp_teams_reduction_type_$_", RecordDecl::TagKind::TTK_Union);
5073 StaticRD->startDefinition();
5074 for (const RecordDecl *TeamReductionRec : TeamsReductions) {
5075 QualType RecTy = C.getRecordType(TeamReductionRec);
5076 auto *Field = FieldDecl::Create(
5077 C, StaticRD, SourceLocation(), SourceLocation(), nullptr, RecTy,
5078 C.getTrivialTypeSourceInfo(RecTy, SourceLocation()),
5079 /*BW=*/nullptr, /*Mutable=*/false,
5080 /*InitStyle=*/ICIS_NoInit);
5081 Field->setAccess(AS_public);
5082 StaticRD->addDecl(Field);
5083 }
5084 StaticRD->completeDefinition();
5085 QualType StaticTy = C.getRecordType(StaticRD);
5086 llvm::Type *LLVMReductionsBufferTy =
5087 CGM.getTypes().ConvertTypeForMem(StaticTy);
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005088 // FIXME: nvlink does not handle weak linkage correctly (object with the
5089 // different size are reported as erroneous).
5090 // Restore CommonLinkage as soon as nvlink is fixed.
Alexey Bataev8061acd2019-02-20 16:36:22 +00005091 auto *GV = new llvm::GlobalVariable(
5092 CGM.getModule(), LLVMReductionsBufferTy,
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005093 /*isConstant=*/false, llvm::GlobalValue::InternalLinkage,
Alexey Bataev8061acd2019-02-20 16:36:22 +00005094 llvm::Constant::getNullValue(LLVMReductionsBufferTy),
5095 "_openmp_teams_reductions_buffer_$_");
5096 KernelTeamsReductionPtr->setInitializer(
5097 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
5098 CGM.VoidPtrTy));
5099 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005100 CGOpenMPRuntime::clear();
5101}