blob: 6c908412e0c71042442d5e1a19db46b3a21bd612 [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,
Alexey Bataev2cd7faf2019-08-26 19:07:48 +0000110 /// Call to int32_t __kmpc_warp_active_thread_mask(void);
111 OMPRTL_NVPTX__kmpc_warp_active_thread_mask,
112 /// Call to void __kmpc_syncwarp(int32_t Mask);
113 OMPRTL_NVPTX__kmpc_syncwarp,
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000114};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000115
116/// Pre(post)-action for different OpenMP constructs specialized for NVPTX.
117class NVPTXActionTy final : public PrePostActionTy {
James Y Knight9871db02019-02-05 16:42:33 +0000118 llvm::FunctionCallee EnterCallee = nullptr;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000119 ArrayRef<llvm::Value *> EnterArgs;
James Y Knight9871db02019-02-05 16:42:33 +0000120 llvm::FunctionCallee ExitCallee = nullptr;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000121 ArrayRef<llvm::Value *> ExitArgs;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000122 bool Conditional = false;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000123 llvm::BasicBlock *ContBlock = nullptr;
124
125public:
James Y Knight9871db02019-02-05 16:42:33 +0000126 NVPTXActionTy(llvm::FunctionCallee EnterCallee,
127 ArrayRef<llvm::Value *> EnterArgs,
128 llvm::FunctionCallee ExitCallee,
129 ArrayRef<llvm::Value *> ExitArgs, bool Conditional = false)
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000130 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
131 ExitArgs(ExitArgs), Conditional(Conditional) {}
132 void Enter(CodeGenFunction &CGF) override {
133 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
134 if (Conditional) {
135 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
136 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
137 ContBlock = CGF.createBasicBlock("omp_if.end");
138 // Generate the branch (If-stmt)
139 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
140 CGF.EmitBlock(ThenBlock);
141 }
142 }
143 void Done(CodeGenFunction &CGF) {
144 // Emit the rest of blocks/branches
145 CGF.EmitBranch(ContBlock);
146 CGF.EmitBlock(ContBlock, true);
147 }
148 void Exit(CodeGenFunction &CGF) override {
149 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
150 }
151};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000152
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000153/// A class to track the execution mode when codegening directives within
154/// a target region. The appropriate mode (SPMD|NON-SPMD) is set on entry
155/// to the target region and used by containing directives such as 'parallel'
156/// to emit optimized code.
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000157class ExecutionRuntimeModesRAII {
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000158private:
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000159 CGOpenMPRuntimeNVPTX::ExecutionMode SavedExecMode =
160 CGOpenMPRuntimeNVPTX::EM_Unknown;
161 CGOpenMPRuntimeNVPTX::ExecutionMode &ExecMode;
162 bool SavedRuntimeMode = false;
163 bool *RuntimeMode = nullptr;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000164
165public:
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000166 /// Constructor for Non-SPMD mode.
167 ExecutionRuntimeModesRAII(CGOpenMPRuntimeNVPTX::ExecutionMode &ExecMode)
168 : ExecMode(ExecMode) {
169 SavedExecMode = ExecMode;
170 ExecMode = CGOpenMPRuntimeNVPTX::EM_NonSPMD;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000171 }
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000172 /// Constructor for SPMD mode.
173 ExecutionRuntimeModesRAII(CGOpenMPRuntimeNVPTX::ExecutionMode &ExecMode,
174 bool &RuntimeMode, bool FullRuntimeMode)
175 : ExecMode(ExecMode), RuntimeMode(&RuntimeMode) {
176 SavedExecMode = ExecMode;
177 SavedRuntimeMode = RuntimeMode;
178 ExecMode = CGOpenMPRuntimeNVPTX::EM_SPMD;
179 RuntimeMode = FullRuntimeMode;
180 }
181 ~ExecutionRuntimeModesRAII() {
182 ExecMode = SavedExecMode;
183 if (RuntimeMode)
184 *RuntimeMode = SavedRuntimeMode;
185 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000186};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000187
188/// GPU Configuration: This information can be derived from cuda registers,
189/// however, providing compile time constants helps generate more efficient
190/// code. For all practical purposes this is fine because the configuration
191/// is the same for all known NVPTX architectures.
192enum MachineConfiguration : unsigned {
193 WarpSize = 32,
194 /// Number of bits required to represent a lane identifier, which is
195 /// computed as log_2(WarpSize).
196 LaneIDBits = 5,
197 LaneIDMask = WarpSize - 1,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +0000198
199 /// Global memory alignment for performance.
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000200 GlobalMemoryAlignment = 128,
Alexey Bataev09c9eea2018-11-09 16:18:04 +0000201
202 /// Maximal size of the shared memory buffer.
203 SharedMemorySize = 128,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000204};
205
Alexey Bataevf2f39be2018-11-16 19:38:21 +0000206static const ValueDecl *getPrivateItem(const Expr *RefExpr) {
207 RefExpr = RefExpr->IgnoreParens();
208 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr)) {
209 const Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
210 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
211 Base = TempASE->getBase()->IgnoreParenImpCasts();
212 RefExpr = Base;
213 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr)) {
214 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
215 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
216 Base = TempOASE->getBase()->IgnoreParenImpCasts();
217 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
218 Base = TempASE->getBase()->IgnoreParenImpCasts();
219 RefExpr = Base;
220 }
221 RefExpr = RefExpr->IgnoreParenImpCasts();
222 if (const auto *DE = dyn_cast<DeclRefExpr>(RefExpr))
223 return cast<ValueDecl>(DE->getDecl()->getCanonicalDecl());
224 const auto *ME = cast<MemberExpr>(RefExpr);
225 return cast<ValueDecl>(ME->getMemberDecl()->getCanonicalDecl());
226}
227
Alexey Bataev2adecff2018-09-21 14:22:53 +0000228
229static RecordDecl *buildRecordForGlobalizedVars(
230 ASTContext &C, ArrayRef<const ValueDecl *> EscapedDecls,
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000231 ArrayRef<const ValueDecl *> EscapedDeclsForTeams,
Alexey Bataev2adecff2018-09-21 14:22:53 +0000232 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
Alexey Bataev8061acd2019-02-20 16:36:22 +0000233 &MappedDeclsFields, int BufSize) {
Fangrui Song899d1392019-04-24 14:43:05 +0000234 using VarsDataTy = std::pair<CharUnits /*Align*/, const ValueDecl *>;
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000235 if (EscapedDecls.empty() && EscapedDeclsForTeams.empty())
Alexey Bataev2adecff2018-09-21 14:22:53 +0000236 return nullptr;
237 SmallVector<VarsDataTy, 4> GlobalizedVars;
238 for (const ValueDecl *D : EscapedDecls)
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000239 GlobalizedVars.emplace_back(
240 CharUnits::fromQuantity(std::max(
241 C.getDeclAlign(D).getQuantity(),
242 static_cast<CharUnits::QuantityType>(GlobalMemoryAlignment))),
243 D);
244 for (const ValueDecl *D : EscapedDeclsForTeams)
Alexey Bataev2adecff2018-09-21 14:22:53 +0000245 GlobalizedVars.emplace_back(C.getDeclAlign(D), D);
Fangrui Song899d1392019-04-24 14:43:05 +0000246 llvm::stable_sort(GlobalizedVars, [](VarsDataTy L, VarsDataTy R) {
247 return L.first > R.first;
248 });
249
Alexey Bataev2adecff2018-09-21 14:22:53 +0000250 // Build struct _globalized_locals_ty {
Alexey Bataevff23bb62018-10-11 18:30:31 +0000251 // /* globalized vars */[WarSize] align (max(decl_align,
252 // GlobalMemoryAlignment))
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000253 // /* globalized vars */ for EscapedDeclsForTeams
Alexey Bataev2adecff2018-09-21 14:22:53 +0000254 // };
255 RecordDecl *GlobalizedRD = C.buildImplicitRecord("_globalized_locals_ty");
256 GlobalizedRD->startDefinition();
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000257 llvm::SmallPtrSet<const ValueDecl *, 16> SingleEscaped(
258 EscapedDeclsForTeams.begin(), EscapedDeclsForTeams.end());
Alexey Bataev2adecff2018-09-21 14:22:53 +0000259 for (const auto &Pair : GlobalizedVars) {
260 const ValueDecl *VD = Pair.second;
261 QualType Type = VD->getType();
262 if (Type->isLValueReferenceType())
263 Type = C.getPointerType(Type.getNonReferenceType());
264 else
265 Type = Type.getNonReferenceType();
266 SourceLocation Loc = VD->getLocation();
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000267 FieldDecl *Field;
268 if (SingleEscaped.count(VD)) {
269 Field = FieldDecl::Create(
270 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
271 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
272 /*BW=*/nullptr, /*Mutable=*/false,
273 /*InitStyle=*/ICIS_NoInit);
274 Field->setAccess(AS_public);
275 if (VD->hasAttrs()) {
276 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
277 E(VD->getAttrs().end());
278 I != E; ++I)
279 Field->addAttr(*I);
280 }
281 } else {
Alexey Bataev8061acd2019-02-20 16:36:22 +0000282 llvm::APInt ArraySize(32, BufSize);
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000283 Type = C.getConstantArrayType(Type, ArraySize, ArrayType::Normal, 0);
284 Field = FieldDecl::Create(
285 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
286 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
287 /*BW=*/nullptr, /*Mutable=*/false,
288 /*InitStyle=*/ICIS_NoInit);
289 Field->setAccess(AS_public);
290 llvm::APInt Align(32, std::max(C.getDeclAlign(VD).getQuantity(),
291 static_cast<CharUnits::QuantityType>(
292 GlobalMemoryAlignment)));
293 Field->addAttr(AlignedAttr::CreateImplicit(
294 C, AlignedAttr::GNU_aligned, /*IsAlignmentExpr=*/true,
295 IntegerLiteral::Create(C, Align,
296 C.getIntTypeForBitwidth(32, /*Signed=*/0),
297 SourceLocation())));
Alexey Bataev2adecff2018-09-21 14:22:53 +0000298 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000299 GlobalizedRD->addDecl(Field);
Alexey Bataev2adecff2018-09-21 14:22:53 +0000300 MappedDeclsFields.try_emplace(VD, Field);
301 }
302 GlobalizedRD->completeDefinition();
303 return GlobalizedRD;
304}
305
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000306/// Get the list of variables that can escape their declaration context.
307class CheckVarsEscapingDeclContext final
308 : public ConstStmtVisitor<CheckVarsEscapingDeclContext> {
309 CodeGenFunction &CGF;
310 llvm::SetVector<const ValueDecl *> EscapedDecls;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000311 llvm::SetVector<const ValueDecl *> EscapedVariableLengthDecls;
Alexey Bataevc99042b2018-03-15 18:10:54 +0000312 llvm::SmallPtrSet<const Decl *, 4> EscapedParameters;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000313 RecordDecl *GlobalizedRD = nullptr;
314 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000315 bool AllEscaped = false;
Alexey Bataev91433f62018-06-26 17:24:03 +0000316 bool IsForCombinedParallelRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000317
318 void markAsEscaped(const ValueDecl *VD) {
Alexey Bataev03f270c2018-03-30 18:31:07 +0000319 // Do not globalize declare target variables.
Alexey Bataev97b72212018-08-14 18:31:20 +0000320 if (!isa<VarDecl>(VD) ||
321 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataev03f270c2018-03-30 18:31:07 +0000322 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000323 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataev1db9bfe2019-04-08 16:53:57 +0000324 // Use user-specified allocation.
325 if (VD->hasAttrs() && VD->hasAttr<OMPAllocateDeclAttr>())
326 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +0000327 // Variables captured by value must be globalized.
328 if (auto *CSI = CGF.CapturedStmtInfo) {
Mikael Holmen9f373a32018-03-16 07:27:57 +0000329 if (const FieldDecl *FD = CSI->lookup(cast<VarDecl>(VD))) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000330 // Check if need to capture the variable that was already captured by
331 // value in the outer region.
Alexey Bataev91433f62018-06-26 17:24:03 +0000332 if (!IsForCombinedParallelRegion) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000333 if (!FD->hasAttrs())
334 return;
335 const auto *Attr = FD->getAttr<OMPCaptureKindAttr>();
336 if (!Attr)
337 return;
Alexey Bataev6393eb72018-12-06 15:35:13 +0000338 if (((Attr->getCaptureKind() != OMPC_map) &&
339 !isOpenMPPrivate(
340 static_cast<OpenMPClauseKind>(Attr->getCaptureKind()))) ||
341 ((Attr->getCaptureKind() == OMPC_map) &&
342 !FD->getType()->isAnyPointerType()))
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000343 return;
344 }
345 if (!FD->getType()->isReferenceType()) {
346 assert(!VD->getType()->isVariablyModifiedType() &&
347 "Parameter captured by value with variably modified type");
348 EscapedParameters.insert(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000349 } else if (!IsForCombinedParallelRegion) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000350 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000351 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000352 }
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000353 }
354 if ((!CGF.CapturedStmtInfo ||
Alexey Bataev91433f62018-06-26 17:24:03 +0000355 (IsForCombinedParallelRegion && CGF.CapturedStmtInfo)) &&
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000356 VD->getType()->isReferenceType())
357 // Do not globalize variables with reference type.
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000358 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000359 if (VD->getType()->isVariablyModifiedType())
360 EscapedVariableLengthDecls.insert(VD);
361 else
362 EscapedDecls.insert(VD);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000363 }
364
365 void VisitValueDecl(const ValueDecl *VD) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000366 if (VD->getType()->isLValueReferenceType())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000367 markAsEscaped(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000368 if (const auto *VarD = dyn_cast<VarDecl>(VD)) {
369 if (!isa<ParmVarDecl>(VarD) && VarD->hasInit()) {
370 const bool SavedAllEscaped = AllEscaped;
371 AllEscaped = VD->getType()->isLValueReferenceType();
372 Visit(VarD->getInit());
373 AllEscaped = SavedAllEscaped;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000374 }
375 }
376 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000377 void VisitOpenMPCapturedStmt(const CapturedStmt *S,
378 ArrayRef<OMPClause *> Clauses,
379 bool IsCombinedParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000380 if (!S)
381 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000382 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000383 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
384 const ValueDecl *VD = C.getCapturedVar();
Alexey Bataev91433f62018-06-26 17:24:03 +0000385 bool SavedIsForCombinedParallelRegion = IsForCombinedParallelRegion;
386 if (IsCombinedParallelRegion) {
387 // Check if the variable is privatized in the combined construct and
388 // those private copies must be shared in the inner parallel
389 // directive.
390 IsForCombinedParallelRegion = false;
391 for (const OMPClause *C : Clauses) {
392 if (!isOpenMPPrivate(C->getClauseKind()) ||
393 C->getClauseKind() == OMPC_reduction ||
394 C->getClauseKind() == OMPC_linear ||
395 C->getClauseKind() == OMPC_private)
396 continue;
397 ArrayRef<const Expr *> Vars;
398 if (const auto *PC = dyn_cast<OMPFirstprivateClause>(C))
399 Vars = PC->getVarRefs();
400 else if (const auto *PC = dyn_cast<OMPLastprivateClause>(C))
401 Vars = PC->getVarRefs();
402 else
403 llvm_unreachable("Unexpected clause.");
404 for (const auto *E : Vars) {
405 const Decl *D =
406 cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
407 if (D == VD->getCanonicalDecl()) {
408 IsForCombinedParallelRegion = true;
409 break;
410 }
411 }
412 if (IsForCombinedParallelRegion)
413 break;
414 }
415 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000416 markAsEscaped(VD);
417 if (isa<OMPCapturedExprDecl>(VD))
418 VisitValueDecl(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000419 IsForCombinedParallelRegion = SavedIsForCombinedParallelRegion;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000420 }
421 }
422 }
423
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000424 void buildRecordForGlobalizedVars(bool IsInTTDRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000425 assert(!GlobalizedRD &&
426 "Record for globalized variables is built already.");
Alexey Bataevff23bb62018-10-11 18:30:31 +0000427 ArrayRef<const ValueDecl *> EscapedDeclsForParallel, EscapedDeclsForTeams;
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000428 if (IsInTTDRegion)
Alexey Bataevff23bb62018-10-11 18:30:31 +0000429 EscapedDeclsForTeams = EscapedDecls.getArrayRef();
430 else
431 EscapedDeclsForParallel = EscapedDecls.getArrayRef();
Alexey Bataev2adecff2018-09-21 14:22:53 +0000432 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataevff23bb62018-10-11 18:30:31 +0000433 CGF.getContext(), EscapedDeclsForParallel, EscapedDeclsForTeams,
Alexey Bataev8061acd2019-02-20 16:36:22 +0000434 MappedDeclsFields, WarpSize);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000435 }
436
437public:
Alexey Bataevf2f39be2018-11-16 19:38:21 +0000438 CheckVarsEscapingDeclContext(CodeGenFunction &CGF,
439 ArrayRef<const ValueDecl *> TeamsReductions)
440 : CGF(CGF), EscapedDecls(TeamsReductions.begin(), TeamsReductions.end()) {
441 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000442 virtual ~CheckVarsEscapingDeclContext() = default;
443 void VisitDeclStmt(const DeclStmt *S) {
444 if (!S)
445 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000446 for (const Decl *D : S->decls())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000447 if (const auto *VD = dyn_cast_or_null<ValueDecl>(D))
448 VisitValueDecl(VD);
449 }
450 void VisitOMPExecutableDirective(const OMPExecutableDirective *D) {
451 if (!D)
452 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000453 if (!D->hasAssociatedStmt())
454 return;
455 if (const auto *S =
456 dyn_cast_or_null<CapturedStmt>(D->getAssociatedStmt())) {
457 // Do not analyze directives that do not actually require capturing,
458 // like `omp for` or `omp simd` directives.
459 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
460 getOpenMPCaptureRegions(CaptureRegions, D->getDirectiveKind());
461 if (CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown) {
462 VisitStmt(S->getCapturedStmt());
463 return;
Alexey Bataev673110d2018-05-16 13:36:30 +0000464 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000465 VisitOpenMPCapturedStmt(
466 S, D->clauses(),
467 CaptureRegions.back() == OMPD_parallel &&
468 isOpenMPDistributeDirective(D->getDirectiveKind()));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000469 }
470 }
471 void VisitCapturedStmt(const CapturedStmt *S) {
472 if (!S)
473 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000474 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000475 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
476 const ValueDecl *VD = C.getCapturedVar();
477 markAsEscaped(VD);
478 if (isa<OMPCapturedExprDecl>(VD))
479 VisitValueDecl(VD);
480 }
481 }
482 }
483 void VisitLambdaExpr(const LambdaExpr *E) {
484 if (!E)
485 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000486 for (const LambdaCapture &C : E->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000487 if (C.capturesVariable()) {
488 if (C.getCaptureKind() == LCK_ByRef) {
489 const ValueDecl *VD = C.getCapturedVar();
490 markAsEscaped(VD);
491 if (E->isInitCapture(&C) || isa<OMPCapturedExprDecl>(VD))
492 VisitValueDecl(VD);
493 }
494 }
495 }
496 }
497 void VisitBlockExpr(const BlockExpr *E) {
498 if (!E)
499 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000500 for (const BlockDecl::Capture &C : E->getBlockDecl()->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000501 if (C.isByRef()) {
502 const VarDecl *VD = C.getVariable();
503 markAsEscaped(VD);
504 if (isa<OMPCapturedExprDecl>(VD) || VD->isInitCapture())
505 VisitValueDecl(VD);
506 }
507 }
508 }
509 void VisitCallExpr(const CallExpr *E) {
510 if (!E)
511 return;
512 for (const Expr *Arg : E->arguments()) {
513 if (!Arg)
514 continue;
515 if (Arg->isLValue()) {
516 const bool SavedAllEscaped = AllEscaped;
517 AllEscaped = true;
518 Visit(Arg);
519 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000520 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000521 Visit(Arg);
Alexey Bataev9ff80832018-04-16 20:16:21 +0000522 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000523 }
524 Visit(E->getCallee());
525 }
526 void VisitDeclRefExpr(const DeclRefExpr *E) {
527 if (!E)
528 return;
529 const ValueDecl *VD = E->getDecl();
530 if (AllEscaped)
531 markAsEscaped(VD);
532 if (isa<OMPCapturedExprDecl>(VD))
533 VisitValueDecl(VD);
534 else if (const auto *VarD = dyn_cast<VarDecl>(VD))
535 if (VarD->isInitCapture())
536 VisitValueDecl(VD);
537 }
538 void VisitUnaryOperator(const UnaryOperator *E) {
539 if (!E)
540 return;
541 if (E->getOpcode() == UO_AddrOf) {
542 const bool SavedAllEscaped = AllEscaped;
543 AllEscaped = true;
544 Visit(E->getSubExpr());
545 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000546 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000547 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000548 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000549 }
550 void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
551 if (!E)
552 return;
553 if (E->getCastKind() == CK_ArrayToPointerDecay) {
554 const bool SavedAllEscaped = AllEscaped;
555 AllEscaped = true;
556 Visit(E->getSubExpr());
557 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000558 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000559 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000560 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000561 }
562 void VisitExpr(const Expr *E) {
563 if (!E)
564 return;
565 bool SavedAllEscaped = AllEscaped;
566 if (!E->isLValue())
567 AllEscaped = false;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000568 for (const Stmt *Child : E->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000569 if (Child)
570 Visit(Child);
571 AllEscaped = SavedAllEscaped;
572 }
573 void VisitStmt(const Stmt *S) {
574 if (!S)
575 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000576 for (const Stmt *Child : S->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000577 if (Child)
578 Visit(Child);
579 }
580
Alexey Bataevc99042b2018-03-15 18:10:54 +0000581 /// Returns the record that handles all the escaped local variables and used
582 /// instead of their original storage.
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000583 const RecordDecl *getGlobalizedRecord(bool IsInTTDRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000584 if (!GlobalizedRD)
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000585 buildRecordForGlobalizedVars(IsInTTDRegion);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000586 return GlobalizedRD;
587 }
588
Alexey Bataevc99042b2018-03-15 18:10:54 +0000589 /// Returns the field in the globalized record for the escaped variable.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000590 const FieldDecl *getFieldForGlobalizedVar(const ValueDecl *VD) const {
591 assert(GlobalizedRD &&
592 "Record for globalized variables must be generated already.");
593 auto I = MappedDeclsFields.find(VD);
594 if (I == MappedDeclsFields.end())
595 return nullptr;
596 return I->getSecond();
597 }
598
Alexey Bataevc99042b2018-03-15 18:10:54 +0000599 /// Returns the list of the escaped local variables/parameters.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000600 ArrayRef<const ValueDecl *> getEscapedDecls() const {
601 return EscapedDecls.getArrayRef();
602 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000603
604 /// Checks if the escaped local variable is actually a parameter passed by
605 /// value.
606 const llvm::SmallPtrSetImpl<const Decl *> &getEscapedParameters() const {
607 return EscapedParameters;
608 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000609
610 /// Returns the list of the escaped variables with the variably modified
611 /// types.
612 ArrayRef<const ValueDecl *> getEscapedVariableLengthDecls() const {
613 return EscapedVariableLengthDecls.getArrayRef();
614 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000615};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000616} // anonymous namespace
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000617
618/// Get the GPU warp size.
619static llvm::Value *getNVPTXWarpSize(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000620 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000621 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000622 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_warpsize),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000623 "nvptx_warp_size");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000624}
625
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000626/// Get the id of the current thread on the GPU.
627static llvm::Value *getNVPTXThreadID(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000628 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000629 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000630 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_tid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000631 "nvptx_tid");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000632}
633
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000634/// Get the id of the warp in the block.
635/// We assume that the warp size is 32, which is always the case
636/// on the NVPTX device, to generate more efficient code.
637static llvm::Value *getNVPTXWarpID(CodeGenFunction &CGF) {
638 CGBuilderTy &Bld = CGF.Builder;
639 return Bld.CreateAShr(getNVPTXThreadID(CGF), LaneIDBits, "nvptx_warp_id");
640}
641
642/// Get the id of the current lane in the Warp.
643/// We assume that the warp size is 32, which is always the case
644/// on the NVPTX device, to generate more efficient code.
645static llvm::Value *getNVPTXLaneID(CodeGenFunction &CGF) {
646 CGBuilderTy &Bld = CGF.Builder;
647 return Bld.CreateAnd(getNVPTXThreadID(CGF), Bld.getInt32(LaneIDMask),
648 "nvptx_lane_id");
649}
650
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000651/// Get the maximum number of threads in a block of the GPU.
652static llvm::Value *getNVPTXNumThreads(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000653 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000654 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000655 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_ntid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000656 "nvptx_num_threads");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000657}
658
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000659/// Get the value of the thread_limit clause in the teams directive.
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000660/// For the 'generic' execution mode, the runtime encodes thread_limit in
661/// the launch parameters, always starting thread_limit+warpSize threads per
662/// CTA. The threads in the last warp are reserved for master execution.
663/// For the 'spmd' execution mode, all threads in a CTA are part of the team.
664static llvm::Value *getThreadLimit(CodeGenFunction &CGF,
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000665 bool IsInSPMDExecutionMode = false) {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000666 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000667 return IsInSPMDExecutionMode
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000668 ? getNVPTXNumThreads(CGF)
Alexey Bataeve290ec02018-04-06 16:03:36 +0000669 : Bld.CreateNUWSub(getNVPTXNumThreads(CGF), getNVPTXWarpSize(CGF),
670 "thread_limit");
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000671}
672
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000673/// Get the thread id of the OMP master thread.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000674/// The master thread id is the first thread (lane) of the last warp in the
675/// GPU block. Warp size is assumed to be some power of 2.
676/// Thread id is 0 indexed.
677/// E.g: If NumThreads is 33, master id is 32.
678/// If NumThreads is 64, master id is 32.
679/// If NumThreads is 1024, master id is 992.
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000680static llvm::Value *getMasterThreadID(CodeGenFunction &CGF) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000681 CGBuilderTy &Bld = CGF.Builder;
682 llvm::Value *NumThreads = getNVPTXNumThreads(CGF);
683
684 // We assume that the warp size is a power of 2.
Alexey Bataeve290ec02018-04-06 16:03:36 +0000685 llvm::Value *Mask = Bld.CreateNUWSub(getNVPTXWarpSize(CGF), Bld.getInt32(1));
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000686
Alexey Bataeve290ec02018-04-06 16:03:36 +0000687 return Bld.CreateAnd(Bld.CreateNUWSub(NumThreads, Bld.getInt32(1)),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000688 Bld.CreateNot(Mask), "master_tid");
689}
690
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000691CGOpenMPRuntimeNVPTX::WorkerFunctionState::WorkerFunctionState(
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000692 CodeGenModule &CGM, SourceLocation Loc)
Alexey Bataev9ff80832018-04-16 20:16:21 +0000693 : WorkerFn(nullptr), CGFI(CGM.getTypes().arrangeNullaryFunction()),
694 Loc(Loc) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000695 createWorkerFunction(CGM);
Vasileios Kalintirise5c09592016-03-22 10:41:20 +0000696}
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000697
698void CGOpenMPRuntimeNVPTX::WorkerFunctionState::createWorkerFunction(
699 CodeGenModule &CGM) {
700 // Create an worker function with no arguments.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000701
702 WorkerFn = llvm::Function::Create(
Alexey Bataev9ff80832018-04-16 20:16:21 +0000703 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataevaee93892018-01-08 20:09:47 +0000704 /*placeholder=*/"_worker", &CGM.getModule());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000705 CGM.SetInternalFunctionAttributes(GlobalDecl(), WorkerFn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +0000706 WorkerFn->setDoesNotRecurse();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000707}
708
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000709CGOpenMPRuntimeNVPTX::ExecutionMode
710CGOpenMPRuntimeNVPTX::getExecutionMode() const {
711 return CurrentExecutionMode;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000712}
713
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000714static CGOpenMPRuntimeNVPTX::DataSharingMode
715getDataSharingMode(CodeGenModule &CGM) {
716 return CGM.getLangOpts().OpenMPCUDAMode ? CGOpenMPRuntimeNVPTX::CUDA
717 : CGOpenMPRuntimeNVPTX::Generic;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000718}
719
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000720/// Check for inner (nested) SPMD construct, if any
721static bool hasNestedSPMDDirective(ASTContext &Ctx,
722 const OMPExecutableDirective &D) {
723 const auto *CS = D.getInnermostCapturedStmt();
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000724 const auto *Body =
725 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5c427362019-04-10 19:11:33 +0000726 const Stmt *ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000727
Alexey Bataev5c427362019-04-10 19:11:33 +0000728 if (const auto *NestedDir =
729 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000730 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000731 switch (D.getDirectiveKind()) {
732 case OMPD_target:
Alexey Bataevdc9e7dc2019-04-17 16:53:08 +0000733 if (isOpenMPParallelDirective(DKind))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000734 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000735 if (DKind == OMPD_teams) {
736 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
737 /*IgnoreCaptured=*/true);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000738 if (!Body)
739 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000740 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
741 if (const auto *NND =
742 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000743 DKind = NND->getDirectiveKind();
Alexey Bataevdc9e7dc2019-04-17 16:53:08 +0000744 if (isOpenMPParallelDirective(DKind))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000745 return true;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000746 }
747 }
748 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000749 case OMPD_target_teams:
Alexey Bataevdc9e7dc2019-04-17 16:53:08 +0000750 return isOpenMPParallelDirective(DKind);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000751 case OMPD_target_simd:
752 case OMPD_target_parallel:
753 case OMPD_target_parallel_for:
754 case OMPD_target_parallel_for_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000755 case OMPD_target_teams_distribute:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000756 case OMPD_target_teams_distribute_simd:
757 case OMPD_target_teams_distribute_parallel_for:
758 case OMPD_target_teams_distribute_parallel_for_simd:
759 case OMPD_parallel:
760 case OMPD_for:
761 case OMPD_parallel_for:
762 case OMPD_parallel_sections:
763 case OMPD_for_simd:
764 case OMPD_parallel_for_simd:
765 case OMPD_cancel:
766 case OMPD_cancellation_point:
767 case OMPD_ordered:
768 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +0000769 case OMPD_allocate:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000770 case OMPD_task:
771 case OMPD_simd:
772 case OMPD_sections:
773 case OMPD_section:
774 case OMPD_single:
775 case OMPD_master:
776 case OMPD_critical:
777 case OMPD_taskyield:
778 case OMPD_barrier:
779 case OMPD_taskwait:
780 case OMPD_taskgroup:
781 case OMPD_atomic:
782 case OMPD_flush:
783 case OMPD_teams:
784 case OMPD_target_data:
785 case OMPD_target_exit_data:
786 case OMPD_target_enter_data:
787 case OMPD_distribute:
788 case OMPD_distribute_simd:
789 case OMPD_distribute_parallel_for:
790 case OMPD_distribute_parallel_for_simd:
791 case OMPD_teams_distribute:
792 case OMPD_teams_distribute_simd:
793 case OMPD_teams_distribute_parallel_for:
794 case OMPD_teams_distribute_parallel_for_simd:
795 case OMPD_target_update:
796 case OMPD_declare_simd:
797 case OMPD_declare_target:
798 case OMPD_end_declare_target:
799 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +0000800 case OMPD_declare_mapper:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000801 case OMPD_taskloop:
802 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000803 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000804 case OMPD_unknown:
805 llvm_unreachable("Unexpected directive.");
806 }
807 }
808
809 return false;
810}
811
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000812static bool supportsSPMDExecutionMode(ASTContext &Ctx,
813 const OMPExecutableDirective &D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000814 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
815 switch (DirectiveKind) {
816 case OMPD_target:
817 case OMPD_target_teams:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000818 return hasNestedSPMDDirective(Ctx, D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000819 case OMPD_target_parallel:
820 case OMPD_target_parallel_for:
821 case OMPD_target_parallel_for_simd:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000822 case OMPD_target_teams_distribute_parallel_for:
823 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000824 case OMPD_target_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000825 case OMPD_target_teams_distribute_simd:
Alexey Bataevdc9e7dc2019-04-17 16:53:08 +0000826 return true;
827 case OMPD_target_teams_distribute:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000828 return false;
829 case OMPD_parallel:
830 case OMPD_for:
831 case OMPD_parallel_for:
832 case OMPD_parallel_sections:
833 case OMPD_for_simd:
834 case OMPD_parallel_for_simd:
835 case OMPD_cancel:
836 case OMPD_cancellation_point:
837 case OMPD_ordered:
838 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +0000839 case OMPD_allocate:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000840 case OMPD_task:
841 case OMPD_simd:
842 case OMPD_sections:
843 case OMPD_section:
844 case OMPD_single:
845 case OMPD_master:
846 case OMPD_critical:
847 case OMPD_taskyield:
848 case OMPD_barrier:
849 case OMPD_taskwait:
850 case OMPD_taskgroup:
851 case OMPD_atomic:
852 case OMPD_flush:
853 case OMPD_teams:
854 case OMPD_target_data:
855 case OMPD_target_exit_data:
856 case OMPD_target_enter_data:
857 case OMPD_distribute:
858 case OMPD_distribute_simd:
859 case OMPD_distribute_parallel_for:
860 case OMPD_distribute_parallel_for_simd:
861 case OMPD_teams_distribute:
862 case OMPD_teams_distribute_simd:
863 case OMPD_teams_distribute_parallel_for:
864 case OMPD_teams_distribute_parallel_for_simd:
865 case OMPD_target_update:
866 case OMPD_declare_simd:
867 case OMPD_declare_target:
868 case OMPD_end_declare_target:
869 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +0000870 case OMPD_declare_mapper:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000871 case OMPD_taskloop:
872 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000873 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000874 case OMPD_unknown:
875 break;
876 }
877 llvm_unreachable(
878 "Unknown programming model for OpenMP directive on NVPTX target.");
879}
880
881/// Check if the directive is loops based and has schedule clause at all or has
882/// static scheduling.
883static bool hasStaticScheduling(const OMPExecutableDirective &D) {
884 assert(isOpenMPWorksharingDirective(D.getDirectiveKind()) &&
885 isOpenMPLoopDirective(D.getDirectiveKind()) &&
886 "Expected loop-based directive.");
887 return !D.hasClausesOfKind<OMPOrderedClause>() &&
888 (!D.hasClausesOfKind<OMPScheduleClause>() ||
889 llvm::any_of(D.getClausesOfKind<OMPScheduleClause>(),
890 [](const OMPScheduleClause *C) {
891 return C->getScheduleKind() == OMPC_SCHEDULE_static;
892 }));
893}
894
895/// Check for inner (nested) lightweight runtime construct, if any
896static bool hasNestedLightweightDirective(ASTContext &Ctx,
897 const OMPExecutableDirective &D) {
898 assert(supportsSPMDExecutionMode(Ctx, D) && "Expected SPMD mode directive.");
899 const auto *CS = D.getInnermostCapturedStmt();
900 const auto *Body =
901 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5c427362019-04-10 19:11:33 +0000902 const Stmt *ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000903
Alexey Bataev5c427362019-04-10 19:11:33 +0000904 if (const auto *NestedDir =
905 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000906 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
907 switch (D.getDirectiveKind()) {
908 case OMPD_target:
909 if (isOpenMPParallelDirective(DKind) &&
910 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
911 hasStaticScheduling(*NestedDir))
912 return true;
Alexey Bataev1472e322019-04-19 16:48:38 +0000913 if (DKind == OMPD_teams_distribute_simd || DKind == OMPD_simd)
914 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000915 if (DKind == OMPD_parallel) {
916 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
917 /*IgnoreCaptured=*/true);
918 if (!Body)
919 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000920 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
921 if (const auto *NND =
922 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000923 DKind = NND->getDirectiveKind();
924 if (isOpenMPWorksharingDirective(DKind) &&
925 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
926 return true;
927 }
928 } else if (DKind == OMPD_teams) {
929 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
930 /*IgnoreCaptured=*/true);
931 if (!Body)
932 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000933 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
934 if (const auto *NND =
935 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000936 DKind = NND->getDirectiveKind();
937 if (isOpenMPParallelDirective(DKind) &&
938 isOpenMPWorksharingDirective(DKind) &&
939 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
940 return true;
941 if (DKind == OMPD_parallel) {
942 Body = NND->getInnermostCapturedStmt()->IgnoreContainers(
943 /*IgnoreCaptured=*/true);
944 if (!Body)
945 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000946 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
947 if (const auto *NND =
948 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000949 DKind = NND->getDirectiveKind();
950 if (isOpenMPWorksharingDirective(DKind) &&
951 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
952 return true;
953 }
954 }
955 }
956 }
957 return false;
958 case OMPD_target_teams:
959 if (isOpenMPParallelDirective(DKind) &&
960 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
961 hasStaticScheduling(*NestedDir))
962 return true;
Alexey Bataev1472e322019-04-19 16:48:38 +0000963 if (DKind == OMPD_distribute_simd || DKind == OMPD_simd)
964 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000965 if (DKind == OMPD_parallel) {
966 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
967 /*IgnoreCaptured=*/true);
968 if (!Body)
969 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000970 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
971 if (const auto *NND =
972 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000973 DKind = NND->getDirectiveKind();
974 if (isOpenMPWorksharingDirective(DKind) &&
975 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
976 return true;
977 }
978 }
979 return false;
980 case OMPD_target_parallel:
Alexey Bataev1472e322019-04-19 16:48:38 +0000981 if (DKind == OMPD_simd)
982 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000983 return isOpenMPWorksharingDirective(DKind) &&
984 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NestedDir);
985 case OMPD_target_teams_distribute:
986 case OMPD_target_simd:
987 case OMPD_target_parallel_for:
988 case OMPD_target_parallel_for_simd:
989 case OMPD_target_teams_distribute_simd:
990 case OMPD_target_teams_distribute_parallel_for:
991 case OMPD_target_teams_distribute_parallel_for_simd:
992 case OMPD_parallel:
993 case OMPD_for:
994 case OMPD_parallel_for:
995 case OMPD_parallel_sections:
996 case OMPD_for_simd:
997 case OMPD_parallel_for_simd:
998 case OMPD_cancel:
999 case OMPD_cancellation_point:
1000 case OMPD_ordered:
1001 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00001002 case OMPD_allocate:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001003 case OMPD_task:
1004 case OMPD_simd:
1005 case OMPD_sections:
1006 case OMPD_section:
1007 case OMPD_single:
1008 case OMPD_master:
1009 case OMPD_critical:
1010 case OMPD_taskyield:
1011 case OMPD_barrier:
1012 case OMPD_taskwait:
1013 case OMPD_taskgroup:
1014 case OMPD_atomic:
1015 case OMPD_flush:
1016 case OMPD_teams:
1017 case OMPD_target_data:
1018 case OMPD_target_exit_data:
1019 case OMPD_target_enter_data:
1020 case OMPD_distribute:
1021 case OMPD_distribute_simd:
1022 case OMPD_distribute_parallel_for:
1023 case OMPD_distribute_parallel_for_simd:
1024 case OMPD_teams_distribute:
1025 case OMPD_teams_distribute_simd:
1026 case OMPD_teams_distribute_parallel_for:
1027 case OMPD_teams_distribute_parallel_for_simd:
1028 case OMPD_target_update:
1029 case OMPD_declare_simd:
1030 case OMPD_declare_target:
1031 case OMPD_end_declare_target:
1032 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00001033 case OMPD_declare_mapper:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001034 case OMPD_taskloop:
1035 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001036 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001037 case OMPD_unknown:
1038 llvm_unreachable("Unexpected directive.");
1039 }
1040 }
1041
1042 return false;
1043}
1044
1045/// Checks if the construct supports lightweight runtime. It must be SPMD
1046/// construct + inner loop-based construct with static scheduling.
1047static bool supportsLightweightRuntime(ASTContext &Ctx,
1048 const OMPExecutableDirective &D) {
1049 if (!supportsSPMDExecutionMode(Ctx, D))
1050 return false;
1051 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
1052 switch (DirectiveKind) {
1053 case OMPD_target:
1054 case OMPD_target_teams:
1055 case OMPD_target_parallel:
1056 return hasNestedLightweightDirective(Ctx, D);
1057 case OMPD_target_parallel_for:
1058 case OMPD_target_parallel_for_simd:
1059 case OMPD_target_teams_distribute_parallel_for:
1060 case OMPD_target_teams_distribute_parallel_for_simd:
1061 // (Last|First)-privates must be shared in parallel region.
1062 return hasStaticScheduling(D);
1063 case OMPD_target_simd:
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001064 case OMPD_target_teams_distribute_simd:
Alexey Bataev1472e322019-04-19 16:48:38 +00001065 return true;
1066 case OMPD_target_teams_distribute:
Alexey Bataevdf093e72018-05-11 19:45:14 +00001067 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001068 case OMPD_parallel:
1069 case OMPD_for:
1070 case OMPD_parallel_for:
1071 case OMPD_parallel_sections:
1072 case OMPD_for_simd:
1073 case OMPD_parallel_for_simd:
1074 case OMPD_cancel:
1075 case OMPD_cancellation_point:
1076 case OMPD_ordered:
1077 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00001078 case OMPD_allocate:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001079 case OMPD_task:
1080 case OMPD_simd:
1081 case OMPD_sections:
1082 case OMPD_section:
1083 case OMPD_single:
1084 case OMPD_master:
1085 case OMPD_critical:
1086 case OMPD_taskyield:
1087 case OMPD_barrier:
1088 case OMPD_taskwait:
1089 case OMPD_taskgroup:
1090 case OMPD_atomic:
1091 case OMPD_flush:
1092 case OMPD_teams:
1093 case OMPD_target_data:
1094 case OMPD_target_exit_data:
1095 case OMPD_target_enter_data:
1096 case OMPD_distribute:
1097 case OMPD_distribute_simd:
1098 case OMPD_distribute_parallel_for:
1099 case OMPD_distribute_parallel_for_simd:
1100 case OMPD_teams_distribute:
1101 case OMPD_teams_distribute_simd:
1102 case OMPD_teams_distribute_parallel_for:
1103 case OMPD_teams_distribute_parallel_for_simd:
1104 case OMPD_target_update:
1105 case OMPD_declare_simd:
1106 case OMPD_declare_target:
1107 case OMPD_end_declare_target:
1108 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00001109 case OMPD_declare_mapper:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001110 case OMPD_taskloop:
1111 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001112 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001113 case OMPD_unknown:
1114 break;
1115 }
1116 llvm_unreachable(
1117 "Unknown programming model for OpenMP directive on NVPTX target.");
1118}
1119
1120void CGOpenMPRuntimeNVPTX::emitNonSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001121 StringRef ParentName,
1122 llvm::Function *&OutlinedFn,
1123 llvm::Constant *&OutlinedFnID,
1124 bool IsOffloadEntry,
1125 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001126 ExecutionRuntimeModesRAII ModeRAII(CurrentExecutionMode);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001127 EntryFunctionState EST;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001128 WorkerFunctionState WST(CGM, D.getBeginLoc());
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001129 Work.clear();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001130 WrapperFunctionsMap.clear();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001131
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001132 // Emit target region as a standalone region.
1133 class NVPTXPrePostActionTy : public PrePostActionTy {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001134 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1135 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001136
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001137 public:
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001138 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001139 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST)
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001140 : EST(EST), WST(WST) {}
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001141 void Enter(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001142 auto &RT =
1143 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001144 RT.emitNonSPMDEntryHeader(CGF, EST, WST);
1145 // Skip target region initialization.
1146 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001147 }
1148 void Exit(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001149 auto &RT =
1150 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001151 RT.clearLocThreadIdInsertPt(CGF);
1152 RT.emitNonSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001153 }
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001154 } Action(EST, WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001155 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001156 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001157 // Reserve place for the globalized memory.
1158 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001159 if (!KernelStaticGlobalized) {
1160 KernelStaticGlobalized = new llvm::GlobalVariable(
1161 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1162 llvm::GlobalValue::InternalLinkage,
1163 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1164 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1165 llvm::GlobalValue::NotThreadLocal,
1166 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1167 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001168 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1169 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001170 IsInTTDRegion = false;
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001171
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001172 // Now change the name of the worker function to correspond to this target
1173 // region's entry function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001174 WST.WorkerFn->setName(Twine(OutlinedFn->getName(), "_worker"));
Alexey Bataevaee93892018-01-08 20:09:47 +00001175
1176 // Create the worker function
1177 emitWorkerFunction(WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001178}
1179
1180// Setup NVPTX threads for master-worker OpenMP scheme.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001181void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryHeader(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001182 EntryFunctionState &EST,
1183 WorkerFunctionState &WST) {
1184 CGBuilderTy &Bld = CGF.Builder;
1185
1186 llvm::BasicBlock *WorkerBB = CGF.createBasicBlock(".worker");
1187 llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
1188 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
1189 EST.ExitBB = CGF.createBasicBlock(".exit");
1190
Alexey Bataev9ff80832018-04-16 20:16:21 +00001191 llvm::Value *IsWorker =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001192 Bld.CreateICmpULT(getNVPTXThreadID(CGF), getThreadLimit(CGF));
1193 Bld.CreateCondBr(IsWorker, WorkerBB, MasterCheckBB);
1194
1195 CGF.EmitBlock(WorkerBB);
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001196 emitCall(CGF, WST.Loc, WST.WorkerFn);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001197 CGF.EmitBranch(EST.ExitBB);
1198
1199 CGF.EmitBlock(MasterCheckBB);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001200 llvm::Value *IsMaster =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001201 Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
1202 Bld.CreateCondBr(IsMaster, MasterBB, EST.ExitBB);
1203
1204 CGF.EmitBlock(MasterBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001205 IsInTargetMasterThreadRegion = true;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001206 // SEQUENTIAL (MASTER) REGION START
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001207 // First action in sequential region:
1208 // Initialize the state of the OpenMP runtime library on the GPU.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001209 // TODO: Optimize runtime initialization and pass in correct value.
1210 llvm::Value *Args[] = {getThreadLimit(CGF),
1211 Bld.getInt16(/*RequiresOMPRuntime=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001212 CGF.EmitRuntimeCall(
1213 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_init), Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001214
1215 // For data sharing, we need to initialize the stack.
1216 CGF.EmitRuntimeCall(
1217 createNVPTXRuntimeFunction(
1218 OMPRTL_NVPTX__kmpc_data_sharing_init_stack));
1219
Alexey Bataevc99042b2018-03-15 18:10:54 +00001220 emitGenericVarsProlog(CGF, WST.Loc);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001221}
1222
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001223void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001224 EntryFunctionState &EST) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001225 IsInTargetMasterThreadRegion = false;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001226 if (!CGF.HaveInsertPoint())
1227 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001228
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001229 emitGenericVarsEpilog(CGF);
1230
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001231 if (!EST.ExitBB)
1232 EST.ExitBB = CGF.createBasicBlock(".exit");
1233
1234 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".termination.notifier");
1235 CGF.EmitBranch(TerminateBB);
1236
1237 CGF.EmitBlock(TerminateBB);
1238 // Signal termination condition.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001239 // TODO: Optimize runtime initialization and pass in correct value.
1240 llvm::Value *Args[] = {CGF.Builder.getInt16(/*IsOMPRuntimeInitialized=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001241 CGF.EmitRuntimeCall(
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001242 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_deinit), Args);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001243 // Barrier to terminate worker threads.
1244 syncCTAThreads(CGF);
1245 // Master thread jumps to exit point.
1246 CGF.EmitBranch(EST.ExitBB);
1247
1248 CGF.EmitBlock(EST.ExitBB);
1249 EST.ExitBB = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001250}
1251
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001252void CGOpenMPRuntimeNVPTX::emitSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001253 StringRef ParentName,
1254 llvm::Function *&OutlinedFn,
1255 llvm::Constant *&OutlinedFnID,
1256 bool IsOffloadEntry,
1257 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001258 ExecutionRuntimeModesRAII ModeRAII(
1259 CurrentExecutionMode, RequiresFullRuntime,
1260 CGM.getLangOpts().OpenMPCUDAForceFullRuntime ||
1261 !supportsLightweightRuntime(CGM.getContext(), D));
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001262 EntryFunctionState EST;
1263
1264 // Emit target region as a standalone region.
1265 class NVPTXPrePostActionTy : public PrePostActionTy {
1266 CGOpenMPRuntimeNVPTX &RT;
1267 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1268 const OMPExecutableDirective &D;
1269
1270 public:
1271 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT,
1272 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
1273 const OMPExecutableDirective &D)
1274 : RT(RT), EST(EST), D(D) {}
1275 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001276 RT.emitSPMDEntryHeader(CGF, EST, D);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001277 // Skip target region initialization.
1278 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001279 }
1280 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevfd006c42018-10-05 15:08:53 +00001281 RT.clearLocThreadIdInsertPt(CGF);
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001282 RT.emitSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001283 }
1284 } Action(*this, EST, D);
1285 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001286 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001287 // Reserve place for the globalized memory.
1288 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001289 if (!KernelStaticGlobalized) {
1290 KernelStaticGlobalized = new llvm::GlobalVariable(
1291 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1292 llvm::GlobalValue::InternalLinkage,
1293 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1294 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1295 llvm::GlobalValue::NotThreadLocal,
1296 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1297 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001298 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1299 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001300 IsInTTDRegion = false;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001301}
1302
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001303void CGOpenMPRuntimeNVPTX::emitSPMDEntryHeader(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001304 CodeGenFunction &CGF, EntryFunctionState &EST,
1305 const OMPExecutableDirective &D) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001306 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001307
1308 // Setup BBs in entry function.
1309 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute");
1310 EST.ExitBB = CGF.createBasicBlock(".exit");
1311
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001312 llvm::Value *Args[] = {getThreadLimit(CGF, /*IsInSPMDExecutionMode=*/true),
1313 /*RequiresOMPRuntime=*/
1314 Bld.getInt16(RequiresFullRuntime ? 1 : 0),
1315 /*RequiresDataSharing=*/Bld.getInt16(0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001316 CGF.EmitRuntimeCall(
1317 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_init), Args);
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001318
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001319 if (RequiresFullRuntime) {
1320 // For data sharing, we need to initialize the stack.
1321 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1322 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd));
1323 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001324
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001325 CGF.EmitBranch(ExecuteBB);
1326
1327 CGF.EmitBlock(ExecuteBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001328
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001329 IsInTargetMasterThreadRegion = true;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001330}
1331
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001332void CGOpenMPRuntimeNVPTX::emitSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001333 EntryFunctionState &EST) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001334 IsInTargetMasterThreadRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001335 if (!CGF.HaveInsertPoint())
1336 return;
1337
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001338 if (!EST.ExitBB)
1339 EST.ExitBB = CGF.createBasicBlock(".exit");
1340
1341 llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit");
1342 CGF.EmitBranch(OMPDeInitBB);
1343
1344 CGF.EmitBlock(OMPDeInitBB);
1345 // DeInitialize the OMP state in the runtime; called by all active threads.
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001346 llvm::Value *Args[] = {/*RequiresOMPRuntime=*/
1347 CGF.Builder.getInt16(RequiresFullRuntime ? 1 : 0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001348 CGF.EmitRuntimeCall(
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001349 createNVPTXRuntimeFunction(
1350 OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2), Args);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001351 CGF.EmitBranch(EST.ExitBB);
1352
1353 CGF.EmitBlock(EST.ExitBB);
1354 EST.ExitBB = nullptr;
1355}
1356
1357// Create a unique global variable to indicate the execution mode of this target
1358// region. The execution mode is either 'generic', or 'spmd' depending on the
1359// target directive. This variable is picked up by the offload library to setup
1360// the device appropriately before kernel launch. If the execution mode is
1361// 'generic', the runtime reserves one warp for the master, otherwise, all
1362// warps participate in parallel work.
1363static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001364 bool Mode) {
1365 auto *GVMode =
1366 new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
1367 llvm::GlobalValue::WeakAnyLinkage,
1368 llvm::ConstantInt::get(CGM.Int8Ty, Mode ? 0 : 1),
1369 Twine(Name, "_exec_mode"));
Alexey Bataev9ff80832018-04-16 20:16:21 +00001370 CGM.addCompilerUsedGlobal(GVMode);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001371}
1372
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001373void CGOpenMPRuntimeNVPTX::emitWorkerFunction(WorkerFunctionState &WST) {
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +00001374 ASTContext &Ctx = CGM.getContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001375
1376 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001377 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, WST.CGFI, {},
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001378 WST.Loc, WST.Loc);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001379 emitWorkerLoop(CGF, WST);
1380 CGF.FinishFunction();
1381}
1382
1383void CGOpenMPRuntimeNVPTX::emitWorkerLoop(CodeGenFunction &CGF,
1384 WorkerFunctionState &WST) {
1385 //
1386 // The workers enter this loop and wait for parallel work from the master.
1387 // When the master encounters a parallel region it sets up the work + variable
1388 // arguments, and wakes up the workers. The workers first check to see if
1389 // they are required for the parallel region, i.e., within the # of requested
1390 // parallel threads. The activated workers load the variable arguments and
1391 // execute the parallel work.
1392 //
1393
1394 CGBuilderTy &Bld = CGF.Builder;
1395
1396 llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work");
1397 llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers");
1398 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel");
1399 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel");
1400 llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel");
1401 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1402
1403 CGF.EmitBranch(AwaitBB);
1404
1405 // Workers wait for work from master.
1406 CGF.EmitBlock(AwaitBB);
1407 // Wait for parallel work
1408 syncCTAThreads(CGF);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001409
1410 Address WorkFn =
1411 CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn");
1412 Address ExecStatus =
1413 CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status");
1414 CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0));
1415 CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy));
1416
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001417 // TODO: Optimize runtime initialization and pass in correct value.
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001418 llvm::Value *Args[] = {WorkFn.getPointer(),
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001419 /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001420 llvm::Value *Ret = CGF.EmitRuntimeCall(
1421 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args);
1422 Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001423
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001424 // On termination condition (workid == 0), exit loop.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001425 llvm::Value *WorkID = Bld.CreateLoad(WorkFn);
1426 llvm::Value *ShouldTerminate = Bld.CreateIsNull(WorkID, "should_terminate");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001427 Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB);
1428
1429 // Activate requested workers.
1430 CGF.EmitBlock(SelectWorkersBB);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001431 llvm::Value *IsActive =
1432 Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active");
1433 Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001434
1435 // Signal start of parallel region.
1436 CGF.EmitBlock(ExecuteBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001437 // Skip initialization.
1438 setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001439
1440 // Process work items: outlined parallel functions.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001441 for (llvm::Function *W : Work) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001442 // Try to match this outlined function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001443 llvm::Value *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001444
1445 llvm::Value *WorkFnMatch =
1446 Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match");
1447
1448 llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn");
1449 llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next");
1450 Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB);
1451
1452 // Execute this outlined function.
1453 CGF.EmitBlock(ExecuteFNBB);
1454
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001455 // Insert call to work function via shared wrapper. The shared
1456 // wrapper takes two arguments:
1457 // - the parallelism level;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001458 // - the thread ID;
1459 emitCall(CGF, WST.Loc, W,
1460 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001461
1462 // Go to end of parallel region.
1463 CGF.EmitBranch(TerminateBB);
1464
1465 CGF.EmitBlock(CheckNextBB);
1466 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001467 // Default case: call to outlined function through pointer if the target
1468 // region makes a declare target call that may contain an orphaned parallel
1469 // directive.
1470 auto *ParallelFnTy =
1471 llvm::FunctionType::get(CGM.VoidTy, {CGM.Int16Ty, CGM.Int32Ty},
James Y Knight9871db02019-02-05 16:42:33 +00001472 /*isVarArg=*/false);
1473 llvm::Value *WorkFnCast =
1474 Bld.CreateBitCast(WorkID, ParallelFnTy->getPointerTo());
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001475 // Insert call to work function via shared wrapper. The shared
1476 // wrapper takes two arguments:
1477 // - the parallelism level;
1478 // - the thread ID;
James Y Knight9871db02019-02-05 16:42:33 +00001479 emitCall(CGF, WST.Loc, {ParallelFnTy, WorkFnCast},
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001480 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
1481 // Go to end of parallel region.
1482 CGF.EmitBranch(TerminateBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001483
1484 // Signal end of parallel region.
1485 CGF.EmitBlock(TerminateBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001486 CGF.EmitRuntimeCall(
1487 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_end_parallel),
1488 llvm::None);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001489 CGF.EmitBranch(BarrierBB);
1490
1491 // All active and inactive workers wait at a barrier after parallel region.
1492 CGF.EmitBlock(BarrierBB);
1493 // Barrier after parallel region.
1494 syncCTAThreads(CGF);
1495 CGF.EmitBranch(AwaitBB);
1496
1497 // Exit target region.
1498 CGF.EmitBlock(ExitBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001499 // Skip initialization.
1500 clearLocThreadIdInsertPt(CGF);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001501}
1502
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001503/// Returns specified OpenMP runtime function for the current OpenMP
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001504/// implementation. Specialized for the NVPTX device.
1505/// \param Function OpenMP runtime function.
1506/// \return Specified function.
James Y Knight9871db02019-02-05 16:42:33 +00001507llvm::FunctionCallee
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001508CGOpenMPRuntimeNVPTX::createNVPTXRuntimeFunction(unsigned Function) {
James Y Knight9871db02019-02-05 16:42:33 +00001509 llvm::FunctionCallee RTLFn = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001510 switch (static_cast<OpenMPRTLFunctionNVPTX>(Function)) {
1511 case OMPRTL_NVPTX__kmpc_kernel_init: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001512 // Build void __kmpc_kernel_init(kmp_int32 thread_limit, int16_t
1513 // RequiresOMPRuntime);
1514 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001515 auto *FnTy =
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001516 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1517 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_init");
1518 break;
1519 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001520 case OMPRTL_NVPTX__kmpc_kernel_deinit: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001521 // Build void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
1522 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001523 auto *FnTy =
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001524 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001525 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_deinit");
1526 break;
1527 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001528 case OMPRTL_NVPTX__kmpc_spmd_kernel_init: {
1529 // Build void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001530 // int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001531 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001532 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001533 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1534 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_init");
1535 break;
1536 }
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001537 case OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2: {
1538 // Build void __kmpc_spmd_kernel_deinit_v2(int16_t RequiresOMPRuntime);
1539 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001540 auto *FnTy =
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001541 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1542 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_deinit_v2");
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001543 break;
1544 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001545 case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: {
1546 /// Build void __kmpc_kernel_prepare_parallel(
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001547 /// void *outlined_function, int16_t IsOMPRuntimeInitialized);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001548 llvm::Type *TypeParams[] = {CGM.Int8PtrTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001549 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001550 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1551 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_prepare_parallel");
1552 break;
1553 }
1554 case OMPRTL_NVPTX__kmpc_kernel_parallel: {
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001555 /// Build bool __kmpc_kernel_parallel(void **outlined_function,
1556 /// int16_t IsOMPRuntimeInitialized);
1557 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy, CGM.Int16Ty};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001558 llvm::Type *RetTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001559 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001560 llvm::FunctionType::get(RetTy, TypeParams, /*isVarArg*/ false);
1561 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_parallel");
1562 break;
1563 }
1564 case OMPRTL_NVPTX__kmpc_kernel_end_parallel: {
1565 /// Build void __kmpc_kernel_end_parallel();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001566 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001567 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1568 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_end_parallel");
1569 break;
1570 }
1571 case OMPRTL_NVPTX__kmpc_serialized_parallel: {
1572 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1573 // global_tid);
1574 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001575 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001576 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1577 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1578 break;
1579 }
1580 case OMPRTL_NVPTX__kmpc_end_serialized_parallel: {
1581 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1582 // global_tid);
1583 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001584 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001585 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1586 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1587 break;
1588 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001589 case OMPRTL_NVPTX__kmpc_shuffle_int32: {
1590 // Build int32_t __kmpc_shuffle_int32(int32_t element,
1591 // int16_t lane_offset, int16_t warp_size);
1592 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001593 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001594 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1595 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int32");
1596 break;
1597 }
1598 case OMPRTL_NVPTX__kmpc_shuffle_int64: {
1599 // Build int64_t __kmpc_shuffle_int64(int64_t element,
1600 // int16_t lane_offset, int16_t warp_size);
1601 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001602 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001603 llvm::FunctionType::get(CGM.Int64Ty, TypeParams, /*isVarArg*/ false);
1604 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int64");
1605 break;
1606 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00001607 case OMPRTL_NVPTX__kmpc_nvptx_parallel_reduce_nowait_v2: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001608 // Build int32_t kmpc_nvptx_parallel_reduce_nowait_v2(ident_t *loc,
1609 // kmp_int32 global_tid, kmp_int32 num_vars, size_t reduce_size, void*
1610 // reduce_data, void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t
1611 // lane_id, int16_t lane_offset, int16_t Algorithm Version), void
1612 // (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001613 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1614 CGM.Int16Ty, CGM.Int16Ty};
1615 auto *ShuffleReduceFnTy =
1616 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1617 /*isVarArg=*/false);
1618 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1619 auto *InterWarpCopyFnTy =
1620 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1621 /*isVarArg=*/false);
Alexey Bataev8e009032019-01-04 17:25:09 +00001622 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1623 CGM.Int32Ty,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001624 CGM.Int32Ty,
1625 CGM.SizeTy,
1626 CGM.VoidPtrTy,
1627 ShuffleReduceFnTy->getPointerTo(),
1628 InterWarpCopyFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001629 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001630 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1631 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev8e009032019-01-04 17:25:09 +00001632 FnTy, /*Name=*/"__kmpc_nvptx_parallel_reduce_nowait_v2");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001633 break;
1634 }
1635 case OMPRTL_NVPTX__kmpc_end_reduce_nowait: {
1636 // Build __kmpc_end_reduce_nowait(kmp_int32 global_tid);
1637 llvm::Type *TypeParams[] = {CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001638 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001639 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1640 RTLFn = CGM.CreateRuntimeFunction(
1641 FnTy, /*Name=*/"__kmpc_nvptx_end_reduce_nowait");
1642 break;
1643 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00001644 case OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_v2: {
1645 // Build int32_t __kmpc_nvptx_teams_reduce_nowait_v2(ident_t *loc, kmp_int32
1646 // global_tid, void *global_buffer, int32_t num_of_records, void*
1647 // reduce_data,
1648 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1649 // lane_offset, int16_t shortCircuit),
1650 // void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num), void
1651 // (*kmp_ListToGlobalCpyFctPtr)(void *buffer, int idx, void *reduce_data),
1652 // void (*kmp_GlobalToListCpyFctPtr)(void *buffer, int idx,
1653 // void *reduce_data), void (*kmp_GlobalToListCpyPtrsFctPtr)(void *buffer,
1654 // int idx, void *reduce_data), void (*kmp_GlobalToListRedFctPtr)(void
1655 // *buffer, int idx, void *reduce_data));
1656 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1657 CGM.Int16Ty, CGM.Int16Ty};
1658 auto *ShuffleReduceFnTy =
1659 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1660 /*isVarArg=*/false);
1661 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1662 auto *InterWarpCopyFnTy =
1663 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1664 /*isVarArg=*/false);
1665 llvm::Type *GlobalListTypeParams[] = {CGM.VoidPtrTy, CGM.IntTy,
1666 CGM.VoidPtrTy};
1667 auto *GlobalListFnTy =
1668 llvm::FunctionType::get(CGM.VoidTy, GlobalListTypeParams,
1669 /*isVarArg=*/false);
1670 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1671 CGM.Int32Ty,
1672 CGM.VoidPtrTy,
1673 CGM.Int32Ty,
1674 CGM.VoidPtrTy,
1675 ShuffleReduceFnTy->getPointerTo(),
1676 InterWarpCopyFnTy->getPointerTo(),
1677 GlobalListFnTy->getPointerTo(),
1678 GlobalListFnTy->getPointerTo(),
1679 GlobalListFnTy->getPointerTo(),
1680 GlobalListFnTy->getPointerTo()};
Alexey Bataeva1166022018-11-27 21:24:54 +00001681 auto *FnTy =
1682 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1683 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev8061acd2019-02-20 16:36:22 +00001684 FnTy, /*Name=*/"__kmpc_nvptx_teams_reduce_nowait_v2");
Alexey Bataeva1166022018-11-27 21:24:54 +00001685 break;
1686 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001687 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack: {
1688 /// Build void __kmpc_data_sharing_init_stack();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001689 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001690 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1691 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack");
1692 break;
1693 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001694 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd: {
1695 /// Build void __kmpc_data_sharing_init_stack_spmd();
1696 auto *FnTy =
1697 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001698 RTLFn =
1699 CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack_spmd");
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001700 break;
1701 }
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001702 case OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack: {
1703 // Build void *__kmpc_data_sharing_coalesced_push_stack(size_t size,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001704 // int16_t UseSharedMemory);
1705 llvm::Type *TypeParams[] = {CGM.SizeTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001706 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001707 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1708 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001709 FnTy, /*Name=*/"__kmpc_data_sharing_coalesced_push_stack");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001710 break;
1711 }
1712 case OMPRTL_NVPTX__kmpc_data_sharing_pop_stack: {
1713 // Build void __kmpc_data_sharing_pop_stack(void *a);
1714 llvm::Type *TypeParams[] = {CGM.VoidPtrTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001715 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001716 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1717 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1718 /*Name=*/"__kmpc_data_sharing_pop_stack");
1719 break;
1720 }
1721 case OMPRTL_NVPTX__kmpc_begin_sharing_variables: {
1722 /// Build void __kmpc_begin_sharing_variables(void ***args,
1723 /// size_t n_args);
1724 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo(), CGM.SizeTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001725 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001726 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1727 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_begin_sharing_variables");
1728 break;
1729 }
1730 case OMPRTL_NVPTX__kmpc_end_sharing_variables: {
1731 /// Build void __kmpc_end_sharing_variables();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001732 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001733 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1734 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_sharing_variables");
1735 break;
1736 }
1737 case OMPRTL_NVPTX__kmpc_get_shared_variables: {
1738 /// Build void __kmpc_get_shared_variables(void ***GlobalArgs);
1739 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001740 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001741 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1742 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_shared_variables");
1743 break;
1744 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001745 case OMPRTL_NVPTX__kmpc_parallel_level: {
1746 // Build uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32 global_tid);
1747 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1748 auto *FnTy =
1749 llvm::FunctionType::get(CGM.Int16Ty, TypeParams, /*isVarArg*/ false);
1750 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_parallel_level");
1751 break;
1752 }
Alexey Bataev673110d2018-05-16 13:36:30 +00001753 case OMPRTL_NVPTX__kmpc_is_spmd_exec_mode: {
1754 // Build int8_t __kmpc_is_spmd_exec_mode();
1755 auto *FnTy = llvm::FunctionType::get(CGM.Int8Ty, /*isVarArg=*/false);
1756 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_is_spmd_exec_mode");
1757 break;
1758 }
Alexey Bataeve4090182018-11-02 14:54:07 +00001759 case OMPRTL_NVPTX__kmpc_get_team_static_memory: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001760 // Build void __kmpc_get_team_static_memory(int16_t isSPMDExecutionMode,
1761 // const void *buf, size_t size, int16_t is_shared, const void **res);
1762 llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.VoidPtrTy, CGM.SizeTy,
1763 CGM.Int16Ty, CGM.VoidPtrPtrTy};
Alexey Bataeve4090182018-11-02 14:54:07 +00001764 auto *FnTy =
1765 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1766 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_team_static_memory");
1767 break;
1768 }
1769 case OMPRTL_NVPTX__kmpc_restore_team_static_memory: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001770 // Build void __kmpc_restore_team_static_memory(int16_t isSPMDExecutionMode,
1771 // int16_t is_shared);
1772 llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataeve4090182018-11-02 14:54:07 +00001773 auto *FnTy =
Alexey Bataev8e009032019-01-04 17:25:09 +00001774 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
Alexey Bataeve4090182018-11-02 14:54:07 +00001775 RTLFn =
1776 CGM.CreateRuntimeFunction(FnTy, "__kmpc_restore_team_static_memory");
1777 break;
1778 }
Alexey Bataevc3028ca2018-12-04 15:03:25 +00001779 case OMPRTL__kmpc_barrier: {
1780 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
1781 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1782 auto *FnTy =
1783 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1784 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
James Y Knight9871db02019-02-05 16:42:33 +00001785 cast<llvm::Function>(RTLFn.getCallee())
1786 ->addFnAttr(llvm::Attribute::Convergent);
Alexey Bataevc3028ca2018-12-04 15:03:25 +00001787 break;
1788 }
Alexey Bataeva3924b52019-01-03 16:25:35 +00001789 case OMPRTL__kmpc_barrier_simple_spmd: {
1790 // Build void __kmpc_barrier_simple_spmd(ident_t *loc, kmp_int32
1791 // global_tid);
1792 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1793 auto *FnTy =
1794 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1795 RTLFn =
1796 CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier_simple_spmd");
James Y Knight9871db02019-02-05 16:42:33 +00001797 cast<llvm::Function>(RTLFn.getCallee())
1798 ->addFnAttr(llvm::Attribute::Convergent);
Alexey Bataeva3924b52019-01-03 16:25:35 +00001799 break;
1800 }
Alexey Bataev2cd7faf2019-08-26 19:07:48 +00001801 case OMPRTL_NVPTX__kmpc_warp_active_thread_mask: {
1802 // Build int32_t __kmpc_warp_active_thread_mask(void);
1803 auto *FnTy =
1804 llvm::FunctionType::get(CGM.Int32Ty, llvm::None, /*isVarArg=*/false);
1805 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_warp_active_thread_mask");
1806 break;
1807 }
1808 case OMPRTL_NVPTX__kmpc_syncwarp: {
1809 // Build void __kmpc_syncwarp(kmp_int32 Mask);
1810 auto *FnTy =
1811 llvm::FunctionType::get(CGM.VoidTy, CGM.Int32Ty, /*isVarArg=*/false);
1812 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_syncwarp");
1813 break;
1814 }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001815 }
1816 return RTLFn;
1817}
1818
1819void CGOpenMPRuntimeNVPTX::createOffloadEntry(llvm::Constant *ID,
1820 llvm::Constant *Addr,
Alexey Bataev03f270c2018-03-30 18:31:07 +00001821 uint64_t Size, int32_t,
1822 llvm::GlobalValue::LinkageTypes) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001823 // TODO: Add support for global variables on the device after declare target
1824 // support.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001825 if (!isa<llvm::Function>(Addr))
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001826 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +00001827 llvm::Module &M = CGM.getModule();
1828 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001829
1830 // Get "nvvm.annotations" metadata node
Alexey Bataev9ff80832018-04-16 20:16:21 +00001831 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001832
1833 llvm::Metadata *MDVals[] = {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001834 llvm::ConstantAsMetadata::get(Addr), llvm::MDString::get(Ctx, "kernel"),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001835 llvm::ConstantAsMetadata::get(
1836 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))};
1837 // Append metadata to nvvm.annotations
1838 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
1839}
1840
1841void CGOpenMPRuntimeNVPTX::emitTargetOutlinedFunction(
1842 const OMPExecutableDirective &D, StringRef ParentName,
1843 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001844 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001845 if (!IsOffloadEntry) // Nothing to do.
1846 return;
1847
1848 assert(!ParentName.empty() && "Invalid target region parent name!");
1849
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001850 bool Mode = supportsSPMDExecutionMode(CGM.getContext(), D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001851 if (Mode)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001852 emitSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001853 CodeGen);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001854 else
1855 emitNonSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1856 CodeGen);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001857
1858 setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001859}
1860
Alexey Bataevceeaa482018-11-21 21:04:34 +00001861namespace {
1862LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
1863/// Enum for accesseing the reserved_2 field of the ident_t struct.
1864enum ModeFlagsTy : unsigned {
1865 /// Bit set to 1 when in SPMD mode.
1866 KMP_IDENT_SPMD_MODE = 0x01,
1867 /// Bit set to 1 when a simplified runtime is used.
1868 KMP_IDENT_SIMPLE_RT_MODE = 0x02,
1869 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/KMP_IDENT_SIMPLE_RT_MODE)
1870};
1871
1872/// Special mode Undefined. Is the combination of Non-SPMD mode + SimpleRuntime.
1873static const ModeFlagsTy UndefinedMode =
1874 (~KMP_IDENT_SPMD_MODE) & KMP_IDENT_SIMPLE_RT_MODE;
1875} // anonymous namespace
1876
1877unsigned CGOpenMPRuntimeNVPTX::getDefaultLocationReserved2Flags() const {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001878 switch (getExecutionMode()) {
1879 case EM_SPMD:
1880 if (requiresFullRuntime())
1881 return KMP_IDENT_SPMD_MODE & (~KMP_IDENT_SIMPLE_RT_MODE);
1882 return KMP_IDENT_SPMD_MODE | KMP_IDENT_SIMPLE_RT_MODE;
1883 case EM_NonSPMD:
1884 assert(requiresFullRuntime() && "Expected full runtime.");
1885 return (~KMP_IDENT_SPMD_MODE) & (~KMP_IDENT_SIMPLE_RT_MODE);
1886 case EM_Unknown:
1887 return UndefinedMode;
1888 }
1889 llvm_unreachable("Unknown flags are requested.");
Alexey Bataevceeaa482018-11-21 21:04:34 +00001890}
1891
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001892CGOpenMPRuntimeNVPTX::CGOpenMPRuntimeNVPTX(CodeGenModule &CGM)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001893 : CGOpenMPRuntime(CGM, "_", "$") {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001894 if (!CGM.getLangOpts().OpenMPIsDevice)
1895 llvm_unreachable("OpenMP NVPTX can only handle device code.");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001896}
Carlo Bertollic6872252016-04-04 15:55:02 +00001897
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001898void CGOpenMPRuntimeNVPTX::emitProcBindClause(CodeGenFunction &CGF,
1899 OpenMPProcBindClauseKind ProcBind,
1900 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001901 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001902 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001903 return;
1904
1905 CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc);
1906}
1907
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001908void CGOpenMPRuntimeNVPTX::emitNumThreadsClause(CodeGenFunction &CGF,
1909 llvm::Value *NumThreads,
1910 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001911 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001912 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001913 return;
1914
1915 CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc);
1916}
1917
Carlo Bertollic6872252016-04-04 15:55:02 +00001918void CGOpenMPRuntimeNVPTX::emitNumTeamsClause(CodeGenFunction &CGF,
1919 const Expr *NumTeams,
1920 const Expr *ThreadLimit,
1921 SourceLocation Loc) {}
1922
James Y Knight9871db02019-02-05 16:42:33 +00001923llvm::Function *CGOpenMPRuntimeNVPTX::emitParallelOutlinedFunction(
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001924 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1925 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00001926 // Emit target region as a standalone region.
1927 class NVPTXPrePostActionTy : public PrePostActionTy {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001928 bool &IsInParallelRegion;
1929 bool PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001930
1931 public:
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001932 NVPTXPrePostActionTy(bool &IsInParallelRegion)
1933 : IsInParallelRegion(IsInParallelRegion) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00001934 void Enter(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001935 PrevIsInParallelRegion = IsInParallelRegion;
1936 IsInParallelRegion = true;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001937 }
1938 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001939 IsInParallelRegion = PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001940 }
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001941 } Action(IsInParallelRegion);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001942 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001943 bool PrevIsInTTDRegion = IsInTTDRegion;
1944 IsInTTDRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001945 bool PrevIsInTargetMasterThreadRegion = IsInTargetMasterThreadRegion;
1946 IsInTargetMasterThreadRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001947 auto *OutlinedFun =
1948 cast<llvm::Function>(CGOpenMPRuntime::emitParallelOutlinedFunction(
1949 D, ThreadIDVar, InnermostKind, CodeGen));
Alexey Bataev8c5555c2019-05-21 15:11:58 +00001950 if (CGM.getLangOpts().Optimize) {
1951 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
1952 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
1953 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
1954 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001955 IsInTargetMasterThreadRegion = PrevIsInTargetMasterThreadRegion;
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001956 IsInTTDRegion = PrevIsInTTDRegion;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001957 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD &&
1958 !IsInParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001959 llvm::Function *WrapperFun =
1960 createParallelDataSharingWrapper(OutlinedFun, D);
1961 WrapperFunctionsMap[OutlinedFun] = WrapperFun;
1962 }
1963
1964 return OutlinedFun;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001965}
1966
Alexey Bataev2adecff2018-09-21 14:22:53 +00001967/// Get list of lastprivate variables from the teams distribute ... or
1968/// teams {distribute ...} directives.
1969static void
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001970getDistributeLastprivateVars(ASTContext &Ctx, const OMPExecutableDirective &D,
Alexey Bataev2adecff2018-09-21 14:22:53 +00001971 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
1972 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
1973 "expected teams directive.");
1974 const OMPExecutableDirective *Dir = &D;
1975 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
Alexey Bataev5c427362019-04-10 19:11:33 +00001976 if (const Stmt *S = CGOpenMPRuntime::getSingleCompoundChild(
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001977 Ctx,
Alexey Bataev2adecff2018-09-21 14:22:53 +00001978 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
1979 /*IgnoreCaptured=*/true))) {
Alexey Bataev5c427362019-04-10 19:11:33 +00001980 Dir = dyn_cast_or_null<OMPExecutableDirective>(S);
Alexey Bataev2adecff2018-09-21 14:22:53 +00001981 if (Dir && !isOpenMPDistributeDirective(Dir->getDirectiveKind()))
1982 Dir = nullptr;
1983 }
1984 }
1985 if (!Dir)
1986 return;
Alexey Bataev9ea3c382018-10-09 14:49:00 +00001987 for (const auto *C : Dir->getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00001988 for (const Expr *E : C->getVarRefs())
1989 Vars.push_back(getPrivateItem(E));
1990 }
1991}
1992
1993/// Get list of reduction variables from the teams ... directives.
1994static void
1995getTeamsReductionVars(ASTContext &Ctx, const OMPExecutableDirective &D,
1996 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
1997 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
1998 "expected teams directive.");
1999 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
2000 for (const Expr *E : C->privates())
2001 Vars.push_back(getPrivateItem(E));
Alexey Bataev2adecff2018-09-21 14:22:53 +00002002 }
2003}
2004
James Y Knight9871db02019-02-05 16:42:33 +00002005llvm::Function *CGOpenMPRuntimeNVPTX::emitTeamsOutlinedFunction(
Carlo Bertollic6872252016-04-04 15:55:02 +00002006 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
2007 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002008 SourceLocation Loc = D.getBeginLoc();
Carlo Bertollic6872252016-04-04 15:55:02 +00002009
Alexey Bataev2adecff2018-09-21 14:22:53 +00002010 const RecordDecl *GlobalizedRD = nullptr;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002011 llvm::SmallVector<const ValueDecl *, 4> LastPrivatesReductions;
Alexey Bataev2adecff2018-09-21 14:22:53 +00002012 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002013 // Globalize team reductions variable unconditionally in all modes.
Alexey Bataev8061acd2019-02-20 16:36:22 +00002014 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
2015 getTeamsReductionVars(CGM.getContext(), D, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002016 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002017 getDistributeLastprivateVars(CGM.getContext(), D, LastPrivatesReductions);
2018 if (!LastPrivatesReductions.empty()) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002019 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002020 CGM.getContext(), llvm::None, LastPrivatesReductions,
Alexey Bataev8061acd2019-02-20 16:36:22 +00002021 MappedDeclsFields, WarpSize);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002022 }
2023 } else if (!LastPrivatesReductions.empty()) {
2024 assert(!TeamAndReductions.first &&
2025 "Previous team declaration is not expected.");
2026 TeamAndReductions.first = D.getCapturedStmt(OMPD_teams)->getCapturedDecl();
2027 std::swap(TeamAndReductions.second, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002028 }
2029
Alexey Bataevc99042b2018-03-15 18:10:54 +00002030 // Emit target region as a standalone region.
2031 class NVPTXPrePostActionTy : public PrePostActionTy {
2032 SourceLocation &Loc;
Alexey Bataev2adecff2018-09-21 14:22:53 +00002033 const RecordDecl *GlobalizedRD;
2034 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2035 &MappedDeclsFields;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002036
2037 public:
Alexey Bataev2adecff2018-09-21 14:22:53 +00002038 NVPTXPrePostActionTy(
2039 SourceLocation &Loc, const RecordDecl *GlobalizedRD,
2040 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2041 &MappedDeclsFields)
2042 : Loc(Loc), GlobalizedRD(GlobalizedRD),
2043 MappedDeclsFields(MappedDeclsFields) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00002044 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002045 auto &Rt =
2046 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
2047 if (GlobalizedRD) {
2048 auto I = Rt.FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
2049 I->getSecond().GlobalRecord = GlobalizedRD;
2050 I->getSecond().MappedParams =
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00002051 std::make_unique<CodeGenFunction::OMPMapVars>();
Alexey Bataev2adecff2018-09-21 14:22:53 +00002052 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
2053 for (const auto &Pair : MappedDeclsFields) {
2054 assert(Pair.getFirst()->isCanonicalDecl() &&
2055 "Expected canonical declaration");
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002056 Data.insert(std::make_pair(Pair.getFirst(),
2057 MappedVarData(Pair.getSecond(),
2058 /*IsOnePerTeam=*/true)));
Alexey Bataev2adecff2018-09-21 14:22:53 +00002059 }
2060 }
2061 Rt.emitGenericVarsProlog(CGF, Loc);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002062 }
2063 void Exit(CodeGenFunction &CGF) override {
2064 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
2065 .emitGenericVarsEpilog(CGF);
2066 }
Alexey Bataev2adecff2018-09-21 14:22:53 +00002067 } Action(Loc, GlobalizedRD, MappedDeclsFields);
2068 CodeGen.setAction(Action);
James Y Knight9871db02019-02-05 16:42:33 +00002069 llvm::Function *OutlinedFun = CGOpenMPRuntime::emitTeamsOutlinedFunction(
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002070 D, ThreadIDVar, InnermostKind, CodeGen);
Alexey Bataev8c5555c2019-05-21 15:11:58 +00002071 if (CGM.getLangOpts().Optimize) {
2072 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
2073 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
2074 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
2075 }
Carlo Bertollic6872252016-04-04 15:55:02 +00002076
2077 return OutlinedFun;
2078}
2079
Alexey Bataevc99042b2018-03-15 18:10:54 +00002080void CGOpenMPRuntimeNVPTX::emitGenericVarsProlog(CodeGenFunction &CGF,
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002081 SourceLocation Loc,
2082 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002083 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2084 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002085 return;
2086
Alexey Bataevc99042b2018-03-15 18:10:54 +00002087 CGBuilderTy &Bld = CGF.Builder;
2088
2089 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
2090 if (I == FunctionGlobalizedDecls.end())
2091 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002092 if (const RecordDecl *GlobalizedVarsRecord = I->getSecond().GlobalRecord) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002093 QualType GlobalRecTy = CGM.getContext().getRecordType(GlobalizedVarsRecord);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002094 QualType SecGlobalRecTy;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002095
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002096 // Recover pointer to this function's global record. The runtime will
2097 // handle the specifics of the allocation of the memory.
2098 // Use actual memory size of the record including the padding
2099 // for alignment purposes.
2100 unsigned Alignment =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002101 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002102 unsigned GlobalRecordSize =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002103 CGM.getContext().getTypeSizeInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002104 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002105
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002106 llvm::PointerType *GlobalRecPtrTy =
2107 CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo();
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002108 llvm::Value *GlobalRecCastAddr;
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002109 llvm::Value *IsTTD = nullptr;
Alexey Bataeve4090182018-11-02 14:54:07 +00002110 if (!IsInTTDRegion &&
2111 (WithSPMDCheck ||
2112 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002113 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2114 llvm::BasicBlock *SPMDBB = CGF.createBasicBlock(".spmd");
2115 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002116 if (I->getSecond().SecondaryGlobalRecord.hasValue()) {
2117 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2118 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2119 llvm::Value *PL = CGF.EmitRuntimeCall(
2120 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2121 {RTLoc, ThreadID});
2122 IsTTD = Bld.CreateIsNull(PL);
2123 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002124 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2125 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
2126 Bld.CreateCondBr(IsSPMD, SPMDBB, NonSPMDBB);
2127 // There is no need to emit line number for unconditional branch.
2128 (void)ApplyDebugLocation::CreateEmpty(CGF);
2129 CGF.EmitBlock(SPMDBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002130 Address RecPtr = Address(llvm::ConstantPointerNull::get(GlobalRecPtrTy),
2131 CharUnits::fromQuantity(Alignment));
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002132 CGF.EmitBranch(ExitBB);
2133 // There is no need to emit line number for unconditional branch.
2134 (void)ApplyDebugLocation::CreateEmpty(CGF);
2135 CGF.EmitBlock(NonSPMDBB);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002136 llvm::Value *Size = llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize);
2137 if (const RecordDecl *SecGlobalizedVarsRecord =
2138 I->getSecond().SecondaryGlobalRecord.getValueOr(nullptr)) {
2139 SecGlobalRecTy =
2140 CGM.getContext().getRecordType(SecGlobalizedVarsRecord);
2141
2142 // Recover pointer to this function's global record. The runtime will
2143 // handle the specifics of the allocation of the memory.
2144 // Use actual memory size of the record including the padding
2145 // for alignment purposes.
2146 unsigned Alignment =
2147 CGM.getContext().getTypeAlignInChars(SecGlobalRecTy).getQuantity();
2148 unsigned GlobalRecordSize =
2149 CGM.getContext().getTypeSizeInChars(SecGlobalRecTy).getQuantity();
2150 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
2151 Size = Bld.CreateSelect(
2152 IsTTD, llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize), Size);
2153 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002154 // TODO: allow the usage of shared memory to be controlled by
2155 // the user, for now, default to global.
2156 llvm::Value *GlobalRecordSizeArg[] = {
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002157 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002158 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2159 createNVPTXRuntimeFunction(
2160 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2161 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002162 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002163 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002164 CGF.EmitBlock(ExitBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002165 auto *Phi = Bld.CreatePHI(GlobalRecPtrTy,
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002166 /*NumReservedValues=*/2, "_select_stack");
2167 Phi->addIncoming(RecPtr.getPointer(), SPMDBB);
2168 Phi->addIncoming(GlobalRecCastAddr, NonSPMDBB);
2169 GlobalRecCastAddr = Phi;
2170 I->getSecond().GlobalRecordAddr = Phi;
2171 I->getSecond().IsInSPMDModeFlag = IsSPMD;
Alexey Bataeve4090182018-11-02 14:54:07 +00002172 } else if (IsInTTDRegion) {
2173 assert(GlobalizedRecords.back().Records.size() < 2 &&
2174 "Expected less than 2 globalized records: one for target and one "
2175 "for teams.");
2176 unsigned Offset = 0;
2177 for (const RecordDecl *RD : GlobalizedRecords.back().Records) {
2178 QualType RDTy = CGM.getContext().getRecordType(RD);
2179 unsigned Alignment =
2180 CGM.getContext().getTypeAlignInChars(RDTy).getQuantity();
2181 unsigned Size = CGM.getContext().getTypeSizeInChars(RDTy).getQuantity();
2182 Offset =
2183 llvm::alignTo(llvm::alignTo(Offset, Alignment) + Size, Alignment);
2184 }
2185 unsigned Alignment =
2186 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
2187 Offset = llvm::alignTo(Offset, Alignment);
2188 GlobalizedRecords.back().Records.push_back(GlobalizedVarsRecord);
2189 ++GlobalizedRecords.back().RegionCounter;
2190 if (GlobalizedRecords.back().Records.size() == 1) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002191 assert(KernelStaticGlobalized &&
2192 "Kernel static pointer must be initialized already.");
2193 auto *UseSharedMemory = new llvm::GlobalVariable(
2194 CGM.getModule(), CGM.Int16Ty, /*isConstant=*/true,
2195 llvm::GlobalValue::InternalLinkage, nullptr,
2196 "_openmp_static_kernel$is_shared");
2197 UseSharedMemory->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2198 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2199 /*DestWidth=*/16, /*Signed=*/0);
2200 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2201 Address(UseSharedMemory,
2202 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2203 /*Volatile=*/false, Int16Ty, Loc);
2204 auto *StaticGlobalized = new llvm::GlobalVariable(
2205 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002206 llvm::GlobalValue::CommonLinkage, nullptr);
Alexey Bataeve4090182018-11-02 14:54:07 +00002207 auto *RecSize = new llvm::GlobalVariable(
2208 CGM.getModule(), CGM.SizeTy, /*isConstant=*/true,
2209 llvm::GlobalValue::InternalLinkage, nullptr,
2210 "_openmp_static_kernel$size");
2211 RecSize->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2212 llvm::Value *Ld = CGF.EmitLoadOfScalar(
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002213 Address(RecSize, CGM.getSizeAlign()), /*Volatile=*/false,
Alexey Bataeve4090182018-11-02 14:54:07 +00002214 CGM.getContext().getSizeType(), Loc);
2215 llvm::Value *ResAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2216 KernelStaticGlobalized, CGM.VoidPtrPtrTy);
Alexey Bataev8e009032019-01-04 17:25:09 +00002217 llvm::Value *GlobalRecordSizeArg[] = {
2218 llvm::ConstantInt::get(
2219 CGM.Int16Ty,
2220 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD ? 1 : 0),
2221 StaticGlobalized, Ld, IsInSharedMemory, ResAddr};
Alexey Bataeve4090182018-11-02 14:54:07 +00002222 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2223 OMPRTL_NVPTX__kmpc_get_team_static_memory),
2224 GlobalRecordSizeArg);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002225 GlobalizedRecords.back().Buffer = StaticGlobalized;
Alexey Bataeve4090182018-11-02 14:54:07 +00002226 GlobalizedRecords.back().RecSize = RecSize;
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002227 GlobalizedRecords.back().UseSharedMemory = UseSharedMemory;
2228 GlobalizedRecords.back().Loc = Loc;
Alexey Bataeve4090182018-11-02 14:54:07 +00002229 }
2230 assert(KernelStaticGlobalized && "Global address must be set already.");
2231 Address FrameAddr = CGF.EmitLoadOfPointer(
2232 Address(KernelStaticGlobalized, CGM.getPointerAlign()),
2233 CGM.getContext()
2234 .getPointerType(CGM.getContext().VoidPtrTy)
2235 .castAs<PointerType>());
2236 llvm::Value *GlobalRecValue =
James Y Knight751fe282019-02-09 22:22:28 +00002237 Bld.CreateConstInBoundsGEP(FrameAddr, Offset).getPointer();
Alexey Bataeve4090182018-11-02 14:54:07 +00002238 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2239 I->getSecond().IsInSPMDModeFlag = nullptr;
2240 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2241 GlobalRecValue, CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo());
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002242 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002243 // TODO: allow the usage of shared memory to be controlled by
2244 // the user, for now, default to global.
2245 llvm::Value *GlobalRecordSizeArg[] = {
2246 llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize),
2247 CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002248 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2249 createNVPTXRuntimeFunction(
2250 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2251 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002252 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002253 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002254 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2255 I->getSecond().IsInSPMDModeFlag = nullptr;
2256 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002257 LValue Base =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002258 CGF.MakeNaturalAlignPointeeAddrLValue(GlobalRecCastAddr, GlobalRecTy);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002259
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002260 // Emit the "global alloca" which is a GEP from the global declaration
2261 // record using the pointer returned by the runtime.
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002262 LValue SecBase;
2263 decltype(I->getSecond().LocalVarData)::const_iterator SecIt;
2264 if (IsTTD) {
2265 SecIt = I->getSecond().SecondaryLocalVarData->begin();
2266 llvm::PointerType *SecGlobalRecPtrTy =
2267 CGF.ConvertTypeForMem(SecGlobalRecTy)->getPointerTo();
2268 SecBase = CGF.MakeNaturalAlignPointeeAddrLValue(
2269 Bld.CreatePointerBitCastOrAddrSpaceCast(
2270 I->getSecond().GlobalRecordAddr, SecGlobalRecPtrTy),
2271 SecGlobalRecTy);
2272 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002273 for (auto &Rec : I->getSecond().LocalVarData) {
2274 bool EscapedParam = I->getSecond().EscapedParameters.count(Rec.first);
2275 llvm::Value *ParValue;
2276 if (EscapedParam) {
2277 const auto *VD = cast<VarDecl>(Rec.first);
2278 LValue ParLVal =
2279 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
2280 ParValue = CGF.EmitLoadOfScalar(ParLVal, Loc);
2281 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002282 LValue VarAddr = CGF.EmitLValueForField(Base, Rec.second.FD);
2283 // Emit VarAddr basing on lane-id if required.
2284 QualType VarTy;
2285 if (Rec.second.IsOnePerTeam) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002286 VarTy = Rec.second.FD->getType();
2287 } else {
2288 llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(
2289 VarAddr.getAddress().getPointer(),
2290 {Bld.getInt32(0), getNVPTXLaneID(CGF)});
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002291 VarTy =
2292 Rec.second.FD->getType()->castAsArrayTypeUnsafe()->getElementType();
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002293 VarAddr = CGF.MakeAddrLValue(
2294 Address(Ptr, CGM.getContext().getDeclAlign(Rec.first)), VarTy,
2295 AlignmentSource::Decl);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002296 }
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002297 Rec.second.PrivateAddr = VarAddr.getAddress();
Alexey Bataeve4090182018-11-02 14:54:07 +00002298 if (!IsInTTDRegion &&
2299 (WithSPMDCheck ||
2300 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002301 assert(I->getSecond().IsInSPMDModeFlag &&
2302 "Expected unknown execution mode or required SPMD check.");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002303 if (IsTTD) {
2304 assert(SecIt->second.IsOnePerTeam &&
2305 "Secondary glob data must be one per team.");
2306 LValue SecVarAddr = CGF.EmitLValueForField(SecBase, SecIt->second.FD);
2307 VarAddr.setAddress(
2308 Address(Bld.CreateSelect(IsTTD, SecVarAddr.getPointer(),
2309 VarAddr.getPointer()),
2310 VarAddr.getAlignment()));
2311 Rec.second.PrivateAddr = VarAddr.getAddress();
2312 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002313 Address GlobalPtr = Rec.second.PrivateAddr;
2314 Address LocalAddr = CGF.CreateMemTemp(VarTy, Rec.second.FD->getName());
2315 Rec.second.PrivateAddr = Address(
2316 Bld.CreateSelect(I->getSecond().IsInSPMDModeFlag,
2317 LocalAddr.getPointer(), GlobalPtr.getPointer()),
2318 LocalAddr.getAlignment());
2319 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002320 if (EscapedParam) {
2321 const auto *VD = cast<VarDecl>(Rec.first);
2322 CGF.EmitStoreOfScalar(ParValue, VarAddr);
2323 I->getSecond().MappedParams->setVarAddr(CGF, VD, VarAddr.getAddress());
2324 }
Alexey Bataev93a38d62018-10-16 00:09:06 +00002325 if (IsTTD)
2326 ++SecIt;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002327 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002328 }
2329 for (const ValueDecl *VD : I->getSecond().EscapedVariableLengthDecls) {
2330 // Recover pointer to this function's global record. The runtime will
2331 // handle the specifics of the allocation of the memory.
2332 // Use actual memory size of the record including the padding
2333 // for alignment purposes.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002334 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002335 llvm::Value *Size = CGF.getTypeSize(VD->getType());
2336 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2337 Size = Bld.CreateNUWAdd(
2338 Size, llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity() - 1));
2339 llvm::Value *AlignVal =
2340 llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity());
2341 Size = Bld.CreateUDiv(Size, AlignVal);
2342 Size = Bld.CreateNUWMul(Size, AlignVal);
2343 // TODO: allow the usage of shared memory to be controlled by
2344 // the user, for now, default to global.
2345 llvm::Value *GlobalRecordSizeArg[] = {
2346 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
2347 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002348 createNVPTXRuntimeFunction(
2349 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002350 GlobalRecordSizeArg);
2351 llvm::Value *GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2352 GlobalRecValue, CGF.ConvertTypeForMem(VD->getType())->getPointerTo());
2353 LValue Base = CGF.MakeAddrLValue(GlobalRecCastAddr, VD->getType(),
2354 CGM.getContext().getDeclAlign(VD),
2355 AlignmentSource::Decl);
2356 I->getSecond().MappedParams->setVarAddr(CGF, cast<VarDecl>(VD),
2357 Base.getAddress());
2358 I->getSecond().EscapedVariableLengthDeclsAddrs.emplace_back(GlobalRecValue);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002359 }
2360 I->getSecond().MappedParams->apply(CGF);
2361}
2362
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002363void CGOpenMPRuntimeNVPTX::emitGenericVarsEpilog(CodeGenFunction &CGF,
2364 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002365 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2366 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002367 return;
2368
Alexey Bataevc99042b2018-03-15 18:10:54 +00002369 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002370 if (I != FunctionGlobalizedDecls.end()) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00002371 I->getSecond().MappedParams->restore(CGF);
2372 if (!CGF.HaveInsertPoint())
2373 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002374 for (llvm::Value *Addr :
2375 llvm::reverse(I->getSecond().EscapedVariableLengthDeclsAddrs)) {
2376 CGF.EmitRuntimeCall(
2377 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2378 Addr);
2379 }
2380 if (I->getSecond().GlobalRecordAddr) {
Alexey Bataeve4090182018-11-02 14:54:07 +00002381 if (!IsInTTDRegion &&
2382 (WithSPMDCheck ||
2383 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002384 CGBuilderTy &Bld = CGF.Builder;
2385 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2386 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
2387 Bld.CreateCondBr(I->getSecond().IsInSPMDModeFlag, ExitBB, NonSPMDBB);
2388 // There is no need to emit line number for unconditional branch.
2389 (void)ApplyDebugLocation::CreateEmpty(CGF);
2390 CGF.EmitBlock(NonSPMDBB);
2391 CGF.EmitRuntimeCall(
2392 createNVPTXRuntimeFunction(
2393 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2394 CGF.EmitCastToVoidPtr(I->getSecond().GlobalRecordAddr));
2395 CGF.EmitBlock(ExitBB);
Alexey Bataeve4090182018-11-02 14:54:07 +00002396 } else if (IsInTTDRegion) {
2397 assert(GlobalizedRecords.back().RegionCounter > 0 &&
2398 "region counter must be > 0.");
2399 --GlobalizedRecords.back().RegionCounter;
2400 // Emit the restore function only in the target region.
2401 if (GlobalizedRecords.back().RegionCounter == 0) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002402 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2403 /*DestWidth=*/16, /*Signed=*/0);
2404 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2405 Address(GlobalizedRecords.back().UseSharedMemory,
2406 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2407 /*Volatile=*/false, Int16Ty, GlobalizedRecords.back().Loc);
Alexey Bataev8e009032019-01-04 17:25:09 +00002408 llvm::Value *Args[] = {
2409 llvm::ConstantInt::get(
2410 CGM.Int16Ty,
2411 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD ? 1 : 0),
2412 IsInSharedMemory};
Alexey Bataeve4090182018-11-02 14:54:07 +00002413 CGF.EmitRuntimeCall(
2414 createNVPTXRuntimeFunction(
2415 OMPRTL_NVPTX__kmpc_restore_team_static_memory),
Alexey Bataev8e009032019-01-04 17:25:09 +00002416 Args);
Alexey Bataeve4090182018-11-02 14:54:07 +00002417 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002418 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002419 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2420 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2421 I->getSecond().GlobalRecordAddr);
2422 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002423 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00002424 }
2425}
2426
Carlo Bertollic6872252016-04-04 15:55:02 +00002427void CGOpenMPRuntimeNVPTX::emitTeamsCall(CodeGenFunction &CGF,
2428 const OMPExecutableDirective &D,
2429 SourceLocation Loc,
James Y Knight9871db02019-02-05 16:42:33 +00002430 llvm::Function *OutlinedFn,
Carlo Bertollic6872252016-04-04 15:55:02 +00002431 ArrayRef<llvm::Value *> CapturedVars) {
2432 if (!CGF.HaveInsertPoint())
2433 return;
2434
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002435 Address ZeroAddr = CGF.CreateMemTemp(
2436 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2437 /*Name*/ ".zero.addr");
Carlo Bertollic6872252016-04-04 15:55:02 +00002438 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2439 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002440 OutlinedFnArgs.push_back(emitThreadIDAddress(CGF, Loc).getPointer());
Carlo Bertollic6872252016-04-04 15:55:02 +00002441 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2442 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002443 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Carlo Bertollic6872252016-04-04 15:55:02 +00002444}
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002445
2446void CGOpenMPRuntimeNVPTX::emitParallelCall(
James Y Knight9871db02019-02-05 16:42:33 +00002447 CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002448 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2449 if (!CGF.HaveInsertPoint())
2450 return;
2451
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002452 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002453 emitSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002454 else
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002455 emitNonSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002456}
2457
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002458void CGOpenMPRuntimeNVPTX::emitNonSPMDParallelCall(
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002459 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2460 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2461 llvm::Function *Fn = cast<llvm::Function>(OutlinedFn);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002462
2463 // Force inline this outlined function at its call site.
2464 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
2465
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002466 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2467 /*DestWidth=*/32, /*Signed=*/1),
2468 ".zero.addr");
2469 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002470 // ThreadId for serialized parallels is 0.
2471 Address ThreadIDAddr = ZeroAddr;
2472 auto &&CodeGen = [this, Fn, CapturedVars, Loc, ZeroAddr, &ThreadIDAddr](
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002473 CodeGenFunction &CGF, PrePostActionTy &Action) {
2474 Action.Enter(CGF);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002475
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002476 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2477 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2478 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2479 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2480 emitOutlinedFunctionCall(CGF, Loc, Fn, OutlinedFnArgs);
2481 };
2482 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2483 PrePostActionTy &) {
2484
2485 RegionCodeGenTy RCG(CodeGen);
2486 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2487 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2488 llvm::Value *Args[] = {RTLoc, ThreadID};
2489
2490 NVPTXActionTy Action(
2491 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2492 Args,
2493 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2494 Args);
2495 RCG.setAction(Action);
2496 RCG(CGF);
2497 };
2498
2499 auto &&L0ParallelGen = [this, CapturedVars, Fn](CodeGenFunction &CGF,
2500 PrePostActionTy &Action) {
2501 CGBuilderTy &Bld = CGF.Builder;
2502 llvm::Function *WFn = WrapperFunctionsMap[Fn];
2503 assert(WFn && "Wrapper function does not exist!");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002504 llvm::Value *ID = Bld.CreateBitOrPointerCast(WFn, CGM.Int8PtrTy);
2505
2506 // Prepare for parallel region. Indicate the outlined function.
2507 llvm::Value *Args[] = {ID, /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002508 CGF.EmitRuntimeCall(
2509 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_prepare_parallel),
2510 Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002511
2512 // Create a private scope that will globalize the arguments
2513 // passed from the outside of the target region.
2514 CodeGenFunction::OMPPrivateScope PrivateArgScope(CGF);
2515
Raphael Isemannb23ccec2018-12-10 12:37:46 +00002516 // There's something to share.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002517 if (!CapturedVars.empty()) {
2518 // Prepare for parallel region. Indicate the outlined function.
2519 Address SharedArgs =
2520 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "shared_arg_refs");
2521 llvm::Value *SharedArgsPtr = SharedArgs.getPointer();
2522
2523 llvm::Value *DataSharingArgs[] = {
2524 SharedArgsPtr,
2525 llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size())};
2526 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2527 OMPRTL_NVPTX__kmpc_begin_sharing_variables),
2528 DataSharingArgs);
2529
2530 // Store variable address in a list of references to pass to workers.
2531 unsigned Idx = 0;
2532 ASTContext &Ctx = CGF.getContext();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002533 Address SharedArgListAddress = CGF.EmitLoadOfPointer(
2534 SharedArgs, Ctx.getPointerType(Ctx.getPointerType(Ctx.VoidPtrTy))
2535 .castAs<PointerType>());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002536 for (llvm::Value *V : CapturedVars) {
James Y Knight751fe282019-02-09 22:22:28 +00002537 Address Dst = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002538 llvm::Value *PtrV;
Alexey Bataev17314212018-03-20 15:41:05 +00002539 if (V->getType()->isIntegerTy())
2540 PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
2541 else
2542 PtrV = Bld.CreatePointerBitCastOrAddrSpaceCast(V, CGF.VoidPtrTy);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002543 CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
2544 Ctx.getPointerType(Ctx.VoidPtrTy));
Alexey Bataevc99042b2018-03-15 18:10:54 +00002545 ++Idx;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002546 }
2547 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002548
2549 // Activate workers. This barrier is used by the master to signal
2550 // work for the workers.
2551 syncCTAThreads(CGF);
2552
2553 // OpenMP [2.5, Parallel Construct, p.49]
2554 // There is an implied barrier at the end of a parallel region. After the
2555 // end of a parallel region, only the master thread of the team resumes
2556 // execution of the enclosing task region.
2557 //
2558 // The master waits at this barrier until all workers are done.
2559 syncCTAThreads(CGF);
2560
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002561 if (!CapturedVars.empty())
2562 CGF.EmitRuntimeCall(
2563 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_sharing_variables));
2564
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002565 // Remember for post-processing in worker loop.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002566 Work.emplace_back(WFn);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002567 };
2568
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002569 auto &&LNParallelGen = [this, Loc, &SeqGen, &L0ParallelGen](
2570 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002571 if (IsInParallelRegion) {
2572 SeqGen(CGF, Action);
2573 } else if (IsInTargetMasterThreadRegion) {
2574 L0ParallelGen(CGF, Action);
2575 } else {
2576 // Check for master and then parallelism:
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002577 // if (__kmpc_is_spmd_exec_mode() || __kmpc_parallel_level(loc, gtid)) {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002578 // Serialized execution.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002579 // } else {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002580 // Worker call.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002581 // }
2582 CGBuilderTy &Bld = CGF.Builder;
2583 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002584 llvm::BasicBlock *SeqBB = CGF.createBasicBlock(".sequential");
2585 llvm::BasicBlock *ParallelCheckBB = CGF.createBasicBlock(".parcheck");
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002586 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
Alexey Bataev673110d2018-05-16 13:36:30 +00002587 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2588 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002589 Bld.CreateCondBr(IsSPMD, SeqBB, ParallelCheckBB);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002590 // There is no need to emit line number for unconditional branch.
2591 (void)ApplyDebugLocation::CreateEmpty(CGF);
2592 CGF.EmitBlock(ParallelCheckBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002593 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2594 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2595 llvm::Value *PL = CGF.EmitRuntimeCall(
2596 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2597 {RTLoc, ThreadID});
2598 llvm::Value *Res = Bld.CreateIsNotNull(PL);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002599 Bld.CreateCondBr(Res, SeqBB, MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002600 CGF.EmitBlock(SeqBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002601 SeqGen(CGF, Action);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002602 CGF.EmitBranch(ExitBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002603 // There is no need to emit line number for unconditional branch.
2604 (void)ApplyDebugLocation::CreateEmpty(CGF);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002605 CGF.EmitBlock(MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002606 L0ParallelGen(CGF, Action);
2607 CGF.EmitBranch(ExitBB);
2608 // There is no need to emit line number for unconditional branch.
2609 (void)ApplyDebugLocation::CreateEmpty(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002610 // Emit the continuation block for code after the if.
2611 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2612 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002613 };
2614
Alexey Bataev9ff80832018-04-16 20:16:21 +00002615 if (IfCond) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002616 emitOMPIfClause(CGF, IfCond, LNParallelGen, SeqGen);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002617 } else {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002618 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002619 RegionCodeGenTy ThenRCG(LNParallelGen);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002620 ThenRCG(CGF);
2621 }
2622}
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002623
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002624void CGOpenMPRuntimeNVPTX::emitSPMDParallelCall(
James Y Knight9871db02019-02-05 16:42:33 +00002625 CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002626 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2627 // Just call the outlined function to execute the parallel region.
2628 // OutlinedFn(&GTid, &zero, CapturedStruct);
2629 //
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002630 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Carlo Bertolli79712092018-02-28 20:48:35 +00002631
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002632 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2633 /*DestWidth=*/32, /*Signed=*/1),
2634 ".zero.addr");
Carlo Bertolli79712092018-02-28 20:48:35 +00002635 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002636 // ThreadId for serialized parallels is 0.
2637 Address ThreadIDAddr = ZeroAddr;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002638 auto &&CodeGen = [this, OutlinedFn, CapturedVars, Loc, ZeroAddr,
Alexey Bataev8521ff62018-07-25 20:03:01 +00002639 &ThreadIDAddr](CodeGenFunction &CGF,
2640 PrePostActionTy &Action) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002641 Action.Enter(CGF);
2642
2643 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2644 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2645 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2646 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2647 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2648 };
2649 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2650 PrePostActionTy &) {
2651
2652 RegionCodeGenTy RCG(CodeGen);
2653 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2654 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2655 llvm::Value *Args[] = {RTLoc, ThreadID};
2656
2657 NVPTXActionTy Action(
2658 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2659 Args,
2660 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2661 Args);
2662 RCG.setAction(Action);
2663 RCG(CGF);
2664 };
2665
2666 if (IsInTargetMasterThreadRegion) {
Alexey Bataev8521ff62018-07-25 20:03:01 +00002667 // In the worker need to use the real thread id.
2668 ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002669 RegionCodeGenTy RCG(CodeGen);
2670 RCG(CGF);
2671 } else {
2672 // If we are not in the target region, it is definitely L2 parallelism or
2673 // more, because for SPMD mode we always has L1 parallel level, sowe don't
2674 // need to check for orphaned directives.
2675 RegionCodeGenTy RCG(SeqGen);
2676 RCG(CGF);
2677 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002678}
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002679
Alexey Bataeva3924b52019-01-03 16:25:35 +00002680void CGOpenMPRuntimeNVPTX::syncCTAThreads(CodeGenFunction &CGF) {
2681 // Always emit simple barriers!
2682 if (!CGF.HaveInsertPoint())
2683 return;
2684 // Build call __kmpc_barrier_simple_spmd(nullptr, 0);
2685 // This function does not use parameters, so we can emit just default values.
2686 llvm::Value *Args[] = {
2687 llvm::ConstantPointerNull::get(
2688 cast<llvm::PointerType>(getIdentTyPointerTy())),
2689 llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/0, /*isSigned=*/true)};
Alexey Bataeva44b2162019-07-18 13:49:24 +00002690 llvm::CallInst *Call = CGF.EmitRuntimeCall(
Alexey Bataeva3924b52019-01-03 16:25:35 +00002691 createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier_simple_spmd), Args);
Alexey Bataeva44b2162019-07-18 13:49:24 +00002692 Call->setConvergent();
Alexey Bataeva3924b52019-01-03 16:25:35 +00002693}
2694
Alexey Bataevc3028ca2018-12-04 15:03:25 +00002695void CGOpenMPRuntimeNVPTX::emitBarrierCall(CodeGenFunction &CGF,
2696 SourceLocation Loc,
2697 OpenMPDirectiveKind Kind, bool,
2698 bool) {
2699 // Always emit simple barriers!
2700 if (!CGF.HaveInsertPoint())
2701 return;
2702 // Build call __kmpc_cancel_barrier(loc, thread_id);
2703 unsigned Flags = getDefaultFlagsForBarriers(Kind);
2704 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2705 getThreadID(CGF, Loc)};
Alexey Bataeva44b2162019-07-18 13:49:24 +00002706 llvm::CallInst *Call = CGF.EmitRuntimeCall(
2707 createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier), Args);
2708 Call->setConvergent();
Alexey Bataevc3028ca2018-12-04 15:03:25 +00002709}
2710
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002711void CGOpenMPRuntimeNVPTX::emitCriticalRegion(
2712 CodeGenFunction &CGF, StringRef CriticalName,
2713 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
2714 const Expr *Hint) {
2715 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
2716 llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
2717 llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
2718 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
2719 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
2720
Alexey Bataev2cd7faf2019-08-26 19:07:48 +00002721 // Get the mask of active threads in the warp.
2722 llvm::Value *Mask = CGF.EmitRuntimeCall(
2723 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_warp_active_thread_mask));
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002724 // Fetch team-local id of the thread.
2725 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
2726
2727 // Get the width of the team.
2728 llvm::Value *TeamWidth = getNVPTXNumThreads(CGF);
2729
2730 // Initialize the counter variable for the loop.
2731 QualType Int32Ty =
2732 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
2733 Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
2734 LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
2735 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
2736 /*isInit=*/true);
2737
2738 // Block checks if loop counter exceeds upper bound.
2739 CGF.EmitBlock(LoopBB);
2740 llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2741 llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
2742 CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
2743
2744 // Block tests which single thread should execute region, and which threads
2745 // should go straight to synchronisation point.
2746 CGF.EmitBlock(TestBB);
2747 CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2748 llvm::Value *CmpThreadToCounter =
2749 CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
2750 CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
2751
2752 // Block emits the body of the critical region.
2753 CGF.EmitBlock(BodyBB);
2754
2755 // Output the critical statement.
Alexey Bataev2c1ff9d2018-12-04 15:25:01 +00002756 CGOpenMPRuntime::emitCriticalRegion(CGF, CriticalName, CriticalOpGen, Loc,
2757 Hint);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002758
2759 // After the body surrounded by the critical region, the single executing
2760 // thread will jump to the synchronisation point.
2761 // Block waits for all threads in current team to finish then increments the
2762 // counter variable and returns to the loop.
2763 CGF.EmitBlock(SyncBB);
Alexey Bataev2cd7faf2019-08-26 19:07:48 +00002764 // Reconverge active threads in the warp.
2765 (void)CGF.EmitRuntimeCall(
2766 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_syncwarp), Mask);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002767
2768 llvm::Value *IncCounterVal =
2769 CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
2770 CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
2771 CGF.EmitBranch(LoopBB);
2772
2773 // Block that is reached when all threads in the team complete the region.
2774 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2775}
2776
Alexey Bataevb2575932018-01-04 20:18:55 +00002777/// Cast value to the specified type.
Alexey Bataeva453f362018-03-19 17:53:56 +00002778static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
2779 QualType ValTy, QualType CastTy,
2780 SourceLocation Loc) {
2781 assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
2782 "Cast type must sized.");
2783 assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
2784 "Val type must sized.");
2785 llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
2786 if (ValTy == CastTy)
Alexey Bataevb2575932018-01-04 20:18:55 +00002787 return Val;
Alexey Bataeva453f362018-03-19 17:53:56 +00002788 if (CGF.getContext().getTypeSizeInChars(ValTy) ==
2789 CGF.getContext().getTypeSizeInChars(CastTy))
2790 return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
2791 if (CastTy->isIntegerType() && ValTy->isIntegerType())
2792 return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
2793 CastTy->hasSignedIntegerRepresentation());
2794 Address CastItem = CGF.CreateMemTemp(CastTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002795 Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2796 CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
Alexey Bataeva453f362018-03-19 17:53:56 +00002797 CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy);
2798 return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc);
Alexey Bataevb2575932018-01-04 20:18:55 +00002799}
2800
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002801/// This function creates calls to one of two shuffle functions to copy
2802/// variables between lanes in a warp.
2803static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002804 llvm::Value *Elem,
Alexey Bataeva453f362018-03-19 17:53:56 +00002805 QualType ElemType,
2806 llvm::Value *Offset,
2807 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002808 CodeGenModule &CGM = CGF.CGM;
2809 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002810 CGOpenMPRuntimeNVPTX &RT =
2811 *(static_cast<CGOpenMPRuntimeNVPTX *>(&CGM.getOpenMPRuntime()));
2812
Alexey Bataeva453f362018-03-19 17:53:56 +00002813 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2814 assert(Size.getQuantity() <= 8 &&
2815 "Unsupported bitwidth in shuffle instruction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002816
Alexey Bataeva453f362018-03-19 17:53:56 +00002817 OpenMPRTLFunctionNVPTX ShuffleFn = Size.getQuantity() <= 4
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002818 ? OMPRTL_NVPTX__kmpc_shuffle_int32
2819 : OMPRTL_NVPTX__kmpc_shuffle_int64;
2820
2821 // Cast all types to 32- or 64-bit values before calling shuffle routines.
Alexey Bataeva453f362018-03-19 17:53:56 +00002822 QualType CastTy = CGF.getContext().getIntTypeForBitwidth(
2823 Size.getQuantity() <= 4 ? 32 : 64, /*Signed=*/1);
2824 llvm::Value *ElemCast = castValueToType(CGF, Elem, ElemType, CastTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002825 llvm::Value *WarpSize =
Alexey Bataevb2575932018-01-04 20:18:55 +00002826 Bld.CreateIntCast(getNVPTXWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002827
Alexey Bataev9ff80832018-04-16 20:16:21 +00002828 llvm::Value *ShuffledVal = CGF.EmitRuntimeCall(
2829 RT.createNVPTXRuntimeFunction(ShuffleFn), {ElemCast, Offset, WarpSize});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002830
Alexey Bataeva453f362018-03-19 17:53:56 +00002831 return castValueToType(CGF, ShuffledVal, CastTy, ElemType, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002832}
2833
Alexey Bataev12c62902018-06-22 19:10:38 +00002834static void shuffleAndStore(CodeGenFunction &CGF, Address SrcAddr,
2835 Address DestAddr, QualType ElemType,
2836 llvm::Value *Offset, SourceLocation Loc) {
2837 CGBuilderTy &Bld = CGF.Builder;
2838
2839 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2840 // Create the loop over the big sized data.
2841 // ptr = (void*)Elem;
2842 // ptrEnd = (void*) Elem + 1;
2843 // Step = 8;
2844 // while (ptr + Step < ptrEnd)
2845 // shuffle((int64_t)*ptr);
2846 // Step = 4;
2847 // while (ptr + Step < ptrEnd)
2848 // shuffle((int32_t)*ptr);
2849 // ...
2850 Address ElemPtr = DestAddr;
2851 Address Ptr = SrcAddr;
2852 Address PtrEnd = Bld.CreatePointerBitCastOrAddrSpaceCast(
James Y Knight751fe282019-02-09 22:22:28 +00002853 Bld.CreateConstGEP(SrcAddr, 1), CGF.VoidPtrTy);
Alexey Bataev12c62902018-06-22 19:10:38 +00002854 for (int IntSize = 8; IntSize >= 1; IntSize /= 2) {
2855 if (Size < CharUnits::fromQuantity(IntSize))
2856 continue;
2857 QualType IntType = CGF.getContext().getIntTypeForBitwidth(
2858 CGF.getContext().toBits(CharUnits::fromQuantity(IntSize)),
2859 /*Signed=*/1);
2860 llvm::Type *IntTy = CGF.ConvertTypeForMem(IntType);
2861 Ptr = Bld.CreatePointerBitCastOrAddrSpaceCast(Ptr, IntTy->getPointerTo());
2862 ElemPtr =
2863 Bld.CreatePointerBitCastOrAddrSpaceCast(ElemPtr, IntTy->getPointerTo());
2864 if (Size.getQuantity() / IntSize > 1) {
2865 llvm::BasicBlock *PreCondBB = CGF.createBasicBlock(".shuffle.pre_cond");
2866 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".shuffle.then");
2867 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".shuffle.exit");
2868 llvm::BasicBlock *CurrentBB = Bld.GetInsertBlock();
2869 CGF.EmitBlock(PreCondBB);
2870 llvm::PHINode *PhiSrc =
2871 Bld.CreatePHI(Ptr.getType(), /*NumReservedValues=*/2);
2872 PhiSrc->addIncoming(Ptr.getPointer(), CurrentBB);
2873 llvm::PHINode *PhiDest =
2874 Bld.CreatePHI(ElemPtr.getType(), /*NumReservedValues=*/2);
2875 PhiDest->addIncoming(ElemPtr.getPointer(), CurrentBB);
2876 Ptr = Address(PhiSrc, Ptr.getAlignment());
2877 ElemPtr = Address(PhiDest, ElemPtr.getAlignment());
2878 llvm::Value *PtrDiff = Bld.CreatePtrDiff(
2879 PtrEnd.getPointer(), Bld.CreatePointerBitCastOrAddrSpaceCast(
2880 Ptr.getPointer(), CGF.VoidPtrTy));
2881 Bld.CreateCondBr(Bld.CreateICmpSGT(PtrDiff, Bld.getInt64(IntSize - 1)),
2882 ThenBB, ExitBB);
2883 CGF.EmitBlock(ThenBB);
2884 llvm::Value *Res = createRuntimeShuffleFunction(
2885 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2886 IntType, Offset, Loc);
2887 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
James Y Knight751fe282019-02-09 22:22:28 +00002888 Address LocalPtr = Bld.CreateConstGEP(Ptr, 1);
2889 Address LocalElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002890 PhiSrc->addIncoming(LocalPtr.getPointer(), ThenBB);
2891 PhiDest->addIncoming(LocalElemPtr.getPointer(), ThenBB);
Alexey Bataev12c62902018-06-22 19:10:38 +00002892 CGF.EmitBranch(PreCondBB);
2893 CGF.EmitBlock(ExitBB);
2894 } else {
2895 llvm::Value *Res = createRuntimeShuffleFunction(
2896 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2897 IntType, Offset, Loc);
2898 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
James Y Knight751fe282019-02-09 22:22:28 +00002899 Ptr = Bld.CreateConstGEP(Ptr, 1);
2900 ElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
Alexey Bataev12c62902018-06-22 19:10:38 +00002901 }
2902 Size = Size % IntSize;
2903 }
2904}
2905
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002906namespace {
2907enum CopyAction : unsigned {
2908 // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
2909 // the warp using shuffle instructions.
2910 RemoteLaneToThread,
2911 // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
2912 ThreadCopy,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002913 // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
2914 ThreadToScratchpad,
2915 // ScratchpadToThread: Copy from a scratchpad array in global memory
2916 // containing team-reduced data to a thread's stack.
2917 ScratchpadToThread,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002918};
2919} // namespace
2920
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002921struct CopyOptionsTy {
2922 llvm::Value *RemoteLaneOffset;
2923 llvm::Value *ScratchpadIndex;
2924 llvm::Value *ScratchpadWidth;
2925};
2926
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002927/// Emit instructions to copy a Reduce list, which contains partially
2928/// aggregated values, in the specified direction.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002929static void emitReductionListCopy(
2930 CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
2931 ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
2932 CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002933
Alexey Bataev9ff80832018-04-16 20:16:21 +00002934 CodeGenModule &CGM = CGF.CGM;
2935 ASTContext &C = CGM.getContext();
2936 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002937
Alexey Bataev9ff80832018-04-16 20:16:21 +00002938 llvm::Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
2939 llvm::Value *ScratchpadIndex = CopyOptions.ScratchpadIndex;
2940 llvm::Value *ScratchpadWidth = CopyOptions.ScratchpadWidth;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002941
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002942 // Iterates, element-by-element, through the source Reduce list and
2943 // make a copy.
2944 unsigned Idx = 0;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002945 unsigned Size = Privates.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00002946 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002947 Address SrcElementAddr = Address::invalid();
2948 Address DestElementAddr = Address::invalid();
2949 Address DestElementPtrAddr = Address::invalid();
2950 // Should we shuffle in an element from a remote lane?
2951 bool ShuffleInElement = false;
2952 // Set to true to update the pointer in the dest Reduce list to a
2953 // newly created element.
2954 bool UpdateDestListPtr = false;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002955 // Increment the src or dest pointer to the scratchpad, for each
2956 // new element.
2957 bool IncrScratchpadSrc = false;
2958 bool IncrScratchpadDest = false;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002959
2960 switch (Action) {
2961 case RemoteLaneToThread: {
2962 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002963 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00002964 SrcElementAddr = CGF.EmitLoadOfPointer(
2965 SrcElementPtrAddr,
2966 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002967
2968 // Step 1.2: Create a temporary to store the element in the destination
2969 // Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002970 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002971 DestElementAddr =
2972 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2973 ShuffleInElement = true;
2974 UpdateDestListPtr = true;
2975 break;
2976 }
2977 case ThreadCopy: {
2978 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002979 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00002980 SrcElementAddr = CGF.EmitLoadOfPointer(
2981 SrcElementPtrAddr,
2982 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002983
2984 // Step 1.2: Get the address for dest element. The destination
2985 // element has already been created on the thread's stack.
James Y Knight751fe282019-02-09 22:22:28 +00002986 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00002987 DestElementAddr = CGF.EmitLoadOfPointer(
2988 DestElementPtrAddr,
2989 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002990 break;
2991 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002992 case ThreadToScratchpad: {
2993 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002994 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00002995 SrcElementAddr = CGF.EmitLoadOfPointer(
2996 SrcElementPtrAddr,
2997 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002998
2999 // Step 1.2: Get the address for dest element:
3000 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00003001 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00003002 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003003 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003004 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003005 Bld.CreateNUWAdd(DestBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003006 ScratchPadElemAbsolutePtrVal =
3007 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00003008 DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
3009 C.getTypeAlignInChars(Private->getType()));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003010 IncrScratchpadDest = true;
3011 break;
3012 }
3013 case ScratchpadToThread: {
3014 // Step 1.1: Get the address for the src element in the scratchpad.
3015 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00003016 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00003017 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003018 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003019 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003020 Bld.CreateNUWAdd(SrcBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003021 ScratchPadElemAbsolutePtrVal =
3022 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
3023 SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
3024 C.getTypeAlignInChars(Private->getType()));
3025 IncrScratchpadSrc = true;
3026
3027 // Step 1.2: Create a temporary to store the element in the destination
3028 // Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00003029 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003030 DestElementAddr =
3031 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
3032 UpdateDestListPtr = true;
3033 break;
3034 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003035 }
3036
3037 // Regardless of src and dest of copy, we emit the load of src
3038 // element as this is required in all directions
3039 SrcElementAddr = Bld.CreateElementBitCast(
3040 SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
Alexey Bataev12c62902018-06-22 19:10:38 +00003041 DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
3042 SrcElementAddr.getElementType());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003043
3044 // Now that all active lanes have read the element in the
3045 // Reduce list, shuffle over the value from the remote lane.
Alexey Bataeva453f362018-03-19 17:53:56 +00003046 if (ShuffleInElement) {
Alexey Bataev12c62902018-06-22 19:10:38 +00003047 shuffleAndStore(CGF, SrcElementAddr, DestElementAddr, Private->getType(),
3048 RemoteLaneOffset, Private->getExprLoc());
3049 } else {
Alexey Bataev8061acd2019-02-20 16:36:22 +00003050 switch (CGF.getEvaluationKind(Private->getType())) {
3051 case TEK_Scalar: {
Alexey Bataev12c62902018-06-22 19:10:38 +00003052 llvm::Value *Elem =
3053 CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false,
3054 Private->getType(), Private->getExprLoc());
3055 // Store the source element value to the dest element address.
3056 CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false,
3057 Private->getType());
Alexey Bataev8061acd2019-02-20 16:36:22 +00003058 break;
3059 }
3060 case TEK_Complex: {
3061 CodeGenFunction::ComplexPairTy Elem = CGF.EmitLoadOfComplex(
3062 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3063 Private->getExprLoc());
3064 CGF.EmitStoreOfComplex(
3065 Elem, CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3066 /*isInit=*/false);
3067 break;
3068 }
3069 case TEK_Aggregate:
Alexey Bataev12c62902018-06-22 19:10:38 +00003070 CGF.EmitAggregateCopy(
3071 CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3072 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3073 Private->getType(), AggValueSlot::DoesNotOverlap);
Alexey Bataev8061acd2019-02-20 16:36:22 +00003074 break;
Alexey Bataev12c62902018-06-22 19:10:38 +00003075 }
Alexey Bataeva453f362018-03-19 17:53:56 +00003076 }
Alexey Bataevb2575932018-01-04 20:18:55 +00003077
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003078 // Step 3.1: Modify reference in dest Reduce list as needed.
3079 // Modifying the reference in Reduce list to point to the newly
3080 // created element. The element is live in the current function
3081 // scope and that of functions it invokes (i.e., reduce_function).
3082 // RemoteReduceData[i] = (void*)&RemoteElem
3083 if (UpdateDestListPtr) {
3084 CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
3085 DestElementAddr.getPointer(), CGF.VoidPtrTy),
3086 DestElementPtrAddr, /*Volatile=*/false,
3087 C.VoidPtrTy);
3088 }
3089
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003090 // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
3091 // address of the next element in scratchpad memory, unless we're currently
3092 // processing the last one. Memory alignment is also taken care of here.
3093 if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
3094 llvm::Value *ScratchpadBasePtr =
3095 IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
Alexey Bataeve290ec02018-04-06 16:03:36 +00003096 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
3097 ScratchpadBasePtr = Bld.CreateNUWAdd(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003098 ScratchpadBasePtr,
Alexey Bataeve290ec02018-04-06 16:03:36 +00003099 Bld.CreateNUWMul(ScratchpadWidth, ElementSizeInChars));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003100
3101 // Take care of global memory alignment for performance
Alexey Bataeve290ec02018-04-06 16:03:36 +00003102 ScratchpadBasePtr = Bld.CreateNUWSub(
3103 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3104 ScratchpadBasePtr = Bld.CreateUDiv(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003105 ScratchpadBasePtr,
3106 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
Alexey Bataeve290ec02018-04-06 16:03:36 +00003107 ScratchpadBasePtr = Bld.CreateNUWAdd(
3108 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3109 ScratchpadBasePtr = Bld.CreateNUWMul(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003110 ScratchpadBasePtr,
3111 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
3112
3113 if (IncrScratchpadDest)
3114 DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3115 else /* IncrScratchpadSrc = true */
3116 SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3117 }
3118
Alexey Bataev9ff80832018-04-16 20:16:21 +00003119 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003120 }
3121}
3122
3123/// This function emits a helper that gathers Reduce lists from the first
3124/// lane of every active warp to lanes in the first warp.
3125///
3126/// void inter_warp_copy_func(void* reduce_data, num_warps)
3127/// shared smem[warp_size];
3128/// For all data entries D in reduce_data:
Alexey Bataev29d47fc2018-12-18 19:20:15 +00003129/// sync
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003130/// If (I am the first lane in each warp)
3131/// Copy my local D to smem[warp_id]
3132/// sync
3133/// if (I am the first warp)
3134/// Copy smem[thread_id] to my local D
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003135static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
3136 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003137 QualType ReductionArrayTy,
3138 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003139 ASTContext &C = CGM.getContext();
3140 llvm::Module &M = CGM.getModule();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003141
3142 // ReduceList: thread local Reduce list.
3143 // At the stage of the computation when this function is called, partially
3144 // aggregated values reside in the first lane of every active warp.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003145 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3146 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003147 // NumWarps: number of warps active in the parallel region. This could
3148 // be smaller than 32 (max warps in a CTA) for partial block reduction.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003149 ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00003150 C.getIntTypeForBitwidth(32, /* Signed */ true),
3151 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003152 FunctionArgList Args;
3153 Args.push_back(&ReduceListArg);
3154 Args.push_back(&NumWarpsArg);
3155
Alexey Bataev9ff80832018-04-16 20:16:21 +00003156 const CGFunctionInfo &CGFI =
3157 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev8061acd2019-02-20 16:36:22 +00003158 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
3159 llvm::GlobalValue::InternalLinkage,
3160 "_omp_reduction_inter_warp_copy_func", &M);
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003161 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003162 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003163 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003164 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003165
Alexey Bataev9ff80832018-04-16 20:16:21 +00003166 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003167
3168 // This array is used as a medium to transfer, one reduce element at a time,
3169 // the data from the first lane of every warp to lanes in the first warp
3170 // in order to perform the final step of a reduction in a parallel region
3171 // (reduction across warps). The array is placed in NVPTX __shared__ memory
3172 // for reduced latency, as well as to have a distinct copy for concurrently
3173 // executing target regions. The array is declared with common linkage so
3174 // as to be shared across compilation units.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003175 StringRef TransferMediumName =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003176 "__openmp_nvptx_data_transfer_temporary_storage";
3177 llvm::GlobalVariable *TransferMedium =
3178 M.getGlobalVariable(TransferMediumName);
3179 if (!TransferMedium) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003180 auto *Ty = llvm::ArrayType::get(CGM.Int32Ty, WarpSize);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003181 unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
3182 TransferMedium = new llvm::GlobalVariable(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003183 M, Ty, /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003184 llvm::Constant::getNullValue(Ty), TransferMediumName,
3185 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3186 SharedAddressSpace);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003187 CGM.addCompilerUsedGlobal(TransferMedium);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003188 }
3189
3190 // Get the CUDA thread id of the current OpenMP thread on the GPU.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003191 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003192 // nvptx_lane_id = nvptx_id % warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003193 llvm::Value *LaneID = getNVPTXLaneID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003194 // nvptx_warp_id = nvptx_id / warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003195 llvm::Value *WarpID = getNVPTXWarpID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003196
3197 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3198 Address LocalReduceList(
3199 Bld.CreatePointerBitCastOrAddrSpaceCast(
3200 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003201 C.VoidPtrTy, Loc),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003202 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3203 CGF.getPointerAlign());
3204
3205 unsigned Idx = 0;
Alexey Bataev9ff80832018-04-16 20:16:21 +00003206 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003207 //
3208 // Warp master copies reduce element to transfer medium in __shared__
3209 // memory.
3210 //
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003211 unsigned RealTySize =
3212 C.getTypeSizeInChars(Private->getType())
3213 .alignTo(C.getTypeAlignInChars(Private->getType()))
3214 .getQuantity();
3215 for (unsigned TySize = 4; TySize > 0 && RealTySize > 0; TySize /=2) {
3216 unsigned NumIters = RealTySize / TySize;
3217 if (NumIters == 0)
3218 continue;
3219 QualType CType = C.getIntTypeForBitwidth(
3220 C.toBits(CharUnits::fromQuantity(TySize)), /*Signed=*/1);
3221 llvm::Type *CopyType = CGF.ConvertTypeForMem(CType);
3222 CharUnits Align = CharUnits::fromQuantity(TySize);
3223 llvm::Value *Cnt = nullptr;
3224 Address CntAddr = Address::invalid();
3225 llvm::BasicBlock *PrecondBB = nullptr;
3226 llvm::BasicBlock *ExitBB = nullptr;
3227 if (NumIters > 1) {
3228 CntAddr = CGF.CreateMemTemp(C.IntTy, ".cnt.addr");
3229 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.IntTy), CntAddr,
3230 /*Volatile=*/false, C.IntTy);
3231 PrecondBB = CGF.createBasicBlock("precond");
3232 ExitBB = CGF.createBasicBlock("exit");
3233 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("body");
3234 // There is no need to emit line number for unconditional branch.
3235 (void)ApplyDebugLocation::CreateEmpty(CGF);
3236 CGF.EmitBlock(PrecondBB);
3237 Cnt = CGF.EmitLoadOfScalar(CntAddr, /*Volatile=*/false, C.IntTy, Loc);
3238 llvm::Value *Cmp =
3239 Bld.CreateICmpULT(Cnt, llvm::ConstantInt::get(CGM.IntTy, NumIters));
3240 Bld.CreateCondBr(Cmp, BodyBB, ExitBB);
3241 CGF.EmitBlock(BodyBB);
3242 }
Alexey Bataev29d47fc2018-12-18 19:20:15 +00003243 // kmpc_barrier.
3244 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3245 /*EmitChecks=*/false,
3246 /*ForceSimpleCall=*/true);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003247 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3248 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3249 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003250
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003251 // if (lane_id == 0)
3252 llvm::Value *IsWarpMaster = Bld.CreateIsNull(LaneID, "warp_master");
3253 Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
3254 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003255
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003256 // Reduce element = LocalReduceList[i]
James Y Knight751fe282019-02-09 22:22:28 +00003257 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003258 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3259 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3260 // elemptr = ((CopyType*)(elemptrptr)) + I
3261 Address ElemPtr = Address(ElemPtrPtr, Align);
3262 ElemPtr = Bld.CreateElementBitCast(ElemPtr, CopyType);
3263 if (NumIters > 1) {
3264 ElemPtr = Address(Bld.CreateGEP(ElemPtr.getPointer(), Cnt),
3265 ElemPtr.getAlignment());
3266 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003267
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003268 // Get pointer to location in transfer medium.
3269 // MediumPtr = &medium[warp_id]
3270 llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
3271 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
3272 Address MediumPtr(MediumPtrVal, Align);
3273 // Casting to actual data type.
3274 // MediumPtr = (CopyType*)MediumPtrAddr;
3275 MediumPtr = Bld.CreateElementBitCast(MediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003276
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003277 // elem = *elemptr
3278 //*MediumPtr = elem
3279 llvm::Value *Elem =
3280 CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003281 // Store the source element value to the dest element address.
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003282 CGF.EmitStoreOfScalar(Elem, MediumPtr, /*Volatile=*/true, CType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003283
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003284 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003285
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003286 CGF.EmitBlock(ElseBB);
3287 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003288
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003289 CGF.EmitBlock(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003290
Alexey Bataevae51b962018-12-14 21:00:58 +00003291 // kmpc_barrier.
3292 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3293 /*EmitChecks=*/false,
3294 /*ForceSimpleCall=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003295
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003296 //
3297 // Warp 0 copies reduce element from transfer medium.
3298 //
3299 llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
3300 llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
3301 llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003302
Alexey Bataevae51b962018-12-14 21:00:58 +00003303 Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
3304 llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
3305 AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, Loc);
3306
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003307 // Up to 32 threads in warp 0 are active.
3308 llvm::Value *IsActiveThread =
3309 Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
3310 Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003311
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003312 CGF.EmitBlock(W0ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003313
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003314 // SrcMediumPtr = &medium[tid]
3315 llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
3316 TransferMedium,
3317 {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
3318 Address SrcMediumPtr(SrcMediumPtrVal, Align);
3319 // SrcMediumVal = *SrcMediumPtr;
3320 SrcMediumPtr = Bld.CreateElementBitCast(SrcMediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003321
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003322 // TargetElemPtr = (CopyType*)(SrcDataAddr[i]) + I
James Y Knight751fe282019-02-09 22:22:28 +00003323 Address TargetElemPtrPtr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003324 llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
3325 TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, Loc);
3326 Address TargetElemPtr = Address(TargetElemPtrVal, Align);
3327 TargetElemPtr = Bld.CreateElementBitCast(TargetElemPtr, CopyType);
3328 if (NumIters > 1) {
3329 TargetElemPtr = Address(Bld.CreateGEP(TargetElemPtr.getPointer(), Cnt),
3330 TargetElemPtr.getAlignment());
3331 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003332
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003333 // *TargetElemPtr = SrcMediumVal;
3334 llvm::Value *SrcMediumValue =
3335 CGF.EmitLoadOfScalar(SrcMediumPtr, /*Volatile=*/true, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003336 CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003337 CType);
3338 Bld.CreateBr(W0MergeBB);
3339
3340 CGF.EmitBlock(W0ElseBB);
3341 Bld.CreateBr(W0MergeBB);
3342
3343 CGF.EmitBlock(W0MergeBB);
3344
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003345 if (NumIters > 1) {
3346 Cnt = Bld.CreateNSWAdd(Cnt, llvm::ConstantInt::get(CGM.IntTy, /*V=*/1));
3347 CGF.EmitStoreOfScalar(Cnt, CntAddr, /*Volatile=*/false, C.IntTy);
3348 CGF.EmitBranch(PrecondBB);
3349 (void)ApplyDebugLocation::CreateEmpty(CGF);
3350 CGF.EmitBlock(ExitBB);
3351 }
3352 RealTySize %= TySize;
Alexey Bataev12c62902018-06-22 19:10:38 +00003353 }
Alexey Bataev9ff80832018-04-16 20:16:21 +00003354 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003355 }
3356
3357 CGF.FinishFunction();
3358 return Fn;
3359}
3360
3361/// Emit a helper that reduces data across two OpenMP threads (lanes)
3362/// in the same warp. It uses shuffle instructions to copy over data from
3363/// a remote lane's stack. The reduction algorithm performed is specified
3364/// by the fourth parameter.
3365///
3366/// Algorithm Versions.
3367/// Full Warp Reduce (argument value 0):
3368/// This algorithm assumes that all 32 lanes are active and gathers
3369/// data from these 32 lanes, producing a single resultant value.
3370/// Contiguous Partial Warp Reduce (argument value 1):
3371/// This algorithm assumes that only a *contiguous* subset of lanes
3372/// are active. This happens for the last warp in a parallel region
3373/// when the user specified num_threads is not an integer multiple of
3374/// 32. This contiguous subset always starts with the zeroth lane.
3375/// Partial Warp Reduce (argument value 2):
3376/// This algorithm gathers data from any number of lanes at any position.
3377/// All reduced values are stored in the lowest possible lane. The set
3378/// of problems every algorithm addresses is a super set of those
3379/// addressable by algorithms with a lower version number. Overhead
3380/// increases as algorithm version increases.
3381///
3382/// Terminology
3383/// Reduce element:
3384/// Reduce element refers to the individual data field with primitive
3385/// data types to be combined and reduced across threads.
3386/// Reduce list:
3387/// Reduce list refers to a collection of local, thread-private
3388/// reduce elements.
3389/// Remote Reduce list:
3390/// Remote Reduce list refers to a collection of remote (relative to
3391/// the current thread) reduce elements.
3392///
3393/// We distinguish between three states of threads that are important to
3394/// the implementation of this function.
3395/// Alive threads:
3396/// Threads in a warp executing the SIMT instruction, as distinguished from
3397/// threads that are inactive due to divergent control flow.
3398/// Active threads:
3399/// The minimal set of threads that has to be alive upon entry to this
3400/// function. The computation is correct iff active threads are alive.
3401/// Some threads are alive but they are not active because they do not
3402/// contribute to the computation in any useful manner. Turning them off
3403/// may introduce control flow overheads without any tangible benefits.
3404/// Effective threads:
3405/// In order to comply with the argument requirements of the shuffle
3406/// function, we must keep all lanes holding data alive. But at most
3407/// half of them perform value aggregation; we refer to this half of
3408/// threads as effective. The other half is simply handing off their
3409/// data.
3410///
3411/// Procedure
3412/// Value shuffle:
3413/// In this step active threads transfer data from higher lane positions
3414/// in the warp to lower lane positions, creating Remote Reduce list.
3415/// Value aggregation:
3416/// In this step, effective threads combine their thread local Reduce list
3417/// with Remote Reduce list and store the result in the thread local
3418/// Reduce list.
3419/// Value copy:
3420/// In this step, we deal with the assumption made by algorithm 2
3421/// (i.e. contiguity assumption). When we have an odd number of lanes
3422/// active, say 2k+1, only k threads will be effective and therefore k
3423/// new values will be produced. However, the Reduce list owned by the
3424/// (2k+1)th thread is ignored in the value aggregation. Therefore
3425/// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
3426/// that the contiguity assumption still holds.
James Y Knight9871db02019-02-05 16:42:33 +00003427static llvm::Function *emitShuffleAndReduceFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003428 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
James Y Knight9871db02019-02-05 16:42:33 +00003429 QualType ReductionArrayTy, llvm::Function *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003430 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003431
3432 // Thread local Reduce list used to host the values of data to be reduced.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003433 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3434 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003435 // Current lane id; could be logical.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003436 ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
3437 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003438 // Offset of the remote source lane relative to the current lane.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003439 ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3440 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003441 // Algorithm version. This is expected to be known at compile time.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003442 ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3443 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003444 FunctionArgList Args;
3445 Args.push_back(&ReduceListArg);
3446 Args.push_back(&LaneIDArg);
3447 Args.push_back(&RemoteLaneOffsetArg);
3448 Args.push_back(&AlgoVerArg);
3449
Alexey Bataev9ff80832018-04-16 20:16:21 +00003450 const CGFunctionInfo &CGFI =
3451 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003452 auto *Fn = llvm::Function::Create(
3453 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3454 "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003455 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003456 Fn->setDoesNotRecurse();
Alexey Bataev8c5555c2019-05-21 15:11:58 +00003457 if (CGM.getLangOpts().Optimize) {
3458 Fn->removeFnAttr(llvm::Attribute::NoInline);
3459 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
3460 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
3461 }
3462
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003463 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003464 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003465
Alexey Bataev9ff80832018-04-16 20:16:21 +00003466 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003467
3468 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3469 Address LocalReduceList(
3470 Bld.CreatePointerBitCastOrAddrSpaceCast(
3471 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3472 C.VoidPtrTy, SourceLocation()),
3473 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3474 CGF.getPointerAlign());
3475
3476 Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
3477 llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
3478 AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3479
3480 Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
3481 llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
3482 AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3483
3484 Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
3485 llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
3486 AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3487
3488 // Create a local thread-private variable to host the Reduce list
3489 // from a remote lane.
3490 Address RemoteReduceList =
3491 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
3492
3493 // This loop iterates through the list of reduce elements and copies,
3494 // element by element, from a remote lane in the warp to RemoteReduceList,
3495 // hosted on the thread's stack.
3496 emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
3497 LocalReduceList, RemoteReduceList,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003498 {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
3499 /*ScratchpadIndex=*/nullptr,
3500 /*ScratchpadWidth=*/nullptr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003501
3502 // The actions to be performed on the Remote Reduce list is dependent
3503 // on the algorithm version.
3504 //
3505 // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
3506 // LaneId % 2 == 0 && Offset > 0):
3507 // do the reduction value aggregation
3508 //
3509 // The thread local variable Reduce list is mutated in place to host the
3510 // reduced data, which is the aggregated value produced from local and
3511 // remote lanes.
3512 //
3513 // Note that AlgoVer is expected to be a constant integer known at compile
3514 // time.
3515 // When AlgoVer==0, the first conjunction evaluates to true, making
3516 // the entire predicate true during compile time.
3517 // When AlgoVer==1, the second conjunction has only the second part to be
3518 // evaluated during runtime. Other conjunctions evaluates to false
3519 // during compile time.
3520 // When AlgoVer==2, the third conjunction has only the second part to be
3521 // evaluated during runtime. Other conjunctions evaluates to false
3522 // during compile time.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003523 llvm::Value *CondAlgo0 = Bld.CreateIsNull(AlgoVerArgVal);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003524
Alexey Bataev9ff80832018-04-16 20:16:21 +00003525 llvm::Value *Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
3526 llvm::Value *CondAlgo1 = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003527 Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
3528
Alexey Bataev9ff80832018-04-16 20:16:21 +00003529 llvm::Value *Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
3530 llvm::Value *CondAlgo2 = Bld.CreateAnd(
3531 Algo2, Bld.CreateIsNull(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1))));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003532 CondAlgo2 = Bld.CreateAnd(
3533 CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
3534
Alexey Bataev9ff80832018-04-16 20:16:21 +00003535 llvm::Value *CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003536 CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
3537
3538 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3539 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3540 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
3541 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
3542
3543 CGF.EmitBlock(ThenBB);
3544 // reduce_function(LocalReduceList, RemoteReduceList)
3545 llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3546 LocalReduceList.getPointer(), CGF.VoidPtrTy);
3547 llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3548 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003549 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3550 CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003551 Bld.CreateBr(MergeBB);
3552
3553 CGF.EmitBlock(ElseBB);
3554 Bld.CreateBr(MergeBB);
3555
3556 CGF.EmitBlock(MergeBB);
3557
3558 // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
3559 // Reduce list.
3560 Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
Alexey Bataev9ff80832018-04-16 20:16:21 +00003561 llvm::Value *CondCopy = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003562 Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
3563
3564 llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
3565 llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
3566 llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
3567 Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
3568
3569 CGF.EmitBlock(CpyThenBB);
3570 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
3571 RemoteReduceList, LocalReduceList);
3572 Bld.CreateBr(CpyMergeBB);
3573
3574 CGF.EmitBlock(CpyElseBB);
3575 Bld.CreateBr(CpyMergeBB);
3576
3577 CGF.EmitBlock(CpyMergeBB);
3578
3579 CGF.FinishFunction();
3580 return Fn;
3581}
3582
Alexey Bataev8061acd2019-02-20 16:36:22 +00003583/// This function emits a helper that copies all the reduction variables from
3584/// the team into the provided global buffer for the reduction variables.
3585///
3586/// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
3587/// For all data entries D in reduce_data:
3588/// Copy local D to buffer.D[Idx]
3589static llvm::Value *emitListToGlobalCopyFunction(
3590 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3591 QualType ReductionArrayTy, SourceLocation Loc,
3592 const RecordDecl *TeamReductionRec,
3593 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3594 &VarFieldMap) {
3595 ASTContext &C = CGM.getContext();
3596
3597 // Buffer: global reduction buffer.
3598 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3599 C.VoidPtrTy, ImplicitParamDecl::Other);
3600 // Idx: index of the buffer.
3601 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3602 ImplicitParamDecl::Other);
3603 // ReduceList: thread local Reduce list.
3604 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3605 C.VoidPtrTy, ImplicitParamDecl::Other);
3606 FunctionArgList Args;
3607 Args.push_back(&BufferArg);
3608 Args.push_back(&IdxArg);
3609 Args.push_back(&ReduceListArg);
3610
3611 const CGFunctionInfo &CGFI =
3612 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3613 auto *Fn = llvm::Function::Create(
3614 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3615 "_omp_reduction_list_to_global_copy_func", &CGM.getModule());
3616 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3617 Fn->setDoesNotRecurse();
3618 CodeGenFunction CGF(CGM);
3619 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3620
3621 CGBuilderTy &Bld = CGF.Builder;
3622
3623 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3624 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3625 Address LocalReduceList(
3626 Bld.CreatePointerBitCastOrAddrSpaceCast(
3627 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3628 C.VoidPtrTy, Loc),
3629 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3630 CGF.getPointerAlign());
3631 QualType StaticTy = C.getRecordType(TeamReductionRec);
3632 llvm::Type *LLVMReductionsBufferTy =
3633 CGM.getTypes().ConvertTypeForMem(StaticTy);
3634 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3635 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3636 LLVMReductionsBufferTy->getPointerTo());
3637 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3638 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3639 /*Volatile=*/false, C.IntTy,
3640 Loc)};
3641 unsigned Idx = 0;
3642 for (const Expr *Private : Privates) {
3643 // Reduce element = LocalReduceList[i]
3644 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
3645 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3646 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3647 // elemptr = ((CopyType*)(elemptrptr)) + I
3648 ElemPtrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3649 ElemPtrPtr, CGF.ConvertTypeForMem(Private->getType())->getPointerTo());
3650 Address ElemPtr =
3651 Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
3652 const ValueDecl *VD = cast<DeclRefExpr>(Private)->getDecl();
3653 // Global = Buffer.VD[Idx];
3654 const FieldDecl *FD = VarFieldMap.lookup(VD);
3655 LValue GlobLVal = CGF.EmitLValueForField(
3656 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3657 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3658 GlobLVal.setAddress(Address(BufferPtr, GlobLVal.getAlignment()));
3659 switch (CGF.getEvaluationKind(Private->getType())) {
3660 case TEK_Scalar: {
3661 llvm::Value *V = CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false,
3662 Private->getType(), Loc);
3663 CGF.EmitStoreOfScalar(V, GlobLVal);
3664 break;
3665 }
3666 case TEK_Complex: {
3667 CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(
3668 CGF.MakeAddrLValue(ElemPtr, Private->getType()), Loc);
3669 CGF.EmitStoreOfComplex(V, GlobLVal, /*isInit=*/false);
3670 break;
3671 }
3672 case TEK_Aggregate:
3673 CGF.EmitAggregateCopy(GlobLVal,
3674 CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3675 Private->getType(), AggValueSlot::DoesNotOverlap);
3676 break;
3677 }
3678 ++Idx;
3679 }
3680
3681 CGF.FinishFunction();
3682 return Fn;
3683}
3684
3685/// This function emits a helper that reduces all the reduction variables from
3686/// the team into the provided global buffer for the reduction variables.
3687///
3688/// void list_to_global_reduce_func(void *buffer, int Idx, void *reduce_data)
3689/// void *GlobPtrs[];
3690/// GlobPtrs[0] = (void*)&buffer.D0[Idx];
3691/// ...
3692/// GlobPtrs[N] = (void*)&buffer.DN[Idx];
3693/// reduce_function(GlobPtrs, reduce_data);
3694static llvm::Value *emitListToGlobalReduceFunction(
3695 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3696 QualType ReductionArrayTy, SourceLocation Loc,
3697 const RecordDecl *TeamReductionRec,
3698 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3699 &VarFieldMap,
3700 llvm::Function *ReduceFn) {
3701 ASTContext &C = CGM.getContext();
3702
3703 // Buffer: global reduction buffer.
3704 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3705 C.VoidPtrTy, ImplicitParamDecl::Other);
3706 // Idx: index of the buffer.
3707 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3708 ImplicitParamDecl::Other);
3709 // ReduceList: thread local Reduce list.
3710 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3711 C.VoidPtrTy, ImplicitParamDecl::Other);
3712 FunctionArgList Args;
3713 Args.push_back(&BufferArg);
3714 Args.push_back(&IdxArg);
3715 Args.push_back(&ReduceListArg);
3716
3717 const CGFunctionInfo &CGFI =
3718 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3719 auto *Fn = llvm::Function::Create(
3720 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3721 "_omp_reduction_list_to_global_reduce_func", &CGM.getModule());
3722 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3723 Fn->setDoesNotRecurse();
3724 CodeGenFunction CGF(CGM);
3725 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3726
3727 CGBuilderTy &Bld = CGF.Builder;
3728
3729 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3730 QualType StaticTy = C.getRecordType(TeamReductionRec);
3731 llvm::Type *LLVMReductionsBufferTy =
3732 CGM.getTypes().ConvertTypeForMem(StaticTy);
3733 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3734 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3735 LLVMReductionsBufferTy->getPointerTo());
3736
3737 // 1. Build a list of reduction variables.
3738 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3739 Address ReductionList =
3740 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3741 auto IPriv = Privates.begin();
3742 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3743 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3744 /*Volatile=*/false, C.IntTy,
3745 Loc)};
3746 unsigned Idx = 0;
3747 for (unsigned I = 0, E = Privates.size(); I < E; ++I, ++IPriv, ++Idx) {
3748 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3749 // Global = Buffer.VD[Idx];
3750 const ValueDecl *VD = cast<DeclRefExpr>(*IPriv)->getDecl();
3751 const FieldDecl *FD = VarFieldMap.lookup(VD);
3752 LValue GlobLVal = CGF.EmitLValueForField(
3753 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3754 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3755 llvm::Value *Ptr = CGF.EmitCastToVoidPtr(BufferPtr);
3756 CGF.EmitStoreOfScalar(Ptr, Elem, /*Volatile=*/false, C.VoidPtrTy);
3757 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3758 // Store array size.
3759 ++Idx;
3760 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3761 llvm::Value *Size = CGF.Builder.CreateIntCast(
3762 CGF.getVLASize(
3763 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3764 .NumElts,
3765 CGF.SizeTy, /*isSigned=*/false);
3766 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3767 Elem);
3768 }
3769 }
3770
3771 // Call reduce_function(GlobalReduceList, ReduceList)
3772 llvm::Value *GlobalReduceList =
3773 CGF.EmitCastToVoidPtr(ReductionList.getPointer());
3774 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3775 llvm::Value *ReducedPtr = CGF.EmitLoadOfScalar(
3776 AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
3777 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3778 CGF, Loc, ReduceFn, {GlobalReduceList, ReducedPtr});
3779 CGF.FinishFunction();
3780 return Fn;
3781}
3782
3783/// This function emits a helper that copies all the reduction variables from
3784/// the team into the provided global buffer for the reduction variables.
3785///
3786/// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
3787/// For all data entries D in reduce_data:
3788/// Copy buffer.D[Idx] to local D;
3789static llvm::Value *emitGlobalToListCopyFunction(
3790 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3791 QualType ReductionArrayTy, SourceLocation Loc,
3792 const RecordDecl *TeamReductionRec,
3793 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3794 &VarFieldMap) {
3795 ASTContext &C = CGM.getContext();
3796
3797 // Buffer: global reduction buffer.
3798 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3799 C.VoidPtrTy, ImplicitParamDecl::Other);
3800 // Idx: index of the buffer.
3801 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3802 ImplicitParamDecl::Other);
3803 // ReduceList: thread local Reduce list.
3804 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3805 C.VoidPtrTy, ImplicitParamDecl::Other);
3806 FunctionArgList Args;
3807 Args.push_back(&BufferArg);
3808 Args.push_back(&IdxArg);
3809 Args.push_back(&ReduceListArg);
3810
3811 const CGFunctionInfo &CGFI =
3812 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3813 auto *Fn = llvm::Function::Create(
3814 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3815 "_omp_reduction_global_to_list_copy_func", &CGM.getModule());
3816 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3817 Fn->setDoesNotRecurse();
3818 CodeGenFunction CGF(CGM);
3819 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3820
3821 CGBuilderTy &Bld = CGF.Builder;
3822
3823 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3824 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3825 Address LocalReduceList(
3826 Bld.CreatePointerBitCastOrAddrSpaceCast(
3827 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3828 C.VoidPtrTy, Loc),
3829 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3830 CGF.getPointerAlign());
3831 QualType StaticTy = C.getRecordType(TeamReductionRec);
3832 llvm::Type *LLVMReductionsBufferTy =
3833 CGM.getTypes().ConvertTypeForMem(StaticTy);
3834 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3835 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3836 LLVMReductionsBufferTy->getPointerTo());
3837
3838 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3839 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3840 /*Volatile=*/false, C.IntTy,
3841 Loc)};
3842 unsigned Idx = 0;
3843 for (const Expr *Private : Privates) {
3844 // Reduce element = LocalReduceList[i]
3845 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
3846 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3847 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3848 // elemptr = ((CopyType*)(elemptrptr)) + I
3849 ElemPtrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3850 ElemPtrPtr, CGF.ConvertTypeForMem(Private->getType())->getPointerTo());
3851 Address ElemPtr =
3852 Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
3853 const ValueDecl *VD = cast<DeclRefExpr>(Private)->getDecl();
3854 // Global = Buffer.VD[Idx];
3855 const FieldDecl *FD = VarFieldMap.lookup(VD);
3856 LValue GlobLVal = CGF.EmitLValueForField(
3857 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3858 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3859 GlobLVal.setAddress(Address(BufferPtr, GlobLVal.getAlignment()));
3860 switch (CGF.getEvaluationKind(Private->getType())) {
3861 case TEK_Scalar: {
3862 llvm::Value *V = CGF.EmitLoadOfScalar(GlobLVal, Loc);
3863 CGF.EmitStoreOfScalar(V, ElemPtr, /*Volatile=*/false, Private->getType());
3864 break;
3865 }
3866 case TEK_Complex: {
3867 CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(GlobLVal, Loc);
3868 CGF.EmitStoreOfComplex(V, CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3869 /*isInit=*/false);
3870 break;
3871 }
3872 case TEK_Aggregate:
3873 CGF.EmitAggregateCopy(CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3874 GlobLVal, Private->getType(),
3875 AggValueSlot::DoesNotOverlap);
3876 break;
3877 }
3878 ++Idx;
3879 }
3880
3881 CGF.FinishFunction();
3882 return Fn;
3883}
3884
3885/// This function emits a helper that reduces all the reduction variables from
3886/// the team into the provided global buffer for the reduction variables.
3887///
3888/// void global_to_list_reduce_func(void *buffer, int Idx, void *reduce_data)
3889/// void *GlobPtrs[];
3890/// GlobPtrs[0] = (void*)&buffer.D0[Idx];
3891/// ...
3892/// GlobPtrs[N] = (void*)&buffer.DN[Idx];
3893/// reduce_function(reduce_data, GlobPtrs);
3894static llvm::Value *emitGlobalToListReduceFunction(
3895 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3896 QualType ReductionArrayTy, SourceLocation Loc,
3897 const RecordDecl *TeamReductionRec,
3898 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3899 &VarFieldMap,
3900 llvm::Function *ReduceFn) {
3901 ASTContext &C = CGM.getContext();
3902
3903 // Buffer: global reduction buffer.
3904 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3905 C.VoidPtrTy, ImplicitParamDecl::Other);
3906 // Idx: index of the buffer.
3907 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3908 ImplicitParamDecl::Other);
3909 // ReduceList: thread local Reduce list.
3910 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3911 C.VoidPtrTy, ImplicitParamDecl::Other);
3912 FunctionArgList Args;
3913 Args.push_back(&BufferArg);
3914 Args.push_back(&IdxArg);
3915 Args.push_back(&ReduceListArg);
3916
3917 const CGFunctionInfo &CGFI =
3918 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3919 auto *Fn = llvm::Function::Create(
3920 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3921 "_omp_reduction_global_to_list_reduce_func", &CGM.getModule());
3922 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3923 Fn->setDoesNotRecurse();
3924 CodeGenFunction CGF(CGM);
3925 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3926
3927 CGBuilderTy &Bld = CGF.Builder;
3928
3929 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3930 QualType StaticTy = C.getRecordType(TeamReductionRec);
3931 llvm::Type *LLVMReductionsBufferTy =
3932 CGM.getTypes().ConvertTypeForMem(StaticTy);
3933 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3934 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3935 LLVMReductionsBufferTy->getPointerTo());
3936
3937 // 1. Build a list of reduction variables.
3938 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3939 Address ReductionList =
3940 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3941 auto IPriv = Privates.begin();
3942 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3943 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3944 /*Volatile=*/false, C.IntTy,
3945 Loc)};
3946 unsigned Idx = 0;
3947 for (unsigned I = 0, E = Privates.size(); I < E; ++I, ++IPriv, ++Idx) {
3948 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3949 // Global = Buffer.VD[Idx];
3950 const ValueDecl *VD = cast<DeclRefExpr>(*IPriv)->getDecl();
3951 const FieldDecl *FD = VarFieldMap.lookup(VD);
3952 LValue GlobLVal = CGF.EmitLValueForField(
3953 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3954 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3955 llvm::Value *Ptr = CGF.EmitCastToVoidPtr(BufferPtr);
3956 CGF.EmitStoreOfScalar(Ptr, Elem, /*Volatile=*/false, C.VoidPtrTy);
3957 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3958 // Store array size.
3959 ++Idx;
3960 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3961 llvm::Value *Size = CGF.Builder.CreateIntCast(
3962 CGF.getVLASize(
3963 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3964 .NumElts,
3965 CGF.SizeTy, /*isSigned=*/false);
3966 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3967 Elem);
3968 }
3969 }
3970
3971 // Call reduce_function(ReduceList, GlobalReduceList)
3972 llvm::Value *GlobalReduceList =
3973 CGF.EmitCastToVoidPtr(ReductionList.getPointer());
3974 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3975 llvm::Value *ReducedPtr = CGF.EmitLoadOfScalar(
3976 AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
3977 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3978 CGF, Loc, ReduceFn, {ReducedPtr, GlobalReduceList});
3979 CGF.FinishFunction();
3980 return Fn;
3981}
3982
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003983///
3984/// Design of OpenMP reductions on the GPU
3985///
3986/// Consider a typical OpenMP program with one or more reduction
3987/// clauses:
3988///
3989/// float foo;
3990/// double bar;
3991/// #pragma omp target teams distribute parallel for \
3992/// reduction(+:foo) reduction(*:bar)
3993/// for (int i = 0; i < N; i++) {
3994/// foo += A[i]; bar *= B[i];
3995/// }
3996///
3997/// where 'foo' and 'bar' are reduced across all OpenMP threads in
3998/// all teams. In our OpenMP implementation on the NVPTX device an
3999/// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
4000/// within a team are mapped to CUDA threads within a threadblock.
4001/// Our goal is to efficiently aggregate values across all OpenMP
4002/// threads such that:
4003///
4004/// - the compiler and runtime are logically concise, and
4005/// - the reduction is performed efficiently in a hierarchical
4006/// manner as follows: within OpenMP threads in the same warp,
4007/// across warps in a threadblock, and finally across teams on
4008/// the NVPTX device.
4009///
4010/// Introduction to Decoupling
4011///
4012/// We would like to decouple the compiler and the runtime so that the
4013/// latter is ignorant of the reduction variables (number, data types)
4014/// and the reduction operators. This allows a simpler interface
4015/// and implementation while still attaining good performance.
4016///
4017/// Pseudocode for the aforementioned OpenMP program generated by the
4018/// compiler is as follows:
4019///
4020/// 1. Create private copies of reduction variables on each OpenMP
4021/// thread: 'foo_private', 'bar_private'
4022/// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
4023/// to it and writes the result in 'foo_private' and 'bar_private'
4024/// respectively.
4025/// 3. Call the OpenMP runtime on the GPU to reduce within a team
4026/// and store the result on the team master:
4027///
Alexey Bataev8e009032019-01-04 17:25:09 +00004028/// __kmpc_nvptx_parallel_reduce_nowait_v2(...,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004029/// reduceData, shuffleReduceFn, interWarpCpyFn)
4030///
4031/// where:
4032/// struct ReduceData {
4033/// double *foo;
4034/// double *bar;
4035/// } reduceData
4036/// reduceData.foo = &foo_private
4037/// reduceData.bar = &bar_private
4038///
4039/// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
4040/// auxiliary functions generated by the compiler that operate on
4041/// variables of type 'ReduceData'. They aid the runtime perform
4042/// algorithmic steps in a data agnostic manner.
4043///
4044/// 'shuffleReduceFn' is a pointer to a function that reduces data
4045/// of type 'ReduceData' across two OpenMP threads (lanes) in the
4046/// same warp. It takes the following arguments as input:
4047///
4048/// a. variable of type 'ReduceData' on the calling lane,
4049/// b. its lane_id,
4050/// c. an offset relative to the current lane_id to generate a
4051/// remote_lane_id. The remote lane contains the second
4052/// variable of type 'ReduceData' that is to be reduced.
4053/// d. an algorithm version parameter determining which reduction
4054/// algorithm to use.
4055///
4056/// 'shuffleReduceFn' retrieves data from the remote lane using
4057/// efficient GPU shuffle intrinsics and reduces, using the
4058/// algorithm specified by the 4th parameter, the two operands
4059/// element-wise. The result is written to the first operand.
4060///
4061/// Different reduction algorithms are implemented in different
4062/// runtime functions, all calling 'shuffleReduceFn' to perform
4063/// the essential reduction step. Therefore, based on the 4th
4064/// parameter, this function behaves slightly differently to
4065/// cooperate with the runtime to ensure correctness under
4066/// different circumstances.
4067///
4068/// 'InterWarpCpyFn' is a pointer to a function that transfers
4069/// reduced variables across warps. It tunnels, through CUDA
4070/// shared memory, the thread-private data of type 'ReduceData'
4071/// from lane 0 of each warp to a lane in the first warp.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004072/// 4. Call the OpenMP runtime on the GPU to reduce across teams.
4073/// The last team writes the global reduced value to memory.
4074///
4075/// ret = __kmpc_nvptx_teams_reduce_nowait(...,
4076/// reduceData, shuffleReduceFn, interWarpCpyFn,
4077/// scratchpadCopyFn, loadAndReduceFn)
4078///
4079/// 'scratchpadCopyFn' is a helper that stores reduced
4080/// data from the team master to a scratchpad array in
4081/// global memory.
4082///
4083/// 'loadAndReduceFn' is a helper that loads data from
4084/// the scratchpad array and reduces it with the input
4085/// operand.
4086///
4087/// These compiler generated functions hide address
4088/// calculation and alignment information from the runtime.
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004089/// 5. if ret == 1:
4090/// The team master of the last team stores the reduced
4091/// result to the globals in memory.
4092/// foo += reduceData.foo; bar *= reduceData.bar
4093///
4094///
4095/// Warp Reduction Algorithms
4096///
4097/// On the warp level, we have three algorithms implemented in the
4098/// OpenMP runtime depending on the number of active lanes:
4099///
4100/// Full Warp Reduction
4101///
4102/// The reduce algorithm within a warp where all lanes are active
4103/// is implemented in the runtime as follows:
4104///
4105/// full_warp_reduce(void *reduce_data,
4106/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
4107/// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
4108/// ShuffleReduceFn(reduce_data, 0, offset, 0);
4109/// }
4110///
4111/// The algorithm completes in log(2, WARPSIZE) steps.
4112///
4113/// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
4114/// not used therefore we save instructions by not retrieving lane_id
4115/// from the corresponding special registers. The 4th parameter, which
4116/// represents the version of the algorithm being used, is set to 0 to
4117/// signify full warp reduction.
4118///
4119/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4120///
4121/// #reduce_elem refers to an element in the local lane's data structure
4122/// #remote_elem is retrieved from a remote lane
4123/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4124/// reduce_elem = reduce_elem REDUCE_OP remote_elem;
4125///
4126/// Contiguous Partial Warp Reduction
4127///
4128/// This reduce algorithm is used within a warp where only the first
4129/// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
4130/// number of OpenMP threads in a parallel region is not a multiple of
4131/// WARPSIZE. The algorithm is implemented in the runtime as follows:
4132///
4133/// void
4134/// contiguous_partial_reduce(void *reduce_data,
4135/// kmp_ShuffleReductFctPtr ShuffleReduceFn,
4136/// int size, int lane_id) {
4137/// int curr_size;
4138/// int offset;
4139/// curr_size = size;
4140/// mask = curr_size/2;
4141/// while (offset>0) {
4142/// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
4143/// curr_size = (curr_size+1)/2;
4144/// offset = curr_size/2;
4145/// }
4146/// }
4147///
4148/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4149///
4150/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4151/// if (lane_id < offset)
4152/// reduce_elem = reduce_elem REDUCE_OP remote_elem
4153/// else
4154/// reduce_elem = remote_elem
4155///
4156/// This algorithm assumes that the data to be reduced are located in a
4157/// contiguous subset of lanes starting from the first. When there is
4158/// an odd number of active lanes, the data in the last lane is not
4159/// aggregated with any other lane's dat but is instead copied over.
4160///
4161/// Dispersed Partial Warp Reduction
4162///
4163/// This algorithm is used within a warp when any discontiguous subset of
4164/// lanes are active. It is used to implement the reduction operation
4165/// across lanes in an OpenMP simd region or in a nested parallel region.
4166///
4167/// void
4168/// dispersed_partial_reduce(void *reduce_data,
4169/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
4170/// int size, remote_id;
4171/// int logical_lane_id = number_of_active_lanes_before_me() * 2;
4172/// do {
4173/// remote_id = next_active_lane_id_right_after_me();
4174/// # the above function returns 0 of no active lane
4175/// # is present right after the current lane.
4176/// size = number_of_active_lanes_in_this_warp();
4177/// logical_lane_id /= 2;
4178/// ShuffleReduceFn(reduce_data, logical_lane_id,
4179/// remote_id-1-threadIdx.x, 2);
4180/// } while (logical_lane_id % 2 == 0 && size > 1);
4181/// }
4182///
4183/// There is no assumption made about the initial state of the reduction.
4184/// Any number of lanes (>=1) could be active at any position. The reduction
4185/// result is returned in the first active lane.
4186///
4187/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4188///
4189/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4190/// if (lane_id % 2 == 0 && offset > 0)
4191/// reduce_elem = reduce_elem REDUCE_OP remote_elem
4192/// else
4193/// reduce_elem = remote_elem
4194///
4195///
4196/// Intra-Team Reduction
4197///
4198/// This function, as implemented in the runtime call
Alexey Bataev8e009032019-01-04 17:25:09 +00004199/// '__kmpc_nvptx_parallel_reduce_nowait_v2', aggregates data across OpenMP
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004200/// threads in a team. It first reduces within a warp using the
4201/// aforementioned algorithms. We then proceed to gather all such
4202/// reduced values at the first warp.
4203///
4204/// The runtime makes use of the function 'InterWarpCpyFn', which copies
4205/// data from each of the "warp master" (zeroth lane of each warp, where
4206/// warp-reduced data is held) to the zeroth warp. This step reduces (in
4207/// a mathematical sense) the problem of reduction across warp masters in
4208/// a block to the problem of warp reduction.
4209///
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004210///
4211/// Inter-Team Reduction
4212///
4213/// Once a team has reduced its data to a single value, it is stored in
4214/// a global scratchpad array. Since each team has a distinct slot, this
4215/// can be done without locking.
4216///
4217/// The last team to write to the scratchpad array proceeds to reduce the
4218/// scratchpad array. One or more workers in the last team use the helper
4219/// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
4220/// the k'th worker reduces every k'th element.
4221///
Alexey Bataev8e009032019-01-04 17:25:09 +00004222/// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait_v2' to
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004223/// reduce across workers and compute a globally reduced value.
4224///
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004225void CGOpenMPRuntimeNVPTX::emitReduction(
4226 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
4227 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
4228 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
4229 if (!CGF.HaveInsertPoint())
4230 return;
4231
4232 bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00004233#ifndef NDEBUG
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004234 bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00004235#endif
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004236
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00004237 if (Options.SimpleReduction) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004238 assert(!TeamsReduction && !ParallelReduction &&
4239 "Invalid reduction selection in emitReduction.");
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00004240 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
4241 ReductionOps, Options);
4242 return;
4243 }
4244
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004245 assert((TeamsReduction || ParallelReduction) &&
4246 "Invalid reduction selection in emitReduction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004247
Alexey Bataeva1166022018-11-27 21:24:54 +00004248 // Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004249 // RedList, shuffle_reduce_func, interwarp_copy_func);
Alexey Bataeva1166022018-11-27 21:24:54 +00004250 // or
4251 // Build res = __kmpc_reduce_teams_nowait_simple(<loc>, <gtid>, <lck>);
Alexey Bataev8e009032019-01-04 17:25:09 +00004252 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004253 llvm::Value *ThreadId = getThreadID(CGF, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004254
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004255 llvm::Value *Res;
Alexey Bataev8061acd2019-02-20 16:36:22 +00004256 ASTContext &C = CGM.getContext();
4257 // 1. Build a list of reduction variables.
4258 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
4259 auto Size = RHSExprs.size();
4260 for (const Expr *E : Privates) {
4261 if (E->getType()->isVariablyModifiedType())
4262 // Reserve place for array size.
4263 ++Size;
4264 }
4265 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
4266 QualType ReductionArrayTy =
4267 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
4268 /*IndexTypeQuals=*/0);
4269 Address ReductionList =
4270 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
4271 auto IPriv = Privates.begin();
4272 unsigned Idx = 0;
4273 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
4274 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
4275 CGF.Builder.CreateStore(
4276 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4277 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
4278 Elem);
4279 if ((*IPriv)->getType()->isVariablyModifiedType()) {
4280 // Store array size.
4281 ++Idx;
4282 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
4283 llvm::Value *Size = CGF.Builder.CreateIntCast(
4284 CGF.getVLASize(
4285 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
4286 .NumElts,
4287 CGF.SizeTy, /*isSigned=*/false);
4288 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
4289 Elem);
4290 }
4291 }
4292
4293 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4294 ReductionList.getPointer(), CGF.VoidPtrTy);
4295 llvm::Function *ReductionFn = emitReductionFunction(
Alexey Bataev982a35e2019-03-19 17:09:52 +00004296 Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
4297 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev8061acd2019-02-20 16:36:22 +00004298 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
4299 llvm::Function *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
4300 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
4301 llvm::Value *InterWarpCopyFn =
4302 emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
4303
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004304 if (ParallelReduction) {
Alexey Bataev8e009032019-01-04 17:25:09 +00004305 llvm::Value *Args[] = {RTLoc,
4306 ThreadId,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004307 CGF.Builder.getInt32(RHSExprs.size()),
4308 ReductionArrayTySize,
4309 RL,
4310 ShuffleAndReduceFn,
4311 InterWarpCopyFn};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004312
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004313 Res = CGF.EmitRuntimeCall(
Alexey Bataeva1166022018-11-27 21:24:54 +00004314 createNVPTXRuntimeFunction(
Alexey Bataev8061acd2019-02-20 16:36:22 +00004315 OMPRTL_NVPTX__kmpc_nvptx_parallel_reduce_nowait_v2),
4316 Args);
4317 } else {
4318 assert(TeamsReduction && "expected teams reduction.");
4319 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> VarFieldMap;
4320 llvm::SmallVector<const ValueDecl *, 4> PrivatesReductions(Privates.size());
4321 int Cnt = 0;
4322 for (const Expr *DRE : Privates) {
4323 PrivatesReductions[Cnt] = cast<DeclRefExpr>(DRE)->getDecl();
4324 ++Cnt;
4325 }
4326 const RecordDecl *TeamReductionRec = ::buildRecordForGlobalizedVars(
4327 CGM.getContext(), PrivatesReductions, llvm::None, VarFieldMap,
4328 C.getLangOpts().OpenMPCUDAReductionBufNum);
4329 TeamsReductions.push_back(TeamReductionRec);
4330 if (!KernelTeamsReductionPtr) {
4331 KernelTeamsReductionPtr = new llvm::GlobalVariable(
4332 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/true,
4333 llvm::GlobalValue::InternalLinkage, nullptr,
4334 "_openmp_teams_reductions_buffer_$_$ptr");
4335 }
4336 llvm::Value *GlobalBufferPtr = CGF.EmitLoadOfScalar(
4337 Address(KernelTeamsReductionPtr, CGM.getPointerAlign()),
4338 /*Volatile=*/false, C.getPointerType(C.VoidPtrTy), Loc);
4339 llvm::Value *GlobalToBufferCpyFn = ::emitListToGlobalCopyFunction(
4340 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
4341 llvm::Value *GlobalToBufferRedFn = ::emitListToGlobalReduceFunction(
4342 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap,
4343 ReductionFn);
4344 llvm::Value *BufferToGlobalCpyFn = ::emitGlobalToListCopyFunction(
4345 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
4346 llvm::Value *BufferToGlobalRedFn = ::emitGlobalToListReduceFunction(
4347 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap,
4348 ReductionFn);
4349
4350 llvm::Value *Args[] = {
4351 RTLoc,
4352 ThreadId,
4353 GlobalBufferPtr,
4354 CGF.Builder.getInt32(C.getLangOpts().OpenMPCUDAReductionBufNum),
4355 RL,
4356 ShuffleAndReduceFn,
4357 InterWarpCopyFn,
4358 GlobalToBufferCpyFn,
4359 GlobalToBufferRedFn,
4360 BufferToGlobalCpyFn,
4361 BufferToGlobalRedFn};
4362
4363 Res = CGF.EmitRuntimeCall(
4364 createNVPTXRuntimeFunction(
4365 OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_v2),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004366 Args);
4367 }
4368
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004369 // 5. Build if (res == 1)
4370 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.reduction.done");
4371 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.then");
4372 llvm::Value *Cond = CGF.Builder.CreateICmpEQ(
4373 Res, llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1));
4374 CGF.Builder.CreateCondBr(Cond, ThenBB, ExitBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004375
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004376 // 6. Build then branch: where we have reduced values in the master
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004377 // thread in each team.
4378 // __kmpc_end_reduce{_nowait}(<gtid>);
4379 // break;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004380 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004381
4382 // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004383 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004384 this](CodeGenFunction &CGF, PrePostActionTy &Action) {
4385 auto IPriv = Privates.begin();
4386 auto ILHS = LHSExprs.begin();
4387 auto IRHS = RHSExprs.begin();
Alexey Bataev9ff80832018-04-16 20:16:21 +00004388 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004389 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4390 cast<DeclRefExpr>(*IRHS));
4391 ++IPriv;
4392 ++ILHS;
4393 ++IRHS;
4394 }
4395 };
Alexey Bataev8061acd2019-02-20 16:36:22 +00004396 llvm::Value *EndArgs[] = {ThreadId};
4397 RegionCodeGenTy RCG(CodeGen);
4398 NVPTXActionTy Action(
4399 nullptr, llvm::None,
4400 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_reduce_nowait),
4401 EndArgs);
4402 RCG.setAction(Action);
4403 RCG(CGF);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004404 // There is no need to emit line number for unconditional branch.
4405 (void)ApplyDebugLocation::CreateEmpty(CGF);
4406 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004407}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004408
4409const VarDecl *
4410CGOpenMPRuntimeNVPTX::translateParameter(const FieldDecl *FD,
4411 const VarDecl *NativeParam) const {
4412 if (!NativeParam->getType()->isReferenceType())
4413 return NativeParam;
4414 QualType ArgType = NativeParam->getType();
4415 QualifierCollector QC;
4416 const Type *NonQualTy = QC.strip(ArgType);
4417 QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4418 if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
4419 if (Attr->getCaptureKind() == OMPC_map) {
4420 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
4421 LangAS::opencl_global);
Alexey Bataev1af5bd52019-03-05 17:47:18 +00004422 } else if (Attr->getCaptureKind() == OMPC_firstprivate &&
4423 PointeeTy.isConstant(CGM.getContext())) {
4424 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
4425 LangAS::opencl_generic);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004426 }
4427 }
4428 ArgType = CGM.getContext().getPointerType(PointeeTy);
4429 QC.addRestrict();
4430 enum { NVPTX_local_addr = 5 };
Alexander Richardson6d989432017-10-15 18:48:14 +00004431 QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004432 ArgType = QC.apply(CGM.getContext(), ArgType);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004433 if (isa<ImplicitParamDecl>(NativeParam))
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004434 return ImplicitParamDecl::Create(
4435 CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
4436 NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004437 return ParmVarDecl::Create(
4438 CGM.getContext(),
4439 const_cast<DeclContext *>(NativeParam->getDeclContext()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004440 NativeParam->getBeginLoc(), NativeParam->getLocation(),
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004441 NativeParam->getIdentifier(), ArgType,
4442 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004443}
4444
4445Address
4446CGOpenMPRuntimeNVPTX::getParameterAddress(CodeGenFunction &CGF,
4447 const VarDecl *NativeParam,
4448 const VarDecl *TargetParam) const {
4449 assert(NativeParam != TargetParam &&
4450 NativeParam->getType()->isReferenceType() &&
4451 "Native arg must not be the same as target arg.");
4452 Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
4453 QualType NativeParamType = NativeParam->getType();
4454 QualifierCollector QC;
4455 const Type *NonQualTy = QC.strip(NativeParamType);
4456 QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4457 unsigned NativePointeeAddrSpace =
Alexander Richardson6d989432017-10-15 18:48:14 +00004458 CGF.getContext().getTargetAddressSpace(NativePointeeTy);
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004459 QualType TargetTy = TargetParam->getType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004460 llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004461 LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004462 // First cast to generic.
4463 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4464 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4465 /*AddrSpace=*/0));
4466 // Cast from generic to native address space.
4467 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4468 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4469 NativePointeeAddrSpace));
4470 Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
4471 CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004472 NativeParamType);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004473 return NativeParamAddr;
4474}
4475
4476void CGOpenMPRuntimeNVPTX::emitOutlinedFunctionCall(
James Y Knight9871db02019-02-05 16:42:33 +00004477 CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn,
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004478 ArrayRef<llvm::Value *> Args) const {
4479 SmallVector<llvm::Value *, 4> TargetArgs;
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004480 TargetArgs.reserve(Args.size());
James Y Knight9871db02019-02-05 16:42:33 +00004481 auto *FnType = OutlinedFn.getFunctionType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004482 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004483 if (FnType->isVarArg() && FnType->getNumParams() <= I) {
4484 TargetArgs.append(std::next(Args.begin(), I), Args.end());
4485 break;
4486 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004487 llvm::Type *TargetType = FnType->getParamType(I);
4488 llvm::Value *NativeArg = Args[I];
4489 if (!TargetType->isPointerTy()) {
4490 TargetArgs.emplace_back(NativeArg);
4491 continue;
4492 }
4493 llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataevc99042b2018-03-15 18:10:54 +00004494 NativeArg,
4495 NativeArg->getType()->getPointerElementType()->getPointerTo());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004496 TargetArgs.emplace_back(
4497 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
4498 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00004499 CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004500}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004501
4502/// Emit function which wraps the outline parallel region
4503/// and controls the arguments which are passed to this function.
4504/// The wrapper ensures that the outlined function is called
4505/// with the correct arguments when data is shared.
4506llvm::Function *CGOpenMPRuntimeNVPTX::createParallelDataSharingWrapper(
4507 llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
4508 ASTContext &Ctx = CGM.getContext();
4509 const auto &CS = *D.getCapturedStmt(OMPD_parallel);
4510
4511 // Create a function that takes as argument the source thread.
4512 FunctionArgList WrapperArgs;
4513 QualType Int16QTy =
4514 Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
4515 QualType Int32QTy =
4516 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004517 ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004518 /*Id=*/nullptr, Int16QTy,
4519 ImplicitParamDecl::Other);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004520 ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004521 /*Id=*/nullptr, Int32QTy,
4522 ImplicitParamDecl::Other);
4523 WrapperArgs.emplace_back(&ParallelLevelArg);
4524 WrapperArgs.emplace_back(&WrapperArg);
4525
Alexey Bataev9ff80832018-04-16 20:16:21 +00004526 const CGFunctionInfo &CGFI =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004527 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
4528
4529 auto *Fn = llvm::Function::Create(
4530 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataev9ff80832018-04-16 20:16:21 +00004531 Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004532 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004533 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004534 Fn->setDoesNotRecurse();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004535
4536 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
4537 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004538 D.getBeginLoc(), D.getBeginLoc());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004539
4540 const auto *RD = CS.getCapturedRecordDecl();
4541 auto CurField = RD->field_begin();
4542
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004543 Address ZeroAddr = CGF.CreateMemTemp(
4544 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
4545 /*Name*/ ".zero.addr");
4546 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004547 // Get the array of arguments.
4548 SmallVector<llvm::Value *, 8> Args;
4549
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004550 Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).getPointer());
4551 Args.emplace_back(ZeroAddr.getPointer());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004552
4553 CGBuilderTy &Bld = CGF.Builder;
4554 auto CI = CS.capture_begin();
4555
4556 // Use global memory for data sharing.
4557 // Handle passing of global args to workers.
4558 Address GlobalArgs =
4559 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
4560 llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
4561 llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
4562 CGF.EmitRuntimeCall(
4563 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_get_shared_variables),
4564 DataSharingArgs);
4565
4566 // Retrieve the shared variables from the list of references returned
4567 // by the runtime. Pass the variables to the outlined function.
Alexey Bataev17314212018-03-20 15:41:05 +00004568 Address SharedArgListAddress = Address::invalid();
4569 if (CS.capture_size() > 0 ||
4570 isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4571 SharedArgListAddress = CGF.EmitLoadOfPointer(
4572 GlobalArgs, CGF.getContext()
4573 .getPointerType(CGF.getContext().getPointerType(
4574 CGF.getContext().VoidPtrTy))
4575 .castAs<PointerType>());
4576 }
4577 unsigned Idx = 0;
4578 if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
James Y Knight751fe282019-02-09 22:22:28 +00004579 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004580 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4581 Src, CGF.SizeTy->getPointerTo());
4582 llvm::Value *LB = CGF.EmitLoadOfScalar(
4583 TypedAddress,
4584 /*Volatile=*/false,
4585 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4586 cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
4587 Args.emplace_back(LB);
4588 ++Idx;
James Y Knight751fe282019-02-09 22:22:28 +00004589 Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004590 TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4591 Src, CGF.SizeTy->getPointerTo());
4592 llvm::Value *UB = CGF.EmitLoadOfScalar(
4593 TypedAddress,
4594 /*Volatile=*/false,
4595 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4596 cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
4597 Args.emplace_back(UB);
4598 ++Idx;
4599 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004600 if (CS.capture_size() > 0) {
4601 ASTContext &CGFContext = CGF.getContext();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004602 for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
4603 QualType ElemTy = CurField->getType();
James Y Knight751fe282019-02-09 22:22:28 +00004604 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004605 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004606 Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)));
4607 llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
4608 /*Volatile=*/false,
4609 CGFContext.getPointerType(ElemTy),
4610 CI->getLocation());
Alexey Bataev2091ca62018-04-23 17:33:41 +00004611 if (CI->capturesVariableByCopy() &&
4612 !CI->getCapturedVar()->getType()->isAnyPointerType()) {
Alexey Bataev17314212018-03-20 15:41:05 +00004613 Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
4614 CI->getLocation());
4615 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004616 Args.emplace_back(Arg);
4617 }
4618 }
4619
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004620 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedParallelFn, Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004621 CGF.FinishFunction();
4622 return Fn;
4623}
4624
4625void CGOpenMPRuntimeNVPTX::emitFunctionProlog(CodeGenFunction &CGF,
4626 const Decl *D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004627 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4628 return;
4629
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004630 assert(D && "Expected function or captured|block decl.");
4631 assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
4632 "Function is registered already.");
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004633 assert((!TeamAndReductions.first || TeamAndReductions.first == D) &&
4634 "Team is set but not processed.");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004635 const Stmt *Body = nullptr;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004636 bool NeedToDelayGlobalization = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004637 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4638 Body = FD->getBody();
4639 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
4640 Body = BD->getBody();
4641 } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
4642 Body = CD->getBody();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004643 NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
Alexey Bataev2adecff2018-09-21 14:22:53 +00004644 if (NeedToDelayGlobalization &&
4645 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
4646 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004647 }
4648 if (!Body)
4649 return;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004650 CheckVarsEscapingDeclContext VarChecker(CGF, TeamAndReductions.second);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004651 VarChecker.Visit(Body);
Alexey Bataevff23bb62018-10-11 18:30:31 +00004652 const RecordDecl *GlobalizedVarsRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004653 VarChecker.getGlobalizedRecord(IsInTTDRegion);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004654 TeamAndReductions.first = nullptr;
4655 TeamAndReductions.second.clear();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004656 ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
4657 VarChecker.getEscapedVariableLengthDecls();
4658 if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004659 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004660 auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
4661 I->getSecond().MappedParams =
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00004662 std::make_unique<CodeGenFunction::OMPMapVars>();
Alexey Bataevc99042b2018-03-15 18:10:54 +00004663 I->getSecond().GlobalRecord = GlobalizedVarsRecord;
4664 I->getSecond().EscapedParameters.insert(
4665 VarChecker.getEscapedParameters().begin(),
4666 VarChecker.getEscapedParameters().end());
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004667 I->getSecond().EscapedVariableLengthDecls.append(
4668 EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004669 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004670 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004671 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004672 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004673 Data.insert(std::make_pair(VD, MappedVarData(FD, IsInTTDRegion)));
Alexey Bataevc99042b2018-03-15 18:10:54 +00004674 }
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004675 if (!IsInTTDRegion && !NeedToDelayGlobalization && !IsInParallelRegion) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004676 CheckVarsEscapingDeclContext VarChecker(CGF, llvm::None);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004677 VarChecker.Visit(Body);
4678 I->getSecond().SecondaryGlobalRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004679 VarChecker.getGlobalizedRecord(/*IsInTTDRegion=*/true);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004680 I->getSecond().SecondaryLocalVarData.emplace();
4681 DeclToAddrMapTy &Data = I->getSecond().SecondaryLocalVarData.getValue();
4682 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
4683 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
4684 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004685 Data.insert(
4686 std::make_pair(VD, MappedVarData(FD, /*IsInTTDRegion=*/true)));
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004687 }
4688 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00004689 if (!NeedToDelayGlobalization) {
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004690 emitGenericVarsProlog(CGF, D->getBeginLoc(), /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004691 struct GlobalizationScope final : EHScopeStack::Cleanup {
4692 GlobalizationScope() = default;
4693
4694 void Emit(CodeGenFunction &CGF, Flags flags) override {
4695 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004696 .emitGenericVarsEpilog(CGF, /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004697 }
4698 };
4699 CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004700 }
4701}
4702
4703Address CGOpenMPRuntimeNVPTX::getAddressOfLocalVariable(CodeGenFunction &CGF,
4704 const VarDecl *VD) {
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004705 if (VD && VD->hasAttr<OMPAllocateDeclAttr>()) {
4706 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
4707 switch (A->getAllocatorType()) {
4708 // Use the default allocator here as by default local vars are
4709 // threadlocal.
4710 case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
4711 case OMPAllocateDeclAttr::OMPThreadMemAlloc:
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004712 case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
4713 case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
Alexey Bataev1db9bfe2019-04-08 16:53:57 +00004714 // Follow the user decision - use default allocation.
4715 return Address::invalid();
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004716 case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
Alexey Bataev1db9bfe2019-04-08 16:53:57 +00004717 // TODO: implement aupport for user-defined allocators.
4718 return Address::invalid();
4719 case OMPAllocateDeclAttr::OMPConstMemAlloc: {
4720 llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
4721 auto *GV = new llvm::GlobalVariable(
4722 CGM.getModule(), VarTy, /*isConstant=*/false,
4723 llvm::GlobalValue::InternalLinkage,
4724 llvm::Constant::getNullValue(VarTy), VD->getName(),
4725 /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
4726 CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant));
4727 CharUnits Align = CGM.getContext().getDeclAlign(VD);
4728 GV->setAlignment(Align.getQuantity());
4729 return Address(GV, Align);
4730 }
4731 case OMPAllocateDeclAttr::OMPPTeamMemAlloc: {
4732 llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
4733 auto *GV = new llvm::GlobalVariable(
4734 CGM.getModule(), VarTy, /*isConstant=*/false,
4735 llvm::GlobalValue::InternalLinkage,
4736 llvm::Constant::getNullValue(VarTy), VD->getName(),
4737 /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
4738 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
4739 CharUnits Align = CGM.getContext().getDeclAlign(VD);
4740 GV->setAlignment(Align.getQuantity());
4741 return Address(GV, Align);
4742 }
4743 case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
4744 case OMPAllocateDeclAttr::OMPCGroupMemAlloc: {
4745 llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
4746 auto *GV = new llvm::GlobalVariable(
4747 CGM.getModule(), VarTy, /*isConstant=*/false,
4748 llvm::GlobalValue::InternalLinkage,
4749 llvm::Constant::getNullValue(VarTy), VD->getName());
4750 CharUnits Align = CGM.getContext().getDeclAlign(VD);
4751 GV->setAlignment(Align.getQuantity());
4752 return Address(GV, Align);
4753 }
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004754 }
4755 }
4756
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004757 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4758 return Address::invalid();
4759
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004760 VD = VD->getCanonicalDecl();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004761 auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
4762 if (I == FunctionGlobalizedDecls.end())
4763 return Address::invalid();
Alexey Bataevc99042b2018-03-15 18:10:54 +00004764 auto VDI = I->getSecond().LocalVarData.find(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004765 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004766 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004767 if (VD->hasAttrs()) {
4768 for (specific_attr_iterator<OMPReferencedVarAttr> IT(VD->attr_begin()),
4769 E(VD->attr_end());
4770 IT != E; ++IT) {
4771 auto VDI = I->getSecond().LocalVarData.find(
4772 cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
4773 ->getCanonicalDecl());
4774 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004775 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004776 }
4777 }
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004778
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004779 return Address::invalid();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004780}
4781
4782void CGOpenMPRuntimeNVPTX::functionFinished(CodeGenFunction &CGF) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004783 FunctionGlobalizedDecls.erase(CGF.CurFn);
4784 CGOpenMPRuntime::functionFinished(CGF);
4785}
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004786
4787void CGOpenMPRuntimeNVPTX::getDefaultDistScheduleAndChunk(
4788 CodeGenFunction &CGF, const OMPLoopDirective &S,
4789 OpenMPDistScheduleClauseKind &ScheduleKind,
4790 llvm::Value *&Chunk) const {
4791 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
4792 ScheduleKind = OMPC_DIST_SCHEDULE_static;
4793 Chunk = CGF.EmitScalarConversion(getNVPTXNumThreads(CGF),
4794 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4795 S.getIterationVariable()->getType(), S.getBeginLoc());
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004796 return;
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004797 }
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004798 CGOpenMPRuntime::getDefaultDistScheduleAndChunk(
4799 CGF, S, ScheduleKind, Chunk);
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004800}
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004801
4802void CGOpenMPRuntimeNVPTX::getDefaultScheduleAndChunk(
4803 CodeGenFunction &CGF, const OMPLoopDirective &S,
4804 OpenMPScheduleClauseKind &ScheduleKind,
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004805 const Expr *&ChunkExpr) const {
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004806 ScheduleKind = OMPC_SCHEDULE_static;
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004807 // Chunk size is 1 in this case.
4808 llvm::APInt ChunkSize(32, 1);
4809 ChunkExpr = IntegerLiteral::Create(CGF.getContext(), ChunkSize,
4810 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4811 SourceLocation());
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004812}
Alexey Bataev60705422018-10-30 15:50:12 +00004813
4814void CGOpenMPRuntimeNVPTX::adjustTargetSpecificDataForLambdas(
4815 CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
4816 assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
4817 " Expected target-based directive.");
4818 const CapturedStmt *CS = D.getCapturedStmt(OMPD_target);
4819 for (const CapturedStmt::Capture &C : CS->captures()) {
4820 // Capture variables captured by reference in lambdas for target-based
4821 // directives.
4822 if (!C.capturesVariable())
4823 continue;
4824 const VarDecl *VD = C.getCapturedVar();
4825 const auto *RD = VD->getType()
4826 .getCanonicalType()
4827 .getNonReferenceType()
4828 ->getAsCXXRecordDecl();
4829 if (!RD || !RD->isLambda())
4830 continue;
4831 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4832 LValue VDLVal;
4833 if (VD->getType().getCanonicalType()->isReferenceType())
4834 VDLVal = CGF.EmitLoadOfReferenceLValue(VDAddr, VD->getType());
4835 else
4836 VDLVal = CGF.MakeAddrLValue(
4837 VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
4838 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4839 FieldDecl *ThisCapture = nullptr;
4840 RD->getCaptureFields(Captures, ThisCapture);
4841 if (ThisCapture && CGF.CapturedStmtInfo->isCXXThisExprCaptured()) {
4842 LValue ThisLVal =
4843 CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
4844 llvm::Value *CXXThis = CGF.LoadCXXThis();
4845 CGF.EmitStoreOfScalar(CXXThis, ThisLVal);
4846 }
4847 for (const LambdaCapture &LC : RD->captures()) {
4848 if (LC.getCaptureKind() != LCK_ByRef)
4849 continue;
4850 const VarDecl *VD = LC.getCapturedVar();
4851 if (!CS->capturesVariable(VD))
4852 continue;
4853 auto It = Captures.find(VD);
4854 assert(It != Captures.end() && "Found lambda capture without field.");
4855 LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
4856 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4857 if (VD->getType().getCanonicalType()->isReferenceType())
4858 VDAddr = CGF.EmitLoadOfReferenceLValue(VDAddr,
4859 VD->getType().getCanonicalType())
4860 .getAddress();
4861 CGF.EmitStoreOfScalar(VDAddr.getPointer(), VarLVal);
4862 }
4863 }
4864}
4865
Alexey Bataev1af5bd52019-03-05 17:47:18 +00004866unsigned CGOpenMPRuntimeNVPTX::getDefaultFirstprivateAddressSpace() const {
4867 return CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant);
4868}
4869
Alexey Bataevc5687252019-03-21 19:35:27 +00004870bool CGOpenMPRuntimeNVPTX::hasAllocateAttributeForGlobalVar(const VarDecl *VD,
4871 LangAS &AS) {
4872 if (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())
4873 return false;
4874 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
4875 switch(A->getAllocatorType()) {
4876 case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
4877 // Not supported, fallback to the default mem space.
4878 case OMPAllocateDeclAttr::OMPThreadMemAlloc:
4879 case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
4880 case OMPAllocateDeclAttr::OMPCGroupMemAlloc:
4881 case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
4882 case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
4883 AS = LangAS::Default;
4884 return true;
4885 case OMPAllocateDeclAttr::OMPConstMemAlloc:
4886 AS = LangAS::cuda_constant;
4887 return true;
4888 case OMPAllocateDeclAttr::OMPPTeamMemAlloc:
4889 AS = LangAS::cuda_shared;
4890 return true;
4891 case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
4892 llvm_unreachable("Expected predefined allocator for the variables with the "
4893 "static storage.");
4894 }
4895 return false;
4896}
4897
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004898// Get current CudaArch and ignore any unknown values
4899static CudaArch getCudaArch(CodeGenModule &CGM) {
4900 if (!CGM.getTarget().hasFeature("ptx"))
4901 return CudaArch::UNKNOWN;
4902 llvm::StringMap<bool> Features;
4903 CGM.getTarget().initFeatureMap(Features, CGM.getDiags(),
4904 CGM.getTarget().getTargetOpts().CPU,
4905 CGM.getTarget().getTargetOpts().Features);
4906 for (const auto &Feature : Features) {
4907 if (Feature.getValue()) {
4908 CudaArch Arch = StringToCudaArch(Feature.getKey());
4909 if (Arch != CudaArch::UNKNOWN)
4910 return Arch;
4911 }
4912 }
4913 return CudaArch::UNKNOWN;
4914}
4915
4916/// Check to see if target architecture supports unified addressing which is
4917/// a restriction for OpenMP requires clause "unified_shared_memory".
4918void CGOpenMPRuntimeNVPTX::checkArchForUnifiedAddressing(
Gheorghe-Teodor Bercea66cdbb472019-05-21 19:42:01 +00004919 const OMPRequiresDecl *D) {
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004920 for (const OMPClause *Clause : D->clauselists()) {
4921 if (Clause->getClauseKind() == OMPC_unified_shared_memory) {
4922 switch (getCudaArch(CGM)) {
4923 case CudaArch::SM_20:
4924 case CudaArch::SM_21:
4925 case CudaArch::SM_30:
4926 case CudaArch::SM_32:
4927 case CudaArch::SM_35:
4928 case CudaArch::SM_37:
4929 case CudaArch::SM_50:
4930 case CudaArch::SM_52:
4931 case CudaArch::SM_53:
4932 case CudaArch::SM_60:
4933 case CudaArch::SM_61:
4934 case CudaArch::SM_62:
4935 CGM.Error(Clause->getBeginLoc(),
4936 "Target architecture does not support unified addressing");
4937 return;
4938 case CudaArch::SM_70:
4939 case CudaArch::SM_72:
4940 case CudaArch::SM_75:
4941 case CudaArch::GFX600:
4942 case CudaArch::GFX601:
4943 case CudaArch::GFX700:
4944 case CudaArch::GFX701:
4945 case CudaArch::GFX702:
4946 case CudaArch::GFX703:
4947 case CudaArch::GFX704:
4948 case CudaArch::GFX801:
4949 case CudaArch::GFX802:
4950 case CudaArch::GFX803:
4951 case CudaArch::GFX810:
4952 case CudaArch::GFX900:
4953 case CudaArch::GFX902:
4954 case CudaArch::GFX904:
4955 case CudaArch::GFX906:
Stanislav Mekhanoshin0cfd75a2019-07-09 18:19:00 +00004956 case CudaArch::GFX908:
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004957 case CudaArch::GFX909:
Yaxun Liu6add24a2019-07-11 17:50:09 +00004958 case CudaArch::GFX1010:
4959 case CudaArch::GFX1011:
4960 case CudaArch::GFX1012:
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004961 case CudaArch::UNKNOWN:
4962 break;
4963 case CudaArch::LAST:
4964 llvm_unreachable("Unexpected Cuda arch.");
4965 }
4966 }
4967 }
Gheorghe-Teodor Bercea66cdbb472019-05-21 19:42:01 +00004968 CGOpenMPRuntime::checkArchForUnifiedAddressing(D);
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004969}
4970
Alexey Bataeve4090182018-11-02 14:54:07 +00004971/// Get number of SMs and number of blocks per SM.
4972static std::pair<unsigned, unsigned> getSMsBlocksPerSM(CodeGenModule &CGM) {
4973 std::pair<unsigned, unsigned> Data;
4974 if (CGM.getLangOpts().OpenMPCUDANumSMs)
4975 Data.first = CGM.getLangOpts().OpenMPCUDANumSMs;
4976 if (CGM.getLangOpts().OpenMPCUDABlocksPerSM)
4977 Data.second = CGM.getLangOpts().OpenMPCUDABlocksPerSM;
4978 if (Data.first && Data.second)
4979 return Data;
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004980 switch (getCudaArch(CGM)) {
4981 case CudaArch::SM_20:
4982 case CudaArch::SM_21:
4983 case CudaArch::SM_30:
4984 case CudaArch::SM_32:
4985 case CudaArch::SM_35:
4986 case CudaArch::SM_37:
4987 case CudaArch::SM_50:
4988 case CudaArch::SM_52:
4989 case CudaArch::SM_53:
4990 return {16, 16};
4991 case CudaArch::SM_60:
4992 case CudaArch::SM_61:
4993 case CudaArch::SM_62:
4994 return {56, 32};
4995 case CudaArch::SM_70:
4996 case CudaArch::SM_72:
4997 case CudaArch::SM_75:
4998 return {84, 32};
4999 case CudaArch::GFX600:
5000 case CudaArch::GFX601:
5001 case CudaArch::GFX700:
5002 case CudaArch::GFX701:
5003 case CudaArch::GFX702:
5004 case CudaArch::GFX703:
5005 case CudaArch::GFX704:
5006 case CudaArch::GFX801:
5007 case CudaArch::GFX802:
5008 case CudaArch::GFX803:
5009 case CudaArch::GFX810:
5010 case CudaArch::GFX900:
5011 case CudaArch::GFX902:
5012 case CudaArch::GFX904:
5013 case CudaArch::GFX906:
Stanislav Mekhanoshin0cfd75a2019-07-09 18:19:00 +00005014 case CudaArch::GFX908:
Patrick Lyster8f7f5862018-11-19 15:09:33 +00005015 case CudaArch::GFX909:
Yaxun Liu6add24a2019-07-11 17:50:09 +00005016 case CudaArch::GFX1010:
5017 case CudaArch::GFX1011:
5018 case CudaArch::GFX1012:
Patrick Lyster8f7f5862018-11-19 15:09:33 +00005019 case CudaArch::UNKNOWN:
5020 break;
5021 case CudaArch::LAST:
5022 llvm_unreachable("Unexpected Cuda arch.");
Alexey Bataeve4090182018-11-02 14:54:07 +00005023 }
5024 llvm_unreachable("Unexpected NVPTX target without ptx feature.");
5025}
5026
5027void CGOpenMPRuntimeNVPTX::clear() {
5028 if (!GlobalizedRecords.empty()) {
5029 ASTContext &C = CGM.getContext();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005030 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> GlobalRecs;
5031 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> SharedRecs;
Alexey Bataeve4090182018-11-02 14:54:07 +00005032 RecordDecl *StaticRD = C.buildImplicitRecord(
5033 "_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
5034 StaticRD->startDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005035 RecordDecl *SharedStaticRD = C.buildImplicitRecord(
5036 "_shared_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
5037 SharedStaticRD->startDefinition();
Alexey Bataeve4090182018-11-02 14:54:07 +00005038 for (const GlobalPtrSizeRecsTy &Records : GlobalizedRecords) {
5039 if (Records.Records.empty())
5040 continue;
5041 unsigned Size = 0;
5042 unsigned RecAlignment = 0;
5043 for (const RecordDecl *RD : Records.Records) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005044 QualType RDTy = C.getRecordType(RD);
5045 unsigned Alignment = C.getTypeAlignInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00005046 RecAlignment = std::max(RecAlignment, Alignment);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005047 unsigned RecSize = C.getTypeSizeInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00005048 Size =
5049 llvm::alignTo(llvm::alignTo(Size, Alignment) + RecSize, Alignment);
5050 }
5051 Size = llvm::alignTo(Size, RecAlignment);
5052 llvm::APInt ArySize(/*numBits=*/64, Size);
5053 QualType SubTy = C.getConstantArrayType(
5054 C.CharTy, ArySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005055 const bool UseSharedMemory = Size <= SharedMemorySize;
5056 auto *Field =
5057 FieldDecl::Create(C, UseSharedMemory ? SharedStaticRD : StaticRD,
5058 SourceLocation(), SourceLocation(), nullptr, SubTy,
5059 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
5060 /*BW=*/nullptr, /*Mutable=*/false,
5061 /*InitStyle=*/ICIS_NoInit);
Alexey Bataeve4090182018-11-02 14:54:07 +00005062 Field->setAccess(AS_public);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005063 if (UseSharedMemory) {
5064 SharedStaticRD->addDecl(Field);
5065 SharedRecs.push_back(&Records);
5066 } else {
5067 StaticRD->addDecl(Field);
5068 GlobalRecs.push_back(&Records);
5069 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005070 Records.RecSize->setInitializer(llvm::ConstantInt::get(CGM.SizeTy, Size));
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005071 Records.UseSharedMemory->setInitializer(
5072 llvm::ConstantInt::get(CGM.Int16Ty, UseSharedMemory ? 1 : 0));
5073 }
Alexey Bataev6a1b06b2018-12-18 21:01:42 +00005074 // Allocate SharedMemorySize buffer for the shared memory.
5075 // FIXME: nvlink does not handle weak linkage correctly (object with the
5076 // different size are reported as erroneous).
5077 // Restore this code as sson as nvlink is fixed.
5078 if (!SharedStaticRD->field_empty()) {
5079 llvm::APInt ArySize(/*numBits=*/64, SharedMemorySize);
5080 QualType SubTy = C.getConstantArrayType(
5081 C.CharTy, ArySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
5082 auto *Field = FieldDecl::Create(
5083 C, SharedStaticRD, SourceLocation(), SourceLocation(), nullptr, SubTy,
5084 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
5085 /*BW=*/nullptr, /*Mutable=*/false,
5086 /*InitStyle=*/ICIS_NoInit);
5087 Field->setAccess(AS_public);
5088 SharedStaticRD->addDecl(Field);
5089 }
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005090 SharedStaticRD->completeDefinition();
5091 if (!SharedStaticRD->field_empty()) {
5092 QualType StaticTy = C.getRecordType(SharedStaticRD);
5093 llvm::Type *LLVMStaticTy = CGM.getTypes().ConvertTypeForMem(StaticTy);
5094 auto *GV = new llvm::GlobalVariable(
5095 CGM.getModule(), LLVMStaticTy,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00005096 /*isConstant=*/false, llvm::GlobalValue::CommonLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005097 llvm::Constant::getNullValue(LLVMStaticTy),
5098 "_openmp_shared_static_glob_rd_$_", /*InsertBefore=*/nullptr,
5099 llvm::GlobalValue::NotThreadLocal,
5100 C.getTargetAddressSpace(LangAS::cuda_shared));
5101 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
5102 GV, CGM.VoidPtrTy);
5103 for (const GlobalPtrSizeRecsTy *Rec : SharedRecs) {
5104 Rec->Buffer->replaceAllUsesWith(Replacement);
5105 Rec->Buffer->eraseFromParent();
5106 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005107 }
5108 StaticRD->completeDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005109 if (!StaticRD->field_empty()) {
5110 QualType StaticTy = C.getRecordType(StaticRD);
5111 std::pair<unsigned, unsigned> SMsBlockPerSM = getSMsBlocksPerSM(CGM);
5112 llvm::APInt Size1(32, SMsBlockPerSM.second);
5113 QualType Arr1Ty =
5114 C.getConstantArrayType(StaticTy, Size1, ArrayType::Normal,
5115 /*IndexTypeQuals=*/0);
5116 llvm::APInt Size2(32, SMsBlockPerSM.first);
5117 QualType Arr2Ty = C.getConstantArrayType(Arr1Ty, Size2, ArrayType::Normal,
5118 /*IndexTypeQuals=*/0);
5119 llvm::Type *LLVMArr2Ty = CGM.getTypes().ConvertTypeForMem(Arr2Ty);
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005120 // FIXME: nvlink does not handle weak linkage correctly (object with the
5121 // different size are reported as erroneous).
5122 // Restore CommonLinkage as soon as nvlink is fixed.
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005123 auto *GV = new llvm::GlobalVariable(
5124 CGM.getModule(), LLVMArr2Ty,
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005125 /*isConstant=*/false, llvm::GlobalValue::InternalLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005126 llvm::Constant::getNullValue(LLVMArr2Ty),
5127 "_openmp_static_glob_rd_$_");
5128 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
5129 GV, CGM.VoidPtrTy);
5130 for (const GlobalPtrSizeRecsTy *Rec : GlobalRecs) {
5131 Rec->Buffer->replaceAllUsesWith(Replacement);
5132 Rec->Buffer->eraseFromParent();
5133 }
5134 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005135 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00005136 if (!TeamsReductions.empty()) {
5137 ASTContext &C = CGM.getContext();
5138 RecordDecl *StaticRD = C.buildImplicitRecord(
5139 "_openmp_teams_reduction_type_$_", RecordDecl::TagKind::TTK_Union);
5140 StaticRD->startDefinition();
5141 for (const RecordDecl *TeamReductionRec : TeamsReductions) {
5142 QualType RecTy = C.getRecordType(TeamReductionRec);
5143 auto *Field = FieldDecl::Create(
5144 C, StaticRD, SourceLocation(), SourceLocation(), nullptr, RecTy,
5145 C.getTrivialTypeSourceInfo(RecTy, SourceLocation()),
5146 /*BW=*/nullptr, /*Mutable=*/false,
5147 /*InitStyle=*/ICIS_NoInit);
5148 Field->setAccess(AS_public);
5149 StaticRD->addDecl(Field);
5150 }
5151 StaticRD->completeDefinition();
5152 QualType StaticTy = C.getRecordType(StaticRD);
5153 llvm::Type *LLVMReductionsBufferTy =
5154 CGM.getTypes().ConvertTypeForMem(StaticTy);
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005155 // FIXME: nvlink does not handle weak linkage correctly (object with the
5156 // different size are reported as erroneous).
5157 // Restore CommonLinkage as soon as nvlink is fixed.
Alexey Bataev8061acd2019-02-20 16:36:22 +00005158 auto *GV = new llvm::GlobalVariable(
5159 CGM.getModule(), LLVMReductionsBufferTy,
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005160 /*isConstant=*/false, llvm::GlobalValue::InternalLinkage,
Alexey Bataev8061acd2019-02-20 16:36:22 +00005161 llvm::Constant::getNullValue(LLVMReductionsBufferTy),
5162 "_openmp_teams_reductions_buffer_$_");
5163 KernelTeamsReductionPtr->setInitializer(
5164 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
5165 CGM.VoidPtrTy));
5166 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005167 CGOpenMPRuntime::clear();
5168}