blob: 09042b92d83b211011953aefdb61ce65042b9001 [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(
Erich Keane6a24e802019-09-13 17:39:31 +0000294 C, /*IsAlignmentExpr=*/true,
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000295 IntegerLiteral::Create(C, Align,
296 C.getIntTypeForBitwidth(32, /*Signed=*/0),
Erich Keane6a24e802019-09-13 17:39:31 +0000297 SourceLocation()),
298 {}, AttributeCommonInfo::AS_GNU, AlignedAttr::GNU_aligned));
Alexey Bataev2adecff2018-09-21 14:22:53 +0000299 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000300 GlobalizedRD->addDecl(Field);
Alexey Bataev2adecff2018-09-21 14:22:53 +0000301 MappedDeclsFields.try_emplace(VD, Field);
302 }
303 GlobalizedRD->completeDefinition();
304 return GlobalizedRD;
305}
306
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000307/// Get the list of variables that can escape their declaration context.
308class CheckVarsEscapingDeclContext final
309 : public ConstStmtVisitor<CheckVarsEscapingDeclContext> {
310 CodeGenFunction &CGF;
311 llvm::SetVector<const ValueDecl *> EscapedDecls;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000312 llvm::SetVector<const ValueDecl *> EscapedVariableLengthDecls;
Alexey Bataevc99042b2018-03-15 18:10:54 +0000313 llvm::SmallPtrSet<const Decl *, 4> EscapedParameters;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000314 RecordDecl *GlobalizedRD = nullptr;
315 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000316 bool AllEscaped = false;
Alexey Bataev91433f62018-06-26 17:24:03 +0000317 bool IsForCombinedParallelRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000318
319 void markAsEscaped(const ValueDecl *VD) {
Alexey Bataev03f270c2018-03-30 18:31:07 +0000320 // Do not globalize declare target variables.
Alexey Bataev97b72212018-08-14 18:31:20 +0000321 if (!isa<VarDecl>(VD) ||
322 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataev03f270c2018-03-30 18:31:07 +0000323 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000324 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataev1db9bfe2019-04-08 16:53:57 +0000325 // Use user-specified allocation.
326 if (VD->hasAttrs() && VD->hasAttr<OMPAllocateDeclAttr>())
327 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +0000328 // Variables captured by value must be globalized.
329 if (auto *CSI = CGF.CapturedStmtInfo) {
Mikael Holmen9f373a32018-03-16 07:27:57 +0000330 if (const FieldDecl *FD = CSI->lookup(cast<VarDecl>(VD))) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000331 // Check if need to capture the variable that was already captured by
332 // value in the outer region.
Alexey Bataev91433f62018-06-26 17:24:03 +0000333 if (!IsForCombinedParallelRegion) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000334 if (!FD->hasAttrs())
335 return;
336 const auto *Attr = FD->getAttr<OMPCaptureKindAttr>();
337 if (!Attr)
338 return;
Alexey Bataev6393eb72018-12-06 15:35:13 +0000339 if (((Attr->getCaptureKind() != OMPC_map) &&
340 !isOpenMPPrivate(
341 static_cast<OpenMPClauseKind>(Attr->getCaptureKind()))) ||
342 ((Attr->getCaptureKind() == OMPC_map) &&
343 !FD->getType()->isAnyPointerType()))
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000344 return;
345 }
346 if (!FD->getType()->isReferenceType()) {
347 assert(!VD->getType()->isVariablyModifiedType() &&
348 "Parameter captured by value with variably modified type");
349 EscapedParameters.insert(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000350 } else if (!IsForCombinedParallelRegion) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000351 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000352 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000353 }
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000354 }
355 if ((!CGF.CapturedStmtInfo ||
Alexey Bataev91433f62018-06-26 17:24:03 +0000356 (IsForCombinedParallelRegion && CGF.CapturedStmtInfo)) &&
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000357 VD->getType()->isReferenceType())
358 // Do not globalize variables with reference type.
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000359 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000360 if (VD->getType()->isVariablyModifiedType())
361 EscapedVariableLengthDecls.insert(VD);
362 else
363 EscapedDecls.insert(VD);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000364 }
365
366 void VisitValueDecl(const ValueDecl *VD) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000367 if (VD->getType()->isLValueReferenceType())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000368 markAsEscaped(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000369 if (const auto *VarD = dyn_cast<VarDecl>(VD)) {
370 if (!isa<ParmVarDecl>(VarD) && VarD->hasInit()) {
371 const bool SavedAllEscaped = AllEscaped;
372 AllEscaped = VD->getType()->isLValueReferenceType();
373 Visit(VarD->getInit());
374 AllEscaped = SavedAllEscaped;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000375 }
376 }
377 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000378 void VisitOpenMPCapturedStmt(const CapturedStmt *S,
379 ArrayRef<OMPClause *> Clauses,
380 bool IsCombinedParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000381 if (!S)
382 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000383 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000384 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
385 const ValueDecl *VD = C.getCapturedVar();
Alexey Bataev91433f62018-06-26 17:24:03 +0000386 bool SavedIsForCombinedParallelRegion = IsForCombinedParallelRegion;
387 if (IsCombinedParallelRegion) {
388 // Check if the variable is privatized in the combined construct and
389 // those private copies must be shared in the inner parallel
390 // directive.
391 IsForCombinedParallelRegion = false;
392 for (const OMPClause *C : Clauses) {
393 if (!isOpenMPPrivate(C->getClauseKind()) ||
394 C->getClauseKind() == OMPC_reduction ||
395 C->getClauseKind() == OMPC_linear ||
396 C->getClauseKind() == OMPC_private)
397 continue;
398 ArrayRef<const Expr *> Vars;
399 if (const auto *PC = dyn_cast<OMPFirstprivateClause>(C))
400 Vars = PC->getVarRefs();
401 else if (const auto *PC = dyn_cast<OMPLastprivateClause>(C))
402 Vars = PC->getVarRefs();
403 else
404 llvm_unreachable("Unexpected clause.");
405 for (const auto *E : Vars) {
406 const Decl *D =
407 cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
408 if (D == VD->getCanonicalDecl()) {
409 IsForCombinedParallelRegion = true;
410 break;
411 }
412 }
413 if (IsForCombinedParallelRegion)
414 break;
415 }
416 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000417 markAsEscaped(VD);
418 if (isa<OMPCapturedExprDecl>(VD))
419 VisitValueDecl(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000420 IsForCombinedParallelRegion = SavedIsForCombinedParallelRegion;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000421 }
422 }
423 }
424
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000425 void buildRecordForGlobalizedVars(bool IsInTTDRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000426 assert(!GlobalizedRD &&
427 "Record for globalized variables is built already.");
Alexey Bataevff23bb62018-10-11 18:30:31 +0000428 ArrayRef<const ValueDecl *> EscapedDeclsForParallel, EscapedDeclsForTeams;
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000429 if (IsInTTDRegion)
Alexey Bataevff23bb62018-10-11 18:30:31 +0000430 EscapedDeclsForTeams = EscapedDecls.getArrayRef();
431 else
432 EscapedDeclsForParallel = EscapedDecls.getArrayRef();
Alexey Bataev2adecff2018-09-21 14:22:53 +0000433 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataevff23bb62018-10-11 18:30:31 +0000434 CGF.getContext(), EscapedDeclsForParallel, EscapedDeclsForTeams,
Alexey Bataev8061acd2019-02-20 16:36:22 +0000435 MappedDeclsFields, WarpSize);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000436 }
437
438public:
Alexey Bataevf2f39be2018-11-16 19:38:21 +0000439 CheckVarsEscapingDeclContext(CodeGenFunction &CGF,
440 ArrayRef<const ValueDecl *> TeamsReductions)
441 : CGF(CGF), EscapedDecls(TeamsReductions.begin(), TeamsReductions.end()) {
442 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000443 virtual ~CheckVarsEscapingDeclContext() = default;
444 void VisitDeclStmt(const DeclStmt *S) {
445 if (!S)
446 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000447 for (const Decl *D : S->decls())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000448 if (const auto *VD = dyn_cast_or_null<ValueDecl>(D))
449 VisitValueDecl(VD);
450 }
451 void VisitOMPExecutableDirective(const OMPExecutableDirective *D) {
452 if (!D)
453 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000454 if (!D->hasAssociatedStmt())
455 return;
456 if (const auto *S =
457 dyn_cast_or_null<CapturedStmt>(D->getAssociatedStmt())) {
458 // Do not analyze directives that do not actually require capturing,
459 // like `omp for` or `omp simd` directives.
460 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
461 getOpenMPCaptureRegions(CaptureRegions, D->getDirectiveKind());
462 if (CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown) {
463 VisitStmt(S->getCapturedStmt());
464 return;
Alexey Bataev673110d2018-05-16 13:36:30 +0000465 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000466 VisitOpenMPCapturedStmt(
467 S, D->clauses(),
468 CaptureRegions.back() == OMPD_parallel &&
469 isOpenMPDistributeDirective(D->getDirectiveKind()));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000470 }
471 }
472 void VisitCapturedStmt(const CapturedStmt *S) {
473 if (!S)
474 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000475 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000476 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
477 const ValueDecl *VD = C.getCapturedVar();
478 markAsEscaped(VD);
479 if (isa<OMPCapturedExprDecl>(VD))
480 VisitValueDecl(VD);
481 }
482 }
483 }
484 void VisitLambdaExpr(const LambdaExpr *E) {
485 if (!E)
486 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000487 for (const LambdaCapture &C : E->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000488 if (C.capturesVariable()) {
489 if (C.getCaptureKind() == LCK_ByRef) {
490 const ValueDecl *VD = C.getCapturedVar();
491 markAsEscaped(VD);
492 if (E->isInitCapture(&C) || isa<OMPCapturedExprDecl>(VD))
493 VisitValueDecl(VD);
494 }
495 }
496 }
497 }
498 void VisitBlockExpr(const BlockExpr *E) {
499 if (!E)
500 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000501 for (const BlockDecl::Capture &C : E->getBlockDecl()->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000502 if (C.isByRef()) {
503 const VarDecl *VD = C.getVariable();
504 markAsEscaped(VD);
505 if (isa<OMPCapturedExprDecl>(VD) || VD->isInitCapture())
506 VisitValueDecl(VD);
507 }
508 }
509 }
510 void VisitCallExpr(const CallExpr *E) {
511 if (!E)
512 return;
513 for (const Expr *Arg : E->arguments()) {
514 if (!Arg)
515 continue;
516 if (Arg->isLValue()) {
517 const bool SavedAllEscaped = AllEscaped;
518 AllEscaped = true;
519 Visit(Arg);
520 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000521 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000522 Visit(Arg);
Alexey Bataev9ff80832018-04-16 20:16:21 +0000523 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000524 }
525 Visit(E->getCallee());
526 }
527 void VisitDeclRefExpr(const DeclRefExpr *E) {
528 if (!E)
529 return;
530 const ValueDecl *VD = E->getDecl();
531 if (AllEscaped)
532 markAsEscaped(VD);
533 if (isa<OMPCapturedExprDecl>(VD))
534 VisitValueDecl(VD);
535 else if (const auto *VarD = dyn_cast<VarDecl>(VD))
536 if (VarD->isInitCapture())
537 VisitValueDecl(VD);
538 }
539 void VisitUnaryOperator(const UnaryOperator *E) {
540 if (!E)
541 return;
542 if (E->getOpcode() == UO_AddrOf) {
543 const bool SavedAllEscaped = AllEscaped;
544 AllEscaped = true;
545 Visit(E->getSubExpr());
546 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000547 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000548 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000549 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000550 }
551 void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
552 if (!E)
553 return;
554 if (E->getCastKind() == CK_ArrayToPointerDecay) {
555 const bool SavedAllEscaped = AllEscaped;
556 AllEscaped = true;
557 Visit(E->getSubExpr());
558 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000559 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000560 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000561 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000562 }
563 void VisitExpr(const Expr *E) {
564 if (!E)
565 return;
566 bool SavedAllEscaped = AllEscaped;
567 if (!E->isLValue())
568 AllEscaped = false;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000569 for (const Stmt *Child : E->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000570 if (Child)
571 Visit(Child);
572 AllEscaped = SavedAllEscaped;
573 }
574 void VisitStmt(const Stmt *S) {
575 if (!S)
576 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000577 for (const Stmt *Child : S->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000578 if (Child)
579 Visit(Child);
580 }
581
Alexey Bataevc99042b2018-03-15 18:10:54 +0000582 /// Returns the record that handles all the escaped local variables and used
583 /// instead of their original storage.
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000584 const RecordDecl *getGlobalizedRecord(bool IsInTTDRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000585 if (!GlobalizedRD)
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000586 buildRecordForGlobalizedVars(IsInTTDRegion);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000587 return GlobalizedRD;
588 }
589
Alexey Bataevc99042b2018-03-15 18:10:54 +0000590 /// Returns the field in the globalized record for the escaped variable.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000591 const FieldDecl *getFieldForGlobalizedVar(const ValueDecl *VD) const {
592 assert(GlobalizedRD &&
593 "Record for globalized variables must be generated already.");
594 auto I = MappedDeclsFields.find(VD);
595 if (I == MappedDeclsFields.end())
596 return nullptr;
597 return I->getSecond();
598 }
599
Alexey Bataevc99042b2018-03-15 18:10:54 +0000600 /// Returns the list of the escaped local variables/parameters.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000601 ArrayRef<const ValueDecl *> getEscapedDecls() const {
602 return EscapedDecls.getArrayRef();
603 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000604
605 /// Checks if the escaped local variable is actually a parameter passed by
606 /// value.
607 const llvm::SmallPtrSetImpl<const Decl *> &getEscapedParameters() const {
608 return EscapedParameters;
609 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000610
611 /// Returns the list of the escaped variables with the variably modified
612 /// types.
613 ArrayRef<const ValueDecl *> getEscapedVariableLengthDecls() const {
614 return EscapedVariableLengthDecls.getArrayRef();
615 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000616};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000617} // anonymous namespace
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000618
619/// Get the GPU warp size.
620static llvm::Value *getNVPTXWarpSize(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000621 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000622 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000623 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_warpsize),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000624 "nvptx_warp_size");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000625}
626
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000627/// Get the id of the current thread on the GPU.
628static llvm::Value *getNVPTXThreadID(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000629 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000630 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000631 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_tid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000632 "nvptx_tid");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000633}
634
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000635/// Get the id of the warp in the block.
636/// We assume that the warp size is 32, which is always the case
637/// on the NVPTX device, to generate more efficient code.
638static llvm::Value *getNVPTXWarpID(CodeGenFunction &CGF) {
639 CGBuilderTy &Bld = CGF.Builder;
640 return Bld.CreateAShr(getNVPTXThreadID(CGF), LaneIDBits, "nvptx_warp_id");
641}
642
643/// Get the id of the current lane in the Warp.
644/// We assume that the warp size is 32, which is always the case
645/// on the NVPTX device, to generate more efficient code.
646static llvm::Value *getNVPTXLaneID(CodeGenFunction &CGF) {
647 CGBuilderTy &Bld = CGF.Builder;
648 return Bld.CreateAnd(getNVPTXThreadID(CGF), Bld.getInt32(LaneIDMask),
649 "nvptx_lane_id");
650}
651
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000652/// Get the maximum number of threads in a block of the GPU.
653static llvm::Value *getNVPTXNumThreads(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000654 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000655 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000656 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_ntid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000657 "nvptx_num_threads");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000658}
659
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000660/// Get the value of the thread_limit clause in the teams directive.
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000661/// For the 'generic' execution mode, the runtime encodes thread_limit in
662/// the launch parameters, always starting thread_limit+warpSize threads per
663/// CTA. The threads in the last warp are reserved for master execution.
664/// For the 'spmd' execution mode, all threads in a CTA are part of the team.
665static llvm::Value *getThreadLimit(CodeGenFunction &CGF,
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000666 bool IsInSPMDExecutionMode = false) {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000667 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000668 return IsInSPMDExecutionMode
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000669 ? getNVPTXNumThreads(CGF)
Alexey Bataeve290ec02018-04-06 16:03:36 +0000670 : Bld.CreateNUWSub(getNVPTXNumThreads(CGF), getNVPTXWarpSize(CGF),
671 "thread_limit");
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000672}
673
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000674/// Get the thread id of the OMP master thread.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000675/// The master thread id is the first thread (lane) of the last warp in the
676/// GPU block. Warp size is assumed to be some power of 2.
677/// Thread id is 0 indexed.
678/// E.g: If NumThreads is 33, master id is 32.
679/// If NumThreads is 64, master id is 32.
680/// If NumThreads is 1024, master id is 992.
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000681static llvm::Value *getMasterThreadID(CodeGenFunction &CGF) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000682 CGBuilderTy &Bld = CGF.Builder;
683 llvm::Value *NumThreads = getNVPTXNumThreads(CGF);
684
685 // We assume that the warp size is a power of 2.
Alexey Bataeve290ec02018-04-06 16:03:36 +0000686 llvm::Value *Mask = Bld.CreateNUWSub(getNVPTXWarpSize(CGF), Bld.getInt32(1));
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000687
Alexey Bataeve290ec02018-04-06 16:03:36 +0000688 return Bld.CreateAnd(Bld.CreateNUWSub(NumThreads, Bld.getInt32(1)),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000689 Bld.CreateNot(Mask), "master_tid");
690}
691
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000692CGOpenMPRuntimeNVPTX::WorkerFunctionState::WorkerFunctionState(
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000693 CodeGenModule &CGM, SourceLocation Loc)
Alexey Bataev9ff80832018-04-16 20:16:21 +0000694 : WorkerFn(nullptr), CGFI(CGM.getTypes().arrangeNullaryFunction()),
695 Loc(Loc) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000696 createWorkerFunction(CGM);
Vasileios Kalintirise5c09592016-03-22 10:41:20 +0000697}
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000698
699void CGOpenMPRuntimeNVPTX::WorkerFunctionState::createWorkerFunction(
700 CodeGenModule &CGM) {
701 // Create an worker function with no arguments.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000702
703 WorkerFn = llvm::Function::Create(
Alexey Bataev9ff80832018-04-16 20:16:21 +0000704 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataevaee93892018-01-08 20:09:47 +0000705 /*placeholder=*/"_worker", &CGM.getModule());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000706 CGM.SetInternalFunctionAttributes(GlobalDecl(), WorkerFn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +0000707 WorkerFn->setDoesNotRecurse();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000708}
709
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000710CGOpenMPRuntimeNVPTX::ExecutionMode
711CGOpenMPRuntimeNVPTX::getExecutionMode() const {
712 return CurrentExecutionMode;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000713}
714
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000715static CGOpenMPRuntimeNVPTX::DataSharingMode
716getDataSharingMode(CodeGenModule &CGM) {
717 return CGM.getLangOpts().OpenMPCUDAMode ? CGOpenMPRuntimeNVPTX::CUDA
718 : CGOpenMPRuntimeNVPTX::Generic;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000719}
720
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000721/// Check for inner (nested) SPMD construct, if any
722static bool hasNestedSPMDDirective(ASTContext &Ctx,
723 const OMPExecutableDirective &D) {
724 const auto *CS = D.getInnermostCapturedStmt();
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000725 const auto *Body =
726 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5c427362019-04-10 19:11:33 +0000727 const Stmt *ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000728
Alexey Bataev5c427362019-04-10 19:11:33 +0000729 if (const auto *NestedDir =
730 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000731 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000732 switch (D.getDirectiveKind()) {
733 case OMPD_target:
Alexey Bataevdc9e7dc2019-04-17 16:53:08 +0000734 if (isOpenMPParallelDirective(DKind))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000735 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000736 if (DKind == OMPD_teams) {
737 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
738 /*IgnoreCaptured=*/true);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000739 if (!Body)
740 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000741 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
742 if (const auto *NND =
743 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000744 DKind = NND->getDirectiveKind();
Alexey Bataevdc9e7dc2019-04-17 16:53:08 +0000745 if (isOpenMPParallelDirective(DKind))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000746 return true;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000747 }
748 }
749 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000750 case OMPD_target_teams:
Alexey Bataevdc9e7dc2019-04-17 16:53:08 +0000751 return isOpenMPParallelDirective(DKind);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000752 case OMPD_target_simd:
753 case OMPD_target_parallel:
754 case OMPD_target_parallel_for:
755 case OMPD_target_parallel_for_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000756 case OMPD_target_teams_distribute:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000757 case OMPD_target_teams_distribute_simd:
758 case OMPD_target_teams_distribute_parallel_for:
759 case OMPD_target_teams_distribute_parallel_for_simd:
760 case OMPD_parallel:
761 case OMPD_for:
762 case OMPD_parallel_for:
763 case OMPD_parallel_sections:
764 case OMPD_for_simd:
765 case OMPD_parallel_for_simd:
766 case OMPD_cancel:
767 case OMPD_cancellation_point:
768 case OMPD_ordered:
769 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +0000770 case OMPD_allocate:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000771 case OMPD_task:
772 case OMPD_simd:
773 case OMPD_sections:
774 case OMPD_section:
775 case OMPD_single:
776 case OMPD_master:
777 case OMPD_critical:
778 case OMPD_taskyield:
779 case OMPD_barrier:
780 case OMPD_taskwait:
781 case OMPD_taskgroup:
782 case OMPD_atomic:
783 case OMPD_flush:
784 case OMPD_teams:
785 case OMPD_target_data:
786 case OMPD_target_exit_data:
787 case OMPD_target_enter_data:
788 case OMPD_distribute:
789 case OMPD_distribute_simd:
790 case OMPD_distribute_parallel_for:
791 case OMPD_distribute_parallel_for_simd:
792 case OMPD_teams_distribute:
793 case OMPD_teams_distribute_simd:
794 case OMPD_teams_distribute_parallel_for:
795 case OMPD_teams_distribute_parallel_for_simd:
796 case OMPD_target_update:
797 case OMPD_declare_simd:
798 case OMPD_declare_target:
799 case OMPD_end_declare_target:
800 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +0000801 case OMPD_declare_mapper:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000802 case OMPD_taskloop:
803 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000804 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000805 case OMPD_unknown:
806 llvm_unreachable("Unexpected directive.");
807 }
808 }
809
810 return false;
811}
812
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000813static bool supportsSPMDExecutionMode(ASTContext &Ctx,
814 const OMPExecutableDirective &D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000815 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
816 switch (DirectiveKind) {
817 case OMPD_target:
818 case OMPD_target_teams:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000819 return hasNestedSPMDDirective(Ctx, D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000820 case OMPD_target_parallel:
821 case OMPD_target_parallel_for:
822 case OMPD_target_parallel_for_simd:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000823 case OMPD_target_teams_distribute_parallel_for:
824 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000825 case OMPD_target_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000826 case OMPD_target_teams_distribute_simd:
Alexey Bataevdc9e7dc2019-04-17 16:53:08 +0000827 return true;
828 case OMPD_target_teams_distribute:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000829 return false;
830 case OMPD_parallel:
831 case OMPD_for:
832 case OMPD_parallel_for:
833 case OMPD_parallel_sections:
834 case OMPD_for_simd:
835 case OMPD_parallel_for_simd:
836 case OMPD_cancel:
837 case OMPD_cancellation_point:
838 case OMPD_ordered:
839 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +0000840 case OMPD_allocate:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000841 case OMPD_task:
842 case OMPD_simd:
843 case OMPD_sections:
844 case OMPD_section:
845 case OMPD_single:
846 case OMPD_master:
847 case OMPD_critical:
848 case OMPD_taskyield:
849 case OMPD_barrier:
850 case OMPD_taskwait:
851 case OMPD_taskgroup:
852 case OMPD_atomic:
853 case OMPD_flush:
854 case OMPD_teams:
855 case OMPD_target_data:
856 case OMPD_target_exit_data:
857 case OMPD_target_enter_data:
858 case OMPD_distribute:
859 case OMPD_distribute_simd:
860 case OMPD_distribute_parallel_for:
861 case OMPD_distribute_parallel_for_simd:
862 case OMPD_teams_distribute:
863 case OMPD_teams_distribute_simd:
864 case OMPD_teams_distribute_parallel_for:
865 case OMPD_teams_distribute_parallel_for_simd:
866 case OMPD_target_update:
867 case OMPD_declare_simd:
868 case OMPD_declare_target:
869 case OMPD_end_declare_target:
870 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +0000871 case OMPD_declare_mapper:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000872 case OMPD_taskloop:
873 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000874 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000875 case OMPD_unknown:
876 break;
877 }
878 llvm_unreachable(
879 "Unknown programming model for OpenMP directive on NVPTX target.");
880}
881
882/// Check if the directive is loops based and has schedule clause at all or has
883/// static scheduling.
884static bool hasStaticScheduling(const OMPExecutableDirective &D) {
885 assert(isOpenMPWorksharingDirective(D.getDirectiveKind()) &&
886 isOpenMPLoopDirective(D.getDirectiveKind()) &&
887 "Expected loop-based directive.");
888 return !D.hasClausesOfKind<OMPOrderedClause>() &&
889 (!D.hasClausesOfKind<OMPScheduleClause>() ||
890 llvm::any_of(D.getClausesOfKind<OMPScheduleClause>(),
891 [](const OMPScheduleClause *C) {
892 return C->getScheduleKind() == OMPC_SCHEDULE_static;
893 }));
894}
895
896/// Check for inner (nested) lightweight runtime construct, if any
897static bool hasNestedLightweightDirective(ASTContext &Ctx,
898 const OMPExecutableDirective &D) {
899 assert(supportsSPMDExecutionMode(Ctx, D) && "Expected SPMD mode directive.");
900 const auto *CS = D.getInnermostCapturedStmt();
901 const auto *Body =
902 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5c427362019-04-10 19:11:33 +0000903 const Stmt *ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000904
Alexey Bataev5c427362019-04-10 19:11:33 +0000905 if (const auto *NestedDir =
906 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000907 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
908 switch (D.getDirectiveKind()) {
909 case OMPD_target:
910 if (isOpenMPParallelDirective(DKind) &&
911 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
912 hasStaticScheduling(*NestedDir))
913 return true;
Alexey Bataev1472e322019-04-19 16:48:38 +0000914 if (DKind == OMPD_teams_distribute_simd || DKind == OMPD_simd)
915 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000916 if (DKind == OMPD_parallel) {
917 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
918 /*IgnoreCaptured=*/true);
919 if (!Body)
920 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000921 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
922 if (const auto *NND =
923 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000924 DKind = NND->getDirectiveKind();
925 if (isOpenMPWorksharingDirective(DKind) &&
926 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
927 return true;
928 }
929 } else if (DKind == OMPD_teams) {
930 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
931 /*IgnoreCaptured=*/true);
932 if (!Body)
933 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000934 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
935 if (const auto *NND =
936 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000937 DKind = NND->getDirectiveKind();
938 if (isOpenMPParallelDirective(DKind) &&
939 isOpenMPWorksharingDirective(DKind) &&
940 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
941 return true;
942 if (DKind == OMPD_parallel) {
943 Body = NND->getInnermostCapturedStmt()->IgnoreContainers(
944 /*IgnoreCaptured=*/true);
945 if (!Body)
946 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000947 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
948 if (const auto *NND =
949 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000950 DKind = NND->getDirectiveKind();
951 if (isOpenMPWorksharingDirective(DKind) &&
952 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
953 return true;
954 }
955 }
956 }
957 }
958 return false;
959 case OMPD_target_teams:
960 if (isOpenMPParallelDirective(DKind) &&
961 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
962 hasStaticScheduling(*NestedDir))
963 return true;
Alexey Bataev1472e322019-04-19 16:48:38 +0000964 if (DKind == OMPD_distribute_simd || DKind == OMPD_simd)
965 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000966 if (DKind == OMPD_parallel) {
967 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
968 /*IgnoreCaptured=*/true);
969 if (!Body)
970 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000971 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
972 if (const auto *NND =
973 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000974 DKind = NND->getDirectiveKind();
975 if (isOpenMPWorksharingDirective(DKind) &&
976 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
977 return true;
978 }
979 }
980 return false;
981 case OMPD_target_parallel:
Alexey Bataev1472e322019-04-19 16:48:38 +0000982 if (DKind == OMPD_simd)
983 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000984 return isOpenMPWorksharingDirective(DKind) &&
985 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NestedDir);
986 case OMPD_target_teams_distribute:
987 case OMPD_target_simd:
988 case OMPD_target_parallel_for:
989 case OMPD_target_parallel_for_simd:
990 case OMPD_target_teams_distribute_simd:
991 case OMPD_target_teams_distribute_parallel_for:
992 case OMPD_target_teams_distribute_parallel_for_simd:
993 case OMPD_parallel:
994 case OMPD_for:
995 case OMPD_parallel_for:
996 case OMPD_parallel_sections:
997 case OMPD_for_simd:
998 case OMPD_parallel_for_simd:
999 case OMPD_cancel:
1000 case OMPD_cancellation_point:
1001 case OMPD_ordered:
1002 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00001003 case OMPD_allocate:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001004 case OMPD_task:
1005 case OMPD_simd:
1006 case OMPD_sections:
1007 case OMPD_section:
1008 case OMPD_single:
1009 case OMPD_master:
1010 case OMPD_critical:
1011 case OMPD_taskyield:
1012 case OMPD_barrier:
1013 case OMPD_taskwait:
1014 case OMPD_taskgroup:
1015 case OMPD_atomic:
1016 case OMPD_flush:
1017 case OMPD_teams:
1018 case OMPD_target_data:
1019 case OMPD_target_exit_data:
1020 case OMPD_target_enter_data:
1021 case OMPD_distribute:
1022 case OMPD_distribute_simd:
1023 case OMPD_distribute_parallel_for:
1024 case OMPD_distribute_parallel_for_simd:
1025 case OMPD_teams_distribute:
1026 case OMPD_teams_distribute_simd:
1027 case OMPD_teams_distribute_parallel_for:
1028 case OMPD_teams_distribute_parallel_for_simd:
1029 case OMPD_target_update:
1030 case OMPD_declare_simd:
1031 case OMPD_declare_target:
1032 case OMPD_end_declare_target:
1033 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00001034 case OMPD_declare_mapper:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001035 case OMPD_taskloop:
1036 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001037 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001038 case OMPD_unknown:
1039 llvm_unreachable("Unexpected directive.");
1040 }
1041 }
1042
1043 return false;
1044}
1045
1046/// Checks if the construct supports lightweight runtime. It must be SPMD
1047/// construct + inner loop-based construct with static scheduling.
1048static bool supportsLightweightRuntime(ASTContext &Ctx,
1049 const OMPExecutableDirective &D) {
1050 if (!supportsSPMDExecutionMode(Ctx, D))
1051 return false;
1052 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
1053 switch (DirectiveKind) {
1054 case OMPD_target:
1055 case OMPD_target_teams:
1056 case OMPD_target_parallel:
1057 return hasNestedLightweightDirective(Ctx, D);
1058 case OMPD_target_parallel_for:
1059 case OMPD_target_parallel_for_simd:
1060 case OMPD_target_teams_distribute_parallel_for:
1061 case OMPD_target_teams_distribute_parallel_for_simd:
1062 // (Last|First)-privates must be shared in parallel region.
1063 return hasStaticScheduling(D);
1064 case OMPD_target_simd:
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001065 case OMPD_target_teams_distribute_simd:
Alexey Bataev1472e322019-04-19 16:48:38 +00001066 return true;
1067 case OMPD_target_teams_distribute:
Alexey Bataevdf093e72018-05-11 19:45:14 +00001068 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001069 case OMPD_parallel:
1070 case OMPD_for:
1071 case OMPD_parallel_for:
1072 case OMPD_parallel_sections:
1073 case OMPD_for_simd:
1074 case OMPD_parallel_for_simd:
1075 case OMPD_cancel:
1076 case OMPD_cancellation_point:
1077 case OMPD_ordered:
1078 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00001079 case OMPD_allocate:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001080 case OMPD_task:
1081 case OMPD_simd:
1082 case OMPD_sections:
1083 case OMPD_section:
1084 case OMPD_single:
1085 case OMPD_master:
1086 case OMPD_critical:
1087 case OMPD_taskyield:
1088 case OMPD_barrier:
1089 case OMPD_taskwait:
1090 case OMPD_taskgroup:
1091 case OMPD_atomic:
1092 case OMPD_flush:
1093 case OMPD_teams:
1094 case OMPD_target_data:
1095 case OMPD_target_exit_data:
1096 case OMPD_target_enter_data:
1097 case OMPD_distribute:
1098 case OMPD_distribute_simd:
1099 case OMPD_distribute_parallel_for:
1100 case OMPD_distribute_parallel_for_simd:
1101 case OMPD_teams_distribute:
1102 case OMPD_teams_distribute_simd:
1103 case OMPD_teams_distribute_parallel_for:
1104 case OMPD_teams_distribute_parallel_for_simd:
1105 case OMPD_target_update:
1106 case OMPD_declare_simd:
1107 case OMPD_declare_target:
1108 case OMPD_end_declare_target:
1109 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00001110 case OMPD_declare_mapper:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001111 case OMPD_taskloop:
1112 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001113 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001114 case OMPD_unknown:
1115 break;
1116 }
1117 llvm_unreachable(
1118 "Unknown programming model for OpenMP directive on NVPTX target.");
1119}
1120
1121void CGOpenMPRuntimeNVPTX::emitNonSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001122 StringRef ParentName,
1123 llvm::Function *&OutlinedFn,
1124 llvm::Constant *&OutlinedFnID,
1125 bool IsOffloadEntry,
1126 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001127 ExecutionRuntimeModesRAII ModeRAII(CurrentExecutionMode);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001128 EntryFunctionState EST;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001129 WorkerFunctionState WST(CGM, D.getBeginLoc());
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001130 Work.clear();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001131 WrapperFunctionsMap.clear();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001132
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001133 // Emit target region as a standalone region.
1134 class NVPTXPrePostActionTy : public PrePostActionTy {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001135 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1136 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001137
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001138 public:
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001139 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001140 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST)
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001141 : EST(EST), WST(WST) {}
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001142 void Enter(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001143 auto &RT =
1144 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001145 RT.emitNonSPMDEntryHeader(CGF, EST, WST);
1146 // Skip target region initialization.
1147 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001148 }
1149 void Exit(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001150 auto &RT =
1151 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001152 RT.clearLocThreadIdInsertPt(CGF);
1153 RT.emitNonSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001154 }
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001155 } Action(EST, WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001156 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001157 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001158 // Reserve place for the globalized memory.
1159 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001160 if (!KernelStaticGlobalized) {
1161 KernelStaticGlobalized = new llvm::GlobalVariable(
1162 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1163 llvm::GlobalValue::InternalLinkage,
1164 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1165 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1166 llvm::GlobalValue::NotThreadLocal,
1167 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1168 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001169 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1170 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001171 IsInTTDRegion = false;
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001172
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001173 // Now change the name of the worker function to correspond to this target
1174 // region's entry function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001175 WST.WorkerFn->setName(Twine(OutlinedFn->getName(), "_worker"));
Alexey Bataevaee93892018-01-08 20:09:47 +00001176
1177 // Create the worker function
1178 emitWorkerFunction(WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001179}
1180
1181// Setup NVPTX threads for master-worker OpenMP scheme.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001182void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryHeader(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001183 EntryFunctionState &EST,
1184 WorkerFunctionState &WST) {
1185 CGBuilderTy &Bld = CGF.Builder;
1186
1187 llvm::BasicBlock *WorkerBB = CGF.createBasicBlock(".worker");
1188 llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
1189 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
1190 EST.ExitBB = CGF.createBasicBlock(".exit");
1191
Alexey Bataev9ff80832018-04-16 20:16:21 +00001192 llvm::Value *IsWorker =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001193 Bld.CreateICmpULT(getNVPTXThreadID(CGF), getThreadLimit(CGF));
1194 Bld.CreateCondBr(IsWorker, WorkerBB, MasterCheckBB);
1195
1196 CGF.EmitBlock(WorkerBB);
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001197 emitCall(CGF, WST.Loc, WST.WorkerFn);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001198 CGF.EmitBranch(EST.ExitBB);
1199
1200 CGF.EmitBlock(MasterCheckBB);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001201 llvm::Value *IsMaster =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001202 Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
1203 Bld.CreateCondBr(IsMaster, MasterBB, EST.ExitBB);
1204
1205 CGF.EmitBlock(MasterBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001206 IsInTargetMasterThreadRegion = true;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001207 // SEQUENTIAL (MASTER) REGION START
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001208 // First action in sequential region:
1209 // Initialize the state of the OpenMP runtime library on the GPU.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001210 // TODO: Optimize runtime initialization and pass in correct value.
1211 llvm::Value *Args[] = {getThreadLimit(CGF),
1212 Bld.getInt16(/*RequiresOMPRuntime=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001213 CGF.EmitRuntimeCall(
1214 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_init), Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001215
1216 // For data sharing, we need to initialize the stack.
1217 CGF.EmitRuntimeCall(
1218 createNVPTXRuntimeFunction(
1219 OMPRTL_NVPTX__kmpc_data_sharing_init_stack));
1220
Alexey Bataevc99042b2018-03-15 18:10:54 +00001221 emitGenericVarsProlog(CGF, WST.Loc);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001222}
1223
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001224void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001225 EntryFunctionState &EST) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001226 IsInTargetMasterThreadRegion = false;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001227 if (!CGF.HaveInsertPoint())
1228 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001229
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001230 emitGenericVarsEpilog(CGF);
1231
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001232 if (!EST.ExitBB)
1233 EST.ExitBB = CGF.createBasicBlock(".exit");
1234
1235 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".termination.notifier");
1236 CGF.EmitBranch(TerminateBB);
1237
1238 CGF.EmitBlock(TerminateBB);
1239 // Signal termination condition.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001240 // TODO: Optimize runtime initialization and pass in correct value.
1241 llvm::Value *Args[] = {CGF.Builder.getInt16(/*IsOMPRuntimeInitialized=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001242 CGF.EmitRuntimeCall(
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001243 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_deinit), Args);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001244 // Barrier to terminate worker threads.
1245 syncCTAThreads(CGF);
1246 // Master thread jumps to exit point.
1247 CGF.EmitBranch(EST.ExitBB);
1248
1249 CGF.EmitBlock(EST.ExitBB);
1250 EST.ExitBB = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001251}
1252
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001253void CGOpenMPRuntimeNVPTX::emitSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001254 StringRef ParentName,
1255 llvm::Function *&OutlinedFn,
1256 llvm::Constant *&OutlinedFnID,
1257 bool IsOffloadEntry,
1258 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001259 ExecutionRuntimeModesRAII ModeRAII(
1260 CurrentExecutionMode, RequiresFullRuntime,
1261 CGM.getLangOpts().OpenMPCUDAForceFullRuntime ||
1262 !supportsLightweightRuntime(CGM.getContext(), D));
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001263 EntryFunctionState EST;
1264
1265 // Emit target region as a standalone region.
1266 class NVPTXPrePostActionTy : public PrePostActionTy {
1267 CGOpenMPRuntimeNVPTX &RT;
1268 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1269 const OMPExecutableDirective &D;
1270
1271 public:
1272 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT,
1273 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
1274 const OMPExecutableDirective &D)
1275 : RT(RT), EST(EST), D(D) {}
1276 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001277 RT.emitSPMDEntryHeader(CGF, EST, D);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001278 // Skip target region initialization.
1279 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001280 }
1281 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevfd006c42018-10-05 15:08:53 +00001282 RT.clearLocThreadIdInsertPt(CGF);
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001283 RT.emitSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001284 }
1285 } Action(*this, EST, D);
1286 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001287 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001288 // Reserve place for the globalized memory.
1289 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001290 if (!KernelStaticGlobalized) {
1291 KernelStaticGlobalized = new llvm::GlobalVariable(
1292 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1293 llvm::GlobalValue::InternalLinkage,
1294 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1295 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1296 llvm::GlobalValue::NotThreadLocal,
1297 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1298 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001299 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1300 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001301 IsInTTDRegion = false;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001302}
1303
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001304void CGOpenMPRuntimeNVPTX::emitSPMDEntryHeader(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001305 CodeGenFunction &CGF, EntryFunctionState &EST,
1306 const OMPExecutableDirective &D) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001307 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001308
1309 // Setup BBs in entry function.
1310 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute");
1311 EST.ExitBB = CGF.createBasicBlock(".exit");
1312
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001313 llvm::Value *Args[] = {getThreadLimit(CGF, /*IsInSPMDExecutionMode=*/true),
1314 /*RequiresOMPRuntime=*/
1315 Bld.getInt16(RequiresFullRuntime ? 1 : 0),
1316 /*RequiresDataSharing=*/Bld.getInt16(0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001317 CGF.EmitRuntimeCall(
1318 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_init), Args);
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001319
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001320 if (RequiresFullRuntime) {
1321 // For data sharing, we need to initialize the stack.
1322 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1323 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd));
1324 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001325
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001326 CGF.EmitBranch(ExecuteBB);
1327
1328 CGF.EmitBlock(ExecuteBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001329
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001330 IsInTargetMasterThreadRegion = true;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001331}
1332
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001333void CGOpenMPRuntimeNVPTX::emitSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001334 EntryFunctionState &EST) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001335 IsInTargetMasterThreadRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001336 if (!CGF.HaveInsertPoint())
1337 return;
1338
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001339 if (!EST.ExitBB)
1340 EST.ExitBB = CGF.createBasicBlock(".exit");
1341
1342 llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit");
1343 CGF.EmitBranch(OMPDeInitBB);
1344
1345 CGF.EmitBlock(OMPDeInitBB);
1346 // DeInitialize the OMP state in the runtime; called by all active threads.
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001347 llvm::Value *Args[] = {/*RequiresOMPRuntime=*/
1348 CGF.Builder.getInt16(RequiresFullRuntime ? 1 : 0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001349 CGF.EmitRuntimeCall(
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001350 createNVPTXRuntimeFunction(
1351 OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2), Args);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001352 CGF.EmitBranch(EST.ExitBB);
1353
1354 CGF.EmitBlock(EST.ExitBB);
1355 EST.ExitBB = nullptr;
1356}
1357
1358// Create a unique global variable to indicate the execution mode of this target
1359// region. The execution mode is either 'generic', or 'spmd' depending on the
1360// target directive. This variable is picked up by the offload library to setup
1361// the device appropriately before kernel launch. If the execution mode is
1362// 'generic', the runtime reserves one warp for the master, otherwise, all
1363// warps participate in parallel work.
1364static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001365 bool Mode) {
1366 auto *GVMode =
1367 new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
1368 llvm::GlobalValue::WeakAnyLinkage,
1369 llvm::ConstantInt::get(CGM.Int8Ty, Mode ? 0 : 1),
1370 Twine(Name, "_exec_mode"));
Alexey Bataev9ff80832018-04-16 20:16:21 +00001371 CGM.addCompilerUsedGlobal(GVMode);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001372}
1373
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001374void CGOpenMPRuntimeNVPTX::emitWorkerFunction(WorkerFunctionState &WST) {
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +00001375 ASTContext &Ctx = CGM.getContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001376
1377 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001378 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, WST.CGFI, {},
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001379 WST.Loc, WST.Loc);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001380 emitWorkerLoop(CGF, WST);
1381 CGF.FinishFunction();
1382}
1383
1384void CGOpenMPRuntimeNVPTX::emitWorkerLoop(CodeGenFunction &CGF,
1385 WorkerFunctionState &WST) {
1386 //
1387 // The workers enter this loop and wait for parallel work from the master.
1388 // When the master encounters a parallel region it sets up the work + variable
1389 // arguments, and wakes up the workers. The workers first check to see if
1390 // they are required for the parallel region, i.e., within the # of requested
1391 // parallel threads. The activated workers load the variable arguments and
1392 // execute the parallel work.
1393 //
1394
1395 CGBuilderTy &Bld = CGF.Builder;
1396
1397 llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work");
1398 llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers");
1399 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel");
1400 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel");
1401 llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel");
1402 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1403
1404 CGF.EmitBranch(AwaitBB);
1405
1406 // Workers wait for work from master.
1407 CGF.EmitBlock(AwaitBB);
1408 // Wait for parallel work
1409 syncCTAThreads(CGF);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001410
1411 Address WorkFn =
1412 CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn");
1413 Address ExecStatus =
1414 CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status");
1415 CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0));
1416 CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy));
1417
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001418 // TODO: Optimize runtime initialization and pass in correct value.
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001419 llvm::Value *Args[] = {WorkFn.getPointer(),
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001420 /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001421 llvm::Value *Ret = CGF.EmitRuntimeCall(
1422 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args);
1423 Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001424
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001425 // On termination condition (workid == 0), exit loop.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001426 llvm::Value *WorkID = Bld.CreateLoad(WorkFn);
1427 llvm::Value *ShouldTerminate = Bld.CreateIsNull(WorkID, "should_terminate");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001428 Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB);
1429
1430 // Activate requested workers.
1431 CGF.EmitBlock(SelectWorkersBB);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001432 llvm::Value *IsActive =
1433 Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active");
1434 Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001435
1436 // Signal start of parallel region.
1437 CGF.EmitBlock(ExecuteBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001438 // Skip initialization.
1439 setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001440
1441 // Process work items: outlined parallel functions.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001442 for (llvm::Function *W : Work) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001443 // Try to match this outlined function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001444 llvm::Value *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001445
1446 llvm::Value *WorkFnMatch =
1447 Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match");
1448
1449 llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn");
1450 llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next");
1451 Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB);
1452
1453 // Execute this outlined function.
1454 CGF.EmitBlock(ExecuteFNBB);
1455
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001456 // Insert call to work function via shared wrapper. The shared
1457 // wrapper takes two arguments:
1458 // - the parallelism level;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001459 // - the thread ID;
1460 emitCall(CGF, WST.Loc, W,
1461 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001462
1463 // Go to end of parallel region.
1464 CGF.EmitBranch(TerminateBB);
1465
1466 CGF.EmitBlock(CheckNextBB);
1467 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001468 // Default case: call to outlined function through pointer if the target
1469 // region makes a declare target call that may contain an orphaned parallel
1470 // directive.
1471 auto *ParallelFnTy =
1472 llvm::FunctionType::get(CGM.VoidTy, {CGM.Int16Ty, CGM.Int32Ty},
James Y Knight9871db02019-02-05 16:42:33 +00001473 /*isVarArg=*/false);
1474 llvm::Value *WorkFnCast =
1475 Bld.CreateBitCast(WorkID, ParallelFnTy->getPointerTo());
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001476 // Insert call to work function via shared wrapper. The shared
1477 // wrapper takes two arguments:
1478 // - the parallelism level;
1479 // - the thread ID;
James Y Knight9871db02019-02-05 16:42:33 +00001480 emitCall(CGF, WST.Loc, {ParallelFnTy, WorkFnCast},
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001481 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
1482 // Go to end of parallel region.
1483 CGF.EmitBranch(TerminateBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001484
1485 // Signal end of parallel region.
1486 CGF.EmitBlock(TerminateBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001487 CGF.EmitRuntimeCall(
1488 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_end_parallel),
1489 llvm::None);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001490 CGF.EmitBranch(BarrierBB);
1491
1492 // All active and inactive workers wait at a barrier after parallel region.
1493 CGF.EmitBlock(BarrierBB);
1494 // Barrier after parallel region.
1495 syncCTAThreads(CGF);
1496 CGF.EmitBranch(AwaitBB);
1497
1498 // Exit target region.
1499 CGF.EmitBlock(ExitBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001500 // Skip initialization.
1501 clearLocThreadIdInsertPt(CGF);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001502}
1503
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001504/// Returns specified OpenMP runtime function for the current OpenMP
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001505/// implementation. Specialized for the NVPTX device.
1506/// \param Function OpenMP runtime function.
1507/// \return Specified function.
James Y Knight9871db02019-02-05 16:42:33 +00001508llvm::FunctionCallee
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001509CGOpenMPRuntimeNVPTX::createNVPTXRuntimeFunction(unsigned Function) {
James Y Knight9871db02019-02-05 16:42:33 +00001510 llvm::FunctionCallee RTLFn = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001511 switch (static_cast<OpenMPRTLFunctionNVPTX>(Function)) {
1512 case OMPRTL_NVPTX__kmpc_kernel_init: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001513 // Build void __kmpc_kernel_init(kmp_int32 thread_limit, int16_t
1514 // RequiresOMPRuntime);
1515 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001516 auto *FnTy =
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001517 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1518 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_init");
1519 break;
1520 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001521 case OMPRTL_NVPTX__kmpc_kernel_deinit: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001522 // Build void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
1523 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001524 auto *FnTy =
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001525 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001526 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_deinit");
1527 break;
1528 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001529 case OMPRTL_NVPTX__kmpc_spmd_kernel_init: {
1530 // Build void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001531 // int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001532 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001533 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001534 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1535 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_init");
1536 break;
1537 }
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001538 case OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2: {
1539 // Build void __kmpc_spmd_kernel_deinit_v2(int16_t RequiresOMPRuntime);
1540 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001541 auto *FnTy =
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001542 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1543 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_deinit_v2");
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001544 break;
1545 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001546 case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: {
1547 /// Build void __kmpc_kernel_prepare_parallel(
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001548 /// void *outlined_function, int16_t IsOMPRuntimeInitialized);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001549 llvm::Type *TypeParams[] = {CGM.Int8PtrTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001550 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001551 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1552 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_prepare_parallel");
1553 break;
1554 }
1555 case OMPRTL_NVPTX__kmpc_kernel_parallel: {
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001556 /// Build bool __kmpc_kernel_parallel(void **outlined_function,
1557 /// int16_t IsOMPRuntimeInitialized);
1558 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy, CGM.Int16Ty};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001559 llvm::Type *RetTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001560 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001561 llvm::FunctionType::get(RetTy, TypeParams, /*isVarArg*/ false);
1562 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_parallel");
1563 break;
1564 }
1565 case OMPRTL_NVPTX__kmpc_kernel_end_parallel: {
1566 /// Build void __kmpc_kernel_end_parallel();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001567 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001568 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1569 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_end_parallel");
1570 break;
1571 }
1572 case OMPRTL_NVPTX__kmpc_serialized_parallel: {
1573 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1574 // global_tid);
1575 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001576 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001577 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1578 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1579 break;
1580 }
1581 case OMPRTL_NVPTX__kmpc_end_serialized_parallel: {
1582 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1583 // global_tid);
1584 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001585 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001586 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1587 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1588 break;
1589 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001590 case OMPRTL_NVPTX__kmpc_shuffle_int32: {
1591 // Build int32_t __kmpc_shuffle_int32(int32_t element,
1592 // int16_t lane_offset, int16_t warp_size);
1593 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001594 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001595 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1596 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int32");
1597 break;
1598 }
1599 case OMPRTL_NVPTX__kmpc_shuffle_int64: {
1600 // Build int64_t __kmpc_shuffle_int64(int64_t element,
1601 // int16_t lane_offset, int16_t warp_size);
1602 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001603 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001604 llvm::FunctionType::get(CGM.Int64Ty, TypeParams, /*isVarArg*/ false);
1605 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int64");
1606 break;
1607 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00001608 case OMPRTL_NVPTX__kmpc_nvptx_parallel_reduce_nowait_v2: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001609 // Build int32_t kmpc_nvptx_parallel_reduce_nowait_v2(ident_t *loc,
1610 // kmp_int32 global_tid, kmp_int32 num_vars, size_t reduce_size, void*
1611 // reduce_data, void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t
1612 // lane_id, int16_t lane_offset, int16_t Algorithm Version), void
1613 // (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001614 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1615 CGM.Int16Ty, CGM.Int16Ty};
1616 auto *ShuffleReduceFnTy =
1617 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1618 /*isVarArg=*/false);
1619 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1620 auto *InterWarpCopyFnTy =
1621 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1622 /*isVarArg=*/false);
Alexey Bataev8e009032019-01-04 17:25:09 +00001623 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1624 CGM.Int32Ty,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001625 CGM.Int32Ty,
1626 CGM.SizeTy,
1627 CGM.VoidPtrTy,
1628 ShuffleReduceFnTy->getPointerTo(),
1629 InterWarpCopyFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001630 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001631 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1632 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev8e009032019-01-04 17:25:09 +00001633 FnTy, /*Name=*/"__kmpc_nvptx_parallel_reduce_nowait_v2");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001634 break;
1635 }
1636 case OMPRTL_NVPTX__kmpc_end_reduce_nowait: {
1637 // Build __kmpc_end_reduce_nowait(kmp_int32 global_tid);
1638 llvm::Type *TypeParams[] = {CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001639 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001640 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1641 RTLFn = CGM.CreateRuntimeFunction(
1642 FnTy, /*Name=*/"__kmpc_nvptx_end_reduce_nowait");
1643 break;
1644 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00001645 case OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_v2: {
1646 // Build int32_t __kmpc_nvptx_teams_reduce_nowait_v2(ident_t *loc, kmp_int32
1647 // global_tid, void *global_buffer, int32_t num_of_records, void*
1648 // reduce_data,
1649 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1650 // lane_offset, int16_t shortCircuit),
1651 // void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num), void
1652 // (*kmp_ListToGlobalCpyFctPtr)(void *buffer, int idx, void *reduce_data),
1653 // void (*kmp_GlobalToListCpyFctPtr)(void *buffer, int idx,
1654 // void *reduce_data), void (*kmp_GlobalToListCpyPtrsFctPtr)(void *buffer,
1655 // int idx, void *reduce_data), void (*kmp_GlobalToListRedFctPtr)(void
1656 // *buffer, int idx, void *reduce_data));
1657 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1658 CGM.Int16Ty, CGM.Int16Ty};
1659 auto *ShuffleReduceFnTy =
1660 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1661 /*isVarArg=*/false);
1662 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1663 auto *InterWarpCopyFnTy =
1664 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1665 /*isVarArg=*/false);
1666 llvm::Type *GlobalListTypeParams[] = {CGM.VoidPtrTy, CGM.IntTy,
1667 CGM.VoidPtrTy};
1668 auto *GlobalListFnTy =
1669 llvm::FunctionType::get(CGM.VoidTy, GlobalListTypeParams,
1670 /*isVarArg=*/false);
1671 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1672 CGM.Int32Ty,
1673 CGM.VoidPtrTy,
1674 CGM.Int32Ty,
1675 CGM.VoidPtrTy,
1676 ShuffleReduceFnTy->getPointerTo(),
1677 InterWarpCopyFnTy->getPointerTo(),
1678 GlobalListFnTy->getPointerTo(),
1679 GlobalListFnTy->getPointerTo(),
1680 GlobalListFnTy->getPointerTo(),
1681 GlobalListFnTy->getPointerTo()};
Alexey Bataeva1166022018-11-27 21:24:54 +00001682 auto *FnTy =
1683 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1684 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev8061acd2019-02-20 16:36:22 +00001685 FnTy, /*Name=*/"__kmpc_nvptx_teams_reduce_nowait_v2");
Alexey Bataeva1166022018-11-27 21:24:54 +00001686 break;
1687 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001688 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack: {
1689 /// Build void __kmpc_data_sharing_init_stack();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001690 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001691 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1692 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack");
1693 break;
1694 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001695 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd: {
1696 /// Build void __kmpc_data_sharing_init_stack_spmd();
1697 auto *FnTy =
1698 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001699 RTLFn =
1700 CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack_spmd");
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001701 break;
1702 }
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001703 case OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack: {
1704 // Build void *__kmpc_data_sharing_coalesced_push_stack(size_t size,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001705 // int16_t UseSharedMemory);
1706 llvm::Type *TypeParams[] = {CGM.SizeTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001707 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001708 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1709 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001710 FnTy, /*Name=*/"__kmpc_data_sharing_coalesced_push_stack");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001711 break;
1712 }
1713 case OMPRTL_NVPTX__kmpc_data_sharing_pop_stack: {
1714 // Build void __kmpc_data_sharing_pop_stack(void *a);
1715 llvm::Type *TypeParams[] = {CGM.VoidPtrTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001716 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001717 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1718 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1719 /*Name=*/"__kmpc_data_sharing_pop_stack");
1720 break;
1721 }
1722 case OMPRTL_NVPTX__kmpc_begin_sharing_variables: {
1723 /// Build void __kmpc_begin_sharing_variables(void ***args,
1724 /// size_t n_args);
1725 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo(), CGM.SizeTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001726 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001727 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1728 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_begin_sharing_variables");
1729 break;
1730 }
1731 case OMPRTL_NVPTX__kmpc_end_sharing_variables: {
1732 /// Build void __kmpc_end_sharing_variables();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001733 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001734 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1735 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_sharing_variables");
1736 break;
1737 }
1738 case OMPRTL_NVPTX__kmpc_get_shared_variables: {
1739 /// Build void __kmpc_get_shared_variables(void ***GlobalArgs);
1740 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001741 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001742 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1743 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_shared_variables");
1744 break;
1745 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001746 case OMPRTL_NVPTX__kmpc_parallel_level: {
1747 // Build uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32 global_tid);
1748 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1749 auto *FnTy =
1750 llvm::FunctionType::get(CGM.Int16Ty, TypeParams, /*isVarArg*/ false);
1751 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_parallel_level");
1752 break;
1753 }
Alexey Bataev673110d2018-05-16 13:36:30 +00001754 case OMPRTL_NVPTX__kmpc_is_spmd_exec_mode: {
1755 // Build int8_t __kmpc_is_spmd_exec_mode();
1756 auto *FnTy = llvm::FunctionType::get(CGM.Int8Ty, /*isVarArg=*/false);
1757 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_is_spmd_exec_mode");
1758 break;
1759 }
Alexey Bataeve4090182018-11-02 14:54:07 +00001760 case OMPRTL_NVPTX__kmpc_get_team_static_memory: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001761 // Build void __kmpc_get_team_static_memory(int16_t isSPMDExecutionMode,
1762 // const void *buf, size_t size, int16_t is_shared, const void **res);
1763 llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.VoidPtrTy, CGM.SizeTy,
1764 CGM.Int16Ty, CGM.VoidPtrPtrTy};
Alexey Bataeve4090182018-11-02 14:54:07 +00001765 auto *FnTy =
1766 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1767 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_team_static_memory");
1768 break;
1769 }
1770 case OMPRTL_NVPTX__kmpc_restore_team_static_memory: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001771 // Build void __kmpc_restore_team_static_memory(int16_t isSPMDExecutionMode,
1772 // int16_t is_shared);
1773 llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataeve4090182018-11-02 14:54:07 +00001774 auto *FnTy =
Alexey Bataev8e009032019-01-04 17:25:09 +00001775 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
Alexey Bataeve4090182018-11-02 14:54:07 +00001776 RTLFn =
1777 CGM.CreateRuntimeFunction(FnTy, "__kmpc_restore_team_static_memory");
1778 break;
1779 }
Alexey Bataevc3028ca2018-12-04 15:03:25 +00001780 case OMPRTL__kmpc_barrier: {
1781 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
1782 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1783 auto *FnTy =
1784 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1785 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
James Y Knight9871db02019-02-05 16:42:33 +00001786 cast<llvm::Function>(RTLFn.getCallee())
1787 ->addFnAttr(llvm::Attribute::Convergent);
Alexey Bataevc3028ca2018-12-04 15:03:25 +00001788 break;
1789 }
Alexey Bataeva3924b52019-01-03 16:25:35 +00001790 case OMPRTL__kmpc_barrier_simple_spmd: {
1791 // Build void __kmpc_barrier_simple_spmd(ident_t *loc, kmp_int32
1792 // global_tid);
1793 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1794 auto *FnTy =
1795 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1796 RTLFn =
1797 CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier_simple_spmd");
James Y Knight9871db02019-02-05 16:42:33 +00001798 cast<llvm::Function>(RTLFn.getCallee())
1799 ->addFnAttr(llvm::Attribute::Convergent);
Alexey Bataeva3924b52019-01-03 16:25:35 +00001800 break;
1801 }
Alexey Bataev2cd7faf2019-08-26 19:07:48 +00001802 case OMPRTL_NVPTX__kmpc_warp_active_thread_mask: {
1803 // Build int32_t __kmpc_warp_active_thread_mask(void);
1804 auto *FnTy =
1805 llvm::FunctionType::get(CGM.Int32Ty, llvm::None, /*isVarArg=*/false);
1806 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_warp_active_thread_mask");
1807 break;
1808 }
1809 case OMPRTL_NVPTX__kmpc_syncwarp: {
1810 // Build void __kmpc_syncwarp(kmp_int32 Mask);
1811 auto *FnTy =
1812 llvm::FunctionType::get(CGM.VoidTy, CGM.Int32Ty, /*isVarArg=*/false);
1813 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_syncwarp");
1814 break;
1815 }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001816 }
1817 return RTLFn;
1818}
1819
1820void CGOpenMPRuntimeNVPTX::createOffloadEntry(llvm::Constant *ID,
1821 llvm::Constant *Addr,
Alexey Bataev03f270c2018-03-30 18:31:07 +00001822 uint64_t Size, int32_t,
1823 llvm::GlobalValue::LinkageTypes) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001824 // TODO: Add support for global variables on the device after declare target
1825 // support.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001826 if (!isa<llvm::Function>(Addr))
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001827 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +00001828 llvm::Module &M = CGM.getModule();
1829 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001830
1831 // Get "nvvm.annotations" metadata node
Alexey Bataev9ff80832018-04-16 20:16:21 +00001832 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001833
1834 llvm::Metadata *MDVals[] = {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001835 llvm::ConstantAsMetadata::get(Addr), llvm::MDString::get(Ctx, "kernel"),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001836 llvm::ConstantAsMetadata::get(
1837 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))};
1838 // Append metadata to nvvm.annotations
1839 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
1840}
1841
1842void CGOpenMPRuntimeNVPTX::emitTargetOutlinedFunction(
1843 const OMPExecutableDirective &D, StringRef ParentName,
1844 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001845 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001846 if (!IsOffloadEntry) // Nothing to do.
1847 return;
1848
1849 assert(!ParentName.empty() && "Invalid target region parent name!");
1850
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001851 bool Mode = supportsSPMDExecutionMode(CGM.getContext(), D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001852 if (Mode)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001853 emitSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001854 CodeGen);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001855 else
1856 emitNonSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1857 CodeGen);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001858
1859 setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001860}
1861
Alexey Bataevceeaa482018-11-21 21:04:34 +00001862namespace {
1863LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
1864/// Enum for accesseing the reserved_2 field of the ident_t struct.
1865enum ModeFlagsTy : unsigned {
1866 /// Bit set to 1 when in SPMD mode.
1867 KMP_IDENT_SPMD_MODE = 0x01,
1868 /// Bit set to 1 when a simplified runtime is used.
1869 KMP_IDENT_SIMPLE_RT_MODE = 0x02,
1870 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/KMP_IDENT_SIMPLE_RT_MODE)
1871};
1872
1873/// Special mode Undefined. Is the combination of Non-SPMD mode + SimpleRuntime.
1874static const ModeFlagsTy UndefinedMode =
1875 (~KMP_IDENT_SPMD_MODE) & KMP_IDENT_SIMPLE_RT_MODE;
1876} // anonymous namespace
1877
1878unsigned CGOpenMPRuntimeNVPTX::getDefaultLocationReserved2Flags() const {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001879 switch (getExecutionMode()) {
1880 case EM_SPMD:
1881 if (requiresFullRuntime())
1882 return KMP_IDENT_SPMD_MODE & (~KMP_IDENT_SIMPLE_RT_MODE);
1883 return KMP_IDENT_SPMD_MODE | KMP_IDENT_SIMPLE_RT_MODE;
1884 case EM_NonSPMD:
1885 assert(requiresFullRuntime() && "Expected full runtime.");
1886 return (~KMP_IDENT_SPMD_MODE) & (~KMP_IDENT_SIMPLE_RT_MODE);
1887 case EM_Unknown:
1888 return UndefinedMode;
1889 }
1890 llvm_unreachable("Unknown flags are requested.");
Alexey Bataevceeaa482018-11-21 21:04:34 +00001891}
1892
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001893CGOpenMPRuntimeNVPTX::CGOpenMPRuntimeNVPTX(CodeGenModule &CGM)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001894 : CGOpenMPRuntime(CGM, "_", "$") {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001895 if (!CGM.getLangOpts().OpenMPIsDevice)
1896 llvm_unreachable("OpenMP NVPTX can only handle device code.");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001897}
Carlo Bertollic6872252016-04-04 15:55:02 +00001898
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001899void CGOpenMPRuntimeNVPTX::emitProcBindClause(CodeGenFunction &CGF,
1900 OpenMPProcBindClauseKind ProcBind,
1901 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001902 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001903 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001904 return;
1905
1906 CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc);
1907}
1908
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001909void CGOpenMPRuntimeNVPTX::emitNumThreadsClause(CodeGenFunction &CGF,
1910 llvm::Value *NumThreads,
1911 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001912 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001913 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001914 return;
1915
1916 CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc);
1917}
1918
Carlo Bertollic6872252016-04-04 15:55:02 +00001919void CGOpenMPRuntimeNVPTX::emitNumTeamsClause(CodeGenFunction &CGF,
1920 const Expr *NumTeams,
1921 const Expr *ThreadLimit,
1922 SourceLocation Loc) {}
1923
James Y Knight9871db02019-02-05 16:42:33 +00001924llvm::Function *CGOpenMPRuntimeNVPTX::emitParallelOutlinedFunction(
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001925 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1926 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00001927 // Emit target region as a standalone region.
1928 class NVPTXPrePostActionTy : public PrePostActionTy {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001929 bool &IsInParallelRegion;
1930 bool PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001931
1932 public:
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001933 NVPTXPrePostActionTy(bool &IsInParallelRegion)
1934 : IsInParallelRegion(IsInParallelRegion) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00001935 void Enter(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001936 PrevIsInParallelRegion = IsInParallelRegion;
1937 IsInParallelRegion = true;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001938 }
1939 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001940 IsInParallelRegion = PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001941 }
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001942 } Action(IsInParallelRegion);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001943 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001944 bool PrevIsInTTDRegion = IsInTTDRegion;
1945 IsInTTDRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001946 bool PrevIsInTargetMasterThreadRegion = IsInTargetMasterThreadRegion;
1947 IsInTargetMasterThreadRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001948 auto *OutlinedFun =
1949 cast<llvm::Function>(CGOpenMPRuntime::emitParallelOutlinedFunction(
1950 D, ThreadIDVar, InnermostKind, CodeGen));
Alexey Bataev8c5555c2019-05-21 15:11:58 +00001951 if (CGM.getLangOpts().Optimize) {
1952 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
1953 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
1954 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
1955 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001956 IsInTargetMasterThreadRegion = PrevIsInTargetMasterThreadRegion;
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001957 IsInTTDRegion = PrevIsInTTDRegion;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001958 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD &&
1959 !IsInParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001960 llvm::Function *WrapperFun =
1961 createParallelDataSharingWrapper(OutlinedFun, D);
1962 WrapperFunctionsMap[OutlinedFun] = WrapperFun;
1963 }
1964
1965 return OutlinedFun;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001966}
1967
Alexey Bataev2adecff2018-09-21 14:22:53 +00001968/// Get list of lastprivate variables from the teams distribute ... or
1969/// teams {distribute ...} directives.
1970static void
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001971getDistributeLastprivateVars(ASTContext &Ctx, const OMPExecutableDirective &D,
Alexey Bataev2adecff2018-09-21 14:22:53 +00001972 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
1973 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
1974 "expected teams directive.");
1975 const OMPExecutableDirective *Dir = &D;
1976 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
Alexey Bataev5c427362019-04-10 19:11:33 +00001977 if (const Stmt *S = CGOpenMPRuntime::getSingleCompoundChild(
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001978 Ctx,
Alexey Bataev2adecff2018-09-21 14:22:53 +00001979 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
1980 /*IgnoreCaptured=*/true))) {
Alexey Bataev5c427362019-04-10 19:11:33 +00001981 Dir = dyn_cast_or_null<OMPExecutableDirective>(S);
Alexey Bataev2adecff2018-09-21 14:22:53 +00001982 if (Dir && !isOpenMPDistributeDirective(Dir->getDirectiveKind()))
1983 Dir = nullptr;
1984 }
1985 }
1986 if (!Dir)
1987 return;
Alexey Bataev9ea3c382018-10-09 14:49:00 +00001988 for (const auto *C : Dir->getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00001989 for (const Expr *E : C->getVarRefs())
1990 Vars.push_back(getPrivateItem(E));
1991 }
1992}
1993
1994/// Get list of reduction variables from the teams ... directives.
1995static void
1996getTeamsReductionVars(ASTContext &Ctx, const OMPExecutableDirective &D,
1997 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
1998 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
1999 "expected teams directive.");
2000 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
2001 for (const Expr *E : C->privates())
2002 Vars.push_back(getPrivateItem(E));
Alexey Bataev2adecff2018-09-21 14:22:53 +00002003 }
2004}
2005
James Y Knight9871db02019-02-05 16:42:33 +00002006llvm::Function *CGOpenMPRuntimeNVPTX::emitTeamsOutlinedFunction(
Carlo Bertollic6872252016-04-04 15:55:02 +00002007 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
2008 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002009 SourceLocation Loc = D.getBeginLoc();
Carlo Bertollic6872252016-04-04 15:55:02 +00002010
Alexey Bataev2adecff2018-09-21 14:22:53 +00002011 const RecordDecl *GlobalizedRD = nullptr;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002012 llvm::SmallVector<const ValueDecl *, 4> LastPrivatesReductions;
Alexey Bataev2adecff2018-09-21 14:22:53 +00002013 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002014 // Globalize team reductions variable unconditionally in all modes.
Alexey Bataev8061acd2019-02-20 16:36:22 +00002015 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
2016 getTeamsReductionVars(CGM.getContext(), D, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002017 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002018 getDistributeLastprivateVars(CGM.getContext(), D, LastPrivatesReductions);
2019 if (!LastPrivatesReductions.empty()) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002020 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002021 CGM.getContext(), llvm::None, LastPrivatesReductions,
Alexey Bataev8061acd2019-02-20 16:36:22 +00002022 MappedDeclsFields, WarpSize);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002023 }
2024 } else if (!LastPrivatesReductions.empty()) {
2025 assert(!TeamAndReductions.first &&
2026 "Previous team declaration is not expected.");
2027 TeamAndReductions.first = D.getCapturedStmt(OMPD_teams)->getCapturedDecl();
2028 std::swap(TeamAndReductions.second, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002029 }
2030
Alexey Bataevc99042b2018-03-15 18:10:54 +00002031 // Emit target region as a standalone region.
2032 class NVPTXPrePostActionTy : public PrePostActionTy {
2033 SourceLocation &Loc;
Alexey Bataev2adecff2018-09-21 14:22:53 +00002034 const RecordDecl *GlobalizedRD;
2035 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2036 &MappedDeclsFields;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002037
2038 public:
Alexey Bataev2adecff2018-09-21 14:22:53 +00002039 NVPTXPrePostActionTy(
2040 SourceLocation &Loc, const RecordDecl *GlobalizedRD,
2041 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2042 &MappedDeclsFields)
2043 : Loc(Loc), GlobalizedRD(GlobalizedRD),
2044 MappedDeclsFields(MappedDeclsFields) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00002045 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002046 auto &Rt =
2047 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
2048 if (GlobalizedRD) {
2049 auto I = Rt.FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
2050 I->getSecond().GlobalRecord = GlobalizedRD;
2051 I->getSecond().MappedParams =
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00002052 std::make_unique<CodeGenFunction::OMPMapVars>();
Alexey Bataev2adecff2018-09-21 14:22:53 +00002053 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
2054 for (const auto &Pair : MappedDeclsFields) {
2055 assert(Pair.getFirst()->isCanonicalDecl() &&
2056 "Expected canonical declaration");
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002057 Data.insert(std::make_pair(Pair.getFirst(),
2058 MappedVarData(Pair.getSecond(),
2059 /*IsOnePerTeam=*/true)));
Alexey Bataev2adecff2018-09-21 14:22:53 +00002060 }
2061 }
2062 Rt.emitGenericVarsProlog(CGF, Loc);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002063 }
2064 void Exit(CodeGenFunction &CGF) override {
2065 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
2066 .emitGenericVarsEpilog(CGF);
2067 }
Alexey Bataev2adecff2018-09-21 14:22:53 +00002068 } Action(Loc, GlobalizedRD, MappedDeclsFields);
2069 CodeGen.setAction(Action);
James Y Knight9871db02019-02-05 16:42:33 +00002070 llvm::Function *OutlinedFun = CGOpenMPRuntime::emitTeamsOutlinedFunction(
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002071 D, ThreadIDVar, InnermostKind, CodeGen);
Alexey Bataev8c5555c2019-05-21 15:11:58 +00002072 if (CGM.getLangOpts().Optimize) {
2073 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
2074 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
2075 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
2076 }
Carlo Bertollic6872252016-04-04 15:55:02 +00002077
2078 return OutlinedFun;
2079}
2080
Alexey Bataevc99042b2018-03-15 18:10:54 +00002081void CGOpenMPRuntimeNVPTX::emitGenericVarsProlog(CodeGenFunction &CGF,
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002082 SourceLocation Loc,
2083 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002084 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2085 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002086 return;
2087
Alexey Bataevc99042b2018-03-15 18:10:54 +00002088 CGBuilderTy &Bld = CGF.Builder;
2089
2090 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
2091 if (I == FunctionGlobalizedDecls.end())
2092 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002093 if (const RecordDecl *GlobalizedVarsRecord = I->getSecond().GlobalRecord) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002094 QualType GlobalRecTy = CGM.getContext().getRecordType(GlobalizedVarsRecord);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002095 QualType SecGlobalRecTy;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002096
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002097 // Recover pointer to this function's global record. The runtime will
2098 // handle the specifics of the allocation of the memory.
2099 // Use actual memory size of the record including the padding
2100 // for alignment purposes.
2101 unsigned Alignment =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002102 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002103 unsigned GlobalRecordSize =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002104 CGM.getContext().getTypeSizeInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002105 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002106
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002107 llvm::PointerType *GlobalRecPtrTy =
2108 CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo();
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002109 llvm::Value *GlobalRecCastAddr;
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002110 llvm::Value *IsTTD = nullptr;
Alexey Bataeve4090182018-11-02 14:54:07 +00002111 if (!IsInTTDRegion &&
2112 (WithSPMDCheck ||
2113 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002114 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2115 llvm::BasicBlock *SPMDBB = CGF.createBasicBlock(".spmd");
2116 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002117 if (I->getSecond().SecondaryGlobalRecord.hasValue()) {
2118 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2119 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2120 llvm::Value *PL = CGF.EmitRuntimeCall(
2121 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2122 {RTLoc, ThreadID});
2123 IsTTD = Bld.CreateIsNull(PL);
2124 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002125 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2126 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
2127 Bld.CreateCondBr(IsSPMD, SPMDBB, NonSPMDBB);
2128 // There is no need to emit line number for unconditional branch.
2129 (void)ApplyDebugLocation::CreateEmpty(CGF);
2130 CGF.EmitBlock(SPMDBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002131 Address RecPtr = Address(llvm::ConstantPointerNull::get(GlobalRecPtrTy),
2132 CharUnits::fromQuantity(Alignment));
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002133 CGF.EmitBranch(ExitBB);
2134 // There is no need to emit line number for unconditional branch.
2135 (void)ApplyDebugLocation::CreateEmpty(CGF);
2136 CGF.EmitBlock(NonSPMDBB);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002137 llvm::Value *Size = llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize);
2138 if (const RecordDecl *SecGlobalizedVarsRecord =
2139 I->getSecond().SecondaryGlobalRecord.getValueOr(nullptr)) {
2140 SecGlobalRecTy =
2141 CGM.getContext().getRecordType(SecGlobalizedVarsRecord);
2142
2143 // Recover pointer to this function's global record. The runtime will
2144 // handle the specifics of the allocation of the memory.
2145 // Use actual memory size of the record including the padding
2146 // for alignment purposes.
2147 unsigned Alignment =
2148 CGM.getContext().getTypeAlignInChars(SecGlobalRecTy).getQuantity();
2149 unsigned GlobalRecordSize =
2150 CGM.getContext().getTypeSizeInChars(SecGlobalRecTy).getQuantity();
2151 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
2152 Size = Bld.CreateSelect(
2153 IsTTD, llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize), Size);
2154 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002155 // TODO: allow the usage of shared memory to be controlled by
2156 // the user, for now, default to global.
2157 llvm::Value *GlobalRecordSizeArg[] = {
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002158 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002159 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2160 createNVPTXRuntimeFunction(
2161 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2162 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002163 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002164 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002165 CGF.EmitBlock(ExitBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002166 auto *Phi = Bld.CreatePHI(GlobalRecPtrTy,
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002167 /*NumReservedValues=*/2, "_select_stack");
2168 Phi->addIncoming(RecPtr.getPointer(), SPMDBB);
2169 Phi->addIncoming(GlobalRecCastAddr, NonSPMDBB);
2170 GlobalRecCastAddr = Phi;
2171 I->getSecond().GlobalRecordAddr = Phi;
2172 I->getSecond().IsInSPMDModeFlag = IsSPMD;
Alexey Bataeve4090182018-11-02 14:54:07 +00002173 } else if (IsInTTDRegion) {
2174 assert(GlobalizedRecords.back().Records.size() < 2 &&
2175 "Expected less than 2 globalized records: one for target and one "
2176 "for teams.");
2177 unsigned Offset = 0;
2178 for (const RecordDecl *RD : GlobalizedRecords.back().Records) {
2179 QualType RDTy = CGM.getContext().getRecordType(RD);
2180 unsigned Alignment =
2181 CGM.getContext().getTypeAlignInChars(RDTy).getQuantity();
2182 unsigned Size = CGM.getContext().getTypeSizeInChars(RDTy).getQuantity();
2183 Offset =
2184 llvm::alignTo(llvm::alignTo(Offset, Alignment) + Size, Alignment);
2185 }
2186 unsigned Alignment =
2187 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
2188 Offset = llvm::alignTo(Offset, Alignment);
2189 GlobalizedRecords.back().Records.push_back(GlobalizedVarsRecord);
2190 ++GlobalizedRecords.back().RegionCounter;
2191 if (GlobalizedRecords.back().Records.size() == 1) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002192 assert(KernelStaticGlobalized &&
2193 "Kernel static pointer must be initialized already.");
2194 auto *UseSharedMemory = new llvm::GlobalVariable(
2195 CGM.getModule(), CGM.Int16Ty, /*isConstant=*/true,
2196 llvm::GlobalValue::InternalLinkage, nullptr,
2197 "_openmp_static_kernel$is_shared");
2198 UseSharedMemory->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2199 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2200 /*DestWidth=*/16, /*Signed=*/0);
2201 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2202 Address(UseSharedMemory,
2203 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2204 /*Volatile=*/false, Int16Ty, Loc);
2205 auto *StaticGlobalized = new llvm::GlobalVariable(
2206 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002207 llvm::GlobalValue::CommonLinkage, nullptr);
Alexey Bataeve4090182018-11-02 14:54:07 +00002208 auto *RecSize = new llvm::GlobalVariable(
2209 CGM.getModule(), CGM.SizeTy, /*isConstant=*/true,
2210 llvm::GlobalValue::InternalLinkage, nullptr,
2211 "_openmp_static_kernel$size");
2212 RecSize->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2213 llvm::Value *Ld = CGF.EmitLoadOfScalar(
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002214 Address(RecSize, CGM.getSizeAlign()), /*Volatile=*/false,
Alexey Bataeve4090182018-11-02 14:54:07 +00002215 CGM.getContext().getSizeType(), Loc);
2216 llvm::Value *ResAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2217 KernelStaticGlobalized, CGM.VoidPtrPtrTy);
Alexey Bataev8e009032019-01-04 17:25:09 +00002218 llvm::Value *GlobalRecordSizeArg[] = {
2219 llvm::ConstantInt::get(
2220 CGM.Int16Ty,
2221 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD ? 1 : 0),
2222 StaticGlobalized, Ld, IsInSharedMemory, ResAddr};
Alexey Bataeve4090182018-11-02 14:54:07 +00002223 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2224 OMPRTL_NVPTX__kmpc_get_team_static_memory),
2225 GlobalRecordSizeArg);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002226 GlobalizedRecords.back().Buffer = StaticGlobalized;
Alexey Bataeve4090182018-11-02 14:54:07 +00002227 GlobalizedRecords.back().RecSize = RecSize;
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002228 GlobalizedRecords.back().UseSharedMemory = UseSharedMemory;
2229 GlobalizedRecords.back().Loc = Loc;
Alexey Bataeve4090182018-11-02 14:54:07 +00002230 }
2231 assert(KernelStaticGlobalized && "Global address must be set already.");
2232 Address FrameAddr = CGF.EmitLoadOfPointer(
2233 Address(KernelStaticGlobalized, CGM.getPointerAlign()),
2234 CGM.getContext()
2235 .getPointerType(CGM.getContext().VoidPtrTy)
2236 .castAs<PointerType>());
2237 llvm::Value *GlobalRecValue =
James Y Knight751fe282019-02-09 22:22:28 +00002238 Bld.CreateConstInBoundsGEP(FrameAddr, Offset).getPointer();
Alexey Bataeve4090182018-11-02 14:54:07 +00002239 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2240 I->getSecond().IsInSPMDModeFlag = nullptr;
2241 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2242 GlobalRecValue, CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo());
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002243 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002244 // TODO: allow the usage of shared memory to be controlled by
2245 // the user, for now, default to global.
2246 llvm::Value *GlobalRecordSizeArg[] = {
2247 llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize),
2248 CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002249 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2250 createNVPTXRuntimeFunction(
2251 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2252 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002253 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002254 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002255 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2256 I->getSecond().IsInSPMDModeFlag = nullptr;
2257 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002258 LValue Base =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002259 CGF.MakeNaturalAlignPointeeAddrLValue(GlobalRecCastAddr, GlobalRecTy);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002260
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002261 // Emit the "global alloca" which is a GEP from the global declaration
2262 // record using the pointer returned by the runtime.
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002263 LValue SecBase;
2264 decltype(I->getSecond().LocalVarData)::const_iterator SecIt;
2265 if (IsTTD) {
2266 SecIt = I->getSecond().SecondaryLocalVarData->begin();
2267 llvm::PointerType *SecGlobalRecPtrTy =
2268 CGF.ConvertTypeForMem(SecGlobalRecTy)->getPointerTo();
2269 SecBase = CGF.MakeNaturalAlignPointeeAddrLValue(
2270 Bld.CreatePointerBitCastOrAddrSpaceCast(
2271 I->getSecond().GlobalRecordAddr, SecGlobalRecPtrTy),
2272 SecGlobalRecTy);
2273 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002274 for (auto &Rec : I->getSecond().LocalVarData) {
2275 bool EscapedParam = I->getSecond().EscapedParameters.count(Rec.first);
2276 llvm::Value *ParValue;
2277 if (EscapedParam) {
2278 const auto *VD = cast<VarDecl>(Rec.first);
2279 LValue ParLVal =
2280 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
2281 ParValue = CGF.EmitLoadOfScalar(ParLVal, Loc);
2282 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002283 LValue VarAddr = CGF.EmitLValueForField(Base, Rec.second.FD);
2284 // Emit VarAddr basing on lane-id if required.
2285 QualType VarTy;
2286 if (Rec.second.IsOnePerTeam) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002287 VarTy = Rec.second.FD->getType();
2288 } else {
2289 llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(
2290 VarAddr.getAddress().getPointer(),
2291 {Bld.getInt32(0), getNVPTXLaneID(CGF)});
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002292 VarTy =
2293 Rec.second.FD->getType()->castAsArrayTypeUnsafe()->getElementType();
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002294 VarAddr = CGF.MakeAddrLValue(
2295 Address(Ptr, CGM.getContext().getDeclAlign(Rec.first)), VarTy,
2296 AlignmentSource::Decl);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002297 }
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002298 Rec.second.PrivateAddr = VarAddr.getAddress();
Alexey Bataeve4090182018-11-02 14:54:07 +00002299 if (!IsInTTDRegion &&
2300 (WithSPMDCheck ||
2301 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002302 assert(I->getSecond().IsInSPMDModeFlag &&
2303 "Expected unknown execution mode or required SPMD check.");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002304 if (IsTTD) {
2305 assert(SecIt->second.IsOnePerTeam &&
2306 "Secondary glob data must be one per team.");
2307 LValue SecVarAddr = CGF.EmitLValueForField(SecBase, SecIt->second.FD);
2308 VarAddr.setAddress(
2309 Address(Bld.CreateSelect(IsTTD, SecVarAddr.getPointer(),
2310 VarAddr.getPointer()),
2311 VarAddr.getAlignment()));
2312 Rec.second.PrivateAddr = VarAddr.getAddress();
2313 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002314 Address GlobalPtr = Rec.second.PrivateAddr;
2315 Address LocalAddr = CGF.CreateMemTemp(VarTy, Rec.second.FD->getName());
2316 Rec.second.PrivateAddr = Address(
2317 Bld.CreateSelect(I->getSecond().IsInSPMDModeFlag,
2318 LocalAddr.getPointer(), GlobalPtr.getPointer()),
2319 LocalAddr.getAlignment());
2320 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002321 if (EscapedParam) {
2322 const auto *VD = cast<VarDecl>(Rec.first);
2323 CGF.EmitStoreOfScalar(ParValue, VarAddr);
2324 I->getSecond().MappedParams->setVarAddr(CGF, VD, VarAddr.getAddress());
2325 }
Alexey Bataev93a38d62018-10-16 00:09:06 +00002326 if (IsTTD)
2327 ++SecIt;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002328 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002329 }
2330 for (const ValueDecl *VD : I->getSecond().EscapedVariableLengthDecls) {
2331 // Recover pointer to this function's global record. The runtime will
2332 // handle the specifics of the allocation of the memory.
2333 // Use actual memory size of the record including the padding
2334 // for alignment purposes.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002335 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002336 llvm::Value *Size = CGF.getTypeSize(VD->getType());
2337 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2338 Size = Bld.CreateNUWAdd(
2339 Size, llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity() - 1));
2340 llvm::Value *AlignVal =
2341 llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity());
2342 Size = Bld.CreateUDiv(Size, AlignVal);
2343 Size = Bld.CreateNUWMul(Size, AlignVal);
2344 // TODO: allow the usage of shared memory to be controlled by
2345 // the user, for now, default to global.
2346 llvm::Value *GlobalRecordSizeArg[] = {
2347 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
2348 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002349 createNVPTXRuntimeFunction(
2350 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002351 GlobalRecordSizeArg);
2352 llvm::Value *GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2353 GlobalRecValue, CGF.ConvertTypeForMem(VD->getType())->getPointerTo());
2354 LValue Base = CGF.MakeAddrLValue(GlobalRecCastAddr, VD->getType(),
2355 CGM.getContext().getDeclAlign(VD),
2356 AlignmentSource::Decl);
2357 I->getSecond().MappedParams->setVarAddr(CGF, cast<VarDecl>(VD),
2358 Base.getAddress());
2359 I->getSecond().EscapedVariableLengthDeclsAddrs.emplace_back(GlobalRecValue);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002360 }
2361 I->getSecond().MappedParams->apply(CGF);
2362}
2363
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002364void CGOpenMPRuntimeNVPTX::emitGenericVarsEpilog(CodeGenFunction &CGF,
2365 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002366 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2367 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002368 return;
2369
Alexey Bataevc99042b2018-03-15 18:10:54 +00002370 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002371 if (I != FunctionGlobalizedDecls.end()) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00002372 I->getSecond().MappedParams->restore(CGF);
2373 if (!CGF.HaveInsertPoint())
2374 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002375 for (llvm::Value *Addr :
2376 llvm::reverse(I->getSecond().EscapedVariableLengthDeclsAddrs)) {
2377 CGF.EmitRuntimeCall(
2378 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2379 Addr);
2380 }
2381 if (I->getSecond().GlobalRecordAddr) {
Alexey Bataeve4090182018-11-02 14:54:07 +00002382 if (!IsInTTDRegion &&
2383 (WithSPMDCheck ||
2384 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002385 CGBuilderTy &Bld = CGF.Builder;
2386 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2387 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
2388 Bld.CreateCondBr(I->getSecond().IsInSPMDModeFlag, ExitBB, NonSPMDBB);
2389 // There is no need to emit line number for unconditional branch.
2390 (void)ApplyDebugLocation::CreateEmpty(CGF);
2391 CGF.EmitBlock(NonSPMDBB);
2392 CGF.EmitRuntimeCall(
2393 createNVPTXRuntimeFunction(
2394 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2395 CGF.EmitCastToVoidPtr(I->getSecond().GlobalRecordAddr));
2396 CGF.EmitBlock(ExitBB);
Alexey Bataeve4090182018-11-02 14:54:07 +00002397 } else if (IsInTTDRegion) {
2398 assert(GlobalizedRecords.back().RegionCounter > 0 &&
2399 "region counter must be > 0.");
2400 --GlobalizedRecords.back().RegionCounter;
2401 // Emit the restore function only in the target region.
2402 if (GlobalizedRecords.back().RegionCounter == 0) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002403 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2404 /*DestWidth=*/16, /*Signed=*/0);
2405 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2406 Address(GlobalizedRecords.back().UseSharedMemory,
2407 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2408 /*Volatile=*/false, Int16Ty, GlobalizedRecords.back().Loc);
Alexey Bataev8e009032019-01-04 17:25:09 +00002409 llvm::Value *Args[] = {
2410 llvm::ConstantInt::get(
2411 CGM.Int16Ty,
2412 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD ? 1 : 0),
2413 IsInSharedMemory};
Alexey Bataeve4090182018-11-02 14:54:07 +00002414 CGF.EmitRuntimeCall(
2415 createNVPTXRuntimeFunction(
2416 OMPRTL_NVPTX__kmpc_restore_team_static_memory),
Alexey Bataev8e009032019-01-04 17:25:09 +00002417 Args);
Alexey Bataeve4090182018-11-02 14:54:07 +00002418 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002419 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002420 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2421 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2422 I->getSecond().GlobalRecordAddr);
2423 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002424 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00002425 }
2426}
2427
Carlo Bertollic6872252016-04-04 15:55:02 +00002428void CGOpenMPRuntimeNVPTX::emitTeamsCall(CodeGenFunction &CGF,
2429 const OMPExecutableDirective &D,
2430 SourceLocation Loc,
James Y Knight9871db02019-02-05 16:42:33 +00002431 llvm::Function *OutlinedFn,
Carlo Bertollic6872252016-04-04 15:55:02 +00002432 ArrayRef<llvm::Value *> CapturedVars) {
2433 if (!CGF.HaveInsertPoint())
2434 return;
2435
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002436 Address ZeroAddr = CGF.CreateMemTemp(
2437 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2438 /*Name*/ ".zero.addr");
Carlo Bertollic6872252016-04-04 15:55:02 +00002439 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2440 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002441 OutlinedFnArgs.push_back(emitThreadIDAddress(CGF, Loc).getPointer());
Carlo Bertollic6872252016-04-04 15:55:02 +00002442 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2443 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002444 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Carlo Bertollic6872252016-04-04 15:55:02 +00002445}
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002446
2447void CGOpenMPRuntimeNVPTX::emitParallelCall(
James Y Knight9871db02019-02-05 16:42:33 +00002448 CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002449 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2450 if (!CGF.HaveInsertPoint())
2451 return;
2452
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002453 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002454 emitSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002455 else
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002456 emitNonSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002457}
2458
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002459void CGOpenMPRuntimeNVPTX::emitNonSPMDParallelCall(
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002460 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2461 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2462 llvm::Function *Fn = cast<llvm::Function>(OutlinedFn);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002463
2464 // Force inline this outlined function at its call site.
2465 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
2466
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002467 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2468 /*DestWidth=*/32, /*Signed=*/1),
2469 ".zero.addr");
2470 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002471 // ThreadId for serialized parallels is 0.
2472 Address ThreadIDAddr = ZeroAddr;
2473 auto &&CodeGen = [this, Fn, CapturedVars, Loc, ZeroAddr, &ThreadIDAddr](
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002474 CodeGenFunction &CGF, PrePostActionTy &Action) {
2475 Action.Enter(CGF);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002476
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002477 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2478 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2479 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2480 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2481 emitOutlinedFunctionCall(CGF, Loc, Fn, OutlinedFnArgs);
2482 };
2483 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2484 PrePostActionTy &) {
2485
2486 RegionCodeGenTy RCG(CodeGen);
2487 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2488 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2489 llvm::Value *Args[] = {RTLoc, ThreadID};
2490
2491 NVPTXActionTy Action(
2492 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2493 Args,
2494 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2495 Args);
2496 RCG.setAction(Action);
2497 RCG(CGF);
2498 };
2499
2500 auto &&L0ParallelGen = [this, CapturedVars, Fn](CodeGenFunction &CGF,
2501 PrePostActionTy &Action) {
2502 CGBuilderTy &Bld = CGF.Builder;
2503 llvm::Function *WFn = WrapperFunctionsMap[Fn];
2504 assert(WFn && "Wrapper function does not exist!");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002505 llvm::Value *ID = Bld.CreateBitOrPointerCast(WFn, CGM.Int8PtrTy);
2506
2507 // Prepare for parallel region. Indicate the outlined function.
2508 llvm::Value *Args[] = {ID, /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002509 CGF.EmitRuntimeCall(
2510 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_prepare_parallel),
2511 Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002512
2513 // Create a private scope that will globalize the arguments
2514 // passed from the outside of the target region.
2515 CodeGenFunction::OMPPrivateScope PrivateArgScope(CGF);
2516
Raphael Isemannb23ccec2018-12-10 12:37:46 +00002517 // There's something to share.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002518 if (!CapturedVars.empty()) {
2519 // Prepare for parallel region. Indicate the outlined function.
2520 Address SharedArgs =
2521 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "shared_arg_refs");
2522 llvm::Value *SharedArgsPtr = SharedArgs.getPointer();
2523
2524 llvm::Value *DataSharingArgs[] = {
2525 SharedArgsPtr,
2526 llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size())};
2527 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2528 OMPRTL_NVPTX__kmpc_begin_sharing_variables),
2529 DataSharingArgs);
2530
2531 // Store variable address in a list of references to pass to workers.
2532 unsigned Idx = 0;
2533 ASTContext &Ctx = CGF.getContext();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002534 Address SharedArgListAddress = CGF.EmitLoadOfPointer(
2535 SharedArgs, Ctx.getPointerType(Ctx.getPointerType(Ctx.VoidPtrTy))
2536 .castAs<PointerType>());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002537 for (llvm::Value *V : CapturedVars) {
James Y Knight751fe282019-02-09 22:22:28 +00002538 Address Dst = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002539 llvm::Value *PtrV;
Alexey Bataev17314212018-03-20 15:41:05 +00002540 if (V->getType()->isIntegerTy())
2541 PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
2542 else
2543 PtrV = Bld.CreatePointerBitCastOrAddrSpaceCast(V, CGF.VoidPtrTy);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002544 CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
2545 Ctx.getPointerType(Ctx.VoidPtrTy));
Alexey Bataevc99042b2018-03-15 18:10:54 +00002546 ++Idx;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002547 }
2548 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002549
2550 // Activate workers. This barrier is used by the master to signal
2551 // work for the workers.
2552 syncCTAThreads(CGF);
2553
2554 // OpenMP [2.5, Parallel Construct, p.49]
2555 // There is an implied barrier at the end of a parallel region. After the
2556 // end of a parallel region, only the master thread of the team resumes
2557 // execution of the enclosing task region.
2558 //
2559 // The master waits at this barrier until all workers are done.
2560 syncCTAThreads(CGF);
2561
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002562 if (!CapturedVars.empty())
2563 CGF.EmitRuntimeCall(
2564 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_sharing_variables));
2565
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002566 // Remember for post-processing in worker loop.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002567 Work.emplace_back(WFn);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002568 };
2569
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002570 auto &&LNParallelGen = [this, Loc, &SeqGen, &L0ParallelGen](
2571 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002572 if (IsInParallelRegion) {
2573 SeqGen(CGF, Action);
2574 } else if (IsInTargetMasterThreadRegion) {
2575 L0ParallelGen(CGF, Action);
2576 } else {
2577 // Check for master and then parallelism:
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002578 // if (__kmpc_is_spmd_exec_mode() || __kmpc_parallel_level(loc, gtid)) {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002579 // Serialized execution.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002580 // } else {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002581 // Worker call.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002582 // }
2583 CGBuilderTy &Bld = CGF.Builder;
2584 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002585 llvm::BasicBlock *SeqBB = CGF.createBasicBlock(".sequential");
2586 llvm::BasicBlock *ParallelCheckBB = CGF.createBasicBlock(".parcheck");
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002587 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
Alexey Bataev673110d2018-05-16 13:36:30 +00002588 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2589 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002590 Bld.CreateCondBr(IsSPMD, SeqBB, ParallelCheckBB);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002591 // There is no need to emit line number for unconditional branch.
2592 (void)ApplyDebugLocation::CreateEmpty(CGF);
2593 CGF.EmitBlock(ParallelCheckBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002594 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2595 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2596 llvm::Value *PL = CGF.EmitRuntimeCall(
2597 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2598 {RTLoc, ThreadID});
2599 llvm::Value *Res = Bld.CreateIsNotNull(PL);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002600 Bld.CreateCondBr(Res, SeqBB, MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002601 CGF.EmitBlock(SeqBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002602 SeqGen(CGF, Action);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002603 CGF.EmitBranch(ExitBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002604 // There is no need to emit line number for unconditional branch.
2605 (void)ApplyDebugLocation::CreateEmpty(CGF);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002606 CGF.EmitBlock(MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002607 L0ParallelGen(CGF, Action);
2608 CGF.EmitBranch(ExitBB);
2609 // There is no need to emit line number for unconditional branch.
2610 (void)ApplyDebugLocation::CreateEmpty(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002611 // Emit the continuation block for code after the if.
2612 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2613 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002614 };
2615
Alexey Bataev9ff80832018-04-16 20:16:21 +00002616 if (IfCond) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002617 emitOMPIfClause(CGF, IfCond, LNParallelGen, SeqGen);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002618 } else {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002619 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002620 RegionCodeGenTy ThenRCG(LNParallelGen);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002621 ThenRCG(CGF);
2622 }
2623}
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002624
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002625void CGOpenMPRuntimeNVPTX::emitSPMDParallelCall(
James Y Knight9871db02019-02-05 16:42:33 +00002626 CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002627 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2628 // Just call the outlined function to execute the parallel region.
2629 // OutlinedFn(&GTid, &zero, CapturedStruct);
2630 //
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002631 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Carlo Bertolli79712092018-02-28 20:48:35 +00002632
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002633 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2634 /*DestWidth=*/32, /*Signed=*/1),
2635 ".zero.addr");
Carlo Bertolli79712092018-02-28 20:48:35 +00002636 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002637 // ThreadId for serialized parallels is 0.
2638 Address ThreadIDAddr = ZeroAddr;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002639 auto &&CodeGen = [this, OutlinedFn, CapturedVars, Loc, ZeroAddr,
Alexey Bataev8521ff62018-07-25 20:03:01 +00002640 &ThreadIDAddr](CodeGenFunction &CGF,
2641 PrePostActionTy &Action) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002642 Action.Enter(CGF);
2643
2644 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2645 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2646 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2647 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2648 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2649 };
2650 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2651 PrePostActionTy &) {
2652
2653 RegionCodeGenTy RCG(CodeGen);
2654 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2655 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2656 llvm::Value *Args[] = {RTLoc, ThreadID};
2657
2658 NVPTXActionTy Action(
2659 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2660 Args,
2661 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2662 Args);
2663 RCG.setAction(Action);
2664 RCG(CGF);
2665 };
2666
2667 if (IsInTargetMasterThreadRegion) {
Alexey Bataev8521ff62018-07-25 20:03:01 +00002668 // In the worker need to use the real thread id.
2669 ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002670 RegionCodeGenTy RCG(CodeGen);
2671 RCG(CGF);
2672 } else {
2673 // If we are not in the target region, it is definitely L2 parallelism or
2674 // more, because for SPMD mode we always has L1 parallel level, sowe don't
2675 // need to check for orphaned directives.
2676 RegionCodeGenTy RCG(SeqGen);
2677 RCG(CGF);
2678 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002679}
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002680
Alexey Bataeva3924b52019-01-03 16:25:35 +00002681void CGOpenMPRuntimeNVPTX::syncCTAThreads(CodeGenFunction &CGF) {
2682 // Always emit simple barriers!
2683 if (!CGF.HaveInsertPoint())
2684 return;
2685 // Build call __kmpc_barrier_simple_spmd(nullptr, 0);
2686 // This function does not use parameters, so we can emit just default values.
2687 llvm::Value *Args[] = {
2688 llvm::ConstantPointerNull::get(
2689 cast<llvm::PointerType>(getIdentTyPointerTy())),
2690 llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/0, /*isSigned=*/true)};
Alexey Bataeva44b2162019-07-18 13:49:24 +00002691 llvm::CallInst *Call = CGF.EmitRuntimeCall(
Alexey Bataeva3924b52019-01-03 16:25:35 +00002692 createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier_simple_spmd), Args);
Alexey Bataeva44b2162019-07-18 13:49:24 +00002693 Call->setConvergent();
Alexey Bataeva3924b52019-01-03 16:25:35 +00002694}
2695
Alexey Bataevc3028ca2018-12-04 15:03:25 +00002696void CGOpenMPRuntimeNVPTX::emitBarrierCall(CodeGenFunction &CGF,
2697 SourceLocation Loc,
2698 OpenMPDirectiveKind Kind, bool,
2699 bool) {
2700 // Always emit simple barriers!
2701 if (!CGF.HaveInsertPoint())
2702 return;
2703 // Build call __kmpc_cancel_barrier(loc, thread_id);
2704 unsigned Flags = getDefaultFlagsForBarriers(Kind);
2705 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2706 getThreadID(CGF, Loc)};
Alexey Bataeva44b2162019-07-18 13:49:24 +00002707 llvm::CallInst *Call = CGF.EmitRuntimeCall(
2708 createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier), Args);
2709 Call->setConvergent();
Alexey Bataevc3028ca2018-12-04 15:03:25 +00002710}
2711
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002712void CGOpenMPRuntimeNVPTX::emitCriticalRegion(
2713 CodeGenFunction &CGF, StringRef CriticalName,
2714 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
2715 const Expr *Hint) {
2716 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
2717 llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
2718 llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
2719 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
2720 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
2721
Alexey Bataev2cd7faf2019-08-26 19:07:48 +00002722 // Get the mask of active threads in the warp.
2723 llvm::Value *Mask = CGF.EmitRuntimeCall(
2724 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_warp_active_thread_mask));
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002725 // Fetch team-local id of the thread.
2726 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
2727
2728 // Get the width of the team.
2729 llvm::Value *TeamWidth = getNVPTXNumThreads(CGF);
2730
2731 // Initialize the counter variable for the loop.
2732 QualType Int32Ty =
2733 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
2734 Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
2735 LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
2736 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
2737 /*isInit=*/true);
2738
2739 // Block checks if loop counter exceeds upper bound.
2740 CGF.EmitBlock(LoopBB);
2741 llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2742 llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
2743 CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
2744
2745 // Block tests which single thread should execute region, and which threads
2746 // should go straight to synchronisation point.
2747 CGF.EmitBlock(TestBB);
2748 CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2749 llvm::Value *CmpThreadToCounter =
2750 CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
2751 CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
2752
2753 // Block emits the body of the critical region.
2754 CGF.EmitBlock(BodyBB);
2755
2756 // Output the critical statement.
Alexey Bataev2c1ff9d2018-12-04 15:25:01 +00002757 CGOpenMPRuntime::emitCriticalRegion(CGF, CriticalName, CriticalOpGen, Loc,
2758 Hint);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002759
2760 // After the body surrounded by the critical region, the single executing
2761 // thread will jump to the synchronisation point.
2762 // Block waits for all threads in current team to finish then increments the
2763 // counter variable and returns to the loop.
2764 CGF.EmitBlock(SyncBB);
Alexey Bataev2cd7faf2019-08-26 19:07:48 +00002765 // Reconverge active threads in the warp.
2766 (void)CGF.EmitRuntimeCall(
2767 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_syncwarp), Mask);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002768
2769 llvm::Value *IncCounterVal =
2770 CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
2771 CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
2772 CGF.EmitBranch(LoopBB);
2773
2774 // Block that is reached when all threads in the team complete the region.
2775 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2776}
2777
Alexey Bataevb2575932018-01-04 20:18:55 +00002778/// Cast value to the specified type.
Alexey Bataeva453f362018-03-19 17:53:56 +00002779static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
2780 QualType ValTy, QualType CastTy,
2781 SourceLocation Loc) {
2782 assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
2783 "Cast type must sized.");
2784 assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
2785 "Val type must sized.");
2786 llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
2787 if (ValTy == CastTy)
Alexey Bataevb2575932018-01-04 20:18:55 +00002788 return Val;
Alexey Bataeva453f362018-03-19 17:53:56 +00002789 if (CGF.getContext().getTypeSizeInChars(ValTy) ==
2790 CGF.getContext().getTypeSizeInChars(CastTy))
2791 return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
2792 if (CastTy->isIntegerType() && ValTy->isIntegerType())
2793 return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
2794 CastTy->hasSignedIntegerRepresentation());
2795 Address CastItem = CGF.CreateMemTemp(CastTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002796 Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2797 CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
Alexey Bataeva453f362018-03-19 17:53:56 +00002798 CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy);
2799 return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc);
Alexey Bataevb2575932018-01-04 20:18:55 +00002800}
2801
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002802/// This function creates calls to one of two shuffle functions to copy
2803/// variables between lanes in a warp.
2804static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002805 llvm::Value *Elem,
Alexey Bataeva453f362018-03-19 17:53:56 +00002806 QualType ElemType,
2807 llvm::Value *Offset,
2808 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002809 CodeGenModule &CGM = CGF.CGM;
2810 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002811 CGOpenMPRuntimeNVPTX &RT =
2812 *(static_cast<CGOpenMPRuntimeNVPTX *>(&CGM.getOpenMPRuntime()));
2813
Alexey Bataeva453f362018-03-19 17:53:56 +00002814 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2815 assert(Size.getQuantity() <= 8 &&
2816 "Unsupported bitwidth in shuffle instruction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002817
Alexey Bataeva453f362018-03-19 17:53:56 +00002818 OpenMPRTLFunctionNVPTX ShuffleFn = Size.getQuantity() <= 4
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002819 ? OMPRTL_NVPTX__kmpc_shuffle_int32
2820 : OMPRTL_NVPTX__kmpc_shuffle_int64;
2821
2822 // Cast all types to 32- or 64-bit values before calling shuffle routines.
Alexey Bataeva453f362018-03-19 17:53:56 +00002823 QualType CastTy = CGF.getContext().getIntTypeForBitwidth(
2824 Size.getQuantity() <= 4 ? 32 : 64, /*Signed=*/1);
2825 llvm::Value *ElemCast = castValueToType(CGF, Elem, ElemType, CastTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002826 llvm::Value *WarpSize =
Alexey Bataevb2575932018-01-04 20:18:55 +00002827 Bld.CreateIntCast(getNVPTXWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002828
Alexey Bataev9ff80832018-04-16 20:16:21 +00002829 llvm::Value *ShuffledVal = CGF.EmitRuntimeCall(
2830 RT.createNVPTXRuntimeFunction(ShuffleFn), {ElemCast, Offset, WarpSize});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002831
Alexey Bataeva453f362018-03-19 17:53:56 +00002832 return castValueToType(CGF, ShuffledVal, CastTy, ElemType, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002833}
2834
Alexey Bataev12c62902018-06-22 19:10:38 +00002835static void shuffleAndStore(CodeGenFunction &CGF, Address SrcAddr,
2836 Address DestAddr, QualType ElemType,
2837 llvm::Value *Offset, SourceLocation Loc) {
2838 CGBuilderTy &Bld = CGF.Builder;
2839
2840 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2841 // Create the loop over the big sized data.
2842 // ptr = (void*)Elem;
2843 // ptrEnd = (void*) Elem + 1;
2844 // Step = 8;
2845 // while (ptr + Step < ptrEnd)
2846 // shuffle((int64_t)*ptr);
2847 // Step = 4;
2848 // while (ptr + Step < ptrEnd)
2849 // shuffle((int32_t)*ptr);
2850 // ...
2851 Address ElemPtr = DestAddr;
2852 Address Ptr = SrcAddr;
2853 Address PtrEnd = Bld.CreatePointerBitCastOrAddrSpaceCast(
James Y Knight751fe282019-02-09 22:22:28 +00002854 Bld.CreateConstGEP(SrcAddr, 1), CGF.VoidPtrTy);
Alexey Bataev12c62902018-06-22 19:10:38 +00002855 for (int IntSize = 8; IntSize >= 1; IntSize /= 2) {
2856 if (Size < CharUnits::fromQuantity(IntSize))
2857 continue;
2858 QualType IntType = CGF.getContext().getIntTypeForBitwidth(
2859 CGF.getContext().toBits(CharUnits::fromQuantity(IntSize)),
2860 /*Signed=*/1);
2861 llvm::Type *IntTy = CGF.ConvertTypeForMem(IntType);
2862 Ptr = Bld.CreatePointerBitCastOrAddrSpaceCast(Ptr, IntTy->getPointerTo());
2863 ElemPtr =
2864 Bld.CreatePointerBitCastOrAddrSpaceCast(ElemPtr, IntTy->getPointerTo());
2865 if (Size.getQuantity() / IntSize > 1) {
2866 llvm::BasicBlock *PreCondBB = CGF.createBasicBlock(".shuffle.pre_cond");
2867 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".shuffle.then");
2868 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".shuffle.exit");
2869 llvm::BasicBlock *CurrentBB = Bld.GetInsertBlock();
2870 CGF.EmitBlock(PreCondBB);
2871 llvm::PHINode *PhiSrc =
2872 Bld.CreatePHI(Ptr.getType(), /*NumReservedValues=*/2);
2873 PhiSrc->addIncoming(Ptr.getPointer(), CurrentBB);
2874 llvm::PHINode *PhiDest =
2875 Bld.CreatePHI(ElemPtr.getType(), /*NumReservedValues=*/2);
2876 PhiDest->addIncoming(ElemPtr.getPointer(), CurrentBB);
2877 Ptr = Address(PhiSrc, Ptr.getAlignment());
2878 ElemPtr = Address(PhiDest, ElemPtr.getAlignment());
2879 llvm::Value *PtrDiff = Bld.CreatePtrDiff(
2880 PtrEnd.getPointer(), Bld.CreatePointerBitCastOrAddrSpaceCast(
2881 Ptr.getPointer(), CGF.VoidPtrTy));
2882 Bld.CreateCondBr(Bld.CreateICmpSGT(PtrDiff, Bld.getInt64(IntSize - 1)),
2883 ThenBB, ExitBB);
2884 CGF.EmitBlock(ThenBB);
2885 llvm::Value *Res = createRuntimeShuffleFunction(
2886 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2887 IntType, Offset, Loc);
2888 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
James Y Knight751fe282019-02-09 22:22:28 +00002889 Address LocalPtr = Bld.CreateConstGEP(Ptr, 1);
2890 Address LocalElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002891 PhiSrc->addIncoming(LocalPtr.getPointer(), ThenBB);
2892 PhiDest->addIncoming(LocalElemPtr.getPointer(), ThenBB);
Alexey Bataev12c62902018-06-22 19:10:38 +00002893 CGF.EmitBranch(PreCondBB);
2894 CGF.EmitBlock(ExitBB);
2895 } else {
2896 llvm::Value *Res = createRuntimeShuffleFunction(
2897 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2898 IntType, Offset, Loc);
2899 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
James Y Knight751fe282019-02-09 22:22:28 +00002900 Ptr = Bld.CreateConstGEP(Ptr, 1);
2901 ElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
Alexey Bataev12c62902018-06-22 19:10:38 +00002902 }
2903 Size = Size % IntSize;
2904 }
2905}
2906
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002907namespace {
2908enum CopyAction : unsigned {
2909 // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
2910 // the warp using shuffle instructions.
2911 RemoteLaneToThread,
2912 // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
2913 ThreadCopy,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002914 // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
2915 ThreadToScratchpad,
2916 // ScratchpadToThread: Copy from a scratchpad array in global memory
2917 // containing team-reduced data to a thread's stack.
2918 ScratchpadToThread,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002919};
2920} // namespace
2921
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002922struct CopyOptionsTy {
2923 llvm::Value *RemoteLaneOffset;
2924 llvm::Value *ScratchpadIndex;
2925 llvm::Value *ScratchpadWidth;
2926};
2927
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002928/// Emit instructions to copy a Reduce list, which contains partially
2929/// aggregated values, in the specified direction.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002930static void emitReductionListCopy(
2931 CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
2932 ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
2933 CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002934
Alexey Bataev9ff80832018-04-16 20:16:21 +00002935 CodeGenModule &CGM = CGF.CGM;
2936 ASTContext &C = CGM.getContext();
2937 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002938
Alexey Bataev9ff80832018-04-16 20:16:21 +00002939 llvm::Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
2940 llvm::Value *ScratchpadIndex = CopyOptions.ScratchpadIndex;
2941 llvm::Value *ScratchpadWidth = CopyOptions.ScratchpadWidth;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002942
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002943 // Iterates, element-by-element, through the source Reduce list and
2944 // make a copy.
2945 unsigned Idx = 0;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002946 unsigned Size = Privates.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00002947 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002948 Address SrcElementAddr = Address::invalid();
2949 Address DestElementAddr = Address::invalid();
2950 Address DestElementPtrAddr = Address::invalid();
2951 // Should we shuffle in an element from a remote lane?
2952 bool ShuffleInElement = false;
2953 // Set to true to update the pointer in the dest Reduce list to a
2954 // newly created element.
2955 bool UpdateDestListPtr = false;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002956 // Increment the src or dest pointer to the scratchpad, for each
2957 // new element.
2958 bool IncrScratchpadSrc = false;
2959 bool IncrScratchpadDest = false;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002960
2961 switch (Action) {
2962 case RemoteLaneToThread: {
2963 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002964 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00002965 SrcElementAddr = CGF.EmitLoadOfPointer(
2966 SrcElementPtrAddr,
2967 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002968
2969 // Step 1.2: Create a temporary to store the element in the destination
2970 // Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002971 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002972 DestElementAddr =
2973 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2974 ShuffleInElement = true;
2975 UpdateDestListPtr = true;
2976 break;
2977 }
2978 case ThreadCopy: {
2979 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002980 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00002981 SrcElementAddr = CGF.EmitLoadOfPointer(
2982 SrcElementPtrAddr,
2983 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002984
2985 // Step 1.2: Get the address for dest element. The destination
2986 // element has already been created on the thread's stack.
James Y Knight751fe282019-02-09 22:22:28 +00002987 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00002988 DestElementAddr = CGF.EmitLoadOfPointer(
2989 DestElementPtrAddr,
2990 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002991 break;
2992 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002993 case ThreadToScratchpad: {
2994 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002995 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00002996 SrcElementAddr = CGF.EmitLoadOfPointer(
2997 SrcElementPtrAddr,
2998 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002999
3000 // Step 1.2: Get the address for dest element:
3001 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00003002 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00003003 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003004 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003005 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003006 Bld.CreateNUWAdd(DestBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003007 ScratchPadElemAbsolutePtrVal =
3008 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00003009 DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
3010 C.getTypeAlignInChars(Private->getType()));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003011 IncrScratchpadDest = true;
3012 break;
3013 }
3014 case ScratchpadToThread: {
3015 // Step 1.1: Get the address for the src element in the scratchpad.
3016 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00003017 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00003018 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003019 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003020 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003021 Bld.CreateNUWAdd(SrcBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003022 ScratchPadElemAbsolutePtrVal =
3023 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
3024 SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
3025 C.getTypeAlignInChars(Private->getType()));
3026 IncrScratchpadSrc = true;
3027
3028 // Step 1.2: Create a temporary to store the element in the destination
3029 // Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00003030 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003031 DestElementAddr =
3032 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
3033 UpdateDestListPtr = true;
3034 break;
3035 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003036 }
3037
3038 // Regardless of src and dest of copy, we emit the load of src
3039 // element as this is required in all directions
3040 SrcElementAddr = Bld.CreateElementBitCast(
3041 SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
Alexey Bataev12c62902018-06-22 19:10:38 +00003042 DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
3043 SrcElementAddr.getElementType());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003044
3045 // Now that all active lanes have read the element in the
3046 // Reduce list, shuffle over the value from the remote lane.
Alexey Bataeva453f362018-03-19 17:53:56 +00003047 if (ShuffleInElement) {
Alexey Bataev12c62902018-06-22 19:10:38 +00003048 shuffleAndStore(CGF, SrcElementAddr, DestElementAddr, Private->getType(),
3049 RemoteLaneOffset, Private->getExprLoc());
3050 } else {
Alexey Bataev8061acd2019-02-20 16:36:22 +00003051 switch (CGF.getEvaluationKind(Private->getType())) {
3052 case TEK_Scalar: {
Alexey Bataev12c62902018-06-22 19:10:38 +00003053 llvm::Value *Elem =
3054 CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false,
3055 Private->getType(), Private->getExprLoc());
3056 // Store the source element value to the dest element address.
3057 CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false,
3058 Private->getType());
Alexey Bataev8061acd2019-02-20 16:36:22 +00003059 break;
3060 }
3061 case TEK_Complex: {
3062 CodeGenFunction::ComplexPairTy Elem = CGF.EmitLoadOfComplex(
3063 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3064 Private->getExprLoc());
3065 CGF.EmitStoreOfComplex(
3066 Elem, CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3067 /*isInit=*/false);
3068 break;
3069 }
3070 case TEK_Aggregate:
Alexey Bataev12c62902018-06-22 19:10:38 +00003071 CGF.EmitAggregateCopy(
3072 CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3073 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3074 Private->getType(), AggValueSlot::DoesNotOverlap);
Alexey Bataev8061acd2019-02-20 16:36:22 +00003075 break;
Alexey Bataev12c62902018-06-22 19:10:38 +00003076 }
Alexey Bataeva453f362018-03-19 17:53:56 +00003077 }
Alexey Bataevb2575932018-01-04 20:18:55 +00003078
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003079 // Step 3.1: Modify reference in dest Reduce list as needed.
3080 // Modifying the reference in Reduce list to point to the newly
3081 // created element. The element is live in the current function
3082 // scope and that of functions it invokes (i.e., reduce_function).
3083 // RemoteReduceData[i] = (void*)&RemoteElem
3084 if (UpdateDestListPtr) {
3085 CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
3086 DestElementAddr.getPointer(), CGF.VoidPtrTy),
3087 DestElementPtrAddr, /*Volatile=*/false,
3088 C.VoidPtrTy);
3089 }
3090
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003091 // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
3092 // address of the next element in scratchpad memory, unless we're currently
3093 // processing the last one. Memory alignment is also taken care of here.
3094 if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
3095 llvm::Value *ScratchpadBasePtr =
3096 IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
Alexey Bataeve290ec02018-04-06 16:03:36 +00003097 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
3098 ScratchpadBasePtr = Bld.CreateNUWAdd(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003099 ScratchpadBasePtr,
Alexey Bataeve290ec02018-04-06 16:03:36 +00003100 Bld.CreateNUWMul(ScratchpadWidth, ElementSizeInChars));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003101
3102 // Take care of global memory alignment for performance
Alexey Bataeve290ec02018-04-06 16:03:36 +00003103 ScratchpadBasePtr = Bld.CreateNUWSub(
3104 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3105 ScratchpadBasePtr = Bld.CreateUDiv(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003106 ScratchpadBasePtr,
3107 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
Alexey Bataeve290ec02018-04-06 16:03:36 +00003108 ScratchpadBasePtr = Bld.CreateNUWAdd(
3109 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3110 ScratchpadBasePtr = Bld.CreateNUWMul(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003111 ScratchpadBasePtr,
3112 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
3113
3114 if (IncrScratchpadDest)
3115 DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3116 else /* IncrScratchpadSrc = true */
3117 SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3118 }
3119
Alexey Bataev9ff80832018-04-16 20:16:21 +00003120 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003121 }
3122}
3123
3124/// This function emits a helper that gathers Reduce lists from the first
3125/// lane of every active warp to lanes in the first warp.
3126///
3127/// void inter_warp_copy_func(void* reduce_data, num_warps)
3128/// shared smem[warp_size];
3129/// For all data entries D in reduce_data:
Alexey Bataev29d47fc2018-12-18 19:20:15 +00003130/// sync
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003131/// If (I am the first lane in each warp)
3132/// Copy my local D to smem[warp_id]
3133/// sync
3134/// if (I am the first warp)
3135/// Copy smem[thread_id] to my local D
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003136static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
3137 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003138 QualType ReductionArrayTy,
3139 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003140 ASTContext &C = CGM.getContext();
3141 llvm::Module &M = CGM.getModule();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003142
3143 // ReduceList: thread local Reduce list.
3144 // At the stage of the computation when this function is called, partially
3145 // aggregated values reside in the first lane of every active warp.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003146 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3147 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003148 // NumWarps: number of warps active in the parallel region. This could
3149 // be smaller than 32 (max warps in a CTA) for partial block reduction.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003150 ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00003151 C.getIntTypeForBitwidth(32, /* Signed */ true),
3152 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003153 FunctionArgList Args;
3154 Args.push_back(&ReduceListArg);
3155 Args.push_back(&NumWarpsArg);
3156
Alexey Bataev9ff80832018-04-16 20:16:21 +00003157 const CGFunctionInfo &CGFI =
3158 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev8061acd2019-02-20 16:36:22 +00003159 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
3160 llvm::GlobalValue::InternalLinkage,
3161 "_omp_reduction_inter_warp_copy_func", &M);
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003162 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003163 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003164 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003165 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003166
Alexey Bataev9ff80832018-04-16 20:16:21 +00003167 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003168
3169 // This array is used as a medium to transfer, one reduce element at a time,
3170 // the data from the first lane of every warp to lanes in the first warp
3171 // in order to perform the final step of a reduction in a parallel region
3172 // (reduction across warps). The array is placed in NVPTX __shared__ memory
3173 // for reduced latency, as well as to have a distinct copy for concurrently
3174 // executing target regions. The array is declared with common linkage so
3175 // as to be shared across compilation units.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003176 StringRef TransferMediumName =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003177 "__openmp_nvptx_data_transfer_temporary_storage";
3178 llvm::GlobalVariable *TransferMedium =
3179 M.getGlobalVariable(TransferMediumName);
3180 if (!TransferMedium) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003181 auto *Ty = llvm::ArrayType::get(CGM.Int32Ty, WarpSize);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003182 unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
3183 TransferMedium = new llvm::GlobalVariable(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003184 M, Ty, /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003185 llvm::Constant::getNullValue(Ty), TransferMediumName,
3186 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3187 SharedAddressSpace);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003188 CGM.addCompilerUsedGlobal(TransferMedium);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003189 }
3190
3191 // Get the CUDA thread id of the current OpenMP thread on the GPU.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003192 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003193 // nvptx_lane_id = nvptx_id % warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003194 llvm::Value *LaneID = getNVPTXLaneID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003195 // nvptx_warp_id = nvptx_id / warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003196 llvm::Value *WarpID = getNVPTXWarpID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003197
3198 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3199 Address LocalReduceList(
3200 Bld.CreatePointerBitCastOrAddrSpaceCast(
3201 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003202 C.VoidPtrTy, Loc),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003203 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3204 CGF.getPointerAlign());
3205
3206 unsigned Idx = 0;
Alexey Bataev9ff80832018-04-16 20:16:21 +00003207 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003208 //
3209 // Warp master copies reduce element to transfer medium in __shared__
3210 // memory.
3211 //
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003212 unsigned RealTySize =
3213 C.getTypeSizeInChars(Private->getType())
3214 .alignTo(C.getTypeAlignInChars(Private->getType()))
3215 .getQuantity();
3216 for (unsigned TySize = 4; TySize > 0 && RealTySize > 0; TySize /=2) {
3217 unsigned NumIters = RealTySize / TySize;
3218 if (NumIters == 0)
3219 continue;
3220 QualType CType = C.getIntTypeForBitwidth(
3221 C.toBits(CharUnits::fromQuantity(TySize)), /*Signed=*/1);
3222 llvm::Type *CopyType = CGF.ConvertTypeForMem(CType);
3223 CharUnits Align = CharUnits::fromQuantity(TySize);
3224 llvm::Value *Cnt = nullptr;
3225 Address CntAddr = Address::invalid();
3226 llvm::BasicBlock *PrecondBB = nullptr;
3227 llvm::BasicBlock *ExitBB = nullptr;
3228 if (NumIters > 1) {
3229 CntAddr = CGF.CreateMemTemp(C.IntTy, ".cnt.addr");
3230 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.IntTy), CntAddr,
3231 /*Volatile=*/false, C.IntTy);
3232 PrecondBB = CGF.createBasicBlock("precond");
3233 ExitBB = CGF.createBasicBlock("exit");
3234 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("body");
3235 // There is no need to emit line number for unconditional branch.
3236 (void)ApplyDebugLocation::CreateEmpty(CGF);
3237 CGF.EmitBlock(PrecondBB);
3238 Cnt = CGF.EmitLoadOfScalar(CntAddr, /*Volatile=*/false, C.IntTy, Loc);
3239 llvm::Value *Cmp =
3240 Bld.CreateICmpULT(Cnt, llvm::ConstantInt::get(CGM.IntTy, NumIters));
3241 Bld.CreateCondBr(Cmp, BodyBB, ExitBB);
3242 CGF.EmitBlock(BodyBB);
3243 }
Alexey Bataev29d47fc2018-12-18 19:20:15 +00003244 // kmpc_barrier.
3245 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3246 /*EmitChecks=*/false,
3247 /*ForceSimpleCall=*/true);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003248 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3249 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3250 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003251
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003252 // if (lane_id == 0)
3253 llvm::Value *IsWarpMaster = Bld.CreateIsNull(LaneID, "warp_master");
3254 Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
3255 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003256
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003257 // Reduce element = LocalReduceList[i]
James Y Knight751fe282019-02-09 22:22:28 +00003258 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003259 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3260 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3261 // elemptr = ((CopyType*)(elemptrptr)) + I
3262 Address ElemPtr = Address(ElemPtrPtr, Align);
3263 ElemPtr = Bld.CreateElementBitCast(ElemPtr, CopyType);
3264 if (NumIters > 1) {
3265 ElemPtr = Address(Bld.CreateGEP(ElemPtr.getPointer(), Cnt),
3266 ElemPtr.getAlignment());
3267 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003268
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003269 // Get pointer to location in transfer medium.
3270 // MediumPtr = &medium[warp_id]
3271 llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
3272 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
3273 Address MediumPtr(MediumPtrVal, Align);
3274 // Casting to actual data type.
3275 // MediumPtr = (CopyType*)MediumPtrAddr;
3276 MediumPtr = Bld.CreateElementBitCast(MediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003277
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003278 // elem = *elemptr
3279 //*MediumPtr = elem
3280 llvm::Value *Elem =
3281 CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003282 // Store the source element value to the dest element address.
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003283 CGF.EmitStoreOfScalar(Elem, MediumPtr, /*Volatile=*/true, CType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003284
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003285 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003286
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003287 CGF.EmitBlock(ElseBB);
3288 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003289
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003290 CGF.EmitBlock(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003291
Alexey Bataevae51b962018-12-14 21:00:58 +00003292 // kmpc_barrier.
3293 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3294 /*EmitChecks=*/false,
3295 /*ForceSimpleCall=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003296
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003297 //
3298 // Warp 0 copies reduce element from transfer medium.
3299 //
3300 llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
3301 llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
3302 llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003303
Alexey Bataevae51b962018-12-14 21:00:58 +00003304 Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
3305 llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
3306 AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, Loc);
3307
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003308 // Up to 32 threads in warp 0 are active.
3309 llvm::Value *IsActiveThread =
3310 Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
3311 Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003312
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003313 CGF.EmitBlock(W0ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003314
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003315 // SrcMediumPtr = &medium[tid]
3316 llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
3317 TransferMedium,
3318 {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
3319 Address SrcMediumPtr(SrcMediumPtrVal, Align);
3320 // SrcMediumVal = *SrcMediumPtr;
3321 SrcMediumPtr = Bld.CreateElementBitCast(SrcMediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003322
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003323 // TargetElemPtr = (CopyType*)(SrcDataAddr[i]) + I
James Y Knight751fe282019-02-09 22:22:28 +00003324 Address TargetElemPtrPtr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003325 llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
3326 TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, Loc);
3327 Address TargetElemPtr = Address(TargetElemPtrVal, Align);
3328 TargetElemPtr = Bld.CreateElementBitCast(TargetElemPtr, CopyType);
3329 if (NumIters > 1) {
3330 TargetElemPtr = Address(Bld.CreateGEP(TargetElemPtr.getPointer(), Cnt),
3331 TargetElemPtr.getAlignment());
3332 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003333
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003334 // *TargetElemPtr = SrcMediumVal;
3335 llvm::Value *SrcMediumValue =
3336 CGF.EmitLoadOfScalar(SrcMediumPtr, /*Volatile=*/true, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003337 CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003338 CType);
3339 Bld.CreateBr(W0MergeBB);
3340
3341 CGF.EmitBlock(W0ElseBB);
3342 Bld.CreateBr(W0MergeBB);
3343
3344 CGF.EmitBlock(W0MergeBB);
3345
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003346 if (NumIters > 1) {
3347 Cnt = Bld.CreateNSWAdd(Cnt, llvm::ConstantInt::get(CGM.IntTy, /*V=*/1));
3348 CGF.EmitStoreOfScalar(Cnt, CntAddr, /*Volatile=*/false, C.IntTy);
3349 CGF.EmitBranch(PrecondBB);
3350 (void)ApplyDebugLocation::CreateEmpty(CGF);
3351 CGF.EmitBlock(ExitBB);
3352 }
3353 RealTySize %= TySize;
Alexey Bataev12c62902018-06-22 19:10:38 +00003354 }
Alexey Bataev9ff80832018-04-16 20:16:21 +00003355 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003356 }
3357
3358 CGF.FinishFunction();
3359 return Fn;
3360}
3361
3362/// Emit a helper that reduces data across two OpenMP threads (lanes)
3363/// in the same warp. It uses shuffle instructions to copy over data from
3364/// a remote lane's stack. The reduction algorithm performed is specified
3365/// by the fourth parameter.
3366///
3367/// Algorithm Versions.
3368/// Full Warp Reduce (argument value 0):
3369/// This algorithm assumes that all 32 lanes are active and gathers
3370/// data from these 32 lanes, producing a single resultant value.
3371/// Contiguous Partial Warp Reduce (argument value 1):
3372/// This algorithm assumes that only a *contiguous* subset of lanes
3373/// are active. This happens for the last warp in a parallel region
3374/// when the user specified num_threads is not an integer multiple of
3375/// 32. This contiguous subset always starts with the zeroth lane.
3376/// Partial Warp Reduce (argument value 2):
3377/// This algorithm gathers data from any number of lanes at any position.
3378/// All reduced values are stored in the lowest possible lane. The set
3379/// of problems every algorithm addresses is a super set of those
3380/// addressable by algorithms with a lower version number. Overhead
3381/// increases as algorithm version increases.
3382///
3383/// Terminology
3384/// Reduce element:
3385/// Reduce element refers to the individual data field with primitive
3386/// data types to be combined and reduced across threads.
3387/// Reduce list:
3388/// Reduce list refers to a collection of local, thread-private
3389/// reduce elements.
3390/// Remote Reduce list:
3391/// Remote Reduce list refers to a collection of remote (relative to
3392/// the current thread) reduce elements.
3393///
3394/// We distinguish between three states of threads that are important to
3395/// the implementation of this function.
3396/// Alive threads:
3397/// Threads in a warp executing the SIMT instruction, as distinguished from
3398/// threads that are inactive due to divergent control flow.
3399/// Active threads:
3400/// The minimal set of threads that has to be alive upon entry to this
3401/// function. The computation is correct iff active threads are alive.
3402/// Some threads are alive but they are not active because they do not
3403/// contribute to the computation in any useful manner. Turning them off
3404/// may introduce control flow overheads without any tangible benefits.
3405/// Effective threads:
3406/// In order to comply with the argument requirements of the shuffle
3407/// function, we must keep all lanes holding data alive. But at most
3408/// half of them perform value aggregation; we refer to this half of
3409/// threads as effective. The other half is simply handing off their
3410/// data.
3411///
3412/// Procedure
3413/// Value shuffle:
3414/// In this step active threads transfer data from higher lane positions
3415/// in the warp to lower lane positions, creating Remote Reduce list.
3416/// Value aggregation:
3417/// In this step, effective threads combine their thread local Reduce list
3418/// with Remote Reduce list and store the result in the thread local
3419/// Reduce list.
3420/// Value copy:
3421/// In this step, we deal with the assumption made by algorithm 2
3422/// (i.e. contiguity assumption). When we have an odd number of lanes
3423/// active, say 2k+1, only k threads will be effective and therefore k
3424/// new values will be produced. However, the Reduce list owned by the
3425/// (2k+1)th thread is ignored in the value aggregation. Therefore
3426/// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
3427/// that the contiguity assumption still holds.
James Y Knight9871db02019-02-05 16:42:33 +00003428static llvm::Function *emitShuffleAndReduceFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003429 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
James Y Knight9871db02019-02-05 16:42:33 +00003430 QualType ReductionArrayTy, llvm::Function *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003431 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003432
3433 // Thread local Reduce list used to host the values of data to be reduced.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003434 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3435 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003436 // Current lane id; could be logical.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003437 ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
3438 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003439 // Offset of the remote source lane relative to the current lane.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003440 ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3441 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003442 // Algorithm version. This is expected to be known at compile time.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003443 ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3444 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003445 FunctionArgList Args;
3446 Args.push_back(&ReduceListArg);
3447 Args.push_back(&LaneIDArg);
3448 Args.push_back(&RemoteLaneOffsetArg);
3449 Args.push_back(&AlgoVerArg);
3450
Alexey Bataev9ff80832018-04-16 20:16:21 +00003451 const CGFunctionInfo &CGFI =
3452 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003453 auto *Fn = llvm::Function::Create(
3454 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3455 "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003456 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003457 Fn->setDoesNotRecurse();
Alexey Bataev8c5555c2019-05-21 15:11:58 +00003458 if (CGM.getLangOpts().Optimize) {
3459 Fn->removeFnAttr(llvm::Attribute::NoInline);
3460 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
3461 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
3462 }
3463
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003464 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003465 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003466
Alexey Bataev9ff80832018-04-16 20:16:21 +00003467 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003468
3469 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3470 Address LocalReduceList(
3471 Bld.CreatePointerBitCastOrAddrSpaceCast(
3472 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3473 C.VoidPtrTy, SourceLocation()),
3474 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3475 CGF.getPointerAlign());
3476
3477 Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
3478 llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
3479 AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3480
3481 Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
3482 llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
3483 AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3484
3485 Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
3486 llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
3487 AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3488
3489 // Create a local thread-private variable to host the Reduce list
3490 // from a remote lane.
3491 Address RemoteReduceList =
3492 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
3493
3494 // This loop iterates through the list of reduce elements and copies,
3495 // element by element, from a remote lane in the warp to RemoteReduceList,
3496 // hosted on the thread's stack.
3497 emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
3498 LocalReduceList, RemoteReduceList,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003499 {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
3500 /*ScratchpadIndex=*/nullptr,
3501 /*ScratchpadWidth=*/nullptr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003502
3503 // The actions to be performed on the Remote Reduce list is dependent
3504 // on the algorithm version.
3505 //
3506 // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
3507 // LaneId % 2 == 0 && Offset > 0):
3508 // do the reduction value aggregation
3509 //
3510 // The thread local variable Reduce list is mutated in place to host the
3511 // reduced data, which is the aggregated value produced from local and
3512 // remote lanes.
3513 //
3514 // Note that AlgoVer is expected to be a constant integer known at compile
3515 // time.
3516 // When AlgoVer==0, the first conjunction evaluates to true, making
3517 // the entire predicate true during compile time.
3518 // When AlgoVer==1, the second conjunction has only the second part to be
3519 // evaluated during runtime. Other conjunctions evaluates to false
3520 // during compile time.
3521 // When AlgoVer==2, the third conjunction has only the second part to be
3522 // evaluated during runtime. Other conjunctions evaluates to false
3523 // during compile time.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003524 llvm::Value *CondAlgo0 = Bld.CreateIsNull(AlgoVerArgVal);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003525
Alexey Bataev9ff80832018-04-16 20:16:21 +00003526 llvm::Value *Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
3527 llvm::Value *CondAlgo1 = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003528 Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
3529
Alexey Bataev9ff80832018-04-16 20:16:21 +00003530 llvm::Value *Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
3531 llvm::Value *CondAlgo2 = Bld.CreateAnd(
3532 Algo2, Bld.CreateIsNull(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1))));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003533 CondAlgo2 = Bld.CreateAnd(
3534 CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
3535
Alexey Bataev9ff80832018-04-16 20:16:21 +00003536 llvm::Value *CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003537 CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
3538
3539 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3540 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3541 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
3542 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
3543
3544 CGF.EmitBlock(ThenBB);
3545 // reduce_function(LocalReduceList, RemoteReduceList)
3546 llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3547 LocalReduceList.getPointer(), CGF.VoidPtrTy);
3548 llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3549 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003550 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3551 CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003552 Bld.CreateBr(MergeBB);
3553
3554 CGF.EmitBlock(ElseBB);
3555 Bld.CreateBr(MergeBB);
3556
3557 CGF.EmitBlock(MergeBB);
3558
3559 // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
3560 // Reduce list.
3561 Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
Alexey Bataev9ff80832018-04-16 20:16:21 +00003562 llvm::Value *CondCopy = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003563 Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
3564
3565 llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
3566 llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
3567 llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
3568 Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
3569
3570 CGF.EmitBlock(CpyThenBB);
3571 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
3572 RemoteReduceList, LocalReduceList);
3573 Bld.CreateBr(CpyMergeBB);
3574
3575 CGF.EmitBlock(CpyElseBB);
3576 Bld.CreateBr(CpyMergeBB);
3577
3578 CGF.EmitBlock(CpyMergeBB);
3579
3580 CGF.FinishFunction();
3581 return Fn;
3582}
3583
Alexey Bataev8061acd2019-02-20 16:36:22 +00003584/// This function emits a helper that copies all the reduction variables from
3585/// the team into the provided global buffer for the reduction variables.
3586///
3587/// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
3588/// For all data entries D in reduce_data:
3589/// Copy local D to buffer.D[Idx]
3590static llvm::Value *emitListToGlobalCopyFunction(
3591 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3592 QualType ReductionArrayTy, SourceLocation Loc,
3593 const RecordDecl *TeamReductionRec,
3594 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3595 &VarFieldMap) {
3596 ASTContext &C = CGM.getContext();
3597
3598 // Buffer: global reduction buffer.
3599 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3600 C.VoidPtrTy, ImplicitParamDecl::Other);
3601 // Idx: index of the buffer.
3602 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3603 ImplicitParamDecl::Other);
3604 // ReduceList: thread local Reduce list.
3605 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3606 C.VoidPtrTy, ImplicitParamDecl::Other);
3607 FunctionArgList Args;
3608 Args.push_back(&BufferArg);
3609 Args.push_back(&IdxArg);
3610 Args.push_back(&ReduceListArg);
3611
3612 const CGFunctionInfo &CGFI =
3613 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3614 auto *Fn = llvm::Function::Create(
3615 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3616 "_omp_reduction_list_to_global_copy_func", &CGM.getModule());
3617 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3618 Fn->setDoesNotRecurse();
3619 CodeGenFunction CGF(CGM);
3620 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3621
3622 CGBuilderTy &Bld = CGF.Builder;
3623
3624 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3625 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3626 Address LocalReduceList(
3627 Bld.CreatePointerBitCastOrAddrSpaceCast(
3628 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3629 C.VoidPtrTy, Loc),
3630 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3631 CGF.getPointerAlign());
3632 QualType StaticTy = C.getRecordType(TeamReductionRec);
3633 llvm::Type *LLVMReductionsBufferTy =
3634 CGM.getTypes().ConvertTypeForMem(StaticTy);
3635 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3636 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3637 LLVMReductionsBufferTy->getPointerTo());
3638 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3639 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3640 /*Volatile=*/false, C.IntTy,
3641 Loc)};
3642 unsigned Idx = 0;
3643 for (const Expr *Private : Privates) {
3644 // Reduce element = LocalReduceList[i]
3645 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
3646 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3647 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3648 // elemptr = ((CopyType*)(elemptrptr)) + I
3649 ElemPtrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3650 ElemPtrPtr, CGF.ConvertTypeForMem(Private->getType())->getPointerTo());
3651 Address ElemPtr =
3652 Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
3653 const ValueDecl *VD = cast<DeclRefExpr>(Private)->getDecl();
3654 // Global = Buffer.VD[Idx];
3655 const FieldDecl *FD = VarFieldMap.lookup(VD);
3656 LValue GlobLVal = CGF.EmitLValueForField(
3657 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3658 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3659 GlobLVal.setAddress(Address(BufferPtr, GlobLVal.getAlignment()));
3660 switch (CGF.getEvaluationKind(Private->getType())) {
3661 case TEK_Scalar: {
3662 llvm::Value *V = CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false,
3663 Private->getType(), Loc);
3664 CGF.EmitStoreOfScalar(V, GlobLVal);
3665 break;
3666 }
3667 case TEK_Complex: {
3668 CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(
3669 CGF.MakeAddrLValue(ElemPtr, Private->getType()), Loc);
3670 CGF.EmitStoreOfComplex(V, GlobLVal, /*isInit=*/false);
3671 break;
3672 }
3673 case TEK_Aggregate:
3674 CGF.EmitAggregateCopy(GlobLVal,
3675 CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3676 Private->getType(), AggValueSlot::DoesNotOverlap);
3677 break;
3678 }
3679 ++Idx;
3680 }
3681
3682 CGF.FinishFunction();
3683 return Fn;
3684}
3685
3686/// This function emits a helper that reduces all the reduction variables from
3687/// the team into the provided global buffer for the reduction variables.
3688///
3689/// void list_to_global_reduce_func(void *buffer, int Idx, void *reduce_data)
3690/// void *GlobPtrs[];
3691/// GlobPtrs[0] = (void*)&buffer.D0[Idx];
3692/// ...
3693/// GlobPtrs[N] = (void*)&buffer.DN[Idx];
3694/// reduce_function(GlobPtrs, reduce_data);
3695static llvm::Value *emitListToGlobalReduceFunction(
3696 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3697 QualType ReductionArrayTy, SourceLocation Loc,
3698 const RecordDecl *TeamReductionRec,
3699 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3700 &VarFieldMap,
3701 llvm::Function *ReduceFn) {
3702 ASTContext &C = CGM.getContext();
3703
3704 // Buffer: global reduction buffer.
3705 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3706 C.VoidPtrTy, ImplicitParamDecl::Other);
3707 // Idx: index of the buffer.
3708 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3709 ImplicitParamDecl::Other);
3710 // ReduceList: thread local Reduce list.
3711 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3712 C.VoidPtrTy, ImplicitParamDecl::Other);
3713 FunctionArgList Args;
3714 Args.push_back(&BufferArg);
3715 Args.push_back(&IdxArg);
3716 Args.push_back(&ReduceListArg);
3717
3718 const CGFunctionInfo &CGFI =
3719 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3720 auto *Fn = llvm::Function::Create(
3721 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3722 "_omp_reduction_list_to_global_reduce_func", &CGM.getModule());
3723 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3724 Fn->setDoesNotRecurse();
3725 CodeGenFunction CGF(CGM);
3726 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3727
3728 CGBuilderTy &Bld = CGF.Builder;
3729
3730 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3731 QualType StaticTy = C.getRecordType(TeamReductionRec);
3732 llvm::Type *LLVMReductionsBufferTy =
3733 CGM.getTypes().ConvertTypeForMem(StaticTy);
3734 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3735 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3736 LLVMReductionsBufferTy->getPointerTo());
3737
3738 // 1. Build a list of reduction variables.
3739 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3740 Address ReductionList =
3741 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3742 auto IPriv = Privates.begin();
3743 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3744 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3745 /*Volatile=*/false, C.IntTy,
3746 Loc)};
3747 unsigned Idx = 0;
3748 for (unsigned I = 0, E = Privates.size(); I < E; ++I, ++IPriv, ++Idx) {
3749 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3750 // Global = Buffer.VD[Idx];
3751 const ValueDecl *VD = cast<DeclRefExpr>(*IPriv)->getDecl();
3752 const FieldDecl *FD = VarFieldMap.lookup(VD);
3753 LValue GlobLVal = CGF.EmitLValueForField(
3754 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3755 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3756 llvm::Value *Ptr = CGF.EmitCastToVoidPtr(BufferPtr);
3757 CGF.EmitStoreOfScalar(Ptr, Elem, /*Volatile=*/false, C.VoidPtrTy);
3758 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3759 // Store array size.
3760 ++Idx;
3761 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3762 llvm::Value *Size = CGF.Builder.CreateIntCast(
3763 CGF.getVLASize(
3764 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3765 .NumElts,
3766 CGF.SizeTy, /*isSigned=*/false);
3767 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3768 Elem);
3769 }
3770 }
3771
3772 // Call reduce_function(GlobalReduceList, ReduceList)
3773 llvm::Value *GlobalReduceList =
3774 CGF.EmitCastToVoidPtr(ReductionList.getPointer());
3775 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3776 llvm::Value *ReducedPtr = CGF.EmitLoadOfScalar(
3777 AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
3778 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3779 CGF, Loc, ReduceFn, {GlobalReduceList, ReducedPtr});
3780 CGF.FinishFunction();
3781 return Fn;
3782}
3783
3784/// This function emits a helper that copies all the reduction variables from
3785/// the team into the provided global buffer for the reduction variables.
3786///
3787/// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
3788/// For all data entries D in reduce_data:
3789/// Copy buffer.D[Idx] to local D;
3790static llvm::Value *emitGlobalToListCopyFunction(
3791 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3792 QualType ReductionArrayTy, SourceLocation Loc,
3793 const RecordDecl *TeamReductionRec,
3794 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3795 &VarFieldMap) {
3796 ASTContext &C = CGM.getContext();
3797
3798 // Buffer: global reduction buffer.
3799 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3800 C.VoidPtrTy, ImplicitParamDecl::Other);
3801 // Idx: index of the buffer.
3802 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3803 ImplicitParamDecl::Other);
3804 // ReduceList: thread local Reduce list.
3805 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3806 C.VoidPtrTy, ImplicitParamDecl::Other);
3807 FunctionArgList Args;
3808 Args.push_back(&BufferArg);
3809 Args.push_back(&IdxArg);
3810 Args.push_back(&ReduceListArg);
3811
3812 const CGFunctionInfo &CGFI =
3813 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3814 auto *Fn = llvm::Function::Create(
3815 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3816 "_omp_reduction_global_to_list_copy_func", &CGM.getModule());
3817 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3818 Fn->setDoesNotRecurse();
3819 CodeGenFunction CGF(CGM);
3820 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3821
3822 CGBuilderTy &Bld = CGF.Builder;
3823
3824 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3825 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3826 Address LocalReduceList(
3827 Bld.CreatePointerBitCastOrAddrSpaceCast(
3828 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3829 C.VoidPtrTy, Loc),
3830 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3831 CGF.getPointerAlign());
3832 QualType StaticTy = C.getRecordType(TeamReductionRec);
3833 llvm::Type *LLVMReductionsBufferTy =
3834 CGM.getTypes().ConvertTypeForMem(StaticTy);
3835 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3836 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3837 LLVMReductionsBufferTy->getPointerTo());
3838
3839 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3840 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3841 /*Volatile=*/false, C.IntTy,
3842 Loc)};
3843 unsigned Idx = 0;
3844 for (const Expr *Private : Privates) {
3845 // Reduce element = LocalReduceList[i]
3846 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
3847 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3848 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3849 // elemptr = ((CopyType*)(elemptrptr)) + I
3850 ElemPtrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3851 ElemPtrPtr, CGF.ConvertTypeForMem(Private->getType())->getPointerTo());
3852 Address ElemPtr =
3853 Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
3854 const ValueDecl *VD = cast<DeclRefExpr>(Private)->getDecl();
3855 // Global = Buffer.VD[Idx];
3856 const FieldDecl *FD = VarFieldMap.lookup(VD);
3857 LValue GlobLVal = CGF.EmitLValueForField(
3858 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3859 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3860 GlobLVal.setAddress(Address(BufferPtr, GlobLVal.getAlignment()));
3861 switch (CGF.getEvaluationKind(Private->getType())) {
3862 case TEK_Scalar: {
3863 llvm::Value *V = CGF.EmitLoadOfScalar(GlobLVal, Loc);
3864 CGF.EmitStoreOfScalar(V, ElemPtr, /*Volatile=*/false, Private->getType());
3865 break;
3866 }
3867 case TEK_Complex: {
3868 CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(GlobLVal, Loc);
3869 CGF.EmitStoreOfComplex(V, CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3870 /*isInit=*/false);
3871 break;
3872 }
3873 case TEK_Aggregate:
3874 CGF.EmitAggregateCopy(CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3875 GlobLVal, Private->getType(),
3876 AggValueSlot::DoesNotOverlap);
3877 break;
3878 }
3879 ++Idx;
3880 }
3881
3882 CGF.FinishFunction();
3883 return Fn;
3884}
3885
3886/// This function emits a helper that reduces all the reduction variables from
3887/// the team into the provided global buffer for the reduction variables.
3888///
3889/// void global_to_list_reduce_func(void *buffer, int Idx, void *reduce_data)
3890/// void *GlobPtrs[];
3891/// GlobPtrs[0] = (void*)&buffer.D0[Idx];
3892/// ...
3893/// GlobPtrs[N] = (void*)&buffer.DN[Idx];
3894/// reduce_function(reduce_data, GlobPtrs);
3895static llvm::Value *emitGlobalToListReduceFunction(
3896 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3897 QualType ReductionArrayTy, SourceLocation Loc,
3898 const RecordDecl *TeamReductionRec,
3899 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3900 &VarFieldMap,
3901 llvm::Function *ReduceFn) {
3902 ASTContext &C = CGM.getContext();
3903
3904 // Buffer: global reduction buffer.
3905 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3906 C.VoidPtrTy, ImplicitParamDecl::Other);
3907 // Idx: index of the buffer.
3908 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3909 ImplicitParamDecl::Other);
3910 // ReduceList: thread local Reduce list.
3911 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3912 C.VoidPtrTy, ImplicitParamDecl::Other);
3913 FunctionArgList Args;
3914 Args.push_back(&BufferArg);
3915 Args.push_back(&IdxArg);
3916 Args.push_back(&ReduceListArg);
3917
3918 const CGFunctionInfo &CGFI =
3919 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3920 auto *Fn = llvm::Function::Create(
3921 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3922 "_omp_reduction_global_to_list_reduce_func", &CGM.getModule());
3923 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3924 Fn->setDoesNotRecurse();
3925 CodeGenFunction CGF(CGM);
3926 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3927
3928 CGBuilderTy &Bld = CGF.Builder;
3929
3930 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3931 QualType StaticTy = C.getRecordType(TeamReductionRec);
3932 llvm::Type *LLVMReductionsBufferTy =
3933 CGM.getTypes().ConvertTypeForMem(StaticTy);
3934 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3935 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3936 LLVMReductionsBufferTy->getPointerTo());
3937
3938 // 1. Build a list of reduction variables.
3939 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3940 Address ReductionList =
3941 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3942 auto IPriv = Privates.begin();
3943 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3944 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3945 /*Volatile=*/false, C.IntTy,
3946 Loc)};
3947 unsigned Idx = 0;
3948 for (unsigned I = 0, E = Privates.size(); I < E; ++I, ++IPriv, ++Idx) {
3949 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3950 // Global = Buffer.VD[Idx];
3951 const ValueDecl *VD = cast<DeclRefExpr>(*IPriv)->getDecl();
3952 const FieldDecl *FD = VarFieldMap.lookup(VD);
3953 LValue GlobLVal = CGF.EmitLValueForField(
3954 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3955 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3956 llvm::Value *Ptr = CGF.EmitCastToVoidPtr(BufferPtr);
3957 CGF.EmitStoreOfScalar(Ptr, Elem, /*Volatile=*/false, C.VoidPtrTy);
3958 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3959 // Store array size.
3960 ++Idx;
3961 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3962 llvm::Value *Size = CGF.Builder.CreateIntCast(
3963 CGF.getVLASize(
3964 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3965 .NumElts,
3966 CGF.SizeTy, /*isSigned=*/false);
3967 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3968 Elem);
3969 }
3970 }
3971
3972 // Call reduce_function(ReduceList, GlobalReduceList)
3973 llvm::Value *GlobalReduceList =
3974 CGF.EmitCastToVoidPtr(ReductionList.getPointer());
3975 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3976 llvm::Value *ReducedPtr = CGF.EmitLoadOfScalar(
3977 AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
3978 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3979 CGF, Loc, ReduceFn, {ReducedPtr, GlobalReduceList});
3980 CGF.FinishFunction();
3981 return Fn;
3982}
3983
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003984///
3985/// Design of OpenMP reductions on the GPU
3986///
3987/// Consider a typical OpenMP program with one or more reduction
3988/// clauses:
3989///
3990/// float foo;
3991/// double bar;
3992/// #pragma omp target teams distribute parallel for \
3993/// reduction(+:foo) reduction(*:bar)
3994/// for (int i = 0; i < N; i++) {
3995/// foo += A[i]; bar *= B[i];
3996/// }
3997///
3998/// where 'foo' and 'bar' are reduced across all OpenMP threads in
3999/// all teams. In our OpenMP implementation on the NVPTX device an
4000/// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
4001/// within a team are mapped to CUDA threads within a threadblock.
4002/// Our goal is to efficiently aggregate values across all OpenMP
4003/// threads such that:
4004///
4005/// - the compiler and runtime are logically concise, and
4006/// - the reduction is performed efficiently in a hierarchical
4007/// manner as follows: within OpenMP threads in the same warp,
4008/// across warps in a threadblock, and finally across teams on
4009/// the NVPTX device.
4010///
4011/// Introduction to Decoupling
4012///
4013/// We would like to decouple the compiler and the runtime so that the
4014/// latter is ignorant of the reduction variables (number, data types)
4015/// and the reduction operators. This allows a simpler interface
4016/// and implementation while still attaining good performance.
4017///
4018/// Pseudocode for the aforementioned OpenMP program generated by the
4019/// compiler is as follows:
4020///
4021/// 1. Create private copies of reduction variables on each OpenMP
4022/// thread: 'foo_private', 'bar_private'
4023/// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
4024/// to it and writes the result in 'foo_private' and 'bar_private'
4025/// respectively.
4026/// 3. Call the OpenMP runtime on the GPU to reduce within a team
4027/// and store the result on the team master:
4028///
Alexey Bataev8e009032019-01-04 17:25:09 +00004029/// __kmpc_nvptx_parallel_reduce_nowait_v2(...,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004030/// reduceData, shuffleReduceFn, interWarpCpyFn)
4031///
4032/// where:
4033/// struct ReduceData {
4034/// double *foo;
4035/// double *bar;
4036/// } reduceData
4037/// reduceData.foo = &foo_private
4038/// reduceData.bar = &bar_private
4039///
4040/// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
4041/// auxiliary functions generated by the compiler that operate on
4042/// variables of type 'ReduceData'. They aid the runtime perform
4043/// algorithmic steps in a data agnostic manner.
4044///
4045/// 'shuffleReduceFn' is a pointer to a function that reduces data
4046/// of type 'ReduceData' across two OpenMP threads (lanes) in the
4047/// same warp. It takes the following arguments as input:
4048///
4049/// a. variable of type 'ReduceData' on the calling lane,
4050/// b. its lane_id,
4051/// c. an offset relative to the current lane_id to generate a
4052/// remote_lane_id. The remote lane contains the second
4053/// variable of type 'ReduceData' that is to be reduced.
4054/// d. an algorithm version parameter determining which reduction
4055/// algorithm to use.
4056///
4057/// 'shuffleReduceFn' retrieves data from the remote lane using
4058/// efficient GPU shuffle intrinsics and reduces, using the
4059/// algorithm specified by the 4th parameter, the two operands
4060/// element-wise. The result is written to the first operand.
4061///
4062/// Different reduction algorithms are implemented in different
4063/// runtime functions, all calling 'shuffleReduceFn' to perform
4064/// the essential reduction step. Therefore, based on the 4th
4065/// parameter, this function behaves slightly differently to
4066/// cooperate with the runtime to ensure correctness under
4067/// different circumstances.
4068///
4069/// 'InterWarpCpyFn' is a pointer to a function that transfers
4070/// reduced variables across warps. It tunnels, through CUDA
4071/// shared memory, the thread-private data of type 'ReduceData'
4072/// from lane 0 of each warp to a lane in the first warp.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004073/// 4. Call the OpenMP runtime on the GPU to reduce across teams.
4074/// The last team writes the global reduced value to memory.
4075///
4076/// ret = __kmpc_nvptx_teams_reduce_nowait(...,
4077/// reduceData, shuffleReduceFn, interWarpCpyFn,
4078/// scratchpadCopyFn, loadAndReduceFn)
4079///
4080/// 'scratchpadCopyFn' is a helper that stores reduced
4081/// data from the team master to a scratchpad array in
4082/// global memory.
4083///
4084/// 'loadAndReduceFn' is a helper that loads data from
4085/// the scratchpad array and reduces it with the input
4086/// operand.
4087///
4088/// These compiler generated functions hide address
4089/// calculation and alignment information from the runtime.
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004090/// 5. if ret == 1:
4091/// The team master of the last team stores the reduced
4092/// result to the globals in memory.
4093/// foo += reduceData.foo; bar *= reduceData.bar
4094///
4095///
4096/// Warp Reduction Algorithms
4097///
4098/// On the warp level, we have three algorithms implemented in the
4099/// OpenMP runtime depending on the number of active lanes:
4100///
4101/// Full Warp Reduction
4102///
4103/// The reduce algorithm within a warp where all lanes are active
4104/// is implemented in the runtime as follows:
4105///
4106/// full_warp_reduce(void *reduce_data,
4107/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
4108/// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
4109/// ShuffleReduceFn(reduce_data, 0, offset, 0);
4110/// }
4111///
4112/// The algorithm completes in log(2, WARPSIZE) steps.
4113///
4114/// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
4115/// not used therefore we save instructions by not retrieving lane_id
4116/// from the corresponding special registers. The 4th parameter, which
4117/// represents the version of the algorithm being used, is set to 0 to
4118/// signify full warp reduction.
4119///
4120/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4121///
4122/// #reduce_elem refers to an element in the local lane's data structure
4123/// #remote_elem is retrieved from a remote lane
4124/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4125/// reduce_elem = reduce_elem REDUCE_OP remote_elem;
4126///
4127/// Contiguous Partial Warp Reduction
4128///
4129/// This reduce algorithm is used within a warp where only the first
4130/// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
4131/// number of OpenMP threads in a parallel region is not a multiple of
4132/// WARPSIZE. The algorithm is implemented in the runtime as follows:
4133///
4134/// void
4135/// contiguous_partial_reduce(void *reduce_data,
4136/// kmp_ShuffleReductFctPtr ShuffleReduceFn,
4137/// int size, int lane_id) {
4138/// int curr_size;
4139/// int offset;
4140/// curr_size = size;
4141/// mask = curr_size/2;
4142/// while (offset>0) {
4143/// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
4144/// curr_size = (curr_size+1)/2;
4145/// offset = curr_size/2;
4146/// }
4147/// }
4148///
4149/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4150///
4151/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4152/// if (lane_id < offset)
4153/// reduce_elem = reduce_elem REDUCE_OP remote_elem
4154/// else
4155/// reduce_elem = remote_elem
4156///
4157/// This algorithm assumes that the data to be reduced are located in a
4158/// contiguous subset of lanes starting from the first. When there is
4159/// an odd number of active lanes, the data in the last lane is not
4160/// aggregated with any other lane's dat but is instead copied over.
4161///
4162/// Dispersed Partial Warp Reduction
4163///
4164/// This algorithm is used within a warp when any discontiguous subset of
4165/// lanes are active. It is used to implement the reduction operation
4166/// across lanes in an OpenMP simd region or in a nested parallel region.
4167///
4168/// void
4169/// dispersed_partial_reduce(void *reduce_data,
4170/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
4171/// int size, remote_id;
4172/// int logical_lane_id = number_of_active_lanes_before_me() * 2;
4173/// do {
4174/// remote_id = next_active_lane_id_right_after_me();
4175/// # the above function returns 0 of no active lane
4176/// # is present right after the current lane.
4177/// size = number_of_active_lanes_in_this_warp();
4178/// logical_lane_id /= 2;
4179/// ShuffleReduceFn(reduce_data, logical_lane_id,
4180/// remote_id-1-threadIdx.x, 2);
4181/// } while (logical_lane_id % 2 == 0 && size > 1);
4182/// }
4183///
4184/// There is no assumption made about the initial state of the reduction.
4185/// Any number of lanes (>=1) could be active at any position. The reduction
4186/// result is returned in the first active lane.
4187///
4188/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4189///
4190/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4191/// if (lane_id % 2 == 0 && offset > 0)
4192/// reduce_elem = reduce_elem REDUCE_OP remote_elem
4193/// else
4194/// reduce_elem = remote_elem
4195///
4196///
4197/// Intra-Team Reduction
4198///
4199/// This function, as implemented in the runtime call
Alexey Bataev8e009032019-01-04 17:25:09 +00004200/// '__kmpc_nvptx_parallel_reduce_nowait_v2', aggregates data across OpenMP
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004201/// threads in a team. It first reduces within a warp using the
4202/// aforementioned algorithms. We then proceed to gather all such
4203/// reduced values at the first warp.
4204///
4205/// The runtime makes use of the function 'InterWarpCpyFn', which copies
4206/// data from each of the "warp master" (zeroth lane of each warp, where
4207/// warp-reduced data is held) to the zeroth warp. This step reduces (in
4208/// a mathematical sense) the problem of reduction across warp masters in
4209/// a block to the problem of warp reduction.
4210///
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004211///
4212/// Inter-Team Reduction
4213///
4214/// Once a team has reduced its data to a single value, it is stored in
4215/// a global scratchpad array. Since each team has a distinct slot, this
4216/// can be done without locking.
4217///
4218/// The last team to write to the scratchpad array proceeds to reduce the
4219/// scratchpad array. One or more workers in the last team use the helper
4220/// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
4221/// the k'th worker reduces every k'th element.
4222///
Alexey Bataev8e009032019-01-04 17:25:09 +00004223/// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait_v2' to
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004224/// reduce across workers and compute a globally reduced value.
4225///
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004226void CGOpenMPRuntimeNVPTX::emitReduction(
4227 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
4228 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
4229 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
4230 if (!CGF.HaveInsertPoint())
4231 return;
4232
4233 bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00004234#ifndef NDEBUG
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004235 bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00004236#endif
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004237
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00004238 if (Options.SimpleReduction) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004239 assert(!TeamsReduction && !ParallelReduction &&
4240 "Invalid reduction selection in emitReduction.");
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00004241 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
4242 ReductionOps, Options);
4243 return;
4244 }
4245
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004246 assert((TeamsReduction || ParallelReduction) &&
4247 "Invalid reduction selection in emitReduction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004248
Alexey Bataeva1166022018-11-27 21:24:54 +00004249 // Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004250 // RedList, shuffle_reduce_func, interwarp_copy_func);
Alexey Bataeva1166022018-11-27 21:24:54 +00004251 // or
4252 // Build res = __kmpc_reduce_teams_nowait_simple(<loc>, <gtid>, <lck>);
Alexey Bataev8e009032019-01-04 17:25:09 +00004253 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004254 llvm::Value *ThreadId = getThreadID(CGF, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004255
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004256 llvm::Value *Res;
Alexey Bataev8061acd2019-02-20 16:36:22 +00004257 ASTContext &C = CGM.getContext();
4258 // 1. Build a list of reduction variables.
4259 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
4260 auto Size = RHSExprs.size();
4261 for (const Expr *E : Privates) {
4262 if (E->getType()->isVariablyModifiedType())
4263 // Reserve place for array size.
4264 ++Size;
4265 }
4266 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
4267 QualType ReductionArrayTy =
4268 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
4269 /*IndexTypeQuals=*/0);
4270 Address ReductionList =
4271 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
4272 auto IPriv = Privates.begin();
4273 unsigned Idx = 0;
4274 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
4275 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
4276 CGF.Builder.CreateStore(
4277 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4278 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
4279 Elem);
4280 if ((*IPriv)->getType()->isVariablyModifiedType()) {
4281 // Store array size.
4282 ++Idx;
4283 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
4284 llvm::Value *Size = CGF.Builder.CreateIntCast(
4285 CGF.getVLASize(
4286 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
4287 .NumElts,
4288 CGF.SizeTy, /*isSigned=*/false);
4289 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
4290 Elem);
4291 }
4292 }
4293
4294 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4295 ReductionList.getPointer(), CGF.VoidPtrTy);
4296 llvm::Function *ReductionFn = emitReductionFunction(
Alexey Bataev982a35e2019-03-19 17:09:52 +00004297 Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
4298 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev8061acd2019-02-20 16:36:22 +00004299 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
4300 llvm::Function *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
4301 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
4302 llvm::Value *InterWarpCopyFn =
4303 emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
4304
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004305 if (ParallelReduction) {
Alexey Bataev8e009032019-01-04 17:25:09 +00004306 llvm::Value *Args[] = {RTLoc,
4307 ThreadId,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004308 CGF.Builder.getInt32(RHSExprs.size()),
4309 ReductionArrayTySize,
4310 RL,
4311 ShuffleAndReduceFn,
4312 InterWarpCopyFn};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004313
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004314 Res = CGF.EmitRuntimeCall(
Alexey Bataeva1166022018-11-27 21:24:54 +00004315 createNVPTXRuntimeFunction(
Alexey Bataev8061acd2019-02-20 16:36:22 +00004316 OMPRTL_NVPTX__kmpc_nvptx_parallel_reduce_nowait_v2),
4317 Args);
4318 } else {
4319 assert(TeamsReduction && "expected teams reduction.");
4320 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> VarFieldMap;
4321 llvm::SmallVector<const ValueDecl *, 4> PrivatesReductions(Privates.size());
4322 int Cnt = 0;
4323 for (const Expr *DRE : Privates) {
4324 PrivatesReductions[Cnt] = cast<DeclRefExpr>(DRE)->getDecl();
4325 ++Cnt;
4326 }
4327 const RecordDecl *TeamReductionRec = ::buildRecordForGlobalizedVars(
4328 CGM.getContext(), PrivatesReductions, llvm::None, VarFieldMap,
4329 C.getLangOpts().OpenMPCUDAReductionBufNum);
4330 TeamsReductions.push_back(TeamReductionRec);
4331 if (!KernelTeamsReductionPtr) {
4332 KernelTeamsReductionPtr = new llvm::GlobalVariable(
4333 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/true,
4334 llvm::GlobalValue::InternalLinkage, nullptr,
4335 "_openmp_teams_reductions_buffer_$_$ptr");
4336 }
4337 llvm::Value *GlobalBufferPtr = CGF.EmitLoadOfScalar(
4338 Address(KernelTeamsReductionPtr, CGM.getPointerAlign()),
4339 /*Volatile=*/false, C.getPointerType(C.VoidPtrTy), Loc);
4340 llvm::Value *GlobalToBufferCpyFn = ::emitListToGlobalCopyFunction(
4341 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
4342 llvm::Value *GlobalToBufferRedFn = ::emitListToGlobalReduceFunction(
4343 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap,
4344 ReductionFn);
4345 llvm::Value *BufferToGlobalCpyFn = ::emitGlobalToListCopyFunction(
4346 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
4347 llvm::Value *BufferToGlobalRedFn = ::emitGlobalToListReduceFunction(
4348 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap,
4349 ReductionFn);
4350
4351 llvm::Value *Args[] = {
4352 RTLoc,
4353 ThreadId,
4354 GlobalBufferPtr,
4355 CGF.Builder.getInt32(C.getLangOpts().OpenMPCUDAReductionBufNum),
4356 RL,
4357 ShuffleAndReduceFn,
4358 InterWarpCopyFn,
4359 GlobalToBufferCpyFn,
4360 GlobalToBufferRedFn,
4361 BufferToGlobalCpyFn,
4362 BufferToGlobalRedFn};
4363
4364 Res = CGF.EmitRuntimeCall(
4365 createNVPTXRuntimeFunction(
4366 OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_v2),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004367 Args);
4368 }
4369
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004370 // 5. Build if (res == 1)
4371 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.reduction.done");
4372 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.then");
4373 llvm::Value *Cond = CGF.Builder.CreateICmpEQ(
4374 Res, llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1));
4375 CGF.Builder.CreateCondBr(Cond, ThenBB, ExitBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004376
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004377 // 6. Build then branch: where we have reduced values in the master
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004378 // thread in each team.
4379 // __kmpc_end_reduce{_nowait}(<gtid>);
4380 // break;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004381 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004382
4383 // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004384 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004385 this](CodeGenFunction &CGF, PrePostActionTy &Action) {
4386 auto IPriv = Privates.begin();
4387 auto ILHS = LHSExprs.begin();
4388 auto IRHS = RHSExprs.begin();
Alexey Bataev9ff80832018-04-16 20:16:21 +00004389 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004390 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4391 cast<DeclRefExpr>(*IRHS));
4392 ++IPriv;
4393 ++ILHS;
4394 ++IRHS;
4395 }
4396 };
Alexey Bataev8061acd2019-02-20 16:36:22 +00004397 llvm::Value *EndArgs[] = {ThreadId};
4398 RegionCodeGenTy RCG(CodeGen);
4399 NVPTXActionTy Action(
4400 nullptr, llvm::None,
4401 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_reduce_nowait),
4402 EndArgs);
4403 RCG.setAction(Action);
4404 RCG(CGF);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004405 // There is no need to emit line number for unconditional branch.
4406 (void)ApplyDebugLocation::CreateEmpty(CGF);
4407 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004408}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004409
4410const VarDecl *
4411CGOpenMPRuntimeNVPTX::translateParameter(const FieldDecl *FD,
4412 const VarDecl *NativeParam) const {
4413 if (!NativeParam->getType()->isReferenceType())
4414 return NativeParam;
4415 QualType ArgType = NativeParam->getType();
4416 QualifierCollector QC;
4417 const Type *NonQualTy = QC.strip(ArgType);
4418 QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4419 if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
4420 if (Attr->getCaptureKind() == OMPC_map) {
4421 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
4422 LangAS::opencl_global);
Alexey Bataev1af5bd52019-03-05 17:47:18 +00004423 } else if (Attr->getCaptureKind() == OMPC_firstprivate &&
4424 PointeeTy.isConstant(CGM.getContext())) {
4425 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
4426 LangAS::opencl_generic);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004427 }
4428 }
4429 ArgType = CGM.getContext().getPointerType(PointeeTy);
4430 QC.addRestrict();
4431 enum { NVPTX_local_addr = 5 };
Alexander Richardson6d989432017-10-15 18:48:14 +00004432 QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004433 ArgType = QC.apply(CGM.getContext(), ArgType);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004434 if (isa<ImplicitParamDecl>(NativeParam))
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004435 return ImplicitParamDecl::Create(
4436 CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
4437 NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004438 return ParmVarDecl::Create(
4439 CGM.getContext(),
4440 const_cast<DeclContext *>(NativeParam->getDeclContext()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004441 NativeParam->getBeginLoc(), NativeParam->getLocation(),
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004442 NativeParam->getIdentifier(), ArgType,
4443 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004444}
4445
4446Address
4447CGOpenMPRuntimeNVPTX::getParameterAddress(CodeGenFunction &CGF,
4448 const VarDecl *NativeParam,
4449 const VarDecl *TargetParam) const {
4450 assert(NativeParam != TargetParam &&
4451 NativeParam->getType()->isReferenceType() &&
4452 "Native arg must not be the same as target arg.");
4453 Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
4454 QualType NativeParamType = NativeParam->getType();
4455 QualifierCollector QC;
4456 const Type *NonQualTy = QC.strip(NativeParamType);
4457 QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4458 unsigned NativePointeeAddrSpace =
Alexander Richardson6d989432017-10-15 18:48:14 +00004459 CGF.getContext().getTargetAddressSpace(NativePointeeTy);
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004460 QualType TargetTy = TargetParam->getType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004461 llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004462 LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004463 // First cast to generic.
4464 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4465 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4466 /*AddrSpace=*/0));
4467 // Cast from generic to native address space.
4468 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4469 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4470 NativePointeeAddrSpace));
4471 Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
4472 CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004473 NativeParamType);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004474 return NativeParamAddr;
4475}
4476
4477void CGOpenMPRuntimeNVPTX::emitOutlinedFunctionCall(
James Y Knight9871db02019-02-05 16:42:33 +00004478 CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn,
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004479 ArrayRef<llvm::Value *> Args) const {
4480 SmallVector<llvm::Value *, 4> TargetArgs;
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004481 TargetArgs.reserve(Args.size());
James Y Knight9871db02019-02-05 16:42:33 +00004482 auto *FnType = OutlinedFn.getFunctionType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004483 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004484 if (FnType->isVarArg() && FnType->getNumParams() <= I) {
4485 TargetArgs.append(std::next(Args.begin(), I), Args.end());
4486 break;
4487 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004488 llvm::Type *TargetType = FnType->getParamType(I);
4489 llvm::Value *NativeArg = Args[I];
4490 if (!TargetType->isPointerTy()) {
4491 TargetArgs.emplace_back(NativeArg);
4492 continue;
4493 }
4494 llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataevc99042b2018-03-15 18:10:54 +00004495 NativeArg,
4496 NativeArg->getType()->getPointerElementType()->getPointerTo());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004497 TargetArgs.emplace_back(
4498 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
4499 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00004500 CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004501}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004502
4503/// Emit function which wraps the outline parallel region
4504/// and controls the arguments which are passed to this function.
4505/// The wrapper ensures that the outlined function is called
4506/// with the correct arguments when data is shared.
4507llvm::Function *CGOpenMPRuntimeNVPTX::createParallelDataSharingWrapper(
4508 llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
4509 ASTContext &Ctx = CGM.getContext();
4510 const auto &CS = *D.getCapturedStmt(OMPD_parallel);
4511
4512 // Create a function that takes as argument the source thread.
4513 FunctionArgList WrapperArgs;
4514 QualType Int16QTy =
4515 Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
4516 QualType Int32QTy =
4517 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004518 ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004519 /*Id=*/nullptr, Int16QTy,
4520 ImplicitParamDecl::Other);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004521 ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004522 /*Id=*/nullptr, Int32QTy,
4523 ImplicitParamDecl::Other);
4524 WrapperArgs.emplace_back(&ParallelLevelArg);
4525 WrapperArgs.emplace_back(&WrapperArg);
4526
Alexey Bataev9ff80832018-04-16 20:16:21 +00004527 const CGFunctionInfo &CGFI =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004528 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
4529
4530 auto *Fn = llvm::Function::Create(
4531 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataev9ff80832018-04-16 20:16:21 +00004532 Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004533 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004534 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004535 Fn->setDoesNotRecurse();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004536
4537 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
4538 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004539 D.getBeginLoc(), D.getBeginLoc());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004540
4541 const auto *RD = CS.getCapturedRecordDecl();
4542 auto CurField = RD->field_begin();
4543
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004544 Address ZeroAddr = CGF.CreateMemTemp(
4545 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
4546 /*Name*/ ".zero.addr");
4547 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004548 // Get the array of arguments.
4549 SmallVector<llvm::Value *, 8> Args;
4550
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004551 Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).getPointer());
4552 Args.emplace_back(ZeroAddr.getPointer());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004553
4554 CGBuilderTy &Bld = CGF.Builder;
4555 auto CI = CS.capture_begin();
4556
4557 // Use global memory for data sharing.
4558 // Handle passing of global args to workers.
4559 Address GlobalArgs =
4560 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
4561 llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
4562 llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
4563 CGF.EmitRuntimeCall(
4564 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_get_shared_variables),
4565 DataSharingArgs);
4566
4567 // Retrieve the shared variables from the list of references returned
4568 // by the runtime. Pass the variables to the outlined function.
Alexey Bataev17314212018-03-20 15:41:05 +00004569 Address SharedArgListAddress = Address::invalid();
4570 if (CS.capture_size() > 0 ||
4571 isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4572 SharedArgListAddress = CGF.EmitLoadOfPointer(
4573 GlobalArgs, CGF.getContext()
4574 .getPointerType(CGF.getContext().getPointerType(
4575 CGF.getContext().VoidPtrTy))
4576 .castAs<PointerType>());
4577 }
4578 unsigned Idx = 0;
4579 if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
James Y Knight751fe282019-02-09 22:22:28 +00004580 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004581 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4582 Src, CGF.SizeTy->getPointerTo());
4583 llvm::Value *LB = CGF.EmitLoadOfScalar(
4584 TypedAddress,
4585 /*Volatile=*/false,
4586 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4587 cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
4588 Args.emplace_back(LB);
4589 ++Idx;
James Y Knight751fe282019-02-09 22:22:28 +00004590 Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004591 TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4592 Src, CGF.SizeTy->getPointerTo());
4593 llvm::Value *UB = CGF.EmitLoadOfScalar(
4594 TypedAddress,
4595 /*Volatile=*/false,
4596 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4597 cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
4598 Args.emplace_back(UB);
4599 ++Idx;
4600 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004601 if (CS.capture_size() > 0) {
4602 ASTContext &CGFContext = CGF.getContext();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004603 for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
4604 QualType ElemTy = CurField->getType();
James Y Knight751fe282019-02-09 22:22:28 +00004605 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004606 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004607 Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)));
4608 llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
4609 /*Volatile=*/false,
4610 CGFContext.getPointerType(ElemTy),
4611 CI->getLocation());
Alexey Bataev2091ca62018-04-23 17:33:41 +00004612 if (CI->capturesVariableByCopy() &&
4613 !CI->getCapturedVar()->getType()->isAnyPointerType()) {
Alexey Bataev17314212018-03-20 15:41:05 +00004614 Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
4615 CI->getLocation());
4616 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004617 Args.emplace_back(Arg);
4618 }
4619 }
4620
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004621 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedParallelFn, Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004622 CGF.FinishFunction();
4623 return Fn;
4624}
4625
4626void CGOpenMPRuntimeNVPTX::emitFunctionProlog(CodeGenFunction &CGF,
4627 const Decl *D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004628 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4629 return;
4630
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004631 assert(D && "Expected function or captured|block decl.");
4632 assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
4633 "Function is registered already.");
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004634 assert((!TeamAndReductions.first || TeamAndReductions.first == D) &&
4635 "Team is set but not processed.");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004636 const Stmt *Body = nullptr;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004637 bool NeedToDelayGlobalization = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004638 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4639 Body = FD->getBody();
4640 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
4641 Body = BD->getBody();
4642 } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
4643 Body = CD->getBody();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004644 NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
Alexey Bataev2adecff2018-09-21 14:22:53 +00004645 if (NeedToDelayGlobalization &&
4646 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
4647 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004648 }
4649 if (!Body)
4650 return;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004651 CheckVarsEscapingDeclContext VarChecker(CGF, TeamAndReductions.second);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004652 VarChecker.Visit(Body);
Alexey Bataevff23bb62018-10-11 18:30:31 +00004653 const RecordDecl *GlobalizedVarsRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004654 VarChecker.getGlobalizedRecord(IsInTTDRegion);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004655 TeamAndReductions.first = nullptr;
4656 TeamAndReductions.second.clear();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004657 ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
4658 VarChecker.getEscapedVariableLengthDecls();
4659 if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004660 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004661 auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
4662 I->getSecond().MappedParams =
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00004663 std::make_unique<CodeGenFunction::OMPMapVars>();
Alexey Bataevc99042b2018-03-15 18:10:54 +00004664 I->getSecond().GlobalRecord = GlobalizedVarsRecord;
4665 I->getSecond().EscapedParameters.insert(
4666 VarChecker.getEscapedParameters().begin(),
4667 VarChecker.getEscapedParameters().end());
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004668 I->getSecond().EscapedVariableLengthDecls.append(
4669 EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004670 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004671 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004672 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004673 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004674 Data.insert(std::make_pair(VD, MappedVarData(FD, IsInTTDRegion)));
Alexey Bataevc99042b2018-03-15 18:10:54 +00004675 }
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004676 if (!IsInTTDRegion && !NeedToDelayGlobalization && !IsInParallelRegion) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004677 CheckVarsEscapingDeclContext VarChecker(CGF, llvm::None);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004678 VarChecker.Visit(Body);
4679 I->getSecond().SecondaryGlobalRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004680 VarChecker.getGlobalizedRecord(/*IsInTTDRegion=*/true);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004681 I->getSecond().SecondaryLocalVarData.emplace();
4682 DeclToAddrMapTy &Data = I->getSecond().SecondaryLocalVarData.getValue();
4683 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
4684 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
4685 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004686 Data.insert(
4687 std::make_pair(VD, MappedVarData(FD, /*IsInTTDRegion=*/true)));
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004688 }
4689 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00004690 if (!NeedToDelayGlobalization) {
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004691 emitGenericVarsProlog(CGF, D->getBeginLoc(), /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004692 struct GlobalizationScope final : EHScopeStack::Cleanup {
4693 GlobalizationScope() = default;
4694
4695 void Emit(CodeGenFunction &CGF, Flags flags) override {
4696 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004697 .emitGenericVarsEpilog(CGF, /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004698 }
4699 };
4700 CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004701 }
4702}
4703
4704Address CGOpenMPRuntimeNVPTX::getAddressOfLocalVariable(CodeGenFunction &CGF,
4705 const VarDecl *VD) {
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004706 if (VD && VD->hasAttr<OMPAllocateDeclAttr>()) {
4707 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
4708 switch (A->getAllocatorType()) {
4709 // Use the default allocator here as by default local vars are
4710 // threadlocal.
4711 case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
4712 case OMPAllocateDeclAttr::OMPThreadMemAlloc:
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004713 case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
4714 case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
Alexey Bataev1db9bfe2019-04-08 16:53:57 +00004715 // Follow the user decision - use default allocation.
4716 return Address::invalid();
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004717 case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
Alexey Bataev1db9bfe2019-04-08 16:53:57 +00004718 // TODO: implement aupport for user-defined allocators.
4719 return Address::invalid();
4720 case OMPAllocateDeclAttr::OMPConstMemAlloc: {
4721 llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
4722 auto *GV = new llvm::GlobalVariable(
4723 CGM.getModule(), VarTy, /*isConstant=*/false,
4724 llvm::GlobalValue::InternalLinkage,
4725 llvm::Constant::getNullValue(VarTy), VD->getName(),
4726 /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
4727 CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant));
4728 CharUnits Align = CGM.getContext().getDeclAlign(VD);
4729 GV->setAlignment(Align.getQuantity());
4730 return Address(GV, Align);
4731 }
4732 case OMPAllocateDeclAttr::OMPPTeamMemAlloc: {
4733 llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
4734 auto *GV = new llvm::GlobalVariable(
4735 CGM.getModule(), VarTy, /*isConstant=*/false,
4736 llvm::GlobalValue::InternalLinkage,
4737 llvm::Constant::getNullValue(VarTy), VD->getName(),
4738 /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
4739 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
4740 CharUnits Align = CGM.getContext().getDeclAlign(VD);
4741 GV->setAlignment(Align.getQuantity());
4742 return Address(GV, Align);
4743 }
4744 case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
4745 case OMPAllocateDeclAttr::OMPCGroupMemAlloc: {
4746 llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
4747 auto *GV = new llvm::GlobalVariable(
4748 CGM.getModule(), VarTy, /*isConstant=*/false,
4749 llvm::GlobalValue::InternalLinkage,
4750 llvm::Constant::getNullValue(VarTy), VD->getName());
4751 CharUnits Align = CGM.getContext().getDeclAlign(VD);
4752 GV->setAlignment(Align.getQuantity());
4753 return Address(GV, Align);
4754 }
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004755 }
4756 }
4757
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004758 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4759 return Address::invalid();
4760
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004761 VD = VD->getCanonicalDecl();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004762 auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
4763 if (I == FunctionGlobalizedDecls.end())
4764 return Address::invalid();
Alexey Bataevc99042b2018-03-15 18:10:54 +00004765 auto VDI = I->getSecond().LocalVarData.find(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004766 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004767 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004768 if (VD->hasAttrs()) {
4769 for (specific_attr_iterator<OMPReferencedVarAttr> IT(VD->attr_begin()),
4770 E(VD->attr_end());
4771 IT != E; ++IT) {
4772 auto VDI = I->getSecond().LocalVarData.find(
4773 cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
4774 ->getCanonicalDecl());
4775 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004776 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004777 }
4778 }
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004779
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004780 return Address::invalid();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004781}
4782
4783void CGOpenMPRuntimeNVPTX::functionFinished(CodeGenFunction &CGF) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004784 FunctionGlobalizedDecls.erase(CGF.CurFn);
4785 CGOpenMPRuntime::functionFinished(CGF);
4786}
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004787
4788void CGOpenMPRuntimeNVPTX::getDefaultDistScheduleAndChunk(
4789 CodeGenFunction &CGF, const OMPLoopDirective &S,
4790 OpenMPDistScheduleClauseKind &ScheduleKind,
4791 llvm::Value *&Chunk) const {
4792 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
4793 ScheduleKind = OMPC_DIST_SCHEDULE_static;
4794 Chunk = CGF.EmitScalarConversion(getNVPTXNumThreads(CGF),
4795 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4796 S.getIterationVariable()->getType(), S.getBeginLoc());
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004797 return;
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004798 }
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004799 CGOpenMPRuntime::getDefaultDistScheduleAndChunk(
4800 CGF, S, ScheduleKind, Chunk);
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004801}
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004802
4803void CGOpenMPRuntimeNVPTX::getDefaultScheduleAndChunk(
4804 CodeGenFunction &CGF, const OMPLoopDirective &S,
4805 OpenMPScheduleClauseKind &ScheduleKind,
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004806 const Expr *&ChunkExpr) const {
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004807 ScheduleKind = OMPC_SCHEDULE_static;
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004808 // Chunk size is 1 in this case.
4809 llvm::APInt ChunkSize(32, 1);
4810 ChunkExpr = IntegerLiteral::Create(CGF.getContext(), ChunkSize,
4811 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4812 SourceLocation());
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004813}
Alexey Bataev60705422018-10-30 15:50:12 +00004814
4815void CGOpenMPRuntimeNVPTX::adjustTargetSpecificDataForLambdas(
4816 CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
4817 assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
4818 " Expected target-based directive.");
4819 const CapturedStmt *CS = D.getCapturedStmt(OMPD_target);
4820 for (const CapturedStmt::Capture &C : CS->captures()) {
4821 // Capture variables captured by reference in lambdas for target-based
4822 // directives.
4823 if (!C.capturesVariable())
4824 continue;
4825 const VarDecl *VD = C.getCapturedVar();
4826 const auto *RD = VD->getType()
4827 .getCanonicalType()
4828 .getNonReferenceType()
4829 ->getAsCXXRecordDecl();
4830 if (!RD || !RD->isLambda())
4831 continue;
4832 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4833 LValue VDLVal;
4834 if (VD->getType().getCanonicalType()->isReferenceType())
4835 VDLVal = CGF.EmitLoadOfReferenceLValue(VDAddr, VD->getType());
4836 else
4837 VDLVal = CGF.MakeAddrLValue(
4838 VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
4839 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4840 FieldDecl *ThisCapture = nullptr;
4841 RD->getCaptureFields(Captures, ThisCapture);
4842 if (ThisCapture && CGF.CapturedStmtInfo->isCXXThisExprCaptured()) {
4843 LValue ThisLVal =
4844 CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
4845 llvm::Value *CXXThis = CGF.LoadCXXThis();
4846 CGF.EmitStoreOfScalar(CXXThis, ThisLVal);
4847 }
4848 for (const LambdaCapture &LC : RD->captures()) {
4849 if (LC.getCaptureKind() != LCK_ByRef)
4850 continue;
4851 const VarDecl *VD = LC.getCapturedVar();
4852 if (!CS->capturesVariable(VD))
4853 continue;
4854 auto It = Captures.find(VD);
4855 assert(It != Captures.end() && "Found lambda capture without field.");
4856 LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
4857 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4858 if (VD->getType().getCanonicalType()->isReferenceType())
4859 VDAddr = CGF.EmitLoadOfReferenceLValue(VDAddr,
4860 VD->getType().getCanonicalType())
4861 .getAddress();
4862 CGF.EmitStoreOfScalar(VDAddr.getPointer(), VarLVal);
4863 }
4864 }
4865}
4866
Alexey Bataev1af5bd52019-03-05 17:47:18 +00004867unsigned CGOpenMPRuntimeNVPTX::getDefaultFirstprivateAddressSpace() const {
4868 return CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant);
4869}
4870
Alexey Bataevc5687252019-03-21 19:35:27 +00004871bool CGOpenMPRuntimeNVPTX::hasAllocateAttributeForGlobalVar(const VarDecl *VD,
4872 LangAS &AS) {
4873 if (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())
4874 return false;
4875 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
4876 switch(A->getAllocatorType()) {
4877 case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
4878 // Not supported, fallback to the default mem space.
4879 case OMPAllocateDeclAttr::OMPThreadMemAlloc:
4880 case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
4881 case OMPAllocateDeclAttr::OMPCGroupMemAlloc:
4882 case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
4883 case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
4884 AS = LangAS::Default;
4885 return true;
4886 case OMPAllocateDeclAttr::OMPConstMemAlloc:
4887 AS = LangAS::cuda_constant;
4888 return true;
4889 case OMPAllocateDeclAttr::OMPPTeamMemAlloc:
4890 AS = LangAS::cuda_shared;
4891 return true;
4892 case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
4893 llvm_unreachable("Expected predefined allocator for the variables with the "
4894 "static storage.");
4895 }
4896 return false;
4897}
4898
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004899// Get current CudaArch and ignore any unknown values
4900static CudaArch getCudaArch(CodeGenModule &CGM) {
4901 if (!CGM.getTarget().hasFeature("ptx"))
4902 return CudaArch::UNKNOWN;
4903 llvm::StringMap<bool> Features;
4904 CGM.getTarget().initFeatureMap(Features, CGM.getDiags(),
4905 CGM.getTarget().getTargetOpts().CPU,
4906 CGM.getTarget().getTargetOpts().Features);
4907 for (const auto &Feature : Features) {
4908 if (Feature.getValue()) {
4909 CudaArch Arch = StringToCudaArch(Feature.getKey());
4910 if (Arch != CudaArch::UNKNOWN)
4911 return Arch;
4912 }
4913 }
4914 return CudaArch::UNKNOWN;
4915}
4916
4917/// Check to see if target architecture supports unified addressing which is
4918/// a restriction for OpenMP requires clause "unified_shared_memory".
4919void CGOpenMPRuntimeNVPTX::checkArchForUnifiedAddressing(
Gheorghe-Teodor Bercea66cdbb472019-05-21 19:42:01 +00004920 const OMPRequiresDecl *D) {
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004921 for (const OMPClause *Clause : D->clauselists()) {
4922 if (Clause->getClauseKind() == OMPC_unified_shared_memory) {
4923 switch (getCudaArch(CGM)) {
4924 case CudaArch::SM_20:
4925 case CudaArch::SM_21:
4926 case CudaArch::SM_30:
4927 case CudaArch::SM_32:
4928 case CudaArch::SM_35:
4929 case CudaArch::SM_37:
4930 case CudaArch::SM_50:
4931 case CudaArch::SM_52:
4932 case CudaArch::SM_53:
4933 case CudaArch::SM_60:
4934 case CudaArch::SM_61:
4935 case CudaArch::SM_62:
4936 CGM.Error(Clause->getBeginLoc(),
4937 "Target architecture does not support unified addressing");
4938 return;
4939 case CudaArch::SM_70:
4940 case CudaArch::SM_72:
4941 case CudaArch::SM_75:
4942 case CudaArch::GFX600:
4943 case CudaArch::GFX601:
4944 case CudaArch::GFX700:
4945 case CudaArch::GFX701:
4946 case CudaArch::GFX702:
4947 case CudaArch::GFX703:
4948 case CudaArch::GFX704:
4949 case CudaArch::GFX801:
4950 case CudaArch::GFX802:
4951 case CudaArch::GFX803:
4952 case CudaArch::GFX810:
4953 case CudaArch::GFX900:
4954 case CudaArch::GFX902:
4955 case CudaArch::GFX904:
4956 case CudaArch::GFX906:
Stanislav Mekhanoshin0cfd75a2019-07-09 18:19:00 +00004957 case CudaArch::GFX908:
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004958 case CudaArch::GFX909:
Yaxun Liu6add24a2019-07-11 17:50:09 +00004959 case CudaArch::GFX1010:
4960 case CudaArch::GFX1011:
4961 case CudaArch::GFX1012:
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004962 case CudaArch::UNKNOWN:
4963 break;
4964 case CudaArch::LAST:
4965 llvm_unreachable("Unexpected Cuda arch.");
4966 }
4967 }
4968 }
Gheorghe-Teodor Bercea66cdbb472019-05-21 19:42:01 +00004969 CGOpenMPRuntime::checkArchForUnifiedAddressing(D);
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004970}
4971
Alexey Bataeve4090182018-11-02 14:54:07 +00004972/// Get number of SMs and number of blocks per SM.
4973static std::pair<unsigned, unsigned> getSMsBlocksPerSM(CodeGenModule &CGM) {
4974 std::pair<unsigned, unsigned> Data;
4975 if (CGM.getLangOpts().OpenMPCUDANumSMs)
4976 Data.first = CGM.getLangOpts().OpenMPCUDANumSMs;
4977 if (CGM.getLangOpts().OpenMPCUDABlocksPerSM)
4978 Data.second = CGM.getLangOpts().OpenMPCUDABlocksPerSM;
4979 if (Data.first && Data.second)
4980 return Data;
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004981 switch (getCudaArch(CGM)) {
4982 case CudaArch::SM_20:
4983 case CudaArch::SM_21:
4984 case CudaArch::SM_30:
4985 case CudaArch::SM_32:
4986 case CudaArch::SM_35:
4987 case CudaArch::SM_37:
4988 case CudaArch::SM_50:
4989 case CudaArch::SM_52:
4990 case CudaArch::SM_53:
4991 return {16, 16};
4992 case CudaArch::SM_60:
4993 case CudaArch::SM_61:
4994 case CudaArch::SM_62:
4995 return {56, 32};
4996 case CudaArch::SM_70:
4997 case CudaArch::SM_72:
4998 case CudaArch::SM_75:
4999 return {84, 32};
5000 case CudaArch::GFX600:
5001 case CudaArch::GFX601:
5002 case CudaArch::GFX700:
5003 case CudaArch::GFX701:
5004 case CudaArch::GFX702:
5005 case CudaArch::GFX703:
5006 case CudaArch::GFX704:
5007 case CudaArch::GFX801:
5008 case CudaArch::GFX802:
5009 case CudaArch::GFX803:
5010 case CudaArch::GFX810:
5011 case CudaArch::GFX900:
5012 case CudaArch::GFX902:
5013 case CudaArch::GFX904:
5014 case CudaArch::GFX906:
Stanislav Mekhanoshin0cfd75a2019-07-09 18:19:00 +00005015 case CudaArch::GFX908:
Patrick Lyster8f7f5862018-11-19 15:09:33 +00005016 case CudaArch::GFX909:
Yaxun Liu6add24a2019-07-11 17:50:09 +00005017 case CudaArch::GFX1010:
5018 case CudaArch::GFX1011:
5019 case CudaArch::GFX1012:
Patrick Lyster8f7f5862018-11-19 15:09:33 +00005020 case CudaArch::UNKNOWN:
5021 break;
5022 case CudaArch::LAST:
5023 llvm_unreachable("Unexpected Cuda arch.");
Alexey Bataeve4090182018-11-02 14:54:07 +00005024 }
5025 llvm_unreachable("Unexpected NVPTX target without ptx feature.");
5026}
5027
5028void CGOpenMPRuntimeNVPTX::clear() {
5029 if (!GlobalizedRecords.empty()) {
5030 ASTContext &C = CGM.getContext();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005031 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> GlobalRecs;
5032 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> SharedRecs;
Alexey Bataeve4090182018-11-02 14:54:07 +00005033 RecordDecl *StaticRD = C.buildImplicitRecord(
5034 "_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
5035 StaticRD->startDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005036 RecordDecl *SharedStaticRD = C.buildImplicitRecord(
5037 "_shared_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
5038 SharedStaticRD->startDefinition();
Alexey Bataeve4090182018-11-02 14:54:07 +00005039 for (const GlobalPtrSizeRecsTy &Records : GlobalizedRecords) {
5040 if (Records.Records.empty())
5041 continue;
5042 unsigned Size = 0;
5043 unsigned RecAlignment = 0;
5044 for (const RecordDecl *RD : Records.Records) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005045 QualType RDTy = C.getRecordType(RD);
5046 unsigned Alignment = C.getTypeAlignInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00005047 RecAlignment = std::max(RecAlignment, Alignment);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005048 unsigned RecSize = C.getTypeSizeInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00005049 Size =
5050 llvm::alignTo(llvm::alignTo(Size, Alignment) + RecSize, Alignment);
5051 }
5052 Size = llvm::alignTo(Size, RecAlignment);
5053 llvm::APInt ArySize(/*numBits=*/64, Size);
5054 QualType SubTy = C.getConstantArrayType(
5055 C.CharTy, ArySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005056 const bool UseSharedMemory = Size <= SharedMemorySize;
5057 auto *Field =
5058 FieldDecl::Create(C, UseSharedMemory ? SharedStaticRD : StaticRD,
5059 SourceLocation(), SourceLocation(), nullptr, SubTy,
5060 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
5061 /*BW=*/nullptr, /*Mutable=*/false,
5062 /*InitStyle=*/ICIS_NoInit);
Alexey Bataeve4090182018-11-02 14:54:07 +00005063 Field->setAccess(AS_public);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005064 if (UseSharedMemory) {
5065 SharedStaticRD->addDecl(Field);
5066 SharedRecs.push_back(&Records);
5067 } else {
5068 StaticRD->addDecl(Field);
5069 GlobalRecs.push_back(&Records);
5070 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005071 Records.RecSize->setInitializer(llvm::ConstantInt::get(CGM.SizeTy, Size));
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005072 Records.UseSharedMemory->setInitializer(
5073 llvm::ConstantInt::get(CGM.Int16Ty, UseSharedMemory ? 1 : 0));
5074 }
Alexey Bataev6a1b06b2018-12-18 21:01:42 +00005075 // Allocate SharedMemorySize buffer for the shared memory.
5076 // FIXME: nvlink does not handle weak linkage correctly (object with the
5077 // different size are reported as erroneous).
5078 // Restore this code as sson as nvlink is fixed.
5079 if (!SharedStaticRD->field_empty()) {
5080 llvm::APInt ArySize(/*numBits=*/64, SharedMemorySize);
5081 QualType SubTy = C.getConstantArrayType(
5082 C.CharTy, ArySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
5083 auto *Field = FieldDecl::Create(
5084 C, SharedStaticRD, SourceLocation(), SourceLocation(), nullptr, SubTy,
5085 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
5086 /*BW=*/nullptr, /*Mutable=*/false,
5087 /*InitStyle=*/ICIS_NoInit);
5088 Field->setAccess(AS_public);
5089 SharedStaticRD->addDecl(Field);
5090 }
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005091 SharedStaticRD->completeDefinition();
5092 if (!SharedStaticRD->field_empty()) {
5093 QualType StaticTy = C.getRecordType(SharedStaticRD);
5094 llvm::Type *LLVMStaticTy = CGM.getTypes().ConvertTypeForMem(StaticTy);
5095 auto *GV = new llvm::GlobalVariable(
5096 CGM.getModule(), LLVMStaticTy,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00005097 /*isConstant=*/false, llvm::GlobalValue::CommonLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005098 llvm::Constant::getNullValue(LLVMStaticTy),
5099 "_openmp_shared_static_glob_rd_$_", /*InsertBefore=*/nullptr,
5100 llvm::GlobalValue::NotThreadLocal,
5101 C.getTargetAddressSpace(LangAS::cuda_shared));
5102 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
5103 GV, CGM.VoidPtrTy);
5104 for (const GlobalPtrSizeRecsTy *Rec : SharedRecs) {
5105 Rec->Buffer->replaceAllUsesWith(Replacement);
5106 Rec->Buffer->eraseFromParent();
5107 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005108 }
5109 StaticRD->completeDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005110 if (!StaticRD->field_empty()) {
5111 QualType StaticTy = C.getRecordType(StaticRD);
5112 std::pair<unsigned, unsigned> SMsBlockPerSM = getSMsBlocksPerSM(CGM);
5113 llvm::APInt Size1(32, SMsBlockPerSM.second);
5114 QualType Arr1Ty =
5115 C.getConstantArrayType(StaticTy, Size1, ArrayType::Normal,
5116 /*IndexTypeQuals=*/0);
5117 llvm::APInt Size2(32, SMsBlockPerSM.first);
5118 QualType Arr2Ty = C.getConstantArrayType(Arr1Ty, Size2, ArrayType::Normal,
5119 /*IndexTypeQuals=*/0);
5120 llvm::Type *LLVMArr2Ty = CGM.getTypes().ConvertTypeForMem(Arr2Ty);
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005121 // FIXME: nvlink does not handle weak linkage correctly (object with the
5122 // different size are reported as erroneous).
5123 // Restore CommonLinkage as soon as nvlink is fixed.
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005124 auto *GV = new llvm::GlobalVariable(
5125 CGM.getModule(), LLVMArr2Ty,
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005126 /*isConstant=*/false, llvm::GlobalValue::InternalLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005127 llvm::Constant::getNullValue(LLVMArr2Ty),
5128 "_openmp_static_glob_rd_$_");
5129 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
5130 GV, CGM.VoidPtrTy);
5131 for (const GlobalPtrSizeRecsTy *Rec : GlobalRecs) {
5132 Rec->Buffer->replaceAllUsesWith(Replacement);
5133 Rec->Buffer->eraseFromParent();
5134 }
5135 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005136 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00005137 if (!TeamsReductions.empty()) {
5138 ASTContext &C = CGM.getContext();
5139 RecordDecl *StaticRD = C.buildImplicitRecord(
5140 "_openmp_teams_reduction_type_$_", RecordDecl::TagKind::TTK_Union);
5141 StaticRD->startDefinition();
5142 for (const RecordDecl *TeamReductionRec : TeamsReductions) {
5143 QualType RecTy = C.getRecordType(TeamReductionRec);
5144 auto *Field = FieldDecl::Create(
5145 C, StaticRD, SourceLocation(), SourceLocation(), nullptr, RecTy,
5146 C.getTrivialTypeSourceInfo(RecTy, SourceLocation()),
5147 /*BW=*/nullptr, /*Mutable=*/false,
5148 /*InitStyle=*/ICIS_NoInit);
5149 Field->setAccess(AS_public);
5150 StaticRD->addDecl(Field);
5151 }
5152 StaticRD->completeDefinition();
5153 QualType StaticTy = C.getRecordType(StaticRD);
5154 llvm::Type *LLVMReductionsBufferTy =
5155 CGM.getTypes().ConvertTypeForMem(StaticTy);
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005156 // FIXME: nvlink does not handle weak linkage correctly (object with the
5157 // different size are reported as erroneous).
5158 // Restore CommonLinkage as soon as nvlink is fixed.
Alexey Bataev8061acd2019-02-20 16:36:22 +00005159 auto *GV = new llvm::GlobalVariable(
5160 CGM.getModule(), LLVMReductionsBufferTy,
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005161 /*isConstant=*/false, llvm::GlobalValue::InternalLinkage,
Alexey Bataev8061acd2019-02-20 16:36:22 +00005162 llvm::Constant::getNullValue(LLVMReductionsBufferTy),
5163 "_openmp_teams_reductions_buffer_$_");
5164 KernelTeamsReductionPtr->setInitializer(
5165 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
5166 CGM.VoidPtrTy));
5167 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005168 CGOpenMPRuntime::clear();
5169}