blob: 8aa03deee7fdf005406d6bb892695912369b0c9b [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 +0000224
225static RecordDecl *buildRecordForGlobalizedVars(
226 ASTContext &C, ArrayRef<const ValueDecl *> EscapedDecls,
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000227 ArrayRef<const ValueDecl *> EscapedDeclsForTeams,
Alexey Bataev2adecff2018-09-21 14:22:53 +0000228 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
Alexey Bataev8061acd2019-02-20 16:36:22 +0000229 &MappedDeclsFields, int BufSize) {
Fangrui Song899d1392019-04-24 14:43:05 +0000230 using VarsDataTy = std::pair<CharUnits /*Align*/, const ValueDecl *>;
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000231 if (EscapedDecls.empty() && EscapedDeclsForTeams.empty())
Alexey Bataev2adecff2018-09-21 14:22:53 +0000232 return nullptr;
233 SmallVector<VarsDataTy, 4> GlobalizedVars;
234 for (const ValueDecl *D : EscapedDecls)
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000235 GlobalizedVars.emplace_back(
236 CharUnits::fromQuantity(std::max(
237 C.getDeclAlign(D).getQuantity(),
238 static_cast<CharUnits::QuantityType>(GlobalMemoryAlignment))),
239 D);
240 for (const ValueDecl *D : EscapedDeclsForTeams)
Alexey Bataev2adecff2018-09-21 14:22:53 +0000241 GlobalizedVars.emplace_back(C.getDeclAlign(D), D);
Fangrui Song899d1392019-04-24 14:43:05 +0000242 llvm::stable_sort(GlobalizedVars, [](VarsDataTy L, VarsDataTy R) {
243 return L.first > R.first;
244 });
245
Alexey Bataev2adecff2018-09-21 14:22:53 +0000246 // Build struct _globalized_locals_ty {
Alexey Bataevff23bb62018-10-11 18:30:31 +0000247 // /* globalized vars */[WarSize] align (max(decl_align,
248 // GlobalMemoryAlignment))
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000249 // /* globalized vars */ for EscapedDeclsForTeams
Alexey Bataev2adecff2018-09-21 14:22:53 +0000250 // };
251 RecordDecl *GlobalizedRD = C.buildImplicitRecord("_globalized_locals_ty");
252 GlobalizedRD->startDefinition();
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000253 llvm::SmallPtrSet<const ValueDecl *, 16> SingleEscaped(
254 EscapedDeclsForTeams.begin(), EscapedDeclsForTeams.end());
Alexey Bataev2adecff2018-09-21 14:22:53 +0000255 for (const auto &Pair : GlobalizedVars) {
256 const ValueDecl *VD = Pair.second;
257 QualType Type = VD->getType();
258 if (Type->isLValueReferenceType())
259 Type = C.getPointerType(Type.getNonReferenceType());
260 else
261 Type = Type.getNonReferenceType();
262 SourceLocation Loc = VD->getLocation();
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000263 FieldDecl *Field;
264 if (SingleEscaped.count(VD)) {
265 Field = FieldDecl::Create(
266 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
267 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
268 /*BW=*/nullptr, /*Mutable=*/false,
269 /*InitStyle=*/ICIS_NoInit);
270 Field->setAccess(AS_public);
271 if (VD->hasAttrs()) {
272 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
273 E(VD->getAttrs().end());
274 I != E; ++I)
275 Field->addAttr(*I);
276 }
277 } else {
Alexey Bataev8061acd2019-02-20 16:36:22 +0000278 llvm::APInt ArraySize(32, BufSize);
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000279 Type = C.getConstantArrayType(Type, ArraySize, ArrayType::Normal, 0);
280 Field = FieldDecl::Create(
281 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
282 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
283 /*BW=*/nullptr, /*Mutable=*/false,
284 /*InitStyle=*/ICIS_NoInit);
285 Field->setAccess(AS_public);
286 llvm::APInt Align(32, std::max(C.getDeclAlign(VD).getQuantity(),
287 static_cast<CharUnits::QuantityType>(
288 GlobalMemoryAlignment)));
289 Field->addAttr(AlignedAttr::CreateImplicit(
290 C, AlignedAttr::GNU_aligned, /*IsAlignmentExpr=*/true,
291 IntegerLiteral::Create(C, Align,
292 C.getIntTypeForBitwidth(32, /*Signed=*/0),
293 SourceLocation())));
Alexey Bataev2adecff2018-09-21 14:22:53 +0000294 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000295 GlobalizedRD->addDecl(Field);
Alexey Bataev2adecff2018-09-21 14:22:53 +0000296 MappedDeclsFields.try_emplace(VD, Field);
297 }
298 GlobalizedRD->completeDefinition();
299 return GlobalizedRD;
300}
301
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000302/// Get the list of variables that can escape their declaration context.
303class CheckVarsEscapingDeclContext final
304 : public ConstStmtVisitor<CheckVarsEscapingDeclContext> {
305 CodeGenFunction &CGF;
306 llvm::SetVector<const ValueDecl *> EscapedDecls;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000307 llvm::SetVector<const ValueDecl *> EscapedVariableLengthDecls;
Alexey Bataevc99042b2018-03-15 18:10:54 +0000308 llvm::SmallPtrSet<const Decl *, 4> EscapedParameters;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000309 RecordDecl *GlobalizedRD = nullptr;
310 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000311 bool AllEscaped = false;
Alexey Bataev91433f62018-06-26 17:24:03 +0000312 bool IsForCombinedParallelRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000313
314 void markAsEscaped(const ValueDecl *VD) {
Alexey Bataev03f270c2018-03-30 18:31:07 +0000315 // Do not globalize declare target variables.
Alexey Bataev97b72212018-08-14 18:31:20 +0000316 if (!isa<VarDecl>(VD) ||
317 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataev03f270c2018-03-30 18:31:07 +0000318 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000319 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataev1db9bfe2019-04-08 16:53:57 +0000320 // Use user-specified allocation.
321 if (VD->hasAttrs() && VD->hasAttr<OMPAllocateDeclAttr>())
322 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +0000323 // Variables captured by value must be globalized.
324 if (auto *CSI = CGF.CapturedStmtInfo) {
Mikael Holmen9f373a32018-03-16 07:27:57 +0000325 if (const FieldDecl *FD = CSI->lookup(cast<VarDecl>(VD))) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000326 // Check if need to capture the variable that was already captured by
327 // value in the outer region.
Alexey Bataev91433f62018-06-26 17:24:03 +0000328 if (!IsForCombinedParallelRegion) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000329 if (!FD->hasAttrs())
330 return;
331 const auto *Attr = FD->getAttr<OMPCaptureKindAttr>();
332 if (!Attr)
333 return;
Alexey Bataev6393eb72018-12-06 15:35:13 +0000334 if (((Attr->getCaptureKind() != OMPC_map) &&
335 !isOpenMPPrivate(
336 static_cast<OpenMPClauseKind>(Attr->getCaptureKind()))) ||
337 ((Attr->getCaptureKind() == OMPC_map) &&
338 !FD->getType()->isAnyPointerType()))
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000339 return;
340 }
341 if (!FD->getType()->isReferenceType()) {
342 assert(!VD->getType()->isVariablyModifiedType() &&
343 "Parameter captured by value with variably modified type");
344 EscapedParameters.insert(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000345 } else if (!IsForCombinedParallelRegion) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000346 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000347 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000348 }
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000349 }
350 if ((!CGF.CapturedStmtInfo ||
Alexey Bataev91433f62018-06-26 17:24:03 +0000351 (IsForCombinedParallelRegion && CGF.CapturedStmtInfo)) &&
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000352 VD->getType()->isReferenceType())
353 // Do not globalize variables with reference type.
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000354 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000355 if (VD->getType()->isVariablyModifiedType())
356 EscapedVariableLengthDecls.insert(VD);
357 else
358 EscapedDecls.insert(VD);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000359 }
360
361 void VisitValueDecl(const ValueDecl *VD) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000362 if (VD->getType()->isLValueReferenceType())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000363 markAsEscaped(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000364 if (const auto *VarD = dyn_cast<VarDecl>(VD)) {
365 if (!isa<ParmVarDecl>(VarD) && VarD->hasInit()) {
366 const bool SavedAllEscaped = AllEscaped;
367 AllEscaped = VD->getType()->isLValueReferenceType();
368 Visit(VarD->getInit());
369 AllEscaped = SavedAllEscaped;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000370 }
371 }
372 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000373 void VisitOpenMPCapturedStmt(const CapturedStmt *S,
374 ArrayRef<OMPClause *> Clauses,
375 bool IsCombinedParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000376 if (!S)
377 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000378 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000379 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
380 const ValueDecl *VD = C.getCapturedVar();
Alexey Bataev91433f62018-06-26 17:24:03 +0000381 bool SavedIsForCombinedParallelRegion = IsForCombinedParallelRegion;
382 if (IsCombinedParallelRegion) {
383 // Check if the variable is privatized in the combined construct and
384 // those private copies must be shared in the inner parallel
385 // directive.
386 IsForCombinedParallelRegion = false;
387 for (const OMPClause *C : Clauses) {
388 if (!isOpenMPPrivate(C->getClauseKind()) ||
389 C->getClauseKind() == OMPC_reduction ||
390 C->getClauseKind() == OMPC_linear ||
391 C->getClauseKind() == OMPC_private)
392 continue;
393 ArrayRef<const Expr *> Vars;
394 if (const auto *PC = dyn_cast<OMPFirstprivateClause>(C))
395 Vars = PC->getVarRefs();
396 else if (const auto *PC = dyn_cast<OMPLastprivateClause>(C))
397 Vars = PC->getVarRefs();
398 else
399 llvm_unreachable("Unexpected clause.");
400 for (const auto *E : Vars) {
401 const Decl *D =
402 cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
403 if (D == VD->getCanonicalDecl()) {
404 IsForCombinedParallelRegion = true;
405 break;
406 }
407 }
408 if (IsForCombinedParallelRegion)
409 break;
410 }
411 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000412 markAsEscaped(VD);
413 if (isa<OMPCapturedExprDecl>(VD))
414 VisitValueDecl(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000415 IsForCombinedParallelRegion = SavedIsForCombinedParallelRegion;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000416 }
417 }
418 }
419
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000420 void buildRecordForGlobalizedVars(bool IsInTTDRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000421 assert(!GlobalizedRD &&
422 "Record for globalized variables is built already.");
Alexey Bataevff23bb62018-10-11 18:30:31 +0000423 ArrayRef<const ValueDecl *> EscapedDeclsForParallel, EscapedDeclsForTeams;
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000424 if (IsInTTDRegion)
Alexey Bataevff23bb62018-10-11 18:30:31 +0000425 EscapedDeclsForTeams = EscapedDecls.getArrayRef();
426 else
427 EscapedDeclsForParallel = EscapedDecls.getArrayRef();
Alexey Bataev2adecff2018-09-21 14:22:53 +0000428 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataevff23bb62018-10-11 18:30:31 +0000429 CGF.getContext(), EscapedDeclsForParallel, EscapedDeclsForTeams,
Alexey Bataev8061acd2019-02-20 16:36:22 +0000430 MappedDeclsFields, WarpSize);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000431 }
432
433public:
Alexey Bataevf2f39be2018-11-16 19:38:21 +0000434 CheckVarsEscapingDeclContext(CodeGenFunction &CGF,
435 ArrayRef<const ValueDecl *> TeamsReductions)
436 : CGF(CGF), EscapedDecls(TeamsReductions.begin(), TeamsReductions.end()) {
437 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000438 virtual ~CheckVarsEscapingDeclContext() = default;
439 void VisitDeclStmt(const DeclStmt *S) {
440 if (!S)
441 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000442 for (const Decl *D : S->decls())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000443 if (const auto *VD = dyn_cast_or_null<ValueDecl>(D))
444 VisitValueDecl(VD);
445 }
446 void VisitOMPExecutableDirective(const OMPExecutableDirective *D) {
447 if (!D)
448 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000449 if (!D->hasAssociatedStmt())
450 return;
451 if (const auto *S =
452 dyn_cast_or_null<CapturedStmt>(D->getAssociatedStmt())) {
453 // Do not analyze directives that do not actually require capturing,
454 // like `omp for` or `omp simd` directives.
455 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
456 getOpenMPCaptureRegions(CaptureRegions, D->getDirectiveKind());
457 if (CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown) {
458 VisitStmt(S->getCapturedStmt());
459 return;
Alexey Bataev673110d2018-05-16 13:36:30 +0000460 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000461 VisitOpenMPCapturedStmt(
462 S, D->clauses(),
463 CaptureRegions.back() == OMPD_parallel &&
464 isOpenMPDistributeDirective(D->getDirectiveKind()));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000465 }
466 }
467 void VisitCapturedStmt(const CapturedStmt *S) {
468 if (!S)
469 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000470 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000471 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
472 const ValueDecl *VD = C.getCapturedVar();
473 markAsEscaped(VD);
474 if (isa<OMPCapturedExprDecl>(VD))
475 VisitValueDecl(VD);
476 }
477 }
478 }
479 void VisitLambdaExpr(const LambdaExpr *E) {
480 if (!E)
481 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000482 for (const LambdaCapture &C : E->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000483 if (C.capturesVariable()) {
484 if (C.getCaptureKind() == LCK_ByRef) {
485 const ValueDecl *VD = C.getCapturedVar();
486 markAsEscaped(VD);
487 if (E->isInitCapture(&C) || isa<OMPCapturedExprDecl>(VD))
488 VisitValueDecl(VD);
489 }
490 }
491 }
492 }
493 void VisitBlockExpr(const BlockExpr *E) {
494 if (!E)
495 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000496 for (const BlockDecl::Capture &C : E->getBlockDecl()->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000497 if (C.isByRef()) {
498 const VarDecl *VD = C.getVariable();
499 markAsEscaped(VD);
500 if (isa<OMPCapturedExprDecl>(VD) || VD->isInitCapture())
501 VisitValueDecl(VD);
502 }
503 }
504 }
505 void VisitCallExpr(const CallExpr *E) {
506 if (!E)
507 return;
508 for (const Expr *Arg : E->arguments()) {
509 if (!Arg)
510 continue;
511 if (Arg->isLValue()) {
512 const bool SavedAllEscaped = AllEscaped;
513 AllEscaped = true;
514 Visit(Arg);
515 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000516 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000517 Visit(Arg);
Alexey Bataev9ff80832018-04-16 20:16:21 +0000518 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000519 }
520 Visit(E->getCallee());
521 }
522 void VisitDeclRefExpr(const DeclRefExpr *E) {
523 if (!E)
524 return;
525 const ValueDecl *VD = E->getDecl();
526 if (AllEscaped)
527 markAsEscaped(VD);
528 if (isa<OMPCapturedExprDecl>(VD))
529 VisitValueDecl(VD);
530 else if (const auto *VarD = dyn_cast<VarDecl>(VD))
531 if (VarD->isInitCapture())
532 VisitValueDecl(VD);
533 }
534 void VisitUnaryOperator(const UnaryOperator *E) {
535 if (!E)
536 return;
537 if (E->getOpcode() == UO_AddrOf) {
538 const bool SavedAllEscaped = AllEscaped;
539 AllEscaped = true;
540 Visit(E->getSubExpr());
541 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000542 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000543 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000544 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000545 }
546 void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
547 if (!E)
548 return;
549 if (E->getCastKind() == CK_ArrayToPointerDecay) {
550 const bool SavedAllEscaped = AllEscaped;
551 AllEscaped = true;
552 Visit(E->getSubExpr());
553 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000554 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000555 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000556 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000557 }
558 void VisitExpr(const Expr *E) {
559 if (!E)
560 return;
561 bool SavedAllEscaped = AllEscaped;
562 if (!E->isLValue())
563 AllEscaped = false;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000564 for (const Stmt *Child : E->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000565 if (Child)
566 Visit(Child);
567 AllEscaped = SavedAllEscaped;
568 }
569 void VisitStmt(const Stmt *S) {
570 if (!S)
571 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000572 for (const Stmt *Child : S->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000573 if (Child)
574 Visit(Child);
575 }
576
Alexey Bataevc99042b2018-03-15 18:10:54 +0000577 /// Returns the record that handles all the escaped local variables and used
578 /// instead of their original storage.
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000579 const RecordDecl *getGlobalizedRecord(bool IsInTTDRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000580 if (!GlobalizedRD)
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000581 buildRecordForGlobalizedVars(IsInTTDRegion);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000582 return GlobalizedRD;
583 }
584
Alexey Bataevc99042b2018-03-15 18:10:54 +0000585 /// Returns the field in the globalized record for the escaped variable.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000586 const FieldDecl *getFieldForGlobalizedVar(const ValueDecl *VD) const {
587 assert(GlobalizedRD &&
588 "Record for globalized variables must be generated already.");
589 auto I = MappedDeclsFields.find(VD);
590 if (I == MappedDeclsFields.end())
591 return nullptr;
592 return I->getSecond();
593 }
594
Alexey Bataevc99042b2018-03-15 18:10:54 +0000595 /// Returns the list of the escaped local variables/parameters.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000596 ArrayRef<const ValueDecl *> getEscapedDecls() const {
597 return EscapedDecls.getArrayRef();
598 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000599
600 /// Checks if the escaped local variable is actually a parameter passed by
601 /// value.
602 const llvm::SmallPtrSetImpl<const Decl *> &getEscapedParameters() const {
603 return EscapedParameters;
604 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000605
606 /// Returns the list of the escaped variables with the variably modified
607 /// types.
608 ArrayRef<const ValueDecl *> getEscapedVariableLengthDecls() const {
609 return EscapedVariableLengthDecls.getArrayRef();
610 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000611};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000612} // anonymous namespace
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000613
614/// Get the GPU warp size.
615static llvm::Value *getNVPTXWarpSize(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000616 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000617 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000618 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_warpsize),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000619 "nvptx_warp_size");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000620}
621
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000622/// Get the id of the current thread on the GPU.
623static llvm::Value *getNVPTXThreadID(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000624 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000625 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000626 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_tid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000627 "nvptx_tid");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000628}
629
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000630/// Get the id of the warp in the block.
631/// We assume that the warp size is 32, which is always the case
632/// on the NVPTX device, to generate more efficient code.
633static llvm::Value *getNVPTXWarpID(CodeGenFunction &CGF) {
634 CGBuilderTy &Bld = CGF.Builder;
635 return Bld.CreateAShr(getNVPTXThreadID(CGF), LaneIDBits, "nvptx_warp_id");
636}
637
638/// Get the id of the current lane in the Warp.
639/// We assume that the warp size is 32, which is always the case
640/// on the NVPTX device, to generate more efficient code.
641static llvm::Value *getNVPTXLaneID(CodeGenFunction &CGF) {
642 CGBuilderTy &Bld = CGF.Builder;
643 return Bld.CreateAnd(getNVPTXThreadID(CGF), Bld.getInt32(LaneIDMask),
644 "nvptx_lane_id");
645}
646
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000647/// Get the maximum number of threads in a block of the GPU.
648static llvm::Value *getNVPTXNumThreads(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000649 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000650 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000651 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_ntid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000652 "nvptx_num_threads");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000653}
654
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000655/// Get the value of the thread_limit clause in the teams directive.
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000656/// For the 'generic' execution mode, the runtime encodes thread_limit in
657/// the launch parameters, always starting thread_limit+warpSize threads per
658/// CTA. The threads in the last warp are reserved for master execution.
659/// For the 'spmd' execution mode, all threads in a CTA are part of the team.
660static llvm::Value *getThreadLimit(CodeGenFunction &CGF,
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000661 bool IsInSPMDExecutionMode = false) {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000662 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000663 return IsInSPMDExecutionMode
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000664 ? getNVPTXNumThreads(CGF)
Alexey Bataeve290ec02018-04-06 16:03:36 +0000665 : Bld.CreateNUWSub(getNVPTXNumThreads(CGF), getNVPTXWarpSize(CGF),
666 "thread_limit");
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000667}
668
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000669/// Get the thread id of the OMP master thread.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000670/// The master thread id is the first thread (lane) of the last warp in the
671/// GPU block. Warp size is assumed to be some power of 2.
672/// Thread id is 0 indexed.
673/// E.g: If NumThreads is 33, master id is 32.
674/// If NumThreads is 64, master id is 32.
675/// If NumThreads is 1024, master id is 992.
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000676static llvm::Value *getMasterThreadID(CodeGenFunction &CGF) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000677 CGBuilderTy &Bld = CGF.Builder;
678 llvm::Value *NumThreads = getNVPTXNumThreads(CGF);
679
680 // We assume that the warp size is a power of 2.
Alexey Bataeve290ec02018-04-06 16:03:36 +0000681 llvm::Value *Mask = Bld.CreateNUWSub(getNVPTXWarpSize(CGF), Bld.getInt32(1));
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000682
Alexey Bataeve290ec02018-04-06 16:03:36 +0000683 return Bld.CreateAnd(Bld.CreateNUWSub(NumThreads, Bld.getInt32(1)),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000684 Bld.CreateNot(Mask), "master_tid");
685}
686
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000687CGOpenMPRuntimeNVPTX::WorkerFunctionState::WorkerFunctionState(
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000688 CodeGenModule &CGM, SourceLocation Loc)
Alexey Bataev9ff80832018-04-16 20:16:21 +0000689 : WorkerFn(nullptr), CGFI(CGM.getTypes().arrangeNullaryFunction()),
690 Loc(Loc) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000691 createWorkerFunction(CGM);
Vasileios Kalintirise5c09592016-03-22 10:41:20 +0000692}
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000693
694void CGOpenMPRuntimeNVPTX::WorkerFunctionState::createWorkerFunction(
695 CodeGenModule &CGM) {
696 // Create an worker function with no arguments.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000697
698 WorkerFn = llvm::Function::Create(
Alexey Bataev9ff80832018-04-16 20:16:21 +0000699 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataevaee93892018-01-08 20:09:47 +0000700 /*placeholder=*/"_worker", &CGM.getModule());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000701 CGM.SetInternalFunctionAttributes(GlobalDecl(), WorkerFn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +0000702 WorkerFn->setDoesNotRecurse();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000703}
704
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000705CGOpenMPRuntimeNVPTX::ExecutionMode
706CGOpenMPRuntimeNVPTX::getExecutionMode() const {
707 return CurrentExecutionMode;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000708}
709
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000710static CGOpenMPRuntimeNVPTX::DataSharingMode
711getDataSharingMode(CodeGenModule &CGM) {
712 return CGM.getLangOpts().OpenMPCUDAMode ? CGOpenMPRuntimeNVPTX::CUDA
713 : CGOpenMPRuntimeNVPTX::Generic;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000714}
715
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000716/// Check for inner (nested) SPMD construct, if any
717static bool hasNestedSPMDDirective(ASTContext &Ctx,
718 const OMPExecutableDirective &D) {
719 const auto *CS = D.getInnermostCapturedStmt();
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000720 const auto *Body =
721 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5c427362019-04-10 19:11:33 +0000722 const Stmt *ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000723
Alexey Bataev5c427362019-04-10 19:11:33 +0000724 if (const auto *NestedDir =
725 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000726 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000727 switch (D.getDirectiveKind()) {
728 case OMPD_target:
Alexey Bataevdc9e7dc2019-04-17 16:53:08 +0000729 if (isOpenMPParallelDirective(DKind))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000730 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000731 if (DKind == OMPD_teams) {
732 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
733 /*IgnoreCaptured=*/true);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000734 if (!Body)
735 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000736 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
737 if (const auto *NND =
738 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000739 DKind = NND->getDirectiveKind();
Alexey Bataevdc9e7dc2019-04-17 16:53:08 +0000740 if (isOpenMPParallelDirective(DKind))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000741 return true;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000742 }
743 }
744 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000745 case OMPD_target_teams:
Alexey Bataevdc9e7dc2019-04-17 16:53:08 +0000746 return isOpenMPParallelDirective(DKind);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000747 case OMPD_target_simd:
748 case OMPD_target_parallel:
749 case OMPD_target_parallel_for:
750 case OMPD_target_parallel_for_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000751 case OMPD_target_teams_distribute:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000752 case OMPD_target_teams_distribute_simd:
753 case OMPD_target_teams_distribute_parallel_for:
754 case OMPD_target_teams_distribute_parallel_for_simd:
755 case OMPD_parallel:
756 case OMPD_for:
757 case OMPD_parallel_for:
758 case OMPD_parallel_sections:
759 case OMPD_for_simd:
760 case OMPD_parallel_for_simd:
761 case OMPD_cancel:
762 case OMPD_cancellation_point:
763 case OMPD_ordered:
764 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +0000765 case OMPD_allocate:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000766 case OMPD_task:
767 case OMPD_simd:
768 case OMPD_sections:
769 case OMPD_section:
770 case OMPD_single:
771 case OMPD_master:
772 case OMPD_critical:
773 case OMPD_taskyield:
774 case OMPD_barrier:
775 case OMPD_taskwait:
776 case OMPD_taskgroup:
777 case OMPD_atomic:
778 case OMPD_flush:
779 case OMPD_teams:
780 case OMPD_target_data:
781 case OMPD_target_exit_data:
782 case OMPD_target_enter_data:
783 case OMPD_distribute:
784 case OMPD_distribute_simd:
785 case OMPD_distribute_parallel_for:
786 case OMPD_distribute_parallel_for_simd:
787 case OMPD_teams_distribute:
788 case OMPD_teams_distribute_simd:
789 case OMPD_teams_distribute_parallel_for:
790 case OMPD_teams_distribute_parallel_for_simd:
791 case OMPD_target_update:
792 case OMPD_declare_simd:
793 case OMPD_declare_target:
794 case OMPD_end_declare_target:
795 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +0000796 case OMPD_declare_mapper:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000797 case OMPD_taskloop:
798 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000799 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000800 case OMPD_unknown:
801 llvm_unreachable("Unexpected directive.");
802 }
803 }
804
805 return false;
806}
807
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000808static bool supportsSPMDExecutionMode(ASTContext &Ctx,
809 const OMPExecutableDirective &D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000810 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
811 switch (DirectiveKind) {
812 case OMPD_target:
813 case OMPD_target_teams:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000814 return hasNestedSPMDDirective(Ctx, D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000815 case OMPD_target_parallel:
816 case OMPD_target_parallel_for:
817 case OMPD_target_parallel_for_simd:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000818 case OMPD_target_teams_distribute_parallel_for:
819 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000820 case OMPD_target_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000821 case OMPD_target_teams_distribute_simd:
Alexey Bataevdc9e7dc2019-04-17 16:53:08 +0000822 return true;
823 case OMPD_target_teams_distribute:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000824 return false;
825 case OMPD_parallel:
826 case OMPD_for:
827 case OMPD_parallel_for:
828 case OMPD_parallel_sections:
829 case OMPD_for_simd:
830 case OMPD_parallel_for_simd:
831 case OMPD_cancel:
832 case OMPD_cancellation_point:
833 case OMPD_ordered:
834 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +0000835 case OMPD_allocate:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000836 case OMPD_task:
837 case OMPD_simd:
838 case OMPD_sections:
839 case OMPD_section:
840 case OMPD_single:
841 case OMPD_master:
842 case OMPD_critical:
843 case OMPD_taskyield:
844 case OMPD_barrier:
845 case OMPD_taskwait:
846 case OMPD_taskgroup:
847 case OMPD_atomic:
848 case OMPD_flush:
849 case OMPD_teams:
850 case OMPD_target_data:
851 case OMPD_target_exit_data:
852 case OMPD_target_enter_data:
853 case OMPD_distribute:
854 case OMPD_distribute_simd:
855 case OMPD_distribute_parallel_for:
856 case OMPD_distribute_parallel_for_simd:
857 case OMPD_teams_distribute:
858 case OMPD_teams_distribute_simd:
859 case OMPD_teams_distribute_parallel_for:
860 case OMPD_teams_distribute_parallel_for_simd:
861 case OMPD_target_update:
862 case OMPD_declare_simd:
863 case OMPD_declare_target:
864 case OMPD_end_declare_target:
865 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +0000866 case OMPD_declare_mapper:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000867 case OMPD_taskloop:
868 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000869 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000870 case OMPD_unknown:
871 break;
872 }
873 llvm_unreachable(
874 "Unknown programming model for OpenMP directive on NVPTX target.");
875}
876
877/// Check if the directive is loops based and has schedule clause at all or has
878/// static scheduling.
879static bool hasStaticScheduling(const OMPExecutableDirective &D) {
880 assert(isOpenMPWorksharingDirective(D.getDirectiveKind()) &&
881 isOpenMPLoopDirective(D.getDirectiveKind()) &&
882 "Expected loop-based directive.");
883 return !D.hasClausesOfKind<OMPOrderedClause>() &&
884 (!D.hasClausesOfKind<OMPScheduleClause>() ||
885 llvm::any_of(D.getClausesOfKind<OMPScheduleClause>(),
886 [](const OMPScheduleClause *C) {
887 return C->getScheduleKind() == OMPC_SCHEDULE_static;
888 }));
889}
890
891/// Check for inner (nested) lightweight runtime construct, if any
892static bool hasNestedLightweightDirective(ASTContext &Ctx,
893 const OMPExecutableDirective &D) {
894 assert(supportsSPMDExecutionMode(Ctx, D) && "Expected SPMD mode directive.");
895 const auto *CS = D.getInnermostCapturedStmt();
896 const auto *Body =
897 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5c427362019-04-10 19:11:33 +0000898 const Stmt *ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000899
Alexey Bataev5c427362019-04-10 19:11:33 +0000900 if (const auto *NestedDir =
901 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000902 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
903 switch (D.getDirectiveKind()) {
904 case OMPD_target:
905 if (isOpenMPParallelDirective(DKind) &&
906 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
907 hasStaticScheduling(*NestedDir))
908 return true;
Alexey Bataev1472e322019-04-19 16:48:38 +0000909 if (DKind == OMPD_teams_distribute_simd || DKind == OMPD_simd)
910 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000911 if (DKind == OMPD_parallel) {
912 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
913 /*IgnoreCaptured=*/true);
914 if (!Body)
915 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000916 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
917 if (const auto *NND =
918 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000919 DKind = NND->getDirectiveKind();
920 if (isOpenMPWorksharingDirective(DKind) &&
921 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
922 return true;
923 }
924 } else if (DKind == OMPD_teams) {
925 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
926 /*IgnoreCaptured=*/true);
927 if (!Body)
928 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000929 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
930 if (const auto *NND =
931 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000932 DKind = NND->getDirectiveKind();
933 if (isOpenMPParallelDirective(DKind) &&
934 isOpenMPWorksharingDirective(DKind) &&
935 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
936 return true;
937 if (DKind == OMPD_parallel) {
938 Body = NND->getInnermostCapturedStmt()->IgnoreContainers(
939 /*IgnoreCaptured=*/true);
940 if (!Body)
941 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000942 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
943 if (const auto *NND =
944 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000945 DKind = NND->getDirectiveKind();
946 if (isOpenMPWorksharingDirective(DKind) &&
947 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
948 return true;
949 }
950 }
951 }
952 }
953 return false;
954 case OMPD_target_teams:
955 if (isOpenMPParallelDirective(DKind) &&
956 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
957 hasStaticScheduling(*NestedDir))
958 return true;
Alexey Bataev1472e322019-04-19 16:48:38 +0000959 if (DKind == OMPD_distribute_simd || DKind == OMPD_simd)
960 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000961 if (DKind == OMPD_parallel) {
962 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
963 /*IgnoreCaptured=*/true);
964 if (!Body)
965 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000966 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
967 if (const auto *NND =
968 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000969 DKind = NND->getDirectiveKind();
970 if (isOpenMPWorksharingDirective(DKind) &&
971 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
972 return true;
973 }
974 }
975 return false;
976 case OMPD_target_parallel:
Alexey Bataev1472e322019-04-19 16:48:38 +0000977 if (DKind == OMPD_simd)
978 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000979 return isOpenMPWorksharingDirective(DKind) &&
980 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NestedDir);
981 case OMPD_target_teams_distribute:
982 case OMPD_target_simd:
983 case OMPD_target_parallel_for:
984 case OMPD_target_parallel_for_simd:
985 case OMPD_target_teams_distribute_simd:
986 case OMPD_target_teams_distribute_parallel_for:
987 case OMPD_target_teams_distribute_parallel_for_simd:
988 case OMPD_parallel:
989 case OMPD_for:
990 case OMPD_parallel_for:
991 case OMPD_parallel_sections:
992 case OMPD_for_simd:
993 case OMPD_parallel_for_simd:
994 case OMPD_cancel:
995 case OMPD_cancellation_point:
996 case OMPD_ordered:
997 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +0000998 case OMPD_allocate:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000999 case OMPD_task:
1000 case OMPD_simd:
1001 case OMPD_sections:
1002 case OMPD_section:
1003 case OMPD_single:
1004 case OMPD_master:
1005 case OMPD_critical:
1006 case OMPD_taskyield:
1007 case OMPD_barrier:
1008 case OMPD_taskwait:
1009 case OMPD_taskgroup:
1010 case OMPD_atomic:
1011 case OMPD_flush:
1012 case OMPD_teams:
1013 case OMPD_target_data:
1014 case OMPD_target_exit_data:
1015 case OMPD_target_enter_data:
1016 case OMPD_distribute:
1017 case OMPD_distribute_simd:
1018 case OMPD_distribute_parallel_for:
1019 case OMPD_distribute_parallel_for_simd:
1020 case OMPD_teams_distribute:
1021 case OMPD_teams_distribute_simd:
1022 case OMPD_teams_distribute_parallel_for:
1023 case OMPD_teams_distribute_parallel_for_simd:
1024 case OMPD_target_update:
1025 case OMPD_declare_simd:
1026 case OMPD_declare_target:
1027 case OMPD_end_declare_target:
1028 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00001029 case OMPD_declare_mapper:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001030 case OMPD_taskloop:
1031 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001032 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001033 case OMPD_unknown:
1034 llvm_unreachable("Unexpected directive.");
1035 }
1036 }
1037
1038 return false;
1039}
1040
1041/// Checks if the construct supports lightweight runtime. It must be SPMD
1042/// construct + inner loop-based construct with static scheduling.
1043static bool supportsLightweightRuntime(ASTContext &Ctx,
1044 const OMPExecutableDirective &D) {
1045 if (!supportsSPMDExecutionMode(Ctx, D))
1046 return false;
1047 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
1048 switch (DirectiveKind) {
1049 case OMPD_target:
1050 case OMPD_target_teams:
1051 case OMPD_target_parallel:
1052 return hasNestedLightweightDirective(Ctx, D);
1053 case OMPD_target_parallel_for:
1054 case OMPD_target_parallel_for_simd:
1055 case OMPD_target_teams_distribute_parallel_for:
1056 case OMPD_target_teams_distribute_parallel_for_simd:
1057 // (Last|First)-privates must be shared in parallel region.
1058 return hasStaticScheduling(D);
1059 case OMPD_target_simd:
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001060 case OMPD_target_teams_distribute_simd:
Alexey Bataev1472e322019-04-19 16:48:38 +00001061 return true;
1062 case OMPD_target_teams_distribute:
Alexey Bataevdf093e72018-05-11 19:45:14 +00001063 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001064 case OMPD_parallel:
1065 case OMPD_for:
1066 case OMPD_parallel_for:
1067 case OMPD_parallel_sections:
1068 case OMPD_for_simd:
1069 case OMPD_parallel_for_simd:
1070 case OMPD_cancel:
1071 case OMPD_cancellation_point:
1072 case OMPD_ordered:
1073 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00001074 case OMPD_allocate:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001075 case OMPD_task:
1076 case OMPD_simd:
1077 case OMPD_sections:
1078 case OMPD_section:
1079 case OMPD_single:
1080 case OMPD_master:
1081 case OMPD_critical:
1082 case OMPD_taskyield:
1083 case OMPD_barrier:
1084 case OMPD_taskwait:
1085 case OMPD_taskgroup:
1086 case OMPD_atomic:
1087 case OMPD_flush:
1088 case OMPD_teams:
1089 case OMPD_target_data:
1090 case OMPD_target_exit_data:
1091 case OMPD_target_enter_data:
1092 case OMPD_distribute:
1093 case OMPD_distribute_simd:
1094 case OMPD_distribute_parallel_for:
1095 case OMPD_distribute_parallel_for_simd:
1096 case OMPD_teams_distribute:
1097 case OMPD_teams_distribute_simd:
1098 case OMPD_teams_distribute_parallel_for:
1099 case OMPD_teams_distribute_parallel_for_simd:
1100 case OMPD_target_update:
1101 case OMPD_declare_simd:
1102 case OMPD_declare_target:
1103 case OMPD_end_declare_target:
1104 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00001105 case OMPD_declare_mapper:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001106 case OMPD_taskloop:
1107 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001108 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001109 case OMPD_unknown:
1110 break;
1111 }
1112 llvm_unreachable(
1113 "Unknown programming model for OpenMP directive on NVPTX target.");
1114}
1115
1116void CGOpenMPRuntimeNVPTX::emitNonSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001117 StringRef ParentName,
1118 llvm::Function *&OutlinedFn,
1119 llvm::Constant *&OutlinedFnID,
1120 bool IsOffloadEntry,
1121 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001122 ExecutionRuntimeModesRAII ModeRAII(CurrentExecutionMode);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001123 EntryFunctionState EST;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001124 WorkerFunctionState WST(CGM, D.getBeginLoc());
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001125 Work.clear();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001126 WrapperFunctionsMap.clear();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001127
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001128 // Emit target region as a standalone region.
1129 class NVPTXPrePostActionTy : public PrePostActionTy {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001130 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1131 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001132
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001133 public:
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001134 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001135 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST)
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001136 : EST(EST), WST(WST) {}
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001137 void Enter(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001138 auto &RT =
1139 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001140 RT.emitNonSPMDEntryHeader(CGF, EST, WST);
1141 // Skip target region initialization.
1142 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001143 }
1144 void Exit(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001145 auto &RT =
1146 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001147 RT.clearLocThreadIdInsertPt(CGF);
1148 RT.emitNonSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001149 }
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001150 } Action(EST, WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001151 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001152 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001153 // Reserve place for the globalized memory.
1154 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001155 if (!KernelStaticGlobalized) {
1156 KernelStaticGlobalized = new llvm::GlobalVariable(
1157 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1158 llvm::GlobalValue::InternalLinkage,
1159 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1160 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1161 llvm::GlobalValue::NotThreadLocal,
1162 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1163 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001164 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1165 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001166 IsInTTDRegion = false;
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001167
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001168 // Now change the name of the worker function to correspond to this target
1169 // region's entry function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001170 WST.WorkerFn->setName(Twine(OutlinedFn->getName(), "_worker"));
Alexey Bataevaee93892018-01-08 20:09:47 +00001171
1172 // Create the worker function
1173 emitWorkerFunction(WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001174}
1175
1176// Setup NVPTX threads for master-worker OpenMP scheme.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001177void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryHeader(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001178 EntryFunctionState &EST,
1179 WorkerFunctionState &WST) {
1180 CGBuilderTy &Bld = CGF.Builder;
1181
1182 llvm::BasicBlock *WorkerBB = CGF.createBasicBlock(".worker");
1183 llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
1184 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
1185 EST.ExitBB = CGF.createBasicBlock(".exit");
1186
Alexey Bataev9ff80832018-04-16 20:16:21 +00001187 llvm::Value *IsWorker =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001188 Bld.CreateICmpULT(getNVPTXThreadID(CGF), getThreadLimit(CGF));
1189 Bld.CreateCondBr(IsWorker, WorkerBB, MasterCheckBB);
1190
1191 CGF.EmitBlock(WorkerBB);
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001192 emitCall(CGF, WST.Loc, WST.WorkerFn);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001193 CGF.EmitBranch(EST.ExitBB);
1194
1195 CGF.EmitBlock(MasterCheckBB);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001196 llvm::Value *IsMaster =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001197 Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
1198 Bld.CreateCondBr(IsMaster, MasterBB, EST.ExitBB);
1199
1200 CGF.EmitBlock(MasterBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001201 IsInTargetMasterThreadRegion = true;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001202 // SEQUENTIAL (MASTER) REGION START
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001203 // First action in sequential region:
1204 // Initialize the state of the OpenMP runtime library on the GPU.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001205 // TODO: Optimize runtime initialization and pass in correct value.
1206 llvm::Value *Args[] = {getThreadLimit(CGF),
1207 Bld.getInt16(/*RequiresOMPRuntime=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001208 CGF.EmitRuntimeCall(
1209 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_init), Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001210
1211 // For data sharing, we need to initialize the stack.
1212 CGF.EmitRuntimeCall(
1213 createNVPTXRuntimeFunction(
1214 OMPRTL_NVPTX__kmpc_data_sharing_init_stack));
1215
Alexey Bataevc99042b2018-03-15 18:10:54 +00001216 emitGenericVarsProlog(CGF, WST.Loc);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001217}
1218
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001219void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001220 EntryFunctionState &EST) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001221 IsInTargetMasterThreadRegion = false;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001222 if (!CGF.HaveInsertPoint())
1223 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001224
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001225 emitGenericVarsEpilog(CGF);
1226
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001227 if (!EST.ExitBB)
1228 EST.ExitBB = CGF.createBasicBlock(".exit");
1229
1230 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".termination.notifier");
1231 CGF.EmitBranch(TerminateBB);
1232
1233 CGF.EmitBlock(TerminateBB);
1234 // Signal termination condition.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001235 // TODO: Optimize runtime initialization and pass in correct value.
1236 llvm::Value *Args[] = {CGF.Builder.getInt16(/*IsOMPRuntimeInitialized=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001237 CGF.EmitRuntimeCall(
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001238 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_deinit), Args);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001239 // Barrier to terminate worker threads.
1240 syncCTAThreads(CGF);
1241 // Master thread jumps to exit point.
1242 CGF.EmitBranch(EST.ExitBB);
1243
1244 CGF.EmitBlock(EST.ExitBB);
1245 EST.ExitBB = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001246}
1247
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001248void CGOpenMPRuntimeNVPTX::emitSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001249 StringRef ParentName,
1250 llvm::Function *&OutlinedFn,
1251 llvm::Constant *&OutlinedFnID,
1252 bool IsOffloadEntry,
1253 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001254 ExecutionRuntimeModesRAII ModeRAII(
1255 CurrentExecutionMode, RequiresFullRuntime,
1256 CGM.getLangOpts().OpenMPCUDAForceFullRuntime ||
1257 !supportsLightweightRuntime(CGM.getContext(), D));
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001258 EntryFunctionState EST;
1259
1260 // Emit target region as a standalone region.
1261 class NVPTXPrePostActionTy : public PrePostActionTy {
1262 CGOpenMPRuntimeNVPTX &RT;
1263 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1264 const OMPExecutableDirective &D;
1265
1266 public:
1267 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT,
1268 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
1269 const OMPExecutableDirective &D)
1270 : RT(RT), EST(EST), D(D) {}
1271 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001272 RT.emitSPMDEntryHeader(CGF, EST, D);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001273 // Skip target region initialization.
1274 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001275 }
1276 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevfd006c42018-10-05 15:08:53 +00001277 RT.clearLocThreadIdInsertPt(CGF);
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001278 RT.emitSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001279 }
1280 } Action(*this, EST, D);
1281 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001282 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001283 // Reserve place for the globalized memory.
1284 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001285 if (!KernelStaticGlobalized) {
1286 KernelStaticGlobalized = new llvm::GlobalVariable(
1287 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1288 llvm::GlobalValue::InternalLinkage,
1289 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1290 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1291 llvm::GlobalValue::NotThreadLocal,
1292 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1293 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001294 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1295 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001296 IsInTTDRegion = false;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001297}
1298
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001299void CGOpenMPRuntimeNVPTX::emitSPMDEntryHeader(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001300 CodeGenFunction &CGF, EntryFunctionState &EST,
1301 const OMPExecutableDirective &D) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001302 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001303
1304 // Setup BBs in entry function.
1305 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute");
1306 EST.ExitBB = CGF.createBasicBlock(".exit");
1307
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001308 llvm::Value *Args[] = {getThreadLimit(CGF, /*IsInSPMDExecutionMode=*/true),
1309 /*RequiresOMPRuntime=*/
1310 Bld.getInt16(RequiresFullRuntime ? 1 : 0),
1311 /*RequiresDataSharing=*/Bld.getInt16(0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001312 CGF.EmitRuntimeCall(
1313 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_init), Args);
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001314
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001315 if (RequiresFullRuntime) {
1316 // For data sharing, we need to initialize the stack.
1317 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1318 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd));
1319 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001320
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001321 CGF.EmitBranch(ExecuteBB);
1322
1323 CGF.EmitBlock(ExecuteBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001324
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001325 IsInTargetMasterThreadRegion = true;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001326}
1327
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001328void CGOpenMPRuntimeNVPTX::emitSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001329 EntryFunctionState &EST) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001330 IsInTargetMasterThreadRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001331 if (!CGF.HaveInsertPoint())
1332 return;
1333
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001334 if (!EST.ExitBB)
1335 EST.ExitBB = CGF.createBasicBlock(".exit");
1336
1337 llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit");
1338 CGF.EmitBranch(OMPDeInitBB);
1339
1340 CGF.EmitBlock(OMPDeInitBB);
1341 // DeInitialize the OMP state in the runtime; called by all active threads.
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001342 llvm::Value *Args[] = {/*RequiresOMPRuntime=*/
1343 CGF.Builder.getInt16(RequiresFullRuntime ? 1 : 0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001344 CGF.EmitRuntimeCall(
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001345 createNVPTXRuntimeFunction(
1346 OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2), Args);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001347 CGF.EmitBranch(EST.ExitBB);
1348
1349 CGF.EmitBlock(EST.ExitBB);
1350 EST.ExitBB = nullptr;
1351}
1352
1353// Create a unique global variable to indicate the execution mode of this target
1354// region. The execution mode is either 'generic', or 'spmd' depending on the
1355// target directive. This variable is picked up by the offload library to setup
1356// the device appropriately before kernel launch. If the execution mode is
1357// 'generic', the runtime reserves one warp for the master, otherwise, all
1358// warps participate in parallel work.
1359static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001360 bool Mode) {
1361 auto *GVMode =
1362 new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
1363 llvm::GlobalValue::WeakAnyLinkage,
1364 llvm::ConstantInt::get(CGM.Int8Ty, Mode ? 0 : 1),
1365 Twine(Name, "_exec_mode"));
Alexey Bataev9ff80832018-04-16 20:16:21 +00001366 CGM.addCompilerUsedGlobal(GVMode);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001367}
1368
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001369void CGOpenMPRuntimeNVPTX::emitWorkerFunction(WorkerFunctionState &WST) {
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +00001370 ASTContext &Ctx = CGM.getContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001371
1372 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001373 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, WST.CGFI, {},
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001374 WST.Loc, WST.Loc);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001375 emitWorkerLoop(CGF, WST);
1376 CGF.FinishFunction();
1377}
1378
1379void CGOpenMPRuntimeNVPTX::emitWorkerLoop(CodeGenFunction &CGF,
1380 WorkerFunctionState &WST) {
1381 //
1382 // The workers enter this loop and wait for parallel work from the master.
1383 // When the master encounters a parallel region it sets up the work + variable
1384 // arguments, and wakes up the workers. The workers first check to see if
1385 // they are required for the parallel region, i.e., within the # of requested
1386 // parallel threads. The activated workers load the variable arguments and
1387 // execute the parallel work.
1388 //
1389
1390 CGBuilderTy &Bld = CGF.Builder;
1391
1392 llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work");
1393 llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers");
1394 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel");
1395 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel");
1396 llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel");
1397 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1398
1399 CGF.EmitBranch(AwaitBB);
1400
1401 // Workers wait for work from master.
1402 CGF.EmitBlock(AwaitBB);
1403 // Wait for parallel work
1404 syncCTAThreads(CGF);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001405
1406 Address WorkFn =
1407 CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn");
1408 Address ExecStatus =
1409 CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status");
1410 CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0));
1411 CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy));
1412
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001413 // TODO: Optimize runtime initialization and pass in correct value.
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001414 llvm::Value *Args[] = {WorkFn.getPointer(),
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001415 /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001416 llvm::Value *Ret = CGF.EmitRuntimeCall(
1417 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args);
1418 Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001419
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001420 // On termination condition (workid == 0), exit loop.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001421 llvm::Value *WorkID = Bld.CreateLoad(WorkFn);
1422 llvm::Value *ShouldTerminate = Bld.CreateIsNull(WorkID, "should_terminate");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001423 Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB);
1424
1425 // Activate requested workers.
1426 CGF.EmitBlock(SelectWorkersBB);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001427 llvm::Value *IsActive =
1428 Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active");
1429 Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001430
1431 // Signal start of parallel region.
1432 CGF.EmitBlock(ExecuteBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001433 // Skip initialization.
1434 setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001435
1436 // Process work items: outlined parallel functions.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001437 for (llvm::Function *W : Work) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001438 // Try to match this outlined function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001439 llvm::Value *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001440
1441 llvm::Value *WorkFnMatch =
1442 Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match");
1443
1444 llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn");
1445 llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next");
1446 Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB);
1447
1448 // Execute this outlined function.
1449 CGF.EmitBlock(ExecuteFNBB);
1450
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001451 // Insert call to work function via shared wrapper. The shared
1452 // wrapper takes two arguments:
1453 // - the parallelism level;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001454 // - the thread ID;
1455 emitCall(CGF, WST.Loc, W,
1456 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001457
1458 // Go to end of parallel region.
1459 CGF.EmitBranch(TerminateBB);
1460
1461 CGF.EmitBlock(CheckNextBB);
1462 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001463 // Default case: call to outlined function through pointer if the target
1464 // region makes a declare target call that may contain an orphaned parallel
1465 // directive.
1466 auto *ParallelFnTy =
1467 llvm::FunctionType::get(CGM.VoidTy, {CGM.Int16Ty, CGM.Int32Ty},
James Y Knight9871db02019-02-05 16:42:33 +00001468 /*isVarArg=*/false);
1469 llvm::Value *WorkFnCast =
1470 Bld.CreateBitCast(WorkID, ParallelFnTy->getPointerTo());
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001471 // Insert call to work function via shared wrapper. The shared
1472 // wrapper takes two arguments:
1473 // - the parallelism level;
1474 // - the thread ID;
James Y Knight9871db02019-02-05 16:42:33 +00001475 emitCall(CGF, WST.Loc, {ParallelFnTy, WorkFnCast},
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001476 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
1477 // Go to end of parallel region.
1478 CGF.EmitBranch(TerminateBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001479
1480 // Signal end of parallel region.
1481 CGF.EmitBlock(TerminateBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001482 CGF.EmitRuntimeCall(
1483 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_end_parallel),
1484 llvm::None);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001485 CGF.EmitBranch(BarrierBB);
1486
1487 // All active and inactive workers wait at a barrier after parallel region.
1488 CGF.EmitBlock(BarrierBB);
1489 // Barrier after parallel region.
1490 syncCTAThreads(CGF);
1491 CGF.EmitBranch(AwaitBB);
1492
1493 // Exit target region.
1494 CGF.EmitBlock(ExitBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001495 // Skip initialization.
1496 clearLocThreadIdInsertPt(CGF);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001497}
1498
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001499/// Returns specified OpenMP runtime function for the current OpenMP
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001500/// implementation. Specialized for the NVPTX device.
1501/// \param Function OpenMP runtime function.
1502/// \return Specified function.
James Y Knight9871db02019-02-05 16:42:33 +00001503llvm::FunctionCallee
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001504CGOpenMPRuntimeNVPTX::createNVPTXRuntimeFunction(unsigned Function) {
James Y Knight9871db02019-02-05 16:42:33 +00001505 llvm::FunctionCallee RTLFn = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001506 switch (static_cast<OpenMPRTLFunctionNVPTX>(Function)) {
1507 case OMPRTL_NVPTX__kmpc_kernel_init: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001508 // Build void __kmpc_kernel_init(kmp_int32 thread_limit, int16_t
1509 // RequiresOMPRuntime);
1510 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001511 auto *FnTy =
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001512 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1513 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_init");
1514 break;
1515 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001516 case OMPRTL_NVPTX__kmpc_kernel_deinit: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001517 // Build void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
1518 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001519 auto *FnTy =
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001520 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001521 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_deinit");
1522 break;
1523 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001524 case OMPRTL_NVPTX__kmpc_spmd_kernel_init: {
1525 // Build void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001526 // int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001527 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001528 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001529 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1530 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_init");
1531 break;
1532 }
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001533 case OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2: {
1534 // Build void __kmpc_spmd_kernel_deinit_v2(int16_t RequiresOMPRuntime);
1535 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001536 auto *FnTy =
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001537 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1538 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_deinit_v2");
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001539 break;
1540 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001541 case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: {
1542 /// Build void __kmpc_kernel_prepare_parallel(
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001543 /// void *outlined_function, int16_t IsOMPRuntimeInitialized);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001544 llvm::Type *TypeParams[] = {CGM.Int8PtrTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001545 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001546 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1547 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_prepare_parallel");
1548 break;
1549 }
1550 case OMPRTL_NVPTX__kmpc_kernel_parallel: {
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001551 /// Build bool __kmpc_kernel_parallel(void **outlined_function,
1552 /// int16_t IsOMPRuntimeInitialized);
1553 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy, CGM.Int16Ty};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001554 llvm::Type *RetTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001555 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001556 llvm::FunctionType::get(RetTy, TypeParams, /*isVarArg*/ false);
1557 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_parallel");
1558 break;
1559 }
1560 case OMPRTL_NVPTX__kmpc_kernel_end_parallel: {
1561 /// Build void __kmpc_kernel_end_parallel();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001562 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001563 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1564 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_end_parallel");
1565 break;
1566 }
1567 case OMPRTL_NVPTX__kmpc_serialized_parallel: {
1568 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1569 // global_tid);
1570 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001571 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001572 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1573 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1574 break;
1575 }
1576 case OMPRTL_NVPTX__kmpc_end_serialized_parallel: {
1577 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1578 // global_tid);
1579 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001580 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001581 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1582 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1583 break;
1584 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001585 case OMPRTL_NVPTX__kmpc_shuffle_int32: {
1586 // Build int32_t __kmpc_shuffle_int32(int32_t element,
1587 // int16_t lane_offset, int16_t warp_size);
1588 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001589 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001590 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1591 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int32");
1592 break;
1593 }
1594 case OMPRTL_NVPTX__kmpc_shuffle_int64: {
1595 // Build int64_t __kmpc_shuffle_int64(int64_t element,
1596 // int16_t lane_offset, int16_t warp_size);
1597 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001598 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001599 llvm::FunctionType::get(CGM.Int64Ty, TypeParams, /*isVarArg*/ false);
1600 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int64");
1601 break;
1602 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00001603 case OMPRTL_NVPTX__kmpc_nvptx_parallel_reduce_nowait_v2: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001604 // Build int32_t kmpc_nvptx_parallel_reduce_nowait_v2(ident_t *loc,
1605 // kmp_int32 global_tid, kmp_int32 num_vars, size_t reduce_size, void*
1606 // reduce_data, void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t
1607 // lane_id, int16_t lane_offset, int16_t Algorithm Version), void
1608 // (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001609 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1610 CGM.Int16Ty, CGM.Int16Ty};
1611 auto *ShuffleReduceFnTy =
1612 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1613 /*isVarArg=*/false);
1614 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1615 auto *InterWarpCopyFnTy =
1616 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1617 /*isVarArg=*/false);
Alexey Bataev8e009032019-01-04 17:25:09 +00001618 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1619 CGM.Int32Ty,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001620 CGM.Int32Ty,
1621 CGM.SizeTy,
1622 CGM.VoidPtrTy,
1623 ShuffleReduceFnTy->getPointerTo(),
1624 InterWarpCopyFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001625 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001626 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1627 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev8e009032019-01-04 17:25:09 +00001628 FnTy, /*Name=*/"__kmpc_nvptx_parallel_reduce_nowait_v2");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001629 break;
1630 }
1631 case OMPRTL_NVPTX__kmpc_end_reduce_nowait: {
1632 // Build __kmpc_end_reduce_nowait(kmp_int32 global_tid);
1633 llvm::Type *TypeParams[] = {CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001634 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001635 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1636 RTLFn = CGM.CreateRuntimeFunction(
1637 FnTy, /*Name=*/"__kmpc_nvptx_end_reduce_nowait");
1638 break;
1639 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00001640 case OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_v2: {
1641 // Build int32_t __kmpc_nvptx_teams_reduce_nowait_v2(ident_t *loc, kmp_int32
1642 // global_tid, void *global_buffer, int32_t num_of_records, void*
1643 // reduce_data,
1644 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1645 // lane_offset, int16_t shortCircuit),
1646 // void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num), void
1647 // (*kmp_ListToGlobalCpyFctPtr)(void *buffer, int idx, void *reduce_data),
1648 // void (*kmp_GlobalToListCpyFctPtr)(void *buffer, int idx,
1649 // void *reduce_data), void (*kmp_GlobalToListCpyPtrsFctPtr)(void *buffer,
1650 // int idx, void *reduce_data), void (*kmp_GlobalToListRedFctPtr)(void
1651 // *buffer, int idx, void *reduce_data));
1652 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1653 CGM.Int16Ty, CGM.Int16Ty};
1654 auto *ShuffleReduceFnTy =
1655 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1656 /*isVarArg=*/false);
1657 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1658 auto *InterWarpCopyFnTy =
1659 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1660 /*isVarArg=*/false);
1661 llvm::Type *GlobalListTypeParams[] = {CGM.VoidPtrTy, CGM.IntTy,
1662 CGM.VoidPtrTy};
1663 auto *GlobalListFnTy =
1664 llvm::FunctionType::get(CGM.VoidTy, GlobalListTypeParams,
1665 /*isVarArg=*/false);
1666 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1667 CGM.Int32Ty,
1668 CGM.VoidPtrTy,
1669 CGM.Int32Ty,
1670 CGM.VoidPtrTy,
1671 ShuffleReduceFnTy->getPointerTo(),
1672 InterWarpCopyFnTy->getPointerTo(),
1673 GlobalListFnTy->getPointerTo(),
1674 GlobalListFnTy->getPointerTo(),
1675 GlobalListFnTy->getPointerTo(),
1676 GlobalListFnTy->getPointerTo()};
Alexey Bataeva1166022018-11-27 21:24:54 +00001677 auto *FnTy =
1678 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1679 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev8061acd2019-02-20 16:36:22 +00001680 FnTy, /*Name=*/"__kmpc_nvptx_teams_reduce_nowait_v2");
Alexey Bataeva1166022018-11-27 21:24:54 +00001681 break;
1682 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001683 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack: {
1684 /// Build void __kmpc_data_sharing_init_stack();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001685 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001686 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1687 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack");
1688 break;
1689 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001690 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd: {
1691 /// Build void __kmpc_data_sharing_init_stack_spmd();
1692 auto *FnTy =
1693 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001694 RTLFn =
1695 CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack_spmd");
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001696 break;
1697 }
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001698 case OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack: {
1699 // Build void *__kmpc_data_sharing_coalesced_push_stack(size_t size,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001700 // int16_t UseSharedMemory);
1701 llvm::Type *TypeParams[] = {CGM.SizeTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001702 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001703 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1704 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001705 FnTy, /*Name=*/"__kmpc_data_sharing_coalesced_push_stack");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001706 break;
1707 }
1708 case OMPRTL_NVPTX__kmpc_data_sharing_pop_stack: {
1709 // Build void __kmpc_data_sharing_pop_stack(void *a);
1710 llvm::Type *TypeParams[] = {CGM.VoidPtrTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001711 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001712 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1713 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1714 /*Name=*/"__kmpc_data_sharing_pop_stack");
1715 break;
1716 }
1717 case OMPRTL_NVPTX__kmpc_begin_sharing_variables: {
1718 /// Build void __kmpc_begin_sharing_variables(void ***args,
1719 /// size_t n_args);
1720 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo(), CGM.SizeTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001721 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001722 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1723 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_begin_sharing_variables");
1724 break;
1725 }
1726 case OMPRTL_NVPTX__kmpc_end_sharing_variables: {
1727 /// Build void __kmpc_end_sharing_variables();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001728 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001729 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1730 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_sharing_variables");
1731 break;
1732 }
1733 case OMPRTL_NVPTX__kmpc_get_shared_variables: {
1734 /// Build void __kmpc_get_shared_variables(void ***GlobalArgs);
1735 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001736 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001737 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1738 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_shared_variables");
1739 break;
1740 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001741 case OMPRTL_NVPTX__kmpc_parallel_level: {
1742 // Build uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32 global_tid);
1743 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1744 auto *FnTy =
1745 llvm::FunctionType::get(CGM.Int16Ty, TypeParams, /*isVarArg*/ false);
1746 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_parallel_level");
1747 break;
1748 }
Alexey Bataev673110d2018-05-16 13:36:30 +00001749 case OMPRTL_NVPTX__kmpc_is_spmd_exec_mode: {
1750 // Build int8_t __kmpc_is_spmd_exec_mode();
1751 auto *FnTy = llvm::FunctionType::get(CGM.Int8Ty, /*isVarArg=*/false);
1752 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_is_spmd_exec_mode");
1753 break;
1754 }
Alexey Bataeve4090182018-11-02 14:54:07 +00001755 case OMPRTL_NVPTX__kmpc_get_team_static_memory: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001756 // Build void __kmpc_get_team_static_memory(int16_t isSPMDExecutionMode,
1757 // const void *buf, size_t size, int16_t is_shared, const void **res);
1758 llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.VoidPtrTy, CGM.SizeTy,
1759 CGM.Int16Ty, CGM.VoidPtrPtrTy};
Alexey Bataeve4090182018-11-02 14:54:07 +00001760 auto *FnTy =
1761 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1762 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_team_static_memory");
1763 break;
1764 }
1765 case OMPRTL_NVPTX__kmpc_restore_team_static_memory: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001766 // Build void __kmpc_restore_team_static_memory(int16_t isSPMDExecutionMode,
1767 // int16_t is_shared);
1768 llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataeve4090182018-11-02 14:54:07 +00001769 auto *FnTy =
Alexey Bataev8e009032019-01-04 17:25:09 +00001770 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
Alexey Bataeve4090182018-11-02 14:54:07 +00001771 RTLFn =
1772 CGM.CreateRuntimeFunction(FnTy, "__kmpc_restore_team_static_memory");
1773 break;
1774 }
Alexey Bataevc3028ca2018-12-04 15:03:25 +00001775 case OMPRTL__kmpc_barrier: {
1776 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
1777 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1778 auto *FnTy =
1779 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1780 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
James Y Knight9871db02019-02-05 16:42:33 +00001781 cast<llvm::Function>(RTLFn.getCallee())
1782 ->addFnAttr(llvm::Attribute::Convergent);
Alexey Bataevc3028ca2018-12-04 15:03:25 +00001783 break;
1784 }
Alexey Bataeva3924b52019-01-03 16:25:35 +00001785 case OMPRTL__kmpc_barrier_simple_spmd: {
1786 // Build void __kmpc_barrier_simple_spmd(ident_t *loc, kmp_int32
1787 // global_tid);
1788 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1789 auto *FnTy =
1790 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1791 RTLFn =
1792 CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier_simple_spmd");
James Y Knight9871db02019-02-05 16:42:33 +00001793 cast<llvm::Function>(RTLFn.getCallee())
1794 ->addFnAttr(llvm::Attribute::Convergent);
Alexey Bataeva3924b52019-01-03 16:25:35 +00001795 break;
1796 }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001797 }
1798 return RTLFn;
1799}
1800
1801void CGOpenMPRuntimeNVPTX::createOffloadEntry(llvm::Constant *ID,
1802 llvm::Constant *Addr,
Alexey Bataev03f270c2018-03-30 18:31:07 +00001803 uint64_t Size, int32_t,
1804 llvm::GlobalValue::LinkageTypes) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001805 // TODO: Add support for global variables on the device after declare target
1806 // support.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001807 if (!isa<llvm::Function>(Addr))
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001808 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +00001809 llvm::Module &M = CGM.getModule();
1810 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001811
1812 // Get "nvvm.annotations" metadata node
Alexey Bataev9ff80832018-04-16 20:16:21 +00001813 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001814
1815 llvm::Metadata *MDVals[] = {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001816 llvm::ConstantAsMetadata::get(Addr), llvm::MDString::get(Ctx, "kernel"),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001817 llvm::ConstantAsMetadata::get(
1818 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))};
1819 // Append metadata to nvvm.annotations
1820 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
1821}
1822
1823void CGOpenMPRuntimeNVPTX::emitTargetOutlinedFunction(
1824 const OMPExecutableDirective &D, StringRef ParentName,
1825 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001826 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001827 if (!IsOffloadEntry) // Nothing to do.
1828 return;
1829
1830 assert(!ParentName.empty() && "Invalid target region parent name!");
1831
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001832 bool Mode = supportsSPMDExecutionMode(CGM.getContext(), D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001833 if (Mode)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001834 emitSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001835 CodeGen);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001836 else
1837 emitNonSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1838 CodeGen);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001839
1840 setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001841}
1842
Alexey Bataevceeaa482018-11-21 21:04:34 +00001843namespace {
1844LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
1845/// Enum for accesseing the reserved_2 field of the ident_t struct.
1846enum ModeFlagsTy : unsigned {
1847 /// Bit set to 1 when in SPMD mode.
1848 KMP_IDENT_SPMD_MODE = 0x01,
1849 /// Bit set to 1 when a simplified runtime is used.
1850 KMP_IDENT_SIMPLE_RT_MODE = 0x02,
1851 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/KMP_IDENT_SIMPLE_RT_MODE)
1852};
1853
1854/// Special mode Undefined. Is the combination of Non-SPMD mode + SimpleRuntime.
1855static const ModeFlagsTy UndefinedMode =
1856 (~KMP_IDENT_SPMD_MODE) & KMP_IDENT_SIMPLE_RT_MODE;
1857} // anonymous namespace
1858
1859unsigned CGOpenMPRuntimeNVPTX::getDefaultLocationReserved2Flags() const {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001860 switch (getExecutionMode()) {
1861 case EM_SPMD:
1862 if (requiresFullRuntime())
1863 return KMP_IDENT_SPMD_MODE & (~KMP_IDENT_SIMPLE_RT_MODE);
1864 return KMP_IDENT_SPMD_MODE | KMP_IDENT_SIMPLE_RT_MODE;
1865 case EM_NonSPMD:
1866 assert(requiresFullRuntime() && "Expected full runtime.");
1867 return (~KMP_IDENT_SPMD_MODE) & (~KMP_IDENT_SIMPLE_RT_MODE);
1868 case EM_Unknown:
1869 return UndefinedMode;
1870 }
1871 llvm_unreachable("Unknown flags are requested.");
Alexey Bataevceeaa482018-11-21 21:04:34 +00001872}
1873
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001874CGOpenMPRuntimeNVPTX::CGOpenMPRuntimeNVPTX(CodeGenModule &CGM)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001875 : CGOpenMPRuntime(CGM, "_", "$") {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001876 if (!CGM.getLangOpts().OpenMPIsDevice)
1877 llvm_unreachable("OpenMP NVPTX can only handle device code.");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001878}
Carlo Bertollic6872252016-04-04 15:55:02 +00001879
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001880void CGOpenMPRuntimeNVPTX::emitProcBindClause(CodeGenFunction &CGF,
1881 OpenMPProcBindClauseKind ProcBind,
1882 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001883 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001884 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001885 return;
1886
1887 CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc);
1888}
1889
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001890void CGOpenMPRuntimeNVPTX::emitNumThreadsClause(CodeGenFunction &CGF,
1891 llvm::Value *NumThreads,
1892 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001893 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001894 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001895 return;
1896
1897 CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc);
1898}
1899
Carlo Bertollic6872252016-04-04 15:55:02 +00001900void CGOpenMPRuntimeNVPTX::emitNumTeamsClause(CodeGenFunction &CGF,
1901 const Expr *NumTeams,
1902 const Expr *ThreadLimit,
1903 SourceLocation Loc) {}
1904
James Y Knight9871db02019-02-05 16:42:33 +00001905llvm::Function *CGOpenMPRuntimeNVPTX::emitParallelOutlinedFunction(
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001906 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1907 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00001908 // Emit target region as a standalone region.
1909 class NVPTXPrePostActionTy : public PrePostActionTy {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001910 bool &IsInParallelRegion;
1911 bool PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001912
1913 public:
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001914 NVPTXPrePostActionTy(bool &IsInParallelRegion)
1915 : IsInParallelRegion(IsInParallelRegion) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00001916 void Enter(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001917 PrevIsInParallelRegion = IsInParallelRegion;
1918 IsInParallelRegion = true;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001919 }
1920 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001921 IsInParallelRegion = PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001922 }
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001923 } Action(IsInParallelRegion);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001924 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001925 bool PrevIsInTTDRegion = IsInTTDRegion;
1926 IsInTTDRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001927 bool PrevIsInTargetMasterThreadRegion = IsInTargetMasterThreadRegion;
1928 IsInTargetMasterThreadRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001929 auto *OutlinedFun =
1930 cast<llvm::Function>(CGOpenMPRuntime::emitParallelOutlinedFunction(
1931 D, ThreadIDVar, InnermostKind, CodeGen));
Alexey Bataev8c5555c2019-05-21 15:11:58 +00001932 if (CGM.getLangOpts().Optimize) {
1933 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
1934 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
1935 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
1936 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001937 IsInTargetMasterThreadRegion = PrevIsInTargetMasterThreadRegion;
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001938 IsInTTDRegion = PrevIsInTTDRegion;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001939 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD &&
1940 !IsInParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001941 llvm::Function *WrapperFun =
1942 createParallelDataSharingWrapper(OutlinedFun, D);
1943 WrapperFunctionsMap[OutlinedFun] = WrapperFun;
1944 }
1945
1946 return OutlinedFun;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001947}
1948
Alexey Bataev2adecff2018-09-21 14:22:53 +00001949/// Get list of lastprivate variables from the teams distribute ... or
1950/// teams {distribute ...} directives.
1951static void
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001952getDistributeLastprivateVars(ASTContext &Ctx, const OMPExecutableDirective &D,
Alexey Bataev2adecff2018-09-21 14:22:53 +00001953 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
1954 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
1955 "expected teams directive.");
1956 const OMPExecutableDirective *Dir = &D;
1957 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
Alexey Bataev5c427362019-04-10 19:11:33 +00001958 if (const Stmt *S = CGOpenMPRuntime::getSingleCompoundChild(
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001959 Ctx,
Alexey Bataev2adecff2018-09-21 14:22:53 +00001960 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
1961 /*IgnoreCaptured=*/true))) {
Alexey Bataev5c427362019-04-10 19:11:33 +00001962 Dir = dyn_cast_or_null<OMPExecutableDirective>(S);
Alexey Bataev2adecff2018-09-21 14:22:53 +00001963 if (Dir && !isOpenMPDistributeDirective(Dir->getDirectiveKind()))
1964 Dir = nullptr;
1965 }
1966 }
1967 if (!Dir)
1968 return;
Alexey Bataev9ea3c382018-10-09 14:49:00 +00001969 for (const auto *C : Dir->getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00001970 for (const Expr *E : C->getVarRefs())
1971 Vars.push_back(getPrivateItem(E));
1972 }
1973}
1974
1975/// Get list of reduction variables from the teams ... directives.
1976static void
1977getTeamsReductionVars(ASTContext &Ctx, const OMPExecutableDirective &D,
1978 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
1979 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
1980 "expected teams directive.");
1981 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1982 for (const Expr *E : C->privates())
1983 Vars.push_back(getPrivateItem(E));
Alexey Bataev2adecff2018-09-21 14:22:53 +00001984 }
1985}
1986
James Y Knight9871db02019-02-05 16:42:33 +00001987llvm::Function *CGOpenMPRuntimeNVPTX::emitTeamsOutlinedFunction(
Carlo Bertollic6872252016-04-04 15:55:02 +00001988 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1989 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001990 SourceLocation Loc = D.getBeginLoc();
Carlo Bertollic6872252016-04-04 15:55:02 +00001991
Alexey Bataev2adecff2018-09-21 14:22:53 +00001992 const RecordDecl *GlobalizedRD = nullptr;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00001993 llvm::SmallVector<const ValueDecl *, 4> LastPrivatesReductions;
Alexey Bataev2adecff2018-09-21 14:22:53 +00001994 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00001995 // Globalize team reductions variable unconditionally in all modes.
Alexey Bataev8061acd2019-02-20 16:36:22 +00001996 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
1997 getTeamsReductionVars(CGM.getContext(), D, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00001998 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00001999 getDistributeLastprivateVars(CGM.getContext(), D, LastPrivatesReductions);
2000 if (!LastPrivatesReductions.empty()) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002001 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002002 CGM.getContext(), llvm::None, LastPrivatesReductions,
Alexey Bataev8061acd2019-02-20 16:36:22 +00002003 MappedDeclsFields, WarpSize);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002004 }
2005 } else if (!LastPrivatesReductions.empty()) {
2006 assert(!TeamAndReductions.first &&
2007 "Previous team declaration is not expected.");
2008 TeamAndReductions.first = D.getCapturedStmt(OMPD_teams)->getCapturedDecl();
2009 std::swap(TeamAndReductions.second, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002010 }
2011
Alexey Bataevc99042b2018-03-15 18:10:54 +00002012 // Emit target region as a standalone region.
2013 class NVPTXPrePostActionTy : public PrePostActionTy {
2014 SourceLocation &Loc;
Alexey Bataev2adecff2018-09-21 14:22:53 +00002015 const RecordDecl *GlobalizedRD;
2016 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2017 &MappedDeclsFields;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002018
2019 public:
Alexey Bataev2adecff2018-09-21 14:22:53 +00002020 NVPTXPrePostActionTy(
2021 SourceLocation &Loc, const RecordDecl *GlobalizedRD,
2022 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2023 &MappedDeclsFields)
2024 : Loc(Loc), GlobalizedRD(GlobalizedRD),
2025 MappedDeclsFields(MappedDeclsFields) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00002026 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002027 auto &Rt =
2028 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
2029 if (GlobalizedRD) {
2030 auto I = Rt.FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
2031 I->getSecond().GlobalRecord = GlobalizedRD;
2032 I->getSecond().MappedParams =
2033 llvm::make_unique<CodeGenFunction::OMPMapVars>();
2034 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
2035 for (const auto &Pair : MappedDeclsFields) {
2036 assert(Pair.getFirst()->isCanonicalDecl() &&
2037 "Expected canonical declaration");
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002038 Data.insert(std::make_pair(Pair.getFirst(),
2039 MappedVarData(Pair.getSecond(),
2040 /*IsOnePerTeam=*/true)));
Alexey Bataev2adecff2018-09-21 14:22:53 +00002041 }
2042 }
2043 Rt.emitGenericVarsProlog(CGF, Loc);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002044 }
2045 void Exit(CodeGenFunction &CGF) override {
2046 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
2047 .emitGenericVarsEpilog(CGF);
2048 }
Alexey Bataev2adecff2018-09-21 14:22:53 +00002049 } Action(Loc, GlobalizedRD, MappedDeclsFields);
2050 CodeGen.setAction(Action);
James Y Knight9871db02019-02-05 16:42:33 +00002051 llvm::Function *OutlinedFun = CGOpenMPRuntime::emitTeamsOutlinedFunction(
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002052 D, ThreadIDVar, InnermostKind, CodeGen);
Alexey Bataev8c5555c2019-05-21 15:11:58 +00002053 if (CGM.getLangOpts().Optimize) {
2054 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
2055 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
2056 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
2057 }
Carlo Bertollic6872252016-04-04 15:55:02 +00002058
2059 return OutlinedFun;
2060}
2061
Alexey Bataevc99042b2018-03-15 18:10:54 +00002062void CGOpenMPRuntimeNVPTX::emitGenericVarsProlog(CodeGenFunction &CGF,
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002063 SourceLocation Loc,
2064 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002065 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2066 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002067 return;
2068
Alexey Bataevc99042b2018-03-15 18:10:54 +00002069 CGBuilderTy &Bld = CGF.Builder;
2070
2071 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
2072 if (I == FunctionGlobalizedDecls.end())
2073 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002074 if (const RecordDecl *GlobalizedVarsRecord = I->getSecond().GlobalRecord) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002075 QualType GlobalRecTy = CGM.getContext().getRecordType(GlobalizedVarsRecord);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002076 QualType SecGlobalRecTy;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002077
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002078 // Recover pointer to this function's global record. The runtime will
2079 // handle the specifics of the allocation of the memory.
2080 // Use actual memory size of the record including the padding
2081 // for alignment purposes.
2082 unsigned Alignment =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002083 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002084 unsigned GlobalRecordSize =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002085 CGM.getContext().getTypeSizeInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002086 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002087
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002088 llvm::PointerType *GlobalRecPtrTy =
2089 CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo();
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002090 llvm::Value *GlobalRecCastAddr;
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002091 llvm::Value *IsTTD = nullptr;
Alexey Bataeve4090182018-11-02 14:54:07 +00002092 if (!IsInTTDRegion &&
2093 (WithSPMDCheck ||
2094 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002095 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2096 llvm::BasicBlock *SPMDBB = CGF.createBasicBlock(".spmd");
2097 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002098 if (I->getSecond().SecondaryGlobalRecord.hasValue()) {
2099 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2100 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2101 llvm::Value *PL = CGF.EmitRuntimeCall(
2102 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2103 {RTLoc, ThreadID});
2104 IsTTD = Bld.CreateIsNull(PL);
2105 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002106 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2107 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
2108 Bld.CreateCondBr(IsSPMD, SPMDBB, NonSPMDBB);
2109 // There is no need to emit line number for unconditional branch.
2110 (void)ApplyDebugLocation::CreateEmpty(CGF);
2111 CGF.EmitBlock(SPMDBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002112 Address RecPtr = Address(llvm::ConstantPointerNull::get(GlobalRecPtrTy),
2113 CharUnits::fromQuantity(Alignment));
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002114 CGF.EmitBranch(ExitBB);
2115 // There is no need to emit line number for unconditional branch.
2116 (void)ApplyDebugLocation::CreateEmpty(CGF);
2117 CGF.EmitBlock(NonSPMDBB);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002118 llvm::Value *Size = llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize);
2119 if (const RecordDecl *SecGlobalizedVarsRecord =
2120 I->getSecond().SecondaryGlobalRecord.getValueOr(nullptr)) {
2121 SecGlobalRecTy =
2122 CGM.getContext().getRecordType(SecGlobalizedVarsRecord);
2123
2124 // Recover pointer to this function's global record. The runtime will
2125 // handle the specifics of the allocation of the memory.
2126 // Use actual memory size of the record including the padding
2127 // for alignment purposes.
2128 unsigned Alignment =
2129 CGM.getContext().getTypeAlignInChars(SecGlobalRecTy).getQuantity();
2130 unsigned GlobalRecordSize =
2131 CGM.getContext().getTypeSizeInChars(SecGlobalRecTy).getQuantity();
2132 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
2133 Size = Bld.CreateSelect(
2134 IsTTD, llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize), Size);
2135 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002136 // TODO: allow the usage of shared memory to be controlled by
2137 // the user, for now, default to global.
2138 llvm::Value *GlobalRecordSizeArg[] = {
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002139 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002140 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2141 createNVPTXRuntimeFunction(
2142 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2143 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002144 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002145 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002146 CGF.EmitBlock(ExitBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002147 auto *Phi = Bld.CreatePHI(GlobalRecPtrTy,
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002148 /*NumReservedValues=*/2, "_select_stack");
2149 Phi->addIncoming(RecPtr.getPointer(), SPMDBB);
2150 Phi->addIncoming(GlobalRecCastAddr, NonSPMDBB);
2151 GlobalRecCastAddr = Phi;
2152 I->getSecond().GlobalRecordAddr = Phi;
2153 I->getSecond().IsInSPMDModeFlag = IsSPMD;
Alexey Bataeve4090182018-11-02 14:54:07 +00002154 } else if (IsInTTDRegion) {
2155 assert(GlobalizedRecords.back().Records.size() < 2 &&
2156 "Expected less than 2 globalized records: one for target and one "
2157 "for teams.");
2158 unsigned Offset = 0;
2159 for (const RecordDecl *RD : GlobalizedRecords.back().Records) {
2160 QualType RDTy = CGM.getContext().getRecordType(RD);
2161 unsigned Alignment =
2162 CGM.getContext().getTypeAlignInChars(RDTy).getQuantity();
2163 unsigned Size = CGM.getContext().getTypeSizeInChars(RDTy).getQuantity();
2164 Offset =
2165 llvm::alignTo(llvm::alignTo(Offset, Alignment) + Size, Alignment);
2166 }
2167 unsigned Alignment =
2168 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
2169 Offset = llvm::alignTo(Offset, Alignment);
2170 GlobalizedRecords.back().Records.push_back(GlobalizedVarsRecord);
2171 ++GlobalizedRecords.back().RegionCounter;
2172 if (GlobalizedRecords.back().Records.size() == 1) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002173 assert(KernelStaticGlobalized &&
2174 "Kernel static pointer must be initialized already.");
2175 auto *UseSharedMemory = new llvm::GlobalVariable(
2176 CGM.getModule(), CGM.Int16Ty, /*isConstant=*/true,
2177 llvm::GlobalValue::InternalLinkage, nullptr,
2178 "_openmp_static_kernel$is_shared");
2179 UseSharedMemory->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2180 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2181 /*DestWidth=*/16, /*Signed=*/0);
2182 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2183 Address(UseSharedMemory,
2184 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2185 /*Volatile=*/false, Int16Ty, Loc);
2186 auto *StaticGlobalized = new llvm::GlobalVariable(
2187 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002188 llvm::GlobalValue::CommonLinkage, nullptr);
Alexey Bataeve4090182018-11-02 14:54:07 +00002189 auto *RecSize = new llvm::GlobalVariable(
2190 CGM.getModule(), CGM.SizeTy, /*isConstant=*/true,
2191 llvm::GlobalValue::InternalLinkage, nullptr,
2192 "_openmp_static_kernel$size");
2193 RecSize->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2194 llvm::Value *Ld = CGF.EmitLoadOfScalar(
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002195 Address(RecSize, CGM.getSizeAlign()), /*Volatile=*/false,
Alexey Bataeve4090182018-11-02 14:54:07 +00002196 CGM.getContext().getSizeType(), Loc);
2197 llvm::Value *ResAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2198 KernelStaticGlobalized, CGM.VoidPtrPtrTy);
Alexey Bataev8e009032019-01-04 17:25:09 +00002199 llvm::Value *GlobalRecordSizeArg[] = {
2200 llvm::ConstantInt::get(
2201 CGM.Int16Ty,
2202 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD ? 1 : 0),
2203 StaticGlobalized, Ld, IsInSharedMemory, ResAddr};
Alexey Bataeve4090182018-11-02 14:54:07 +00002204 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2205 OMPRTL_NVPTX__kmpc_get_team_static_memory),
2206 GlobalRecordSizeArg);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002207 GlobalizedRecords.back().Buffer = StaticGlobalized;
Alexey Bataeve4090182018-11-02 14:54:07 +00002208 GlobalizedRecords.back().RecSize = RecSize;
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002209 GlobalizedRecords.back().UseSharedMemory = UseSharedMemory;
2210 GlobalizedRecords.back().Loc = Loc;
Alexey Bataeve4090182018-11-02 14:54:07 +00002211 }
2212 assert(KernelStaticGlobalized && "Global address must be set already.");
2213 Address FrameAddr = CGF.EmitLoadOfPointer(
2214 Address(KernelStaticGlobalized, CGM.getPointerAlign()),
2215 CGM.getContext()
2216 .getPointerType(CGM.getContext().VoidPtrTy)
2217 .castAs<PointerType>());
2218 llvm::Value *GlobalRecValue =
James Y Knight751fe282019-02-09 22:22:28 +00002219 Bld.CreateConstInBoundsGEP(FrameAddr, Offset).getPointer();
Alexey Bataeve4090182018-11-02 14:54:07 +00002220 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2221 I->getSecond().IsInSPMDModeFlag = nullptr;
2222 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2223 GlobalRecValue, CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo());
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002224 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002225 // TODO: allow the usage of shared memory to be controlled by
2226 // the user, for now, default to global.
2227 llvm::Value *GlobalRecordSizeArg[] = {
2228 llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize),
2229 CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002230 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2231 createNVPTXRuntimeFunction(
2232 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2233 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002234 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002235 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002236 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2237 I->getSecond().IsInSPMDModeFlag = nullptr;
2238 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002239 LValue Base =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002240 CGF.MakeNaturalAlignPointeeAddrLValue(GlobalRecCastAddr, GlobalRecTy);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002241
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002242 // Emit the "global alloca" which is a GEP from the global declaration
2243 // record using the pointer returned by the runtime.
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002244 LValue SecBase;
2245 decltype(I->getSecond().LocalVarData)::const_iterator SecIt;
2246 if (IsTTD) {
2247 SecIt = I->getSecond().SecondaryLocalVarData->begin();
2248 llvm::PointerType *SecGlobalRecPtrTy =
2249 CGF.ConvertTypeForMem(SecGlobalRecTy)->getPointerTo();
2250 SecBase = CGF.MakeNaturalAlignPointeeAddrLValue(
2251 Bld.CreatePointerBitCastOrAddrSpaceCast(
2252 I->getSecond().GlobalRecordAddr, SecGlobalRecPtrTy),
2253 SecGlobalRecTy);
2254 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002255 for (auto &Rec : I->getSecond().LocalVarData) {
2256 bool EscapedParam = I->getSecond().EscapedParameters.count(Rec.first);
2257 llvm::Value *ParValue;
2258 if (EscapedParam) {
2259 const auto *VD = cast<VarDecl>(Rec.first);
2260 LValue ParLVal =
2261 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
2262 ParValue = CGF.EmitLoadOfScalar(ParLVal, Loc);
2263 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002264 LValue VarAddr = CGF.EmitLValueForField(Base, Rec.second.FD);
2265 // Emit VarAddr basing on lane-id if required.
2266 QualType VarTy;
2267 if (Rec.second.IsOnePerTeam) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002268 VarTy = Rec.second.FD->getType();
2269 } else {
2270 llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(
2271 VarAddr.getAddress().getPointer(),
2272 {Bld.getInt32(0), getNVPTXLaneID(CGF)});
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002273 VarTy =
2274 Rec.second.FD->getType()->castAsArrayTypeUnsafe()->getElementType();
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002275 VarAddr = CGF.MakeAddrLValue(
2276 Address(Ptr, CGM.getContext().getDeclAlign(Rec.first)), VarTy,
2277 AlignmentSource::Decl);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002278 }
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002279 Rec.second.PrivateAddr = VarAddr.getAddress();
Alexey Bataeve4090182018-11-02 14:54:07 +00002280 if (!IsInTTDRegion &&
2281 (WithSPMDCheck ||
2282 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002283 assert(I->getSecond().IsInSPMDModeFlag &&
2284 "Expected unknown execution mode or required SPMD check.");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002285 if (IsTTD) {
2286 assert(SecIt->second.IsOnePerTeam &&
2287 "Secondary glob data must be one per team.");
2288 LValue SecVarAddr = CGF.EmitLValueForField(SecBase, SecIt->second.FD);
2289 VarAddr.setAddress(
2290 Address(Bld.CreateSelect(IsTTD, SecVarAddr.getPointer(),
2291 VarAddr.getPointer()),
2292 VarAddr.getAlignment()));
2293 Rec.second.PrivateAddr = VarAddr.getAddress();
2294 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002295 Address GlobalPtr = Rec.second.PrivateAddr;
2296 Address LocalAddr = CGF.CreateMemTemp(VarTy, Rec.second.FD->getName());
2297 Rec.second.PrivateAddr = Address(
2298 Bld.CreateSelect(I->getSecond().IsInSPMDModeFlag,
2299 LocalAddr.getPointer(), GlobalPtr.getPointer()),
2300 LocalAddr.getAlignment());
2301 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002302 if (EscapedParam) {
2303 const auto *VD = cast<VarDecl>(Rec.first);
2304 CGF.EmitStoreOfScalar(ParValue, VarAddr);
2305 I->getSecond().MappedParams->setVarAddr(CGF, VD, VarAddr.getAddress());
2306 }
Alexey Bataev93a38d62018-10-16 00:09:06 +00002307 if (IsTTD)
2308 ++SecIt;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002309 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002310 }
2311 for (const ValueDecl *VD : I->getSecond().EscapedVariableLengthDecls) {
2312 // Recover pointer to this function's global record. The runtime will
2313 // handle the specifics of the allocation of the memory.
2314 // Use actual memory size of the record including the padding
2315 // for alignment purposes.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002316 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002317 llvm::Value *Size = CGF.getTypeSize(VD->getType());
2318 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2319 Size = Bld.CreateNUWAdd(
2320 Size, llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity() - 1));
2321 llvm::Value *AlignVal =
2322 llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity());
2323 Size = Bld.CreateUDiv(Size, AlignVal);
2324 Size = Bld.CreateNUWMul(Size, AlignVal);
2325 // TODO: allow the usage of shared memory to be controlled by
2326 // the user, for now, default to global.
2327 llvm::Value *GlobalRecordSizeArg[] = {
2328 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
2329 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002330 createNVPTXRuntimeFunction(
2331 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002332 GlobalRecordSizeArg);
2333 llvm::Value *GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2334 GlobalRecValue, CGF.ConvertTypeForMem(VD->getType())->getPointerTo());
2335 LValue Base = CGF.MakeAddrLValue(GlobalRecCastAddr, VD->getType(),
2336 CGM.getContext().getDeclAlign(VD),
2337 AlignmentSource::Decl);
2338 I->getSecond().MappedParams->setVarAddr(CGF, cast<VarDecl>(VD),
2339 Base.getAddress());
2340 I->getSecond().EscapedVariableLengthDeclsAddrs.emplace_back(GlobalRecValue);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002341 }
2342 I->getSecond().MappedParams->apply(CGF);
2343}
2344
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002345void CGOpenMPRuntimeNVPTX::emitGenericVarsEpilog(CodeGenFunction &CGF,
2346 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002347 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2348 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002349 return;
2350
Alexey Bataevc99042b2018-03-15 18:10:54 +00002351 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002352 if (I != FunctionGlobalizedDecls.end()) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00002353 I->getSecond().MappedParams->restore(CGF);
2354 if (!CGF.HaveInsertPoint())
2355 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002356 for (llvm::Value *Addr :
2357 llvm::reverse(I->getSecond().EscapedVariableLengthDeclsAddrs)) {
2358 CGF.EmitRuntimeCall(
2359 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2360 Addr);
2361 }
2362 if (I->getSecond().GlobalRecordAddr) {
Alexey Bataeve4090182018-11-02 14:54:07 +00002363 if (!IsInTTDRegion &&
2364 (WithSPMDCheck ||
2365 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002366 CGBuilderTy &Bld = CGF.Builder;
2367 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2368 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
2369 Bld.CreateCondBr(I->getSecond().IsInSPMDModeFlag, ExitBB, NonSPMDBB);
2370 // There is no need to emit line number for unconditional branch.
2371 (void)ApplyDebugLocation::CreateEmpty(CGF);
2372 CGF.EmitBlock(NonSPMDBB);
2373 CGF.EmitRuntimeCall(
2374 createNVPTXRuntimeFunction(
2375 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2376 CGF.EmitCastToVoidPtr(I->getSecond().GlobalRecordAddr));
2377 CGF.EmitBlock(ExitBB);
Alexey Bataeve4090182018-11-02 14:54:07 +00002378 } else if (IsInTTDRegion) {
2379 assert(GlobalizedRecords.back().RegionCounter > 0 &&
2380 "region counter must be > 0.");
2381 --GlobalizedRecords.back().RegionCounter;
2382 // Emit the restore function only in the target region.
2383 if (GlobalizedRecords.back().RegionCounter == 0) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002384 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2385 /*DestWidth=*/16, /*Signed=*/0);
2386 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2387 Address(GlobalizedRecords.back().UseSharedMemory,
2388 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2389 /*Volatile=*/false, Int16Ty, GlobalizedRecords.back().Loc);
Alexey Bataev8e009032019-01-04 17:25:09 +00002390 llvm::Value *Args[] = {
2391 llvm::ConstantInt::get(
2392 CGM.Int16Ty,
2393 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD ? 1 : 0),
2394 IsInSharedMemory};
Alexey Bataeve4090182018-11-02 14:54:07 +00002395 CGF.EmitRuntimeCall(
2396 createNVPTXRuntimeFunction(
2397 OMPRTL_NVPTX__kmpc_restore_team_static_memory),
Alexey Bataev8e009032019-01-04 17:25:09 +00002398 Args);
Alexey Bataeve4090182018-11-02 14:54:07 +00002399 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002400 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002401 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2402 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2403 I->getSecond().GlobalRecordAddr);
2404 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002405 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00002406 }
2407}
2408
Carlo Bertollic6872252016-04-04 15:55:02 +00002409void CGOpenMPRuntimeNVPTX::emitTeamsCall(CodeGenFunction &CGF,
2410 const OMPExecutableDirective &D,
2411 SourceLocation Loc,
James Y Knight9871db02019-02-05 16:42:33 +00002412 llvm::Function *OutlinedFn,
Carlo Bertollic6872252016-04-04 15:55:02 +00002413 ArrayRef<llvm::Value *> CapturedVars) {
2414 if (!CGF.HaveInsertPoint())
2415 return;
2416
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002417 Address ZeroAddr = CGF.CreateMemTemp(
2418 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2419 /*Name*/ ".zero.addr");
Carlo Bertollic6872252016-04-04 15:55:02 +00002420 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2421 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002422 OutlinedFnArgs.push_back(emitThreadIDAddress(CGF, Loc).getPointer());
Carlo Bertollic6872252016-04-04 15:55:02 +00002423 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2424 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002425 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Carlo Bertollic6872252016-04-04 15:55:02 +00002426}
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002427
2428void CGOpenMPRuntimeNVPTX::emitParallelCall(
James Y Knight9871db02019-02-05 16:42:33 +00002429 CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002430 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2431 if (!CGF.HaveInsertPoint())
2432 return;
2433
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002434 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002435 emitSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002436 else
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002437 emitNonSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002438}
2439
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002440void CGOpenMPRuntimeNVPTX::emitNonSPMDParallelCall(
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002441 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2442 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2443 llvm::Function *Fn = cast<llvm::Function>(OutlinedFn);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002444
2445 // Force inline this outlined function at its call site.
2446 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
2447
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002448 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2449 /*DestWidth=*/32, /*Signed=*/1),
2450 ".zero.addr");
2451 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002452 // ThreadId for serialized parallels is 0.
2453 Address ThreadIDAddr = ZeroAddr;
2454 auto &&CodeGen = [this, Fn, CapturedVars, Loc, ZeroAddr, &ThreadIDAddr](
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002455 CodeGenFunction &CGF, PrePostActionTy &Action) {
2456 Action.Enter(CGF);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002457
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002458 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2459 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2460 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2461 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2462 emitOutlinedFunctionCall(CGF, Loc, Fn, OutlinedFnArgs);
2463 };
2464 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2465 PrePostActionTy &) {
2466
2467 RegionCodeGenTy RCG(CodeGen);
2468 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2469 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2470 llvm::Value *Args[] = {RTLoc, ThreadID};
2471
2472 NVPTXActionTy Action(
2473 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2474 Args,
2475 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2476 Args);
2477 RCG.setAction(Action);
2478 RCG(CGF);
2479 };
2480
2481 auto &&L0ParallelGen = [this, CapturedVars, Fn](CodeGenFunction &CGF,
2482 PrePostActionTy &Action) {
2483 CGBuilderTy &Bld = CGF.Builder;
2484 llvm::Function *WFn = WrapperFunctionsMap[Fn];
2485 assert(WFn && "Wrapper function does not exist!");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002486 llvm::Value *ID = Bld.CreateBitOrPointerCast(WFn, CGM.Int8PtrTy);
2487
2488 // Prepare for parallel region. Indicate the outlined function.
2489 llvm::Value *Args[] = {ID, /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002490 CGF.EmitRuntimeCall(
2491 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_prepare_parallel),
2492 Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002493
2494 // Create a private scope that will globalize the arguments
2495 // passed from the outside of the target region.
2496 CodeGenFunction::OMPPrivateScope PrivateArgScope(CGF);
2497
Raphael Isemannb23ccec2018-12-10 12:37:46 +00002498 // There's something to share.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002499 if (!CapturedVars.empty()) {
2500 // Prepare for parallel region. Indicate the outlined function.
2501 Address SharedArgs =
2502 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "shared_arg_refs");
2503 llvm::Value *SharedArgsPtr = SharedArgs.getPointer();
2504
2505 llvm::Value *DataSharingArgs[] = {
2506 SharedArgsPtr,
2507 llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size())};
2508 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2509 OMPRTL_NVPTX__kmpc_begin_sharing_variables),
2510 DataSharingArgs);
2511
2512 // Store variable address in a list of references to pass to workers.
2513 unsigned Idx = 0;
2514 ASTContext &Ctx = CGF.getContext();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002515 Address SharedArgListAddress = CGF.EmitLoadOfPointer(
2516 SharedArgs, Ctx.getPointerType(Ctx.getPointerType(Ctx.VoidPtrTy))
2517 .castAs<PointerType>());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002518 for (llvm::Value *V : CapturedVars) {
James Y Knight751fe282019-02-09 22:22:28 +00002519 Address Dst = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002520 llvm::Value *PtrV;
Alexey Bataev17314212018-03-20 15:41:05 +00002521 if (V->getType()->isIntegerTy())
2522 PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
2523 else
2524 PtrV = Bld.CreatePointerBitCastOrAddrSpaceCast(V, CGF.VoidPtrTy);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002525 CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
2526 Ctx.getPointerType(Ctx.VoidPtrTy));
Alexey Bataevc99042b2018-03-15 18:10:54 +00002527 ++Idx;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002528 }
2529 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002530
2531 // Activate workers. This barrier is used by the master to signal
2532 // work for the workers.
2533 syncCTAThreads(CGF);
2534
2535 // OpenMP [2.5, Parallel Construct, p.49]
2536 // There is an implied barrier at the end of a parallel region. After the
2537 // end of a parallel region, only the master thread of the team resumes
2538 // execution of the enclosing task region.
2539 //
2540 // The master waits at this barrier until all workers are done.
2541 syncCTAThreads(CGF);
2542
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002543 if (!CapturedVars.empty())
2544 CGF.EmitRuntimeCall(
2545 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_sharing_variables));
2546
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002547 // Remember for post-processing in worker loop.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002548 Work.emplace_back(WFn);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002549 };
2550
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002551 auto &&LNParallelGen = [this, Loc, &SeqGen, &L0ParallelGen](
2552 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002553 if (IsInParallelRegion) {
2554 SeqGen(CGF, Action);
2555 } else if (IsInTargetMasterThreadRegion) {
2556 L0ParallelGen(CGF, Action);
2557 } else {
2558 // Check for master and then parallelism:
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002559 // if (__kmpc_is_spmd_exec_mode() || __kmpc_parallel_level(loc, gtid)) {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002560 // Serialized execution.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002561 // } else {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002562 // Worker call.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002563 // }
2564 CGBuilderTy &Bld = CGF.Builder;
2565 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002566 llvm::BasicBlock *SeqBB = CGF.createBasicBlock(".sequential");
2567 llvm::BasicBlock *ParallelCheckBB = CGF.createBasicBlock(".parcheck");
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002568 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
Alexey Bataev673110d2018-05-16 13:36:30 +00002569 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2570 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002571 Bld.CreateCondBr(IsSPMD, SeqBB, ParallelCheckBB);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002572 // There is no need to emit line number for unconditional branch.
2573 (void)ApplyDebugLocation::CreateEmpty(CGF);
2574 CGF.EmitBlock(ParallelCheckBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002575 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2576 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2577 llvm::Value *PL = CGF.EmitRuntimeCall(
2578 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2579 {RTLoc, ThreadID});
2580 llvm::Value *Res = Bld.CreateIsNotNull(PL);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002581 Bld.CreateCondBr(Res, SeqBB, MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002582 CGF.EmitBlock(SeqBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002583 SeqGen(CGF, Action);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002584 CGF.EmitBranch(ExitBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002585 // There is no need to emit line number for unconditional branch.
2586 (void)ApplyDebugLocation::CreateEmpty(CGF);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002587 CGF.EmitBlock(MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002588 L0ParallelGen(CGF, Action);
2589 CGF.EmitBranch(ExitBB);
2590 // There is no need to emit line number for unconditional branch.
2591 (void)ApplyDebugLocation::CreateEmpty(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002592 // Emit the continuation block for code after the if.
2593 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2594 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002595 };
2596
Alexey Bataev9ff80832018-04-16 20:16:21 +00002597 if (IfCond) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002598 emitOMPIfClause(CGF, IfCond, LNParallelGen, SeqGen);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002599 } else {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002600 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002601 RegionCodeGenTy ThenRCG(LNParallelGen);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002602 ThenRCG(CGF);
2603 }
2604}
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002605
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002606void CGOpenMPRuntimeNVPTX::emitSPMDParallelCall(
James Y Knight9871db02019-02-05 16:42:33 +00002607 CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002608 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2609 // Just call the outlined function to execute the parallel region.
2610 // OutlinedFn(&GTid, &zero, CapturedStruct);
2611 //
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002612 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Carlo Bertolli79712092018-02-28 20:48:35 +00002613
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002614 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2615 /*DestWidth=*/32, /*Signed=*/1),
2616 ".zero.addr");
Carlo Bertolli79712092018-02-28 20:48:35 +00002617 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002618 // ThreadId for serialized parallels is 0.
2619 Address ThreadIDAddr = ZeroAddr;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002620 auto &&CodeGen = [this, OutlinedFn, CapturedVars, Loc, ZeroAddr,
Alexey Bataev8521ff62018-07-25 20:03:01 +00002621 &ThreadIDAddr](CodeGenFunction &CGF,
2622 PrePostActionTy &Action) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002623 Action.Enter(CGF);
2624
2625 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2626 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2627 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2628 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2629 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2630 };
2631 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2632 PrePostActionTy &) {
2633
2634 RegionCodeGenTy RCG(CodeGen);
2635 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2636 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2637 llvm::Value *Args[] = {RTLoc, ThreadID};
2638
2639 NVPTXActionTy Action(
2640 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2641 Args,
2642 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2643 Args);
2644 RCG.setAction(Action);
2645 RCG(CGF);
2646 };
2647
2648 if (IsInTargetMasterThreadRegion) {
Alexey Bataev8521ff62018-07-25 20:03:01 +00002649 // In the worker need to use the real thread id.
2650 ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002651 RegionCodeGenTy RCG(CodeGen);
2652 RCG(CGF);
2653 } else {
2654 // If we are not in the target region, it is definitely L2 parallelism or
2655 // more, because for SPMD mode we always has L1 parallel level, sowe don't
2656 // need to check for orphaned directives.
2657 RegionCodeGenTy RCG(SeqGen);
2658 RCG(CGF);
2659 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002660}
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002661
Alexey Bataeva3924b52019-01-03 16:25:35 +00002662void CGOpenMPRuntimeNVPTX::syncCTAThreads(CodeGenFunction &CGF) {
2663 // Always emit simple barriers!
2664 if (!CGF.HaveInsertPoint())
2665 return;
2666 // Build call __kmpc_barrier_simple_spmd(nullptr, 0);
2667 // This function does not use parameters, so we can emit just default values.
2668 llvm::Value *Args[] = {
2669 llvm::ConstantPointerNull::get(
2670 cast<llvm::PointerType>(getIdentTyPointerTy())),
2671 llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/0, /*isSigned=*/true)};
Alexey Bataeva44b2162019-07-18 13:49:24 +00002672 llvm::CallInst *Call = CGF.EmitRuntimeCall(
Alexey Bataeva3924b52019-01-03 16:25:35 +00002673 createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier_simple_spmd), Args);
Alexey Bataeva44b2162019-07-18 13:49:24 +00002674 Call->setConvergent();
Alexey Bataeva3924b52019-01-03 16:25:35 +00002675}
2676
Alexey Bataevc3028ca2018-12-04 15:03:25 +00002677void CGOpenMPRuntimeNVPTX::emitBarrierCall(CodeGenFunction &CGF,
2678 SourceLocation Loc,
2679 OpenMPDirectiveKind Kind, bool,
2680 bool) {
2681 // Always emit simple barriers!
2682 if (!CGF.HaveInsertPoint())
2683 return;
2684 // Build call __kmpc_cancel_barrier(loc, thread_id);
2685 unsigned Flags = getDefaultFlagsForBarriers(Kind);
2686 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2687 getThreadID(CGF, Loc)};
Alexey Bataeva44b2162019-07-18 13:49:24 +00002688 llvm::CallInst *Call = CGF.EmitRuntimeCall(
2689 createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier), Args);
2690 Call->setConvergent();
Alexey Bataevc3028ca2018-12-04 15:03:25 +00002691}
2692
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002693void CGOpenMPRuntimeNVPTX::emitCriticalRegion(
2694 CodeGenFunction &CGF, StringRef CriticalName,
2695 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
2696 const Expr *Hint) {
2697 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
2698 llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
2699 llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
2700 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
2701 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
2702
2703 // Fetch team-local id of the thread.
2704 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
2705
2706 // Get the width of the team.
2707 llvm::Value *TeamWidth = getNVPTXNumThreads(CGF);
2708
2709 // Initialize the counter variable for the loop.
2710 QualType Int32Ty =
2711 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
2712 Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
2713 LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
2714 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
2715 /*isInit=*/true);
2716
2717 // Block checks if loop counter exceeds upper bound.
2718 CGF.EmitBlock(LoopBB);
2719 llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2720 llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
2721 CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
2722
2723 // Block tests which single thread should execute region, and which threads
2724 // should go straight to synchronisation point.
2725 CGF.EmitBlock(TestBB);
2726 CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2727 llvm::Value *CmpThreadToCounter =
2728 CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
2729 CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
2730
2731 // Block emits the body of the critical region.
2732 CGF.EmitBlock(BodyBB);
2733
2734 // Output the critical statement.
Alexey Bataev2c1ff9d2018-12-04 15:25:01 +00002735 CGOpenMPRuntime::emitCriticalRegion(CGF, CriticalName, CriticalOpGen, Loc,
2736 Hint);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002737
2738 // After the body surrounded by the critical region, the single executing
2739 // thread will jump to the synchronisation point.
2740 // Block waits for all threads in current team to finish then increments the
2741 // counter variable and returns to the loop.
2742 CGF.EmitBlock(SyncBB);
Alexey Bataev2c1ff9d2018-12-04 15:25:01 +00002743 emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false,
2744 /*ForceSimpleCall=*/true);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002745
2746 llvm::Value *IncCounterVal =
2747 CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
2748 CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
2749 CGF.EmitBranch(LoopBB);
2750
2751 // Block that is reached when all threads in the team complete the region.
2752 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2753}
2754
Alexey Bataevb2575932018-01-04 20:18:55 +00002755/// Cast value to the specified type.
Alexey Bataeva453f362018-03-19 17:53:56 +00002756static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
2757 QualType ValTy, QualType CastTy,
2758 SourceLocation Loc) {
2759 assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
2760 "Cast type must sized.");
2761 assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
2762 "Val type must sized.");
2763 llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
2764 if (ValTy == CastTy)
Alexey Bataevb2575932018-01-04 20:18:55 +00002765 return Val;
Alexey Bataeva453f362018-03-19 17:53:56 +00002766 if (CGF.getContext().getTypeSizeInChars(ValTy) ==
2767 CGF.getContext().getTypeSizeInChars(CastTy))
2768 return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
2769 if (CastTy->isIntegerType() && ValTy->isIntegerType())
2770 return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
2771 CastTy->hasSignedIntegerRepresentation());
2772 Address CastItem = CGF.CreateMemTemp(CastTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002773 Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2774 CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
Alexey Bataeva453f362018-03-19 17:53:56 +00002775 CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy);
2776 return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc);
Alexey Bataevb2575932018-01-04 20:18:55 +00002777}
2778
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002779/// This function creates calls to one of two shuffle functions to copy
2780/// variables between lanes in a warp.
2781static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002782 llvm::Value *Elem,
Alexey Bataeva453f362018-03-19 17:53:56 +00002783 QualType ElemType,
2784 llvm::Value *Offset,
2785 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002786 CodeGenModule &CGM = CGF.CGM;
2787 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002788 CGOpenMPRuntimeNVPTX &RT =
2789 *(static_cast<CGOpenMPRuntimeNVPTX *>(&CGM.getOpenMPRuntime()));
2790
Alexey Bataeva453f362018-03-19 17:53:56 +00002791 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2792 assert(Size.getQuantity() <= 8 &&
2793 "Unsupported bitwidth in shuffle instruction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002794
Alexey Bataeva453f362018-03-19 17:53:56 +00002795 OpenMPRTLFunctionNVPTX ShuffleFn = Size.getQuantity() <= 4
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002796 ? OMPRTL_NVPTX__kmpc_shuffle_int32
2797 : OMPRTL_NVPTX__kmpc_shuffle_int64;
2798
2799 // Cast all types to 32- or 64-bit values before calling shuffle routines.
Alexey Bataeva453f362018-03-19 17:53:56 +00002800 QualType CastTy = CGF.getContext().getIntTypeForBitwidth(
2801 Size.getQuantity() <= 4 ? 32 : 64, /*Signed=*/1);
2802 llvm::Value *ElemCast = castValueToType(CGF, Elem, ElemType, CastTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002803 llvm::Value *WarpSize =
Alexey Bataevb2575932018-01-04 20:18:55 +00002804 Bld.CreateIntCast(getNVPTXWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002805
Alexey Bataev9ff80832018-04-16 20:16:21 +00002806 llvm::Value *ShuffledVal = CGF.EmitRuntimeCall(
2807 RT.createNVPTXRuntimeFunction(ShuffleFn), {ElemCast, Offset, WarpSize});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002808
Alexey Bataeva453f362018-03-19 17:53:56 +00002809 return castValueToType(CGF, ShuffledVal, CastTy, ElemType, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002810}
2811
Alexey Bataev12c62902018-06-22 19:10:38 +00002812static void shuffleAndStore(CodeGenFunction &CGF, Address SrcAddr,
2813 Address DestAddr, QualType ElemType,
2814 llvm::Value *Offset, SourceLocation Loc) {
2815 CGBuilderTy &Bld = CGF.Builder;
2816
2817 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2818 // Create the loop over the big sized data.
2819 // ptr = (void*)Elem;
2820 // ptrEnd = (void*) Elem + 1;
2821 // Step = 8;
2822 // while (ptr + Step < ptrEnd)
2823 // shuffle((int64_t)*ptr);
2824 // Step = 4;
2825 // while (ptr + Step < ptrEnd)
2826 // shuffle((int32_t)*ptr);
2827 // ...
2828 Address ElemPtr = DestAddr;
2829 Address Ptr = SrcAddr;
2830 Address PtrEnd = Bld.CreatePointerBitCastOrAddrSpaceCast(
James Y Knight751fe282019-02-09 22:22:28 +00002831 Bld.CreateConstGEP(SrcAddr, 1), CGF.VoidPtrTy);
Alexey Bataev12c62902018-06-22 19:10:38 +00002832 for (int IntSize = 8; IntSize >= 1; IntSize /= 2) {
2833 if (Size < CharUnits::fromQuantity(IntSize))
2834 continue;
2835 QualType IntType = CGF.getContext().getIntTypeForBitwidth(
2836 CGF.getContext().toBits(CharUnits::fromQuantity(IntSize)),
2837 /*Signed=*/1);
2838 llvm::Type *IntTy = CGF.ConvertTypeForMem(IntType);
2839 Ptr = Bld.CreatePointerBitCastOrAddrSpaceCast(Ptr, IntTy->getPointerTo());
2840 ElemPtr =
2841 Bld.CreatePointerBitCastOrAddrSpaceCast(ElemPtr, IntTy->getPointerTo());
2842 if (Size.getQuantity() / IntSize > 1) {
2843 llvm::BasicBlock *PreCondBB = CGF.createBasicBlock(".shuffle.pre_cond");
2844 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".shuffle.then");
2845 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".shuffle.exit");
2846 llvm::BasicBlock *CurrentBB = Bld.GetInsertBlock();
2847 CGF.EmitBlock(PreCondBB);
2848 llvm::PHINode *PhiSrc =
2849 Bld.CreatePHI(Ptr.getType(), /*NumReservedValues=*/2);
2850 PhiSrc->addIncoming(Ptr.getPointer(), CurrentBB);
2851 llvm::PHINode *PhiDest =
2852 Bld.CreatePHI(ElemPtr.getType(), /*NumReservedValues=*/2);
2853 PhiDest->addIncoming(ElemPtr.getPointer(), CurrentBB);
2854 Ptr = Address(PhiSrc, Ptr.getAlignment());
2855 ElemPtr = Address(PhiDest, ElemPtr.getAlignment());
2856 llvm::Value *PtrDiff = Bld.CreatePtrDiff(
2857 PtrEnd.getPointer(), Bld.CreatePointerBitCastOrAddrSpaceCast(
2858 Ptr.getPointer(), CGF.VoidPtrTy));
2859 Bld.CreateCondBr(Bld.CreateICmpSGT(PtrDiff, Bld.getInt64(IntSize - 1)),
2860 ThenBB, ExitBB);
2861 CGF.EmitBlock(ThenBB);
2862 llvm::Value *Res = createRuntimeShuffleFunction(
2863 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2864 IntType, Offset, Loc);
2865 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
James Y Knight751fe282019-02-09 22:22:28 +00002866 Address LocalPtr = Bld.CreateConstGEP(Ptr, 1);
2867 Address LocalElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002868 PhiSrc->addIncoming(LocalPtr.getPointer(), ThenBB);
2869 PhiDest->addIncoming(LocalElemPtr.getPointer(), ThenBB);
Alexey Bataev12c62902018-06-22 19:10:38 +00002870 CGF.EmitBranch(PreCondBB);
2871 CGF.EmitBlock(ExitBB);
2872 } else {
2873 llvm::Value *Res = createRuntimeShuffleFunction(
2874 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2875 IntType, Offset, Loc);
2876 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
James Y Knight751fe282019-02-09 22:22:28 +00002877 Ptr = Bld.CreateConstGEP(Ptr, 1);
2878 ElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
Alexey Bataev12c62902018-06-22 19:10:38 +00002879 }
2880 Size = Size % IntSize;
2881 }
2882}
2883
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002884namespace {
2885enum CopyAction : unsigned {
2886 // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
2887 // the warp using shuffle instructions.
2888 RemoteLaneToThread,
2889 // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
2890 ThreadCopy,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002891 // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
2892 ThreadToScratchpad,
2893 // ScratchpadToThread: Copy from a scratchpad array in global memory
2894 // containing team-reduced data to a thread's stack.
2895 ScratchpadToThread,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002896};
2897} // namespace
2898
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002899struct CopyOptionsTy {
2900 llvm::Value *RemoteLaneOffset;
2901 llvm::Value *ScratchpadIndex;
2902 llvm::Value *ScratchpadWidth;
2903};
2904
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002905/// Emit instructions to copy a Reduce list, which contains partially
2906/// aggregated values, in the specified direction.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002907static void emitReductionListCopy(
2908 CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
2909 ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
2910 CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002911
Alexey Bataev9ff80832018-04-16 20:16:21 +00002912 CodeGenModule &CGM = CGF.CGM;
2913 ASTContext &C = CGM.getContext();
2914 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002915
Alexey Bataev9ff80832018-04-16 20:16:21 +00002916 llvm::Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
2917 llvm::Value *ScratchpadIndex = CopyOptions.ScratchpadIndex;
2918 llvm::Value *ScratchpadWidth = CopyOptions.ScratchpadWidth;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002919
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002920 // Iterates, element-by-element, through the source Reduce list and
2921 // make a copy.
2922 unsigned Idx = 0;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002923 unsigned Size = Privates.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00002924 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002925 Address SrcElementAddr = Address::invalid();
2926 Address DestElementAddr = Address::invalid();
2927 Address DestElementPtrAddr = Address::invalid();
2928 // Should we shuffle in an element from a remote lane?
2929 bool ShuffleInElement = false;
2930 // Set to true to update the pointer in the dest Reduce list to a
2931 // newly created element.
2932 bool UpdateDestListPtr = false;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002933 // Increment the src or dest pointer to the scratchpad, for each
2934 // new element.
2935 bool IncrScratchpadSrc = false;
2936 bool IncrScratchpadDest = false;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002937
2938 switch (Action) {
2939 case RemoteLaneToThread: {
2940 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002941 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00002942 SrcElementAddr = CGF.EmitLoadOfPointer(
2943 SrcElementPtrAddr,
2944 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002945
2946 // Step 1.2: Create a temporary to store the element in the destination
2947 // Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002948 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002949 DestElementAddr =
2950 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2951 ShuffleInElement = true;
2952 UpdateDestListPtr = true;
2953 break;
2954 }
2955 case ThreadCopy: {
2956 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002957 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00002958 SrcElementAddr = CGF.EmitLoadOfPointer(
2959 SrcElementPtrAddr,
2960 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002961
2962 // Step 1.2: Get the address for dest element. The destination
2963 // element has already been created on the thread's stack.
James Y Knight751fe282019-02-09 22:22:28 +00002964 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00002965 DestElementAddr = CGF.EmitLoadOfPointer(
2966 DestElementPtrAddr,
2967 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002968 break;
2969 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002970 case ThreadToScratchpad: {
2971 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002972 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00002973 SrcElementAddr = CGF.EmitLoadOfPointer(
2974 SrcElementPtrAddr,
2975 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002976
2977 // Step 1.2: Get the address for dest element:
2978 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00002979 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00002980 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002981 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002982 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002983 Bld.CreateNUWAdd(DestBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002984 ScratchPadElemAbsolutePtrVal =
2985 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002986 DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
2987 C.getTypeAlignInChars(Private->getType()));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002988 IncrScratchpadDest = true;
2989 break;
2990 }
2991 case ScratchpadToThread: {
2992 // Step 1.1: Get the address for the src element in the scratchpad.
2993 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00002994 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00002995 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002996 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002997 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002998 Bld.CreateNUWAdd(SrcBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002999 ScratchPadElemAbsolutePtrVal =
3000 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
3001 SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
3002 C.getTypeAlignInChars(Private->getType()));
3003 IncrScratchpadSrc = true;
3004
3005 // Step 1.2: Create a temporary to store the element in the destination
3006 // Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00003007 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003008 DestElementAddr =
3009 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
3010 UpdateDestListPtr = true;
3011 break;
3012 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003013 }
3014
3015 // Regardless of src and dest of copy, we emit the load of src
3016 // element as this is required in all directions
3017 SrcElementAddr = Bld.CreateElementBitCast(
3018 SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
Alexey Bataev12c62902018-06-22 19:10:38 +00003019 DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
3020 SrcElementAddr.getElementType());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003021
3022 // Now that all active lanes have read the element in the
3023 // Reduce list, shuffle over the value from the remote lane.
Alexey Bataeva453f362018-03-19 17:53:56 +00003024 if (ShuffleInElement) {
Alexey Bataev12c62902018-06-22 19:10:38 +00003025 shuffleAndStore(CGF, SrcElementAddr, DestElementAddr, Private->getType(),
3026 RemoteLaneOffset, Private->getExprLoc());
3027 } else {
Alexey Bataev8061acd2019-02-20 16:36:22 +00003028 switch (CGF.getEvaluationKind(Private->getType())) {
3029 case TEK_Scalar: {
Alexey Bataev12c62902018-06-22 19:10:38 +00003030 llvm::Value *Elem =
3031 CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false,
3032 Private->getType(), Private->getExprLoc());
3033 // Store the source element value to the dest element address.
3034 CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false,
3035 Private->getType());
Alexey Bataev8061acd2019-02-20 16:36:22 +00003036 break;
3037 }
3038 case TEK_Complex: {
3039 CodeGenFunction::ComplexPairTy Elem = CGF.EmitLoadOfComplex(
3040 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3041 Private->getExprLoc());
3042 CGF.EmitStoreOfComplex(
3043 Elem, CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3044 /*isInit=*/false);
3045 break;
3046 }
3047 case TEK_Aggregate:
Alexey Bataev12c62902018-06-22 19:10:38 +00003048 CGF.EmitAggregateCopy(
3049 CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3050 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3051 Private->getType(), AggValueSlot::DoesNotOverlap);
Alexey Bataev8061acd2019-02-20 16:36:22 +00003052 break;
Alexey Bataev12c62902018-06-22 19:10:38 +00003053 }
Alexey Bataeva453f362018-03-19 17:53:56 +00003054 }
Alexey Bataevb2575932018-01-04 20:18:55 +00003055
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003056 // Step 3.1: Modify reference in dest Reduce list as needed.
3057 // Modifying the reference in Reduce list to point to the newly
3058 // created element. The element is live in the current function
3059 // scope and that of functions it invokes (i.e., reduce_function).
3060 // RemoteReduceData[i] = (void*)&RemoteElem
3061 if (UpdateDestListPtr) {
3062 CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
3063 DestElementAddr.getPointer(), CGF.VoidPtrTy),
3064 DestElementPtrAddr, /*Volatile=*/false,
3065 C.VoidPtrTy);
3066 }
3067
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003068 // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
3069 // address of the next element in scratchpad memory, unless we're currently
3070 // processing the last one. Memory alignment is also taken care of here.
3071 if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
3072 llvm::Value *ScratchpadBasePtr =
3073 IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
Alexey Bataeve290ec02018-04-06 16:03:36 +00003074 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
3075 ScratchpadBasePtr = Bld.CreateNUWAdd(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003076 ScratchpadBasePtr,
Alexey Bataeve290ec02018-04-06 16:03:36 +00003077 Bld.CreateNUWMul(ScratchpadWidth, ElementSizeInChars));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003078
3079 // Take care of global memory alignment for performance
Alexey Bataeve290ec02018-04-06 16:03:36 +00003080 ScratchpadBasePtr = Bld.CreateNUWSub(
3081 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3082 ScratchpadBasePtr = Bld.CreateUDiv(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003083 ScratchpadBasePtr,
3084 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
Alexey Bataeve290ec02018-04-06 16:03:36 +00003085 ScratchpadBasePtr = Bld.CreateNUWAdd(
3086 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3087 ScratchpadBasePtr = Bld.CreateNUWMul(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003088 ScratchpadBasePtr,
3089 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
3090
3091 if (IncrScratchpadDest)
3092 DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3093 else /* IncrScratchpadSrc = true */
3094 SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3095 }
3096
Alexey Bataev9ff80832018-04-16 20:16:21 +00003097 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003098 }
3099}
3100
3101/// This function emits a helper that gathers Reduce lists from the first
3102/// lane of every active warp to lanes in the first warp.
3103///
3104/// void inter_warp_copy_func(void* reduce_data, num_warps)
3105/// shared smem[warp_size];
3106/// For all data entries D in reduce_data:
Alexey Bataev29d47fc2018-12-18 19:20:15 +00003107/// sync
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003108/// If (I am the first lane in each warp)
3109/// Copy my local D to smem[warp_id]
3110/// sync
3111/// if (I am the first warp)
3112/// Copy smem[thread_id] to my local D
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003113static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
3114 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003115 QualType ReductionArrayTy,
3116 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003117 ASTContext &C = CGM.getContext();
3118 llvm::Module &M = CGM.getModule();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003119
3120 // ReduceList: thread local Reduce list.
3121 // At the stage of the computation when this function is called, partially
3122 // aggregated values reside in the first lane of every active warp.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003123 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3124 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003125 // NumWarps: number of warps active in the parallel region. This could
3126 // be smaller than 32 (max warps in a CTA) for partial block reduction.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003127 ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00003128 C.getIntTypeForBitwidth(32, /* Signed */ true),
3129 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003130 FunctionArgList Args;
3131 Args.push_back(&ReduceListArg);
3132 Args.push_back(&NumWarpsArg);
3133
Alexey Bataev9ff80832018-04-16 20:16:21 +00003134 const CGFunctionInfo &CGFI =
3135 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev8061acd2019-02-20 16:36:22 +00003136 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
3137 llvm::GlobalValue::InternalLinkage,
3138 "_omp_reduction_inter_warp_copy_func", &M);
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003139 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003140 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003141 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003142 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003143
Alexey Bataev9ff80832018-04-16 20:16:21 +00003144 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003145
3146 // This array is used as a medium to transfer, one reduce element at a time,
3147 // the data from the first lane of every warp to lanes in the first warp
3148 // in order to perform the final step of a reduction in a parallel region
3149 // (reduction across warps). The array is placed in NVPTX __shared__ memory
3150 // for reduced latency, as well as to have a distinct copy for concurrently
3151 // executing target regions. The array is declared with common linkage so
3152 // as to be shared across compilation units.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003153 StringRef TransferMediumName =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003154 "__openmp_nvptx_data_transfer_temporary_storage";
3155 llvm::GlobalVariable *TransferMedium =
3156 M.getGlobalVariable(TransferMediumName);
3157 if (!TransferMedium) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003158 auto *Ty = llvm::ArrayType::get(CGM.Int32Ty, WarpSize);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003159 unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
3160 TransferMedium = new llvm::GlobalVariable(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003161 M, Ty, /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003162 llvm::Constant::getNullValue(Ty), TransferMediumName,
3163 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3164 SharedAddressSpace);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003165 CGM.addCompilerUsedGlobal(TransferMedium);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003166 }
3167
3168 // Get the CUDA thread id of the current OpenMP thread on the GPU.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003169 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003170 // nvptx_lane_id = nvptx_id % warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003171 llvm::Value *LaneID = getNVPTXLaneID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003172 // nvptx_warp_id = nvptx_id / warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003173 llvm::Value *WarpID = getNVPTXWarpID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003174
3175 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3176 Address LocalReduceList(
3177 Bld.CreatePointerBitCastOrAddrSpaceCast(
3178 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003179 C.VoidPtrTy, Loc),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003180 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3181 CGF.getPointerAlign());
3182
3183 unsigned Idx = 0;
Alexey Bataev9ff80832018-04-16 20:16:21 +00003184 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003185 //
3186 // Warp master copies reduce element to transfer medium in __shared__
3187 // memory.
3188 //
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003189 unsigned RealTySize =
3190 C.getTypeSizeInChars(Private->getType())
3191 .alignTo(C.getTypeAlignInChars(Private->getType()))
3192 .getQuantity();
3193 for (unsigned TySize = 4; TySize > 0 && RealTySize > 0; TySize /=2) {
3194 unsigned NumIters = RealTySize / TySize;
3195 if (NumIters == 0)
3196 continue;
3197 QualType CType = C.getIntTypeForBitwidth(
3198 C.toBits(CharUnits::fromQuantity(TySize)), /*Signed=*/1);
3199 llvm::Type *CopyType = CGF.ConvertTypeForMem(CType);
3200 CharUnits Align = CharUnits::fromQuantity(TySize);
3201 llvm::Value *Cnt = nullptr;
3202 Address CntAddr = Address::invalid();
3203 llvm::BasicBlock *PrecondBB = nullptr;
3204 llvm::BasicBlock *ExitBB = nullptr;
3205 if (NumIters > 1) {
3206 CntAddr = CGF.CreateMemTemp(C.IntTy, ".cnt.addr");
3207 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.IntTy), CntAddr,
3208 /*Volatile=*/false, C.IntTy);
3209 PrecondBB = CGF.createBasicBlock("precond");
3210 ExitBB = CGF.createBasicBlock("exit");
3211 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("body");
3212 // There is no need to emit line number for unconditional branch.
3213 (void)ApplyDebugLocation::CreateEmpty(CGF);
3214 CGF.EmitBlock(PrecondBB);
3215 Cnt = CGF.EmitLoadOfScalar(CntAddr, /*Volatile=*/false, C.IntTy, Loc);
3216 llvm::Value *Cmp =
3217 Bld.CreateICmpULT(Cnt, llvm::ConstantInt::get(CGM.IntTy, NumIters));
3218 Bld.CreateCondBr(Cmp, BodyBB, ExitBB);
3219 CGF.EmitBlock(BodyBB);
3220 }
Alexey Bataev29d47fc2018-12-18 19:20:15 +00003221 // kmpc_barrier.
3222 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3223 /*EmitChecks=*/false,
3224 /*ForceSimpleCall=*/true);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003225 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3226 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3227 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003228
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003229 // if (lane_id == 0)
3230 llvm::Value *IsWarpMaster = Bld.CreateIsNull(LaneID, "warp_master");
3231 Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
3232 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003233
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003234 // Reduce element = LocalReduceList[i]
James Y Knight751fe282019-02-09 22:22:28 +00003235 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003236 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3237 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3238 // elemptr = ((CopyType*)(elemptrptr)) + I
3239 Address ElemPtr = Address(ElemPtrPtr, Align);
3240 ElemPtr = Bld.CreateElementBitCast(ElemPtr, CopyType);
3241 if (NumIters > 1) {
3242 ElemPtr = Address(Bld.CreateGEP(ElemPtr.getPointer(), Cnt),
3243 ElemPtr.getAlignment());
3244 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003245
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003246 // Get pointer to location in transfer medium.
3247 // MediumPtr = &medium[warp_id]
3248 llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
3249 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
3250 Address MediumPtr(MediumPtrVal, Align);
3251 // Casting to actual data type.
3252 // MediumPtr = (CopyType*)MediumPtrAddr;
3253 MediumPtr = Bld.CreateElementBitCast(MediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003254
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003255 // elem = *elemptr
3256 //*MediumPtr = elem
3257 llvm::Value *Elem =
3258 CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003259 // Store the source element value to the dest element address.
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003260 CGF.EmitStoreOfScalar(Elem, MediumPtr, /*Volatile=*/true, CType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003261
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003262 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003263
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003264 CGF.EmitBlock(ElseBB);
3265 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003266
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003267 CGF.EmitBlock(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003268
Alexey Bataevae51b962018-12-14 21:00:58 +00003269 // kmpc_barrier.
3270 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3271 /*EmitChecks=*/false,
3272 /*ForceSimpleCall=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003273
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003274 //
3275 // Warp 0 copies reduce element from transfer medium.
3276 //
3277 llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
3278 llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
3279 llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003280
Alexey Bataevae51b962018-12-14 21:00:58 +00003281 Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
3282 llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
3283 AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, Loc);
3284
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003285 // Up to 32 threads in warp 0 are active.
3286 llvm::Value *IsActiveThread =
3287 Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
3288 Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003289
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003290 CGF.EmitBlock(W0ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003291
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003292 // SrcMediumPtr = &medium[tid]
3293 llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
3294 TransferMedium,
3295 {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
3296 Address SrcMediumPtr(SrcMediumPtrVal, Align);
3297 // SrcMediumVal = *SrcMediumPtr;
3298 SrcMediumPtr = Bld.CreateElementBitCast(SrcMediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003299
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003300 // TargetElemPtr = (CopyType*)(SrcDataAddr[i]) + I
James Y Knight751fe282019-02-09 22:22:28 +00003301 Address TargetElemPtrPtr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003302 llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
3303 TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, Loc);
3304 Address TargetElemPtr = Address(TargetElemPtrVal, Align);
3305 TargetElemPtr = Bld.CreateElementBitCast(TargetElemPtr, CopyType);
3306 if (NumIters > 1) {
3307 TargetElemPtr = Address(Bld.CreateGEP(TargetElemPtr.getPointer(), Cnt),
3308 TargetElemPtr.getAlignment());
3309 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003310
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003311 // *TargetElemPtr = SrcMediumVal;
3312 llvm::Value *SrcMediumValue =
3313 CGF.EmitLoadOfScalar(SrcMediumPtr, /*Volatile=*/true, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003314 CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003315 CType);
3316 Bld.CreateBr(W0MergeBB);
3317
3318 CGF.EmitBlock(W0ElseBB);
3319 Bld.CreateBr(W0MergeBB);
3320
3321 CGF.EmitBlock(W0MergeBB);
3322
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003323 if (NumIters > 1) {
3324 Cnt = Bld.CreateNSWAdd(Cnt, llvm::ConstantInt::get(CGM.IntTy, /*V=*/1));
3325 CGF.EmitStoreOfScalar(Cnt, CntAddr, /*Volatile=*/false, C.IntTy);
3326 CGF.EmitBranch(PrecondBB);
3327 (void)ApplyDebugLocation::CreateEmpty(CGF);
3328 CGF.EmitBlock(ExitBB);
3329 }
3330 RealTySize %= TySize;
Alexey Bataev12c62902018-06-22 19:10:38 +00003331 }
Alexey Bataev9ff80832018-04-16 20:16:21 +00003332 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003333 }
3334
3335 CGF.FinishFunction();
3336 return Fn;
3337}
3338
3339/// Emit a helper that reduces data across two OpenMP threads (lanes)
3340/// in the same warp. It uses shuffle instructions to copy over data from
3341/// a remote lane's stack. The reduction algorithm performed is specified
3342/// by the fourth parameter.
3343///
3344/// Algorithm Versions.
3345/// Full Warp Reduce (argument value 0):
3346/// This algorithm assumes that all 32 lanes are active and gathers
3347/// data from these 32 lanes, producing a single resultant value.
3348/// Contiguous Partial Warp Reduce (argument value 1):
3349/// This algorithm assumes that only a *contiguous* subset of lanes
3350/// are active. This happens for the last warp in a parallel region
3351/// when the user specified num_threads is not an integer multiple of
3352/// 32. This contiguous subset always starts with the zeroth lane.
3353/// Partial Warp Reduce (argument value 2):
3354/// This algorithm gathers data from any number of lanes at any position.
3355/// All reduced values are stored in the lowest possible lane. The set
3356/// of problems every algorithm addresses is a super set of those
3357/// addressable by algorithms with a lower version number. Overhead
3358/// increases as algorithm version increases.
3359///
3360/// Terminology
3361/// Reduce element:
3362/// Reduce element refers to the individual data field with primitive
3363/// data types to be combined and reduced across threads.
3364/// Reduce list:
3365/// Reduce list refers to a collection of local, thread-private
3366/// reduce elements.
3367/// Remote Reduce list:
3368/// Remote Reduce list refers to a collection of remote (relative to
3369/// the current thread) reduce elements.
3370///
3371/// We distinguish between three states of threads that are important to
3372/// the implementation of this function.
3373/// Alive threads:
3374/// Threads in a warp executing the SIMT instruction, as distinguished from
3375/// threads that are inactive due to divergent control flow.
3376/// Active threads:
3377/// The minimal set of threads that has to be alive upon entry to this
3378/// function. The computation is correct iff active threads are alive.
3379/// Some threads are alive but they are not active because they do not
3380/// contribute to the computation in any useful manner. Turning them off
3381/// may introduce control flow overheads without any tangible benefits.
3382/// Effective threads:
3383/// In order to comply with the argument requirements of the shuffle
3384/// function, we must keep all lanes holding data alive. But at most
3385/// half of them perform value aggregation; we refer to this half of
3386/// threads as effective. The other half is simply handing off their
3387/// data.
3388///
3389/// Procedure
3390/// Value shuffle:
3391/// In this step active threads transfer data from higher lane positions
3392/// in the warp to lower lane positions, creating Remote Reduce list.
3393/// Value aggregation:
3394/// In this step, effective threads combine their thread local Reduce list
3395/// with Remote Reduce list and store the result in the thread local
3396/// Reduce list.
3397/// Value copy:
3398/// In this step, we deal with the assumption made by algorithm 2
3399/// (i.e. contiguity assumption). When we have an odd number of lanes
3400/// active, say 2k+1, only k threads will be effective and therefore k
3401/// new values will be produced. However, the Reduce list owned by the
3402/// (2k+1)th thread is ignored in the value aggregation. Therefore
3403/// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
3404/// that the contiguity assumption still holds.
James Y Knight9871db02019-02-05 16:42:33 +00003405static llvm::Function *emitShuffleAndReduceFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003406 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
James Y Knight9871db02019-02-05 16:42:33 +00003407 QualType ReductionArrayTy, llvm::Function *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003408 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003409
3410 // Thread local Reduce list used to host the values of data to be reduced.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003411 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3412 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003413 // Current lane id; could be logical.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003414 ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
3415 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003416 // Offset of the remote source lane relative to the current lane.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003417 ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3418 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003419 // Algorithm version. This is expected to be known at compile time.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003420 ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3421 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003422 FunctionArgList Args;
3423 Args.push_back(&ReduceListArg);
3424 Args.push_back(&LaneIDArg);
3425 Args.push_back(&RemoteLaneOffsetArg);
3426 Args.push_back(&AlgoVerArg);
3427
Alexey Bataev9ff80832018-04-16 20:16:21 +00003428 const CGFunctionInfo &CGFI =
3429 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003430 auto *Fn = llvm::Function::Create(
3431 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3432 "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003433 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003434 Fn->setDoesNotRecurse();
Alexey Bataev8c5555c2019-05-21 15:11:58 +00003435 if (CGM.getLangOpts().Optimize) {
3436 Fn->removeFnAttr(llvm::Attribute::NoInline);
3437 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
3438 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
3439 }
3440
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003441 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003442 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003443
Alexey Bataev9ff80832018-04-16 20:16:21 +00003444 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003445
3446 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3447 Address LocalReduceList(
3448 Bld.CreatePointerBitCastOrAddrSpaceCast(
3449 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3450 C.VoidPtrTy, SourceLocation()),
3451 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3452 CGF.getPointerAlign());
3453
3454 Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
3455 llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
3456 AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3457
3458 Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
3459 llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
3460 AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3461
3462 Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
3463 llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
3464 AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3465
3466 // Create a local thread-private variable to host the Reduce list
3467 // from a remote lane.
3468 Address RemoteReduceList =
3469 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
3470
3471 // This loop iterates through the list of reduce elements and copies,
3472 // element by element, from a remote lane in the warp to RemoteReduceList,
3473 // hosted on the thread's stack.
3474 emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
3475 LocalReduceList, RemoteReduceList,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003476 {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
3477 /*ScratchpadIndex=*/nullptr,
3478 /*ScratchpadWidth=*/nullptr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003479
3480 // The actions to be performed on the Remote Reduce list is dependent
3481 // on the algorithm version.
3482 //
3483 // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
3484 // LaneId % 2 == 0 && Offset > 0):
3485 // do the reduction value aggregation
3486 //
3487 // The thread local variable Reduce list is mutated in place to host the
3488 // reduced data, which is the aggregated value produced from local and
3489 // remote lanes.
3490 //
3491 // Note that AlgoVer is expected to be a constant integer known at compile
3492 // time.
3493 // When AlgoVer==0, the first conjunction evaluates to true, making
3494 // the entire predicate true during compile time.
3495 // When AlgoVer==1, the second conjunction has only the second part to be
3496 // evaluated during runtime. Other conjunctions evaluates to false
3497 // during compile time.
3498 // When AlgoVer==2, the third conjunction has only the second part to be
3499 // evaluated during runtime. Other conjunctions evaluates to false
3500 // during compile time.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003501 llvm::Value *CondAlgo0 = Bld.CreateIsNull(AlgoVerArgVal);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003502
Alexey Bataev9ff80832018-04-16 20:16:21 +00003503 llvm::Value *Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
3504 llvm::Value *CondAlgo1 = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003505 Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
3506
Alexey Bataev9ff80832018-04-16 20:16:21 +00003507 llvm::Value *Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
3508 llvm::Value *CondAlgo2 = Bld.CreateAnd(
3509 Algo2, Bld.CreateIsNull(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1))));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003510 CondAlgo2 = Bld.CreateAnd(
3511 CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
3512
Alexey Bataev9ff80832018-04-16 20:16:21 +00003513 llvm::Value *CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003514 CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
3515
3516 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3517 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3518 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
3519 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
3520
3521 CGF.EmitBlock(ThenBB);
3522 // reduce_function(LocalReduceList, RemoteReduceList)
3523 llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3524 LocalReduceList.getPointer(), CGF.VoidPtrTy);
3525 llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3526 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003527 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3528 CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003529 Bld.CreateBr(MergeBB);
3530
3531 CGF.EmitBlock(ElseBB);
3532 Bld.CreateBr(MergeBB);
3533
3534 CGF.EmitBlock(MergeBB);
3535
3536 // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
3537 // Reduce list.
3538 Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
Alexey Bataev9ff80832018-04-16 20:16:21 +00003539 llvm::Value *CondCopy = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003540 Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
3541
3542 llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
3543 llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
3544 llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
3545 Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
3546
3547 CGF.EmitBlock(CpyThenBB);
3548 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
3549 RemoteReduceList, LocalReduceList);
3550 Bld.CreateBr(CpyMergeBB);
3551
3552 CGF.EmitBlock(CpyElseBB);
3553 Bld.CreateBr(CpyMergeBB);
3554
3555 CGF.EmitBlock(CpyMergeBB);
3556
3557 CGF.FinishFunction();
3558 return Fn;
3559}
3560
Alexey Bataev8061acd2019-02-20 16:36:22 +00003561/// This function emits a helper that copies all the reduction variables from
3562/// the team into the provided global buffer for the reduction variables.
3563///
3564/// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
3565/// For all data entries D in reduce_data:
3566/// Copy local D to buffer.D[Idx]
3567static llvm::Value *emitListToGlobalCopyFunction(
3568 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3569 QualType ReductionArrayTy, SourceLocation Loc,
3570 const RecordDecl *TeamReductionRec,
3571 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3572 &VarFieldMap) {
3573 ASTContext &C = CGM.getContext();
3574
3575 // Buffer: global reduction buffer.
3576 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3577 C.VoidPtrTy, ImplicitParamDecl::Other);
3578 // Idx: index of the buffer.
3579 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3580 ImplicitParamDecl::Other);
3581 // ReduceList: thread local Reduce list.
3582 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3583 C.VoidPtrTy, ImplicitParamDecl::Other);
3584 FunctionArgList Args;
3585 Args.push_back(&BufferArg);
3586 Args.push_back(&IdxArg);
3587 Args.push_back(&ReduceListArg);
3588
3589 const CGFunctionInfo &CGFI =
3590 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3591 auto *Fn = llvm::Function::Create(
3592 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3593 "_omp_reduction_list_to_global_copy_func", &CGM.getModule());
3594 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3595 Fn->setDoesNotRecurse();
3596 CodeGenFunction CGF(CGM);
3597 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3598
3599 CGBuilderTy &Bld = CGF.Builder;
3600
3601 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3602 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3603 Address LocalReduceList(
3604 Bld.CreatePointerBitCastOrAddrSpaceCast(
3605 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3606 C.VoidPtrTy, Loc),
3607 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3608 CGF.getPointerAlign());
3609 QualType StaticTy = C.getRecordType(TeamReductionRec);
3610 llvm::Type *LLVMReductionsBufferTy =
3611 CGM.getTypes().ConvertTypeForMem(StaticTy);
3612 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3613 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3614 LLVMReductionsBufferTy->getPointerTo());
3615 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3616 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3617 /*Volatile=*/false, C.IntTy,
3618 Loc)};
3619 unsigned Idx = 0;
3620 for (const Expr *Private : Privates) {
3621 // Reduce element = LocalReduceList[i]
3622 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
3623 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3624 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3625 // elemptr = ((CopyType*)(elemptrptr)) + I
3626 ElemPtrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3627 ElemPtrPtr, CGF.ConvertTypeForMem(Private->getType())->getPointerTo());
3628 Address ElemPtr =
3629 Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
3630 const ValueDecl *VD = cast<DeclRefExpr>(Private)->getDecl();
3631 // Global = Buffer.VD[Idx];
3632 const FieldDecl *FD = VarFieldMap.lookup(VD);
3633 LValue GlobLVal = CGF.EmitLValueForField(
3634 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3635 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3636 GlobLVal.setAddress(Address(BufferPtr, GlobLVal.getAlignment()));
3637 switch (CGF.getEvaluationKind(Private->getType())) {
3638 case TEK_Scalar: {
3639 llvm::Value *V = CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false,
3640 Private->getType(), Loc);
3641 CGF.EmitStoreOfScalar(V, GlobLVal);
3642 break;
3643 }
3644 case TEK_Complex: {
3645 CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(
3646 CGF.MakeAddrLValue(ElemPtr, Private->getType()), Loc);
3647 CGF.EmitStoreOfComplex(V, GlobLVal, /*isInit=*/false);
3648 break;
3649 }
3650 case TEK_Aggregate:
3651 CGF.EmitAggregateCopy(GlobLVal,
3652 CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3653 Private->getType(), AggValueSlot::DoesNotOverlap);
3654 break;
3655 }
3656 ++Idx;
3657 }
3658
3659 CGF.FinishFunction();
3660 return Fn;
3661}
3662
3663/// This function emits a helper that reduces all the reduction variables from
3664/// the team into the provided global buffer for the reduction variables.
3665///
3666/// void list_to_global_reduce_func(void *buffer, int Idx, void *reduce_data)
3667/// void *GlobPtrs[];
3668/// GlobPtrs[0] = (void*)&buffer.D0[Idx];
3669/// ...
3670/// GlobPtrs[N] = (void*)&buffer.DN[Idx];
3671/// reduce_function(GlobPtrs, reduce_data);
3672static llvm::Value *emitListToGlobalReduceFunction(
3673 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3674 QualType ReductionArrayTy, SourceLocation Loc,
3675 const RecordDecl *TeamReductionRec,
3676 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3677 &VarFieldMap,
3678 llvm::Function *ReduceFn) {
3679 ASTContext &C = CGM.getContext();
3680
3681 // Buffer: global reduction buffer.
3682 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3683 C.VoidPtrTy, ImplicitParamDecl::Other);
3684 // Idx: index of the buffer.
3685 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3686 ImplicitParamDecl::Other);
3687 // ReduceList: thread local Reduce list.
3688 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3689 C.VoidPtrTy, ImplicitParamDecl::Other);
3690 FunctionArgList Args;
3691 Args.push_back(&BufferArg);
3692 Args.push_back(&IdxArg);
3693 Args.push_back(&ReduceListArg);
3694
3695 const CGFunctionInfo &CGFI =
3696 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3697 auto *Fn = llvm::Function::Create(
3698 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3699 "_omp_reduction_list_to_global_reduce_func", &CGM.getModule());
3700 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3701 Fn->setDoesNotRecurse();
3702 CodeGenFunction CGF(CGM);
3703 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3704
3705 CGBuilderTy &Bld = CGF.Builder;
3706
3707 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3708 QualType StaticTy = C.getRecordType(TeamReductionRec);
3709 llvm::Type *LLVMReductionsBufferTy =
3710 CGM.getTypes().ConvertTypeForMem(StaticTy);
3711 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3712 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3713 LLVMReductionsBufferTy->getPointerTo());
3714
3715 // 1. Build a list of reduction variables.
3716 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3717 Address ReductionList =
3718 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3719 auto IPriv = Privates.begin();
3720 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3721 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3722 /*Volatile=*/false, C.IntTy,
3723 Loc)};
3724 unsigned Idx = 0;
3725 for (unsigned I = 0, E = Privates.size(); I < E; ++I, ++IPriv, ++Idx) {
3726 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3727 // Global = Buffer.VD[Idx];
3728 const ValueDecl *VD = cast<DeclRefExpr>(*IPriv)->getDecl();
3729 const FieldDecl *FD = VarFieldMap.lookup(VD);
3730 LValue GlobLVal = CGF.EmitLValueForField(
3731 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3732 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3733 llvm::Value *Ptr = CGF.EmitCastToVoidPtr(BufferPtr);
3734 CGF.EmitStoreOfScalar(Ptr, Elem, /*Volatile=*/false, C.VoidPtrTy);
3735 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3736 // Store array size.
3737 ++Idx;
3738 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3739 llvm::Value *Size = CGF.Builder.CreateIntCast(
3740 CGF.getVLASize(
3741 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3742 .NumElts,
3743 CGF.SizeTy, /*isSigned=*/false);
3744 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3745 Elem);
3746 }
3747 }
3748
3749 // Call reduce_function(GlobalReduceList, ReduceList)
3750 llvm::Value *GlobalReduceList =
3751 CGF.EmitCastToVoidPtr(ReductionList.getPointer());
3752 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3753 llvm::Value *ReducedPtr = CGF.EmitLoadOfScalar(
3754 AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
3755 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3756 CGF, Loc, ReduceFn, {GlobalReduceList, ReducedPtr});
3757 CGF.FinishFunction();
3758 return Fn;
3759}
3760
3761/// This function emits a helper that copies all the reduction variables from
3762/// the team into the provided global buffer for the reduction variables.
3763///
3764/// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
3765/// For all data entries D in reduce_data:
3766/// Copy buffer.D[Idx] to local D;
3767static llvm::Value *emitGlobalToListCopyFunction(
3768 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3769 QualType ReductionArrayTy, SourceLocation Loc,
3770 const RecordDecl *TeamReductionRec,
3771 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3772 &VarFieldMap) {
3773 ASTContext &C = CGM.getContext();
3774
3775 // Buffer: global reduction buffer.
3776 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3777 C.VoidPtrTy, ImplicitParamDecl::Other);
3778 // Idx: index of the buffer.
3779 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3780 ImplicitParamDecl::Other);
3781 // ReduceList: thread local Reduce list.
3782 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3783 C.VoidPtrTy, ImplicitParamDecl::Other);
3784 FunctionArgList Args;
3785 Args.push_back(&BufferArg);
3786 Args.push_back(&IdxArg);
3787 Args.push_back(&ReduceListArg);
3788
3789 const CGFunctionInfo &CGFI =
3790 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3791 auto *Fn = llvm::Function::Create(
3792 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3793 "_omp_reduction_global_to_list_copy_func", &CGM.getModule());
3794 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3795 Fn->setDoesNotRecurse();
3796 CodeGenFunction CGF(CGM);
3797 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3798
3799 CGBuilderTy &Bld = CGF.Builder;
3800
3801 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3802 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3803 Address LocalReduceList(
3804 Bld.CreatePointerBitCastOrAddrSpaceCast(
3805 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3806 C.VoidPtrTy, Loc),
3807 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3808 CGF.getPointerAlign());
3809 QualType StaticTy = C.getRecordType(TeamReductionRec);
3810 llvm::Type *LLVMReductionsBufferTy =
3811 CGM.getTypes().ConvertTypeForMem(StaticTy);
3812 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3813 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3814 LLVMReductionsBufferTy->getPointerTo());
3815
3816 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3817 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3818 /*Volatile=*/false, C.IntTy,
3819 Loc)};
3820 unsigned Idx = 0;
3821 for (const Expr *Private : Privates) {
3822 // Reduce element = LocalReduceList[i]
3823 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
3824 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3825 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3826 // elemptr = ((CopyType*)(elemptrptr)) + I
3827 ElemPtrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3828 ElemPtrPtr, CGF.ConvertTypeForMem(Private->getType())->getPointerTo());
3829 Address ElemPtr =
3830 Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
3831 const ValueDecl *VD = cast<DeclRefExpr>(Private)->getDecl();
3832 // Global = Buffer.VD[Idx];
3833 const FieldDecl *FD = VarFieldMap.lookup(VD);
3834 LValue GlobLVal = CGF.EmitLValueForField(
3835 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3836 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3837 GlobLVal.setAddress(Address(BufferPtr, GlobLVal.getAlignment()));
3838 switch (CGF.getEvaluationKind(Private->getType())) {
3839 case TEK_Scalar: {
3840 llvm::Value *V = CGF.EmitLoadOfScalar(GlobLVal, Loc);
3841 CGF.EmitStoreOfScalar(V, ElemPtr, /*Volatile=*/false, Private->getType());
3842 break;
3843 }
3844 case TEK_Complex: {
3845 CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(GlobLVal, Loc);
3846 CGF.EmitStoreOfComplex(V, CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3847 /*isInit=*/false);
3848 break;
3849 }
3850 case TEK_Aggregate:
3851 CGF.EmitAggregateCopy(CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3852 GlobLVal, Private->getType(),
3853 AggValueSlot::DoesNotOverlap);
3854 break;
3855 }
3856 ++Idx;
3857 }
3858
3859 CGF.FinishFunction();
3860 return Fn;
3861}
3862
3863/// This function emits a helper that reduces all the reduction variables from
3864/// the team into the provided global buffer for the reduction variables.
3865///
3866/// void global_to_list_reduce_func(void *buffer, int Idx, void *reduce_data)
3867/// void *GlobPtrs[];
3868/// GlobPtrs[0] = (void*)&buffer.D0[Idx];
3869/// ...
3870/// GlobPtrs[N] = (void*)&buffer.DN[Idx];
3871/// reduce_function(reduce_data, GlobPtrs);
3872static llvm::Value *emitGlobalToListReduceFunction(
3873 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3874 QualType ReductionArrayTy, SourceLocation Loc,
3875 const RecordDecl *TeamReductionRec,
3876 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3877 &VarFieldMap,
3878 llvm::Function *ReduceFn) {
3879 ASTContext &C = CGM.getContext();
3880
3881 // Buffer: global reduction buffer.
3882 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3883 C.VoidPtrTy, ImplicitParamDecl::Other);
3884 // Idx: index of the buffer.
3885 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3886 ImplicitParamDecl::Other);
3887 // ReduceList: thread local Reduce list.
3888 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3889 C.VoidPtrTy, ImplicitParamDecl::Other);
3890 FunctionArgList Args;
3891 Args.push_back(&BufferArg);
3892 Args.push_back(&IdxArg);
3893 Args.push_back(&ReduceListArg);
3894
3895 const CGFunctionInfo &CGFI =
3896 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3897 auto *Fn = llvm::Function::Create(
3898 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3899 "_omp_reduction_global_to_list_reduce_func", &CGM.getModule());
3900 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3901 Fn->setDoesNotRecurse();
3902 CodeGenFunction CGF(CGM);
3903 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3904
3905 CGBuilderTy &Bld = CGF.Builder;
3906
3907 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3908 QualType StaticTy = C.getRecordType(TeamReductionRec);
3909 llvm::Type *LLVMReductionsBufferTy =
3910 CGM.getTypes().ConvertTypeForMem(StaticTy);
3911 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3912 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3913 LLVMReductionsBufferTy->getPointerTo());
3914
3915 // 1. Build a list of reduction variables.
3916 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3917 Address ReductionList =
3918 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3919 auto IPriv = Privates.begin();
3920 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3921 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3922 /*Volatile=*/false, C.IntTy,
3923 Loc)};
3924 unsigned Idx = 0;
3925 for (unsigned I = 0, E = Privates.size(); I < E; ++I, ++IPriv, ++Idx) {
3926 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3927 // Global = Buffer.VD[Idx];
3928 const ValueDecl *VD = cast<DeclRefExpr>(*IPriv)->getDecl();
3929 const FieldDecl *FD = VarFieldMap.lookup(VD);
3930 LValue GlobLVal = CGF.EmitLValueForField(
3931 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3932 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3933 llvm::Value *Ptr = CGF.EmitCastToVoidPtr(BufferPtr);
3934 CGF.EmitStoreOfScalar(Ptr, Elem, /*Volatile=*/false, C.VoidPtrTy);
3935 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3936 // Store array size.
3937 ++Idx;
3938 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3939 llvm::Value *Size = CGF.Builder.CreateIntCast(
3940 CGF.getVLASize(
3941 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3942 .NumElts,
3943 CGF.SizeTy, /*isSigned=*/false);
3944 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3945 Elem);
3946 }
3947 }
3948
3949 // Call reduce_function(ReduceList, GlobalReduceList)
3950 llvm::Value *GlobalReduceList =
3951 CGF.EmitCastToVoidPtr(ReductionList.getPointer());
3952 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3953 llvm::Value *ReducedPtr = CGF.EmitLoadOfScalar(
3954 AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
3955 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3956 CGF, Loc, ReduceFn, {ReducedPtr, GlobalReduceList});
3957 CGF.FinishFunction();
3958 return Fn;
3959}
3960
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003961///
3962/// Design of OpenMP reductions on the GPU
3963///
3964/// Consider a typical OpenMP program with one or more reduction
3965/// clauses:
3966///
3967/// float foo;
3968/// double bar;
3969/// #pragma omp target teams distribute parallel for \
3970/// reduction(+:foo) reduction(*:bar)
3971/// for (int i = 0; i < N; i++) {
3972/// foo += A[i]; bar *= B[i];
3973/// }
3974///
3975/// where 'foo' and 'bar' are reduced across all OpenMP threads in
3976/// all teams. In our OpenMP implementation on the NVPTX device an
3977/// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
3978/// within a team are mapped to CUDA threads within a threadblock.
3979/// Our goal is to efficiently aggregate values across all OpenMP
3980/// threads such that:
3981///
3982/// - the compiler and runtime are logically concise, and
3983/// - the reduction is performed efficiently in a hierarchical
3984/// manner as follows: within OpenMP threads in the same warp,
3985/// across warps in a threadblock, and finally across teams on
3986/// the NVPTX device.
3987///
3988/// Introduction to Decoupling
3989///
3990/// We would like to decouple the compiler and the runtime so that the
3991/// latter is ignorant of the reduction variables (number, data types)
3992/// and the reduction operators. This allows a simpler interface
3993/// and implementation while still attaining good performance.
3994///
3995/// Pseudocode for the aforementioned OpenMP program generated by the
3996/// compiler is as follows:
3997///
3998/// 1. Create private copies of reduction variables on each OpenMP
3999/// thread: 'foo_private', 'bar_private'
4000/// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
4001/// to it and writes the result in 'foo_private' and 'bar_private'
4002/// respectively.
4003/// 3. Call the OpenMP runtime on the GPU to reduce within a team
4004/// and store the result on the team master:
4005///
Alexey Bataev8e009032019-01-04 17:25:09 +00004006/// __kmpc_nvptx_parallel_reduce_nowait_v2(...,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004007/// reduceData, shuffleReduceFn, interWarpCpyFn)
4008///
4009/// where:
4010/// struct ReduceData {
4011/// double *foo;
4012/// double *bar;
4013/// } reduceData
4014/// reduceData.foo = &foo_private
4015/// reduceData.bar = &bar_private
4016///
4017/// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
4018/// auxiliary functions generated by the compiler that operate on
4019/// variables of type 'ReduceData'. They aid the runtime perform
4020/// algorithmic steps in a data agnostic manner.
4021///
4022/// 'shuffleReduceFn' is a pointer to a function that reduces data
4023/// of type 'ReduceData' across two OpenMP threads (lanes) in the
4024/// same warp. It takes the following arguments as input:
4025///
4026/// a. variable of type 'ReduceData' on the calling lane,
4027/// b. its lane_id,
4028/// c. an offset relative to the current lane_id to generate a
4029/// remote_lane_id. The remote lane contains the second
4030/// variable of type 'ReduceData' that is to be reduced.
4031/// d. an algorithm version parameter determining which reduction
4032/// algorithm to use.
4033///
4034/// 'shuffleReduceFn' retrieves data from the remote lane using
4035/// efficient GPU shuffle intrinsics and reduces, using the
4036/// algorithm specified by the 4th parameter, the two operands
4037/// element-wise. The result is written to the first operand.
4038///
4039/// Different reduction algorithms are implemented in different
4040/// runtime functions, all calling 'shuffleReduceFn' to perform
4041/// the essential reduction step. Therefore, based on the 4th
4042/// parameter, this function behaves slightly differently to
4043/// cooperate with the runtime to ensure correctness under
4044/// different circumstances.
4045///
4046/// 'InterWarpCpyFn' is a pointer to a function that transfers
4047/// reduced variables across warps. It tunnels, through CUDA
4048/// shared memory, the thread-private data of type 'ReduceData'
4049/// from lane 0 of each warp to a lane in the first warp.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004050/// 4. Call the OpenMP runtime on the GPU to reduce across teams.
4051/// The last team writes the global reduced value to memory.
4052///
4053/// ret = __kmpc_nvptx_teams_reduce_nowait(...,
4054/// reduceData, shuffleReduceFn, interWarpCpyFn,
4055/// scratchpadCopyFn, loadAndReduceFn)
4056///
4057/// 'scratchpadCopyFn' is a helper that stores reduced
4058/// data from the team master to a scratchpad array in
4059/// global memory.
4060///
4061/// 'loadAndReduceFn' is a helper that loads data from
4062/// the scratchpad array and reduces it with the input
4063/// operand.
4064///
4065/// These compiler generated functions hide address
4066/// calculation and alignment information from the runtime.
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004067/// 5. if ret == 1:
4068/// The team master of the last team stores the reduced
4069/// result to the globals in memory.
4070/// foo += reduceData.foo; bar *= reduceData.bar
4071///
4072///
4073/// Warp Reduction Algorithms
4074///
4075/// On the warp level, we have three algorithms implemented in the
4076/// OpenMP runtime depending on the number of active lanes:
4077///
4078/// Full Warp Reduction
4079///
4080/// The reduce algorithm within a warp where all lanes are active
4081/// is implemented in the runtime as follows:
4082///
4083/// full_warp_reduce(void *reduce_data,
4084/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
4085/// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
4086/// ShuffleReduceFn(reduce_data, 0, offset, 0);
4087/// }
4088///
4089/// The algorithm completes in log(2, WARPSIZE) steps.
4090///
4091/// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
4092/// not used therefore we save instructions by not retrieving lane_id
4093/// from the corresponding special registers. The 4th parameter, which
4094/// represents the version of the algorithm being used, is set to 0 to
4095/// signify full warp reduction.
4096///
4097/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4098///
4099/// #reduce_elem refers to an element in the local lane's data structure
4100/// #remote_elem is retrieved from a remote lane
4101/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4102/// reduce_elem = reduce_elem REDUCE_OP remote_elem;
4103///
4104/// Contiguous Partial Warp Reduction
4105///
4106/// This reduce algorithm is used within a warp where only the first
4107/// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
4108/// number of OpenMP threads in a parallel region is not a multiple of
4109/// WARPSIZE. The algorithm is implemented in the runtime as follows:
4110///
4111/// void
4112/// contiguous_partial_reduce(void *reduce_data,
4113/// kmp_ShuffleReductFctPtr ShuffleReduceFn,
4114/// int size, int lane_id) {
4115/// int curr_size;
4116/// int offset;
4117/// curr_size = size;
4118/// mask = curr_size/2;
4119/// while (offset>0) {
4120/// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
4121/// curr_size = (curr_size+1)/2;
4122/// offset = curr_size/2;
4123/// }
4124/// }
4125///
4126/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4127///
4128/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4129/// if (lane_id < offset)
4130/// reduce_elem = reduce_elem REDUCE_OP remote_elem
4131/// else
4132/// reduce_elem = remote_elem
4133///
4134/// This algorithm assumes that the data to be reduced are located in a
4135/// contiguous subset of lanes starting from the first. When there is
4136/// an odd number of active lanes, the data in the last lane is not
4137/// aggregated with any other lane's dat but is instead copied over.
4138///
4139/// Dispersed Partial Warp Reduction
4140///
4141/// This algorithm is used within a warp when any discontiguous subset of
4142/// lanes are active. It is used to implement the reduction operation
4143/// across lanes in an OpenMP simd region or in a nested parallel region.
4144///
4145/// void
4146/// dispersed_partial_reduce(void *reduce_data,
4147/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
4148/// int size, remote_id;
4149/// int logical_lane_id = number_of_active_lanes_before_me() * 2;
4150/// do {
4151/// remote_id = next_active_lane_id_right_after_me();
4152/// # the above function returns 0 of no active lane
4153/// # is present right after the current lane.
4154/// size = number_of_active_lanes_in_this_warp();
4155/// logical_lane_id /= 2;
4156/// ShuffleReduceFn(reduce_data, logical_lane_id,
4157/// remote_id-1-threadIdx.x, 2);
4158/// } while (logical_lane_id % 2 == 0 && size > 1);
4159/// }
4160///
4161/// There is no assumption made about the initial state of the reduction.
4162/// Any number of lanes (>=1) could be active at any position. The reduction
4163/// result is returned in the first active lane.
4164///
4165/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4166///
4167/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4168/// if (lane_id % 2 == 0 && offset > 0)
4169/// reduce_elem = reduce_elem REDUCE_OP remote_elem
4170/// else
4171/// reduce_elem = remote_elem
4172///
4173///
4174/// Intra-Team Reduction
4175///
4176/// This function, as implemented in the runtime call
Alexey Bataev8e009032019-01-04 17:25:09 +00004177/// '__kmpc_nvptx_parallel_reduce_nowait_v2', aggregates data across OpenMP
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004178/// threads in a team. It first reduces within a warp using the
4179/// aforementioned algorithms. We then proceed to gather all such
4180/// reduced values at the first warp.
4181///
4182/// The runtime makes use of the function 'InterWarpCpyFn', which copies
4183/// data from each of the "warp master" (zeroth lane of each warp, where
4184/// warp-reduced data is held) to the zeroth warp. This step reduces (in
4185/// a mathematical sense) the problem of reduction across warp masters in
4186/// a block to the problem of warp reduction.
4187///
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004188///
4189/// Inter-Team Reduction
4190///
4191/// Once a team has reduced its data to a single value, it is stored in
4192/// a global scratchpad array. Since each team has a distinct slot, this
4193/// can be done without locking.
4194///
4195/// The last team to write to the scratchpad array proceeds to reduce the
4196/// scratchpad array. One or more workers in the last team use the helper
4197/// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
4198/// the k'th worker reduces every k'th element.
4199///
Alexey Bataev8e009032019-01-04 17:25:09 +00004200/// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait_v2' to
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004201/// reduce across workers and compute a globally reduced value.
4202///
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004203void CGOpenMPRuntimeNVPTX::emitReduction(
4204 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
4205 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
4206 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
4207 if (!CGF.HaveInsertPoint())
4208 return;
4209
4210 bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00004211#ifndef NDEBUG
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004212 bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00004213#endif
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004214
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00004215 if (Options.SimpleReduction) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004216 assert(!TeamsReduction && !ParallelReduction &&
4217 "Invalid reduction selection in emitReduction.");
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00004218 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
4219 ReductionOps, Options);
4220 return;
4221 }
4222
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004223 assert((TeamsReduction || ParallelReduction) &&
4224 "Invalid reduction selection in emitReduction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004225
Alexey Bataeva1166022018-11-27 21:24:54 +00004226 // Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004227 // RedList, shuffle_reduce_func, interwarp_copy_func);
Alexey Bataeva1166022018-11-27 21:24:54 +00004228 // or
4229 // Build res = __kmpc_reduce_teams_nowait_simple(<loc>, <gtid>, <lck>);
Alexey Bataev8e009032019-01-04 17:25:09 +00004230 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004231 llvm::Value *ThreadId = getThreadID(CGF, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004232
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004233 llvm::Value *Res;
Alexey Bataev8061acd2019-02-20 16:36:22 +00004234 ASTContext &C = CGM.getContext();
4235 // 1. Build a list of reduction variables.
4236 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
4237 auto Size = RHSExprs.size();
4238 for (const Expr *E : Privates) {
4239 if (E->getType()->isVariablyModifiedType())
4240 // Reserve place for array size.
4241 ++Size;
4242 }
4243 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
4244 QualType ReductionArrayTy =
4245 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
4246 /*IndexTypeQuals=*/0);
4247 Address ReductionList =
4248 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
4249 auto IPriv = Privates.begin();
4250 unsigned Idx = 0;
4251 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
4252 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
4253 CGF.Builder.CreateStore(
4254 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4255 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
4256 Elem);
4257 if ((*IPriv)->getType()->isVariablyModifiedType()) {
4258 // Store array size.
4259 ++Idx;
4260 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
4261 llvm::Value *Size = CGF.Builder.CreateIntCast(
4262 CGF.getVLASize(
4263 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
4264 .NumElts,
4265 CGF.SizeTy, /*isSigned=*/false);
4266 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
4267 Elem);
4268 }
4269 }
4270
4271 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4272 ReductionList.getPointer(), CGF.VoidPtrTy);
4273 llvm::Function *ReductionFn = emitReductionFunction(
Alexey Bataev982a35e2019-03-19 17:09:52 +00004274 Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
4275 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev8061acd2019-02-20 16:36:22 +00004276 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
4277 llvm::Function *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
4278 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
4279 llvm::Value *InterWarpCopyFn =
4280 emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
4281
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004282 if (ParallelReduction) {
Alexey Bataev8e009032019-01-04 17:25:09 +00004283 llvm::Value *Args[] = {RTLoc,
4284 ThreadId,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004285 CGF.Builder.getInt32(RHSExprs.size()),
4286 ReductionArrayTySize,
4287 RL,
4288 ShuffleAndReduceFn,
4289 InterWarpCopyFn};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004290
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004291 Res = CGF.EmitRuntimeCall(
Alexey Bataeva1166022018-11-27 21:24:54 +00004292 createNVPTXRuntimeFunction(
Alexey Bataev8061acd2019-02-20 16:36:22 +00004293 OMPRTL_NVPTX__kmpc_nvptx_parallel_reduce_nowait_v2),
4294 Args);
4295 } else {
4296 assert(TeamsReduction && "expected teams reduction.");
4297 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> VarFieldMap;
4298 llvm::SmallVector<const ValueDecl *, 4> PrivatesReductions(Privates.size());
4299 int Cnt = 0;
4300 for (const Expr *DRE : Privates) {
4301 PrivatesReductions[Cnt] = cast<DeclRefExpr>(DRE)->getDecl();
4302 ++Cnt;
4303 }
4304 const RecordDecl *TeamReductionRec = ::buildRecordForGlobalizedVars(
4305 CGM.getContext(), PrivatesReductions, llvm::None, VarFieldMap,
4306 C.getLangOpts().OpenMPCUDAReductionBufNum);
4307 TeamsReductions.push_back(TeamReductionRec);
4308 if (!KernelTeamsReductionPtr) {
4309 KernelTeamsReductionPtr = new llvm::GlobalVariable(
4310 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/true,
4311 llvm::GlobalValue::InternalLinkage, nullptr,
4312 "_openmp_teams_reductions_buffer_$_$ptr");
4313 }
4314 llvm::Value *GlobalBufferPtr = CGF.EmitLoadOfScalar(
4315 Address(KernelTeamsReductionPtr, CGM.getPointerAlign()),
4316 /*Volatile=*/false, C.getPointerType(C.VoidPtrTy), Loc);
4317 llvm::Value *GlobalToBufferCpyFn = ::emitListToGlobalCopyFunction(
4318 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
4319 llvm::Value *GlobalToBufferRedFn = ::emitListToGlobalReduceFunction(
4320 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap,
4321 ReductionFn);
4322 llvm::Value *BufferToGlobalCpyFn = ::emitGlobalToListCopyFunction(
4323 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
4324 llvm::Value *BufferToGlobalRedFn = ::emitGlobalToListReduceFunction(
4325 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap,
4326 ReductionFn);
4327
4328 llvm::Value *Args[] = {
4329 RTLoc,
4330 ThreadId,
4331 GlobalBufferPtr,
4332 CGF.Builder.getInt32(C.getLangOpts().OpenMPCUDAReductionBufNum),
4333 RL,
4334 ShuffleAndReduceFn,
4335 InterWarpCopyFn,
4336 GlobalToBufferCpyFn,
4337 GlobalToBufferRedFn,
4338 BufferToGlobalCpyFn,
4339 BufferToGlobalRedFn};
4340
4341 Res = CGF.EmitRuntimeCall(
4342 createNVPTXRuntimeFunction(
4343 OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_v2),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004344 Args);
4345 }
4346
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004347 // 5. Build if (res == 1)
4348 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.reduction.done");
4349 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.then");
4350 llvm::Value *Cond = CGF.Builder.CreateICmpEQ(
4351 Res, llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1));
4352 CGF.Builder.CreateCondBr(Cond, ThenBB, ExitBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004353
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004354 // 6. Build then branch: where we have reduced values in the master
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004355 // thread in each team.
4356 // __kmpc_end_reduce{_nowait}(<gtid>);
4357 // break;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004358 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004359
4360 // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004361 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004362 this](CodeGenFunction &CGF, PrePostActionTy &Action) {
4363 auto IPriv = Privates.begin();
4364 auto ILHS = LHSExprs.begin();
4365 auto IRHS = RHSExprs.begin();
Alexey Bataev9ff80832018-04-16 20:16:21 +00004366 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004367 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4368 cast<DeclRefExpr>(*IRHS));
4369 ++IPriv;
4370 ++ILHS;
4371 ++IRHS;
4372 }
4373 };
Alexey Bataev8061acd2019-02-20 16:36:22 +00004374 llvm::Value *EndArgs[] = {ThreadId};
4375 RegionCodeGenTy RCG(CodeGen);
4376 NVPTXActionTy Action(
4377 nullptr, llvm::None,
4378 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_reduce_nowait),
4379 EndArgs);
4380 RCG.setAction(Action);
4381 RCG(CGF);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004382 // There is no need to emit line number for unconditional branch.
4383 (void)ApplyDebugLocation::CreateEmpty(CGF);
4384 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004385}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004386
4387const VarDecl *
4388CGOpenMPRuntimeNVPTX::translateParameter(const FieldDecl *FD,
4389 const VarDecl *NativeParam) const {
4390 if (!NativeParam->getType()->isReferenceType())
4391 return NativeParam;
4392 QualType ArgType = NativeParam->getType();
4393 QualifierCollector QC;
4394 const Type *NonQualTy = QC.strip(ArgType);
4395 QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4396 if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
4397 if (Attr->getCaptureKind() == OMPC_map) {
4398 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
4399 LangAS::opencl_global);
Alexey Bataev1af5bd52019-03-05 17:47:18 +00004400 } else if (Attr->getCaptureKind() == OMPC_firstprivate &&
4401 PointeeTy.isConstant(CGM.getContext())) {
4402 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
4403 LangAS::opencl_generic);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004404 }
4405 }
4406 ArgType = CGM.getContext().getPointerType(PointeeTy);
4407 QC.addRestrict();
4408 enum { NVPTX_local_addr = 5 };
Alexander Richardson6d989432017-10-15 18:48:14 +00004409 QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004410 ArgType = QC.apply(CGM.getContext(), ArgType);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004411 if (isa<ImplicitParamDecl>(NativeParam))
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004412 return ImplicitParamDecl::Create(
4413 CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
4414 NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004415 return ParmVarDecl::Create(
4416 CGM.getContext(),
4417 const_cast<DeclContext *>(NativeParam->getDeclContext()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004418 NativeParam->getBeginLoc(), NativeParam->getLocation(),
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004419 NativeParam->getIdentifier(), ArgType,
4420 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004421}
4422
4423Address
4424CGOpenMPRuntimeNVPTX::getParameterAddress(CodeGenFunction &CGF,
4425 const VarDecl *NativeParam,
4426 const VarDecl *TargetParam) const {
4427 assert(NativeParam != TargetParam &&
4428 NativeParam->getType()->isReferenceType() &&
4429 "Native arg must not be the same as target arg.");
4430 Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
4431 QualType NativeParamType = NativeParam->getType();
4432 QualifierCollector QC;
4433 const Type *NonQualTy = QC.strip(NativeParamType);
4434 QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4435 unsigned NativePointeeAddrSpace =
Alexander Richardson6d989432017-10-15 18:48:14 +00004436 CGF.getContext().getTargetAddressSpace(NativePointeeTy);
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004437 QualType TargetTy = TargetParam->getType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004438 llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004439 LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004440 // First cast to generic.
4441 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4442 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4443 /*AddrSpace=*/0));
4444 // Cast from generic to native address space.
4445 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4446 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4447 NativePointeeAddrSpace));
4448 Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
4449 CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004450 NativeParamType);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004451 return NativeParamAddr;
4452}
4453
4454void CGOpenMPRuntimeNVPTX::emitOutlinedFunctionCall(
James Y Knight9871db02019-02-05 16:42:33 +00004455 CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn,
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004456 ArrayRef<llvm::Value *> Args) const {
4457 SmallVector<llvm::Value *, 4> TargetArgs;
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004458 TargetArgs.reserve(Args.size());
James Y Knight9871db02019-02-05 16:42:33 +00004459 auto *FnType = OutlinedFn.getFunctionType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004460 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004461 if (FnType->isVarArg() && FnType->getNumParams() <= I) {
4462 TargetArgs.append(std::next(Args.begin(), I), Args.end());
4463 break;
4464 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004465 llvm::Type *TargetType = FnType->getParamType(I);
4466 llvm::Value *NativeArg = Args[I];
4467 if (!TargetType->isPointerTy()) {
4468 TargetArgs.emplace_back(NativeArg);
4469 continue;
4470 }
4471 llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataevc99042b2018-03-15 18:10:54 +00004472 NativeArg,
4473 NativeArg->getType()->getPointerElementType()->getPointerTo());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004474 TargetArgs.emplace_back(
4475 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
4476 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00004477 CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004478}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004479
4480/// Emit function which wraps the outline parallel region
4481/// and controls the arguments which are passed to this function.
4482/// The wrapper ensures that the outlined function is called
4483/// with the correct arguments when data is shared.
4484llvm::Function *CGOpenMPRuntimeNVPTX::createParallelDataSharingWrapper(
4485 llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
4486 ASTContext &Ctx = CGM.getContext();
4487 const auto &CS = *D.getCapturedStmt(OMPD_parallel);
4488
4489 // Create a function that takes as argument the source thread.
4490 FunctionArgList WrapperArgs;
4491 QualType Int16QTy =
4492 Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
4493 QualType Int32QTy =
4494 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004495 ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004496 /*Id=*/nullptr, Int16QTy,
4497 ImplicitParamDecl::Other);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004498 ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004499 /*Id=*/nullptr, Int32QTy,
4500 ImplicitParamDecl::Other);
4501 WrapperArgs.emplace_back(&ParallelLevelArg);
4502 WrapperArgs.emplace_back(&WrapperArg);
4503
Alexey Bataev9ff80832018-04-16 20:16:21 +00004504 const CGFunctionInfo &CGFI =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004505 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
4506
4507 auto *Fn = llvm::Function::Create(
4508 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataev9ff80832018-04-16 20:16:21 +00004509 Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004510 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004511 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004512 Fn->setDoesNotRecurse();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004513
4514 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
4515 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004516 D.getBeginLoc(), D.getBeginLoc());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004517
4518 const auto *RD = CS.getCapturedRecordDecl();
4519 auto CurField = RD->field_begin();
4520
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004521 Address ZeroAddr = CGF.CreateMemTemp(
4522 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
4523 /*Name*/ ".zero.addr");
4524 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004525 // Get the array of arguments.
4526 SmallVector<llvm::Value *, 8> Args;
4527
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004528 Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).getPointer());
4529 Args.emplace_back(ZeroAddr.getPointer());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004530
4531 CGBuilderTy &Bld = CGF.Builder;
4532 auto CI = CS.capture_begin();
4533
4534 // Use global memory for data sharing.
4535 // Handle passing of global args to workers.
4536 Address GlobalArgs =
4537 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
4538 llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
4539 llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
4540 CGF.EmitRuntimeCall(
4541 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_get_shared_variables),
4542 DataSharingArgs);
4543
4544 // Retrieve the shared variables from the list of references returned
4545 // by the runtime. Pass the variables to the outlined function.
Alexey Bataev17314212018-03-20 15:41:05 +00004546 Address SharedArgListAddress = Address::invalid();
4547 if (CS.capture_size() > 0 ||
4548 isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4549 SharedArgListAddress = CGF.EmitLoadOfPointer(
4550 GlobalArgs, CGF.getContext()
4551 .getPointerType(CGF.getContext().getPointerType(
4552 CGF.getContext().VoidPtrTy))
4553 .castAs<PointerType>());
4554 }
4555 unsigned Idx = 0;
4556 if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
James Y Knight751fe282019-02-09 22:22:28 +00004557 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004558 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4559 Src, CGF.SizeTy->getPointerTo());
4560 llvm::Value *LB = CGF.EmitLoadOfScalar(
4561 TypedAddress,
4562 /*Volatile=*/false,
4563 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4564 cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
4565 Args.emplace_back(LB);
4566 ++Idx;
James Y Knight751fe282019-02-09 22:22:28 +00004567 Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004568 TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4569 Src, CGF.SizeTy->getPointerTo());
4570 llvm::Value *UB = CGF.EmitLoadOfScalar(
4571 TypedAddress,
4572 /*Volatile=*/false,
4573 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4574 cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
4575 Args.emplace_back(UB);
4576 ++Idx;
4577 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004578 if (CS.capture_size() > 0) {
4579 ASTContext &CGFContext = CGF.getContext();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004580 for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
4581 QualType ElemTy = CurField->getType();
James Y Knight751fe282019-02-09 22:22:28 +00004582 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004583 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004584 Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)));
4585 llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
4586 /*Volatile=*/false,
4587 CGFContext.getPointerType(ElemTy),
4588 CI->getLocation());
Alexey Bataev2091ca62018-04-23 17:33:41 +00004589 if (CI->capturesVariableByCopy() &&
4590 !CI->getCapturedVar()->getType()->isAnyPointerType()) {
Alexey Bataev17314212018-03-20 15:41:05 +00004591 Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
4592 CI->getLocation());
4593 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004594 Args.emplace_back(Arg);
4595 }
4596 }
4597
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004598 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedParallelFn, Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004599 CGF.FinishFunction();
4600 return Fn;
4601}
4602
4603void CGOpenMPRuntimeNVPTX::emitFunctionProlog(CodeGenFunction &CGF,
4604 const Decl *D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004605 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4606 return;
4607
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004608 assert(D && "Expected function or captured|block decl.");
4609 assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
4610 "Function is registered already.");
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004611 assert((!TeamAndReductions.first || TeamAndReductions.first == D) &&
4612 "Team is set but not processed.");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004613 const Stmt *Body = nullptr;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004614 bool NeedToDelayGlobalization = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004615 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4616 Body = FD->getBody();
4617 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
4618 Body = BD->getBody();
4619 } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
4620 Body = CD->getBody();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004621 NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
Alexey Bataev2adecff2018-09-21 14:22:53 +00004622 if (NeedToDelayGlobalization &&
4623 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
4624 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004625 }
4626 if (!Body)
4627 return;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004628 CheckVarsEscapingDeclContext VarChecker(CGF, TeamAndReductions.second);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004629 VarChecker.Visit(Body);
Alexey Bataevff23bb62018-10-11 18:30:31 +00004630 const RecordDecl *GlobalizedVarsRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004631 VarChecker.getGlobalizedRecord(IsInTTDRegion);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004632 TeamAndReductions.first = nullptr;
4633 TeamAndReductions.second.clear();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004634 ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
4635 VarChecker.getEscapedVariableLengthDecls();
4636 if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004637 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004638 auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
4639 I->getSecond().MappedParams =
4640 llvm::make_unique<CodeGenFunction::OMPMapVars>();
4641 I->getSecond().GlobalRecord = GlobalizedVarsRecord;
4642 I->getSecond().EscapedParameters.insert(
4643 VarChecker.getEscapedParameters().begin(),
4644 VarChecker.getEscapedParameters().end());
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004645 I->getSecond().EscapedVariableLengthDecls.append(
4646 EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004647 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004648 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004649 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004650 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004651 Data.insert(std::make_pair(VD, MappedVarData(FD, IsInTTDRegion)));
Alexey Bataevc99042b2018-03-15 18:10:54 +00004652 }
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004653 if (!IsInTTDRegion && !NeedToDelayGlobalization && !IsInParallelRegion) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004654 CheckVarsEscapingDeclContext VarChecker(CGF, llvm::None);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004655 VarChecker.Visit(Body);
4656 I->getSecond().SecondaryGlobalRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004657 VarChecker.getGlobalizedRecord(/*IsInTTDRegion=*/true);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004658 I->getSecond().SecondaryLocalVarData.emplace();
4659 DeclToAddrMapTy &Data = I->getSecond().SecondaryLocalVarData.getValue();
4660 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
4661 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
4662 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004663 Data.insert(
4664 std::make_pair(VD, MappedVarData(FD, /*IsInTTDRegion=*/true)));
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004665 }
4666 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00004667 if (!NeedToDelayGlobalization) {
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004668 emitGenericVarsProlog(CGF, D->getBeginLoc(), /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004669 struct GlobalizationScope final : EHScopeStack::Cleanup {
4670 GlobalizationScope() = default;
4671
4672 void Emit(CodeGenFunction &CGF, Flags flags) override {
4673 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004674 .emitGenericVarsEpilog(CGF, /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004675 }
4676 };
4677 CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004678 }
4679}
4680
4681Address CGOpenMPRuntimeNVPTX::getAddressOfLocalVariable(CodeGenFunction &CGF,
4682 const VarDecl *VD) {
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004683 if (VD && VD->hasAttr<OMPAllocateDeclAttr>()) {
4684 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
4685 switch (A->getAllocatorType()) {
4686 // Use the default allocator here as by default local vars are
4687 // threadlocal.
4688 case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
4689 case OMPAllocateDeclAttr::OMPThreadMemAlloc:
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004690 case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
4691 case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
Alexey Bataev1db9bfe2019-04-08 16:53:57 +00004692 // Follow the user decision - use default allocation.
4693 return Address::invalid();
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004694 case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
Alexey Bataev1db9bfe2019-04-08 16:53:57 +00004695 // TODO: implement aupport for user-defined allocators.
4696 return Address::invalid();
4697 case OMPAllocateDeclAttr::OMPConstMemAlloc: {
4698 llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
4699 auto *GV = new llvm::GlobalVariable(
4700 CGM.getModule(), VarTy, /*isConstant=*/false,
4701 llvm::GlobalValue::InternalLinkage,
4702 llvm::Constant::getNullValue(VarTy), VD->getName(),
4703 /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
4704 CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant));
4705 CharUnits Align = CGM.getContext().getDeclAlign(VD);
4706 GV->setAlignment(Align.getQuantity());
4707 return Address(GV, Align);
4708 }
4709 case OMPAllocateDeclAttr::OMPPTeamMemAlloc: {
4710 llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
4711 auto *GV = new llvm::GlobalVariable(
4712 CGM.getModule(), VarTy, /*isConstant=*/false,
4713 llvm::GlobalValue::InternalLinkage,
4714 llvm::Constant::getNullValue(VarTy), VD->getName(),
4715 /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
4716 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
4717 CharUnits Align = CGM.getContext().getDeclAlign(VD);
4718 GV->setAlignment(Align.getQuantity());
4719 return Address(GV, Align);
4720 }
4721 case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
4722 case OMPAllocateDeclAttr::OMPCGroupMemAlloc: {
4723 llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
4724 auto *GV = new llvm::GlobalVariable(
4725 CGM.getModule(), VarTy, /*isConstant=*/false,
4726 llvm::GlobalValue::InternalLinkage,
4727 llvm::Constant::getNullValue(VarTy), VD->getName());
4728 CharUnits Align = CGM.getContext().getDeclAlign(VD);
4729 GV->setAlignment(Align.getQuantity());
4730 return Address(GV, Align);
4731 }
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004732 }
4733 }
4734
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004735 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4736 return Address::invalid();
4737
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004738 VD = VD->getCanonicalDecl();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004739 auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
4740 if (I == FunctionGlobalizedDecls.end())
4741 return Address::invalid();
Alexey Bataevc99042b2018-03-15 18:10:54 +00004742 auto VDI = I->getSecond().LocalVarData.find(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004743 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004744 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004745 if (VD->hasAttrs()) {
4746 for (specific_attr_iterator<OMPReferencedVarAttr> IT(VD->attr_begin()),
4747 E(VD->attr_end());
4748 IT != E; ++IT) {
4749 auto VDI = I->getSecond().LocalVarData.find(
4750 cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
4751 ->getCanonicalDecl());
4752 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004753 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004754 }
4755 }
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004756
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004757 return Address::invalid();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004758}
4759
4760void CGOpenMPRuntimeNVPTX::functionFinished(CodeGenFunction &CGF) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004761 FunctionGlobalizedDecls.erase(CGF.CurFn);
4762 CGOpenMPRuntime::functionFinished(CGF);
4763}
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004764
4765void CGOpenMPRuntimeNVPTX::getDefaultDistScheduleAndChunk(
4766 CodeGenFunction &CGF, const OMPLoopDirective &S,
4767 OpenMPDistScheduleClauseKind &ScheduleKind,
4768 llvm::Value *&Chunk) const {
4769 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
4770 ScheduleKind = OMPC_DIST_SCHEDULE_static;
4771 Chunk = CGF.EmitScalarConversion(getNVPTXNumThreads(CGF),
4772 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4773 S.getIterationVariable()->getType(), S.getBeginLoc());
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004774 return;
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004775 }
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004776 CGOpenMPRuntime::getDefaultDistScheduleAndChunk(
4777 CGF, S, ScheduleKind, Chunk);
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004778}
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004779
4780void CGOpenMPRuntimeNVPTX::getDefaultScheduleAndChunk(
4781 CodeGenFunction &CGF, const OMPLoopDirective &S,
4782 OpenMPScheduleClauseKind &ScheduleKind,
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004783 const Expr *&ChunkExpr) const {
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004784 ScheduleKind = OMPC_SCHEDULE_static;
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004785 // Chunk size is 1 in this case.
4786 llvm::APInt ChunkSize(32, 1);
4787 ChunkExpr = IntegerLiteral::Create(CGF.getContext(), ChunkSize,
4788 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4789 SourceLocation());
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004790}
Alexey Bataev60705422018-10-30 15:50:12 +00004791
4792void CGOpenMPRuntimeNVPTX::adjustTargetSpecificDataForLambdas(
4793 CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
4794 assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
4795 " Expected target-based directive.");
4796 const CapturedStmt *CS = D.getCapturedStmt(OMPD_target);
4797 for (const CapturedStmt::Capture &C : CS->captures()) {
4798 // Capture variables captured by reference in lambdas for target-based
4799 // directives.
4800 if (!C.capturesVariable())
4801 continue;
4802 const VarDecl *VD = C.getCapturedVar();
4803 const auto *RD = VD->getType()
4804 .getCanonicalType()
4805 .getNonReferenceType()
4806 ->getAsCXXRecordDecl();
4807 if (!RD || !RD->isLambda())
4808 continue;
4809 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4810 LValue VDLVal;
4811 if (VD->getType().getCanonicalType()->isReferenceType())
4812 VDLVal = CGF.EmitLoadOfReferenceLValue(VDAddr, VD->getType());
4813 else
4814 VDLVal = CGF.MakeAddrLValue(
4815 VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
4816 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4817 FieldDecl *ThisCapture = nullptr;
4818 RD->getCaptureFields(Captures, ThisCapture);
4819 if (ThisCapture && CGF.CapturedStmtInfo->isCXXThisExprCaptured()) {
4820 LValue ThisLVal =
4821 CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
4822 llvm::Value *CXXThis = CGF.LoadCXXThis();
4823 CGF.EmitStoreOfScalar(CXXThis, ThisLVal);
4824 }
4825 for (const LambdaCapture &LC : RD->captures()) {
4826 if (LC.getCaptureKind() != LCK_ByRef)
4827 continue;
4828 const VarDecl *VD = LC.getCapturedVar();
4829 if (!CS->capturesVariable(VD))
4830 continue;
4831 auto It = Captures.find(VD);
4832 assert(It != Captures.end() && "Found lambda capture without field.");
4833 LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
4834 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4835 if (VD->getType().getCanonicalType()->isReferenceType())
4836 VDAddr = CGF.EmitLoadOfReferenceLValue(VDAddr,
4837 VD->getType().getCanonicalType())
4838 .getAddress();
4839 CGF.EmitStoreOfScalar(VDAddr.getPointer(), VarLVal);
4840 }
4841 }
4842}
4843
Alexey Bataev1af5bd52019-03-05 17:47:18 +00004844unsigned CGOpenMPRuntimeNVPTX::getDefaultFirstprivateAddressSpace() const {
4845 return CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant);
4846}
4847
Alexey Bataevc5687252019-03-21 19:35:27 +00004848bool CGOpenMPRuntimeNVPTX::hasAllocateAttributeForGlobalVar(const VarDecl *VD,
4849 LangAS &AS) {
4850 if (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())
4851 return false;
4852 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
4853 switch(A->getAllocatorType()) {
4854 case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
4855 // Not supported, fallback to the default mem space.
4856 case OMPAllocateDeclAttr::OMPThreadMemAlloc:
4857 case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
4858 case OMPAllocateDeclAttr::OMPCGroupMemAlloc:
4859 case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
4860 case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
4861 AS = LangAS::Default;
4862 return true;
4863 case OMPAllocateDeclAttr::OMPConstMemAlloc:
4864 AS = LangAS::cuda_constant;
4865 return true;
4866 case OMPAllocateDeclAttr::OMPPTeamMemAlloc:
4867 AS = LangAS::cuda_shared;
4868 return true;
4869 case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
4870 llvm_unreachable("Expected predefined allocator for the variables with the "
4871 "static storage.");
4872 }
4873 return false;
4874}
4875
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004876// Get current CudaArch and ignore any unknown values
4877static CudaArch getCudaArch(CodeGenModule &CGM) {
4878 if (!CGM.getTarget().hasFeature("ptx"))
4879 return CudaArch::UNKNOWN;
4880 llvm::StringMap<bool> Features;
4881 CGM.getTarget().initFeatureMap(Features, CGM.getDiags(),
4882 CGM.getTarget().getTargetOpts().CPU,
4883 CGM.getTarget().getTargetOpts().Features);
4884 for (const auto &Feature : Features) {
4885 if (Feature.getValue()) {
4886 CudaArch Arch = StringToCudaArch(Feature.getKey());
4887 if (Arch != CudaArch::UNKNOWN)
4888 return Arch;
4889 }
4890 }
4891 return CudaArch::UNKNOWN;
4892}
4893
4894/// Check to see if target architecture supports unified addressing which is
4895/// a restriction for OpenMP requires clause "unified_shared_memory".
4896void CGOpenMPRuntimeNVPTX::checkArchForUnifiedAddressing(
Gheorghe-Teodor Bercea66cdbb472019-05-21 19:42:01 +00004897 const OMPRequiresDecl *D) {
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004898 for (const OMPClause *Clause : D->clauselists()) {
4899 if (Clause->getClauseKind() == OMPC_unified_shared_memory) {
4900 switch (getCudaArch(CGM)) {
4901 case CudaArch::SM_20:
4902 case CudaArch::SM_21:
4903 case CudaArch::SM_30:
4904 case CudaArch::SM_32:
4905 case CudaArch::SM_35:
4906 case CudaArch::SM_37:
4907 case CudaArch::SM_50:
4908 case CudaArch::SM_52:
4909 case CudaArch::SM_53:
4910 case CudaArch::SM_60:
4911 case CudaArch::SM_61:
4912 case CudaArch::SM_62:
4913 CGM.Error(Clause->getBeginLoc(),
4914 "Target architecture does not support unified addressing");
4915 return;
4916 case CudaArch::SM_70:
4917 case CudaArch::SM_72:
4918 case CudaArch::SM_75:
4919 case CudaArch::GFX600:
4920 case CudaArch::GFX601:
4921 case CudaArch::GFX700:
4922 case CudaArch::GFX701:
4923 case CudaArch::GFX702:
4924 case CudaArch::GFX703:
4925 case CudaArch::GFX704:
4926 case CudaArch::GFX801:
4927 case CudaArch::GFX802:
4928 case CudaArch::GFX803:
4929 case CudaArch::GFX810:
4930 case CudaArch::GFX900:
4931 case CudaArch::GFX902:
4932 case CudaArch::GFX904:
4933 case CudaArch::GFX906:
Stanislav Mekhanoshin0cfd75a2019-07-09 18:19:00 +00004934 case CudaArch::GFX908:
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004935 case CudaArch::GFX909:
Yaxun Liu6add24a2019-07-11 17:50:09 +00004936 case CudaArch::GFX1010:
4937 case CudaArch::GFX1011:
4938 case CudaArch::GFX1012:
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004939 case CudaArch::UNKNOWN:
4940 break;
4941 case CudaArch::LAST:
4942 llvm_unreachable("Unexpected Cuda arch.");
4943 }
4944 }
4945 }
Gheorghe-Teodor Bercea66cdbb472019-05-21 19:42:01 +00004946 CGOpenMPRuntime::checkArchForUnifiedAddressing(D);
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004947}
4948
Alexey Bataeve4090182018-11-02 14:54:07 +00004949/// Get number of SMs and number of blocks per SM.
4950static std::pair<unsigned, unsigned> getSMsBlocksPerSM(CodeGenModule &CGM) {
4951 std::pair<unsigned, unsigned> Data;
4952 if (CGM.getLangOpts().OpenMPCUDANumSMs)
4953 Data.first = CGM.getLangOpts().OpenMPCUDANumSMs;
4954 if (CGM.getLangOpts().OpenMPCUDABlocksPerSM)
4955 Data.second = CGM.getLangOpts().OpenMPCUDABlocksPerSM;
4956 if (Data.first && Data.second)
4957 return Data;
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004958 switch (getCudaArch(CGM)) {
4959 case CudaArch::SM_20:
4960 case CudaArch::SM_21:
4961 case CudaArch::SM_30:
4962 case CudaArch::SM_32:
4963 case CudaArch::SM_35:
4964 case CudaArch::SM_37:
4965 case CudaArch::SM_50:
4966 case CudaArch::SM_52:
4967 case CudaArch::SM_53:
4968 return {16, 16};
4969 case CudaArch::SM_60:
4970 case CudaArch::SM_61:
4971 case CudaArch::SM_62:
4972 return {56, 32};
4973 case CudaArch::SM_70:
4974 case CudaArch::SM_72:
4975 case CudaArch::SM_75:
4976 return {84, 32};
4977 case CudaArch::GFX600:
4978 case CudaArch::GFX601:
4979 case CudaArch::GFX700:
4980 case CudaArch::GFX701:
4981 case CudaArch::GFX702:
4982 case CudaArch::GFX703:
4983 case CudaArch::GFX704:
4984 case CudaArch::GFX801:
4985 case CudaArch::GFX802:
4986 case CudaArch::GFX803:
4987 case CudaArch::GFX810:
4988 case CudaArch::GFX900:
4989 case CudaArch::GFX902:
4990 case CudaArch::GFX904:
4991 case CudaArch::GFX906:
Stanislav Mekhanoshin0cfd75a2019-07-09 18:19:00 +00004992 case CudaArch::GFX908:
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004993 case CudaArch::GFX909:
Yaxun Liu6add24a2019-07-11 17:50:09 +00004994 case CudaArch::GFX1010:
4995 case CudaArch::GFX1011:
4996 case CudaArch::GFX1012:
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004997 case CudaArch::UNKNOWN:
4998 break;
4999 case CudaArch::LAST:
5000 llvm_unreachable("Unexpected Cuda arch.");
Alexey Bataeve4090182018-11-02 14:54:07 +00005001 }
5002 llvm_unreachable("Unexpected NVPTX target without ptx feature.");
5003}
5004
5005void CGOpenMPRuntimeNVPTX::clear() {
5006 if (!GlobalizedRecords.empty()) {
5007 ASTContext &C = CGM.getContext();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005008 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> GlobalRecs;
5009 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> SharedRecs;
Alexey Bataeve4090182018-11-02 14:54:07 +00005010 RecordDecl *StaticRD = C.buildImplicitRecord(
5011 "_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
5012 StaticRD->startDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005013 RecordDecl *SharedStaticRD = C.buildImplicitRecord(
5014 "_shared_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
5015 SharedStaticRD->startDefinition();
Alexey Bataeve4090182018-11-02 14:54:07 +00005016 for (const GlobalPtrSizeRecsTy &Records : GlobalizedRecords) {
5017 if (Records.Records.empty())
5018 continue;
5019 unsigned Size = 0;
5020 unsigned RecAlignment = 0;
5021 for (const RecordDecl *RD : Records.Records) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005022 QualType RDTy = C.getRecordType(RD);
5023 unsigned Alignment = C.getTypeAlignInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00005024 RecAlignment = std::max(RecAlignment, Alignment);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005025 unsigned RecSize = C.getTypeSizeInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00005026 Size =
5027 llvm::alignTo(llvm::alignTo(Size, Alignment) + RecSize, Alignment);
5028 }
5029 Size = llvm::alignTo(Size, RecAlignment);
5030 llvm::APInt ArySize(/*numBits=*/64, Size);
5031 QualType SubTy = C.getConstantArrayType(
5032 C.CharTy, ArySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005033 const bool UseSharedMemory = Size <= SharedMemorySize;
5034 auto *Field =
5035 FieldDecl::Create(C, UseSharedMemory ? SharedStaticRD : StaticRD,
5036 SourceLocation(), SourceLocation(), nullptr, SubTy,
5037 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
5038 /*BW=*/nullptr, /*Mutable=*/false,
5039 /*InitStyle=*/ICIS_NoInit);
Alexey Bataeve4090182018-11-02 14:54:07 +00005040 Field->setAccess(AS_public);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005041 if (UseSharedMemory) {
5042 SharedStaticRD->addDecl(Field);
5043 SharedRecs.push_back(&Records);
5044 } else {
5045 StaticRD->addDecl(Field);
5046 GlobalRecs.push_back(&Records);
5047 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005048 Records.RecSize->setInitializer(llvm::ConstantInt::get(CGM.SizeTy, Size));
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005049 Records.UseSharedMemory->setInitializer(
5050 llvm::ConstantInt::get(CGM.Int16Ty, UseSharedMemory ? 1 : 0));
5051 }
Alexey Bataev6a1b06b2018-12-18 21:01:42 +00005052 // Allocate SharedMemorySize buffer for the shared memory.
5053 // FIXME: nvlink does not handle weak linkage correctly (object with the
5054 // different size are reported as erroneous).
5055 // Restore this code as sson as nvlink is fixed.
5056 if (!SharedStaticRD->field_empty()) {
5057 llvm::APInt ArySize(/*numBits=*/64, SharedMemorySize);
5058 QualType SubTy = C.getConstantArrayType(
5059 C.CharTy, ArySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
5060 auto *Field = FieldDecl::Create(
5061 C, SharedStaticRD, SourceLocation(), SourceLocation(), nullptr, SubTy,
5062 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
5063 /*BW=*/nullptr, /*Mutable=*/false,
5064 /*InitStyle=*/ICIS_NoInit);
5065 Field->setAccess(AS_public);
5066 SharedStaticRD->addDecl(Field);
5067 }
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005068 SharedStaticRD->completeDefinition();
5069 if (!SharedStaticRD->field_empty()) {
5070 QualType StaticTy = C.getRecordType(SharedStaticRD);
5071 llvm::Type *LLVMStaticTy = CGM.getTypes().ConvertTypeForMem(StaticTy);
5072 auto *GV = new llvm::GlobalVariable(
5073 CGM.getModule(), LLVMStaticTy,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00005074 /*isConstant=*/false, llvm::GlobalValue::CommonLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005075 llvm::Constant::getNullValue(LLVMStaticTy),
5076 "_openmp_shared_static_glob_rd_$_", /*InsertBefore=*/nullptr,
5077 llvm::GlobalValue::NotThreadLocal,
5078 C.getTargetAddressSpace(LangAS::cuda_shared));
5079 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
5080 GV, CGM.VoidPtrTy);
5081 for (const GlobalPtrSizeRecsTy *Rec : SharedRecs) {
5082 Rec->Buffer->replaceAllUsesWith(Replacement);
5083 Rec->Buffer->eraseFromParent();
5084 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005085 }
5086 StaticRD->completeDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005087 if (!StaticRD->field_empty()) {
5088 QualType StaticTy = C.getRecordType(StaticRD);
5089 std::pair<unsigned, unsigned> SMsBlockPerSM = getSMsBlocksPerSM(CGM);
5090 llvm::APInt Size1(32, SMsBlockPerSM.second);
5091 QualType Arr1Ty =
5092 C.getConstantArrayType(StaticTy, Size1, ArrayType::Normal,
5093 /*IndexTypeQuals=*/0);
5094 llvm::APInt Size2(32, SMsBlockPerSM.first);
5095 QualType Arr2Ty = C.getConstantArrayType(Arr1Ty, Size2, ArrayType::Normal,
5096 /*IndexTypeQuals=*/0);
5097 llvm::Type *LLVMArr2Ty = CGM.getTypes().ConvertTypeForMem(Arr2Ty);
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005098 // FIXME: nvlink does not handle weak linkage correctly (object with the
5099 // different size are reported as erroneous).
5100 // Restore CommonLinkage as soon as nvlink is fixed.
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005101 auto *GV = new llvm::GlobalVariable(
5102 CGM.getModule(), LLVMArr2Ty,
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005103 /*isConstant=*/false, llvm::GlobalValue::InternalLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005104 llvm::Constant::getNullValue(LLVMArr2Ty),
5105 "_openmp_static_glob_rd_$_");
5106 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
5107 GV, CGM.VoidPtrTy);
5108 for (const GlobalPtrSizeRecsTy *Rec : GlobalRecs) {
5109 Rec->Buffer->replaceAllUsesWith(Replacement);
5110 Rec->Buffer->eraseFromParent();
5111 }
5112 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005113 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00005114 if (!TeamsReductions.empty()) {
5115 ASTContext &C = CGM.getContext();
5116 RecordDecl *StaticRD = C.buildImplicitRecord(
5117 "_openmp_teams_reduction_type_$_", RecordDecl::TagKind::TTK_Union);
5118 StaticRD->startDefinition();
5119 for (const RecordDecl *TeamReductionRec : TeamsReductions) {
5120 QualType RecTy = C.getRecordType(TeamReductionRec);
5121 auto *Field = FieldDecl::Create(
5122 C, StaticRD, SourceLocation(), SourceLocation(), nullptr, RecTy,
5123 C.getTrivialTypeSourceInfo(RecTy, SourceLocation()),
5124 /*BW=*/nullptr, /*Mutable=*/false,
5125 /*InitStyle=*/ICIS_NoInit);
5126 Field->setAccess(AS_public);
5127 StaticRD->addDecl(Field);
5128 }
5129 StaticRD->completeDefinition();
5130 QualType StaticTy = C.getRecordType(StaticRD);
5131 llvm::Type *LLVMReductionsBufferTy =
5132 CGM.getTypes().ConvertTypeForMem(StaticTy);
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005133 // FIXME: nvlink does not handle weak linkage correctly (object with the
5134 // different size are reported as erroneous).
5135 // Restore CommonLinkage as soon as nvlink is fixed.
Alexey Bataev8061acd2019-02-20 16:36:22 +00005136 auto *GV = new llvm::GlobalVariable(
5137 CGM.getModule(), LLVMReductionsBufferTy,
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005138 /*isConstant=*/false, llvm::GlobalValue::InternalLinkage,
Alexey Bataev8061acd2019-02-20 16:36:22 +00005139 llvm::Constant::getNullValue(LLVMReductionsBufferTy),
5140 "_openmp_teams_reductions_buffer_$_");
5141 KernelTeamsReductionPtr->setInitializer(
5142 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
5143 CGM.VoidPtrTy));
5144 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005145 CGOpenMPRuntime::clear();
5146}