blob: c1233044cd60e3df7ee20ffb167c44d392df4c5b [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 Bataev8e009032019-01-04 17:25:09 +000063 OMPRTL_NVPTX__kmpc_parallel_reduce_nowait_v2,
Alexey Bataeva1166022018-11-27 21:24:54 +000064 /// Call to __kmpc_nvptx_teams_reduce_nowait_simple(ident_t *loc, kmp_int32
65 /// global_tid, kmp_critical_name *lck)
66 OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_simple,
67 /// Call to __kmpc_nvptx_teams_end_reduce_nowait_simple(ident_t *loc,
68 /// kmp_int32 global_tid, kmp_critical_name *lck)
69 OMPRTL_NVPTX__kmpc_nvptx_teams_end_reduce_nowait_simple,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000070 /// Call to __kmpc_nvptx_end_reduce_nowait(int32_t global_tid);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000071 OMPRTL_NVPTX__kmpc_end_reduce_nowait,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000072 /// Call to void __kmpc_data_sharing_init_stack();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000073 OMPRTL_NVPTX__kmpc_data_sharing_init_stack,
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +000074 /// Call to void __kmpc_data_sharing_init_stack_spmd();
75 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd,
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +000076 /// Call to void* __kmpc_data_sharing_coalesced_push_stack(size_t size,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000077 /// int16_t UseSharedMemory);
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +000078 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000079 /// Call to void __kmpc_data_sharing_pop_stack(void *a);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000080 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000081 /// Call to void __kmpc_begin_sharing_variables(void ***args,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000082 /// size_t n_args);
83 OMPRTL_NVPTX__kmpc_begin_sharing_variables,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000084 /// Call to void __kmpc_end_sharing_variables();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000085 OMPRTL_NVPTX__kmpc_end_sharing_variables,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000086 /// Call to void __kmpc_get_shared_variables(void ***GlobalArgs)
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000087 OMPRTL_NVPTX__kmpc_get_shared_variables,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +000088 /// Call to uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32
89 /// global_tid);
90 OMPRTL_NVPTX__kmpc_parallel_level,
Alexey Bataev673110d2018-05-16 13:36:30 +000091 /// Call to int8_t __kmpc_is_spmd_exec_mode();
92 OMPRTL_NVPTX__kmpc_is_spmd_exec_mode,
Alexey Bataev8e009032019-01-04 17:25:09 +000093 /// Call to void __kmpc_get_team_static_memory(int16_t isSPMDExecutionMode,
94 /// const void *buf, size_t size, int16_t is_shared, const void **res);
Alexey Bataeve4090182018-11-02 14:54:07 +000095 OMPRTL_NVPTX__kmpc_get_team_static_memory,
Alexey Bataev8e009032019-01-04 17:25:09 +000096 /// Call to void __kmpc_restore_team_static_memory(int16_t
97 /// isSPMDExecutionMode, int16_t is_shared);
Alexey Bataeve4090182018-11-02 14:54:07 +000098 OMPRTL_NVPTX__kmpc_restore_team_static_memory,
Alexey Bataeva3924b52019-01-03 16:25:35 +000099 /// Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataevc3028ca2018-12-04 15:03:25 +0000100 OMPRTL__kmpc_barrier,
Alexey Bataeva3924b52019-01-03 16:25:35 +0000101 /// Call to void __kmpc_barrier_simple_spmd(ident_t *loc, kmp_int32
102 /// global_tid);
103 OMPRTL__kmpc_barrier_simple_spmd,
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000104};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000105
106/// Pre(post)-action for different OpenMP constructs specialized for NVPTX.
107class NVPTXActionTy final : public PrePostActionTy {
Alexey Bataev9ff80832018-04-16 20:16:21 +0000108 llvm::Value *EnterCallee = nullptr;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000109 ArrayRef<llvm::Value *> EnterArgs;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000110 llvm::Value *ExitCallee = nullptr;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000111 ArrayRef<llvm::Value *> ExitArgs;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000112 bool Conditional = false;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000113 llvm::BasicBlock *ContBlock = nullptr;
114
115public:
116 NVPTXActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
117 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
118 bool Conditional = false)
119 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
120 ExitArgs(ExitArgs), Conditional(Conditional) {}
121 void Enter(CodeGenFunction &CGF) override {
122 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
123 if (Conditional) {
124 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
125 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
126 ContBlock = CGF.createBasicBlock("omp_if.end");
127 // Generate the branch (If-stmt)
128 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
129 CGF.EmitBlock(ThenBlock);
130 }
131 }
132 void Done(CodeGenFunction &CGF) {
133 // Emit the rest of blocks/branches
134 CGF.EmitBranch(ContBlock);
135 CGF.EmitBlock(ContBlock, true);
136 }
137 void Exit(CodeGenFunction &CGF) override {
138 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
139 }
140};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000141
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000142/// A class to track the execution mode when codegening directives within
143/// a target region. The appropriate mode (SPMD|NON-SPMD) is set on entry
144/// to the target region and used by containing directives such as 'parallel'
145/// to emit optimized code.
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000146class ExecutionRuntimeModesRAII {
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000147private:
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000148 CGOpenMPRuntimeNVPTX::ExecutionMode SavedExecMode =
149 CGOpenMPRuntimeNVPTX::EM_Unknown;
150 CGOpenMPRuntimeNVPTX::ExecutionMode &ExecMode;
151 bool SavedRuntimeMode = false;
152 bool *RuntimeMode = nullptr;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000153
154public:
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000155 /// Constructor for Non-SPMD mode.
156 ExecutionRuntimeModesRAII(CGOpenMPRuntimeNVPTX::ExecutionMode &ExecMode)
157 : ExecMode(ExecMode) {
158 SavedExecMode = ExecMode;
159 ExecMode = CGOpenMPRuntimeNVPTX::EM_NonSPMD;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000160 }
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000161 /// Constructor for SPMD mode.
162 ExecutionRuntimeModesRAII(CGOpenMPRuntimeNVPTX::ExecutionMode &ExecMode,
163 bool &RuntimeMode, bool FullRuntimeMode)
164 : ExecMode(ExecMode), RuntimeMode(&RuntimeMode) {
165 SavedExecMode = ExecMode;
166 SavedRuntimeMode = RuntimeMode;
167 ExecMode = CGOpenMPRuntimeNVPTX::EM_SPMD;
168 RuntimeMode = FullRuntimeMode;
169 }
170 ~ExecutionRuntimeModesRAII() {
171 ExecMode = SavedExecMode;
172 if (RuntimeMode)
173 *RuntimeMode = SavedRuntimeMode;
174 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000175};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000176
177/// GPU Configuration: This information can be derived from cuda registers,
178/// however, providing compile time constants helps generate more efficient
179/// code. For all practical purposes this is fine because the configuration
180/// is the same for all known NVPTX architectures.
181enum MachineConfiguration : unsigned {
182 WarpSize = 32,
183 /// Number of bits required to represent a lane identifier, which is
184 /// computed as log_2(WarpSize).
185 LaneIDBits = 5,
186 LaneIDMask = WarpSize - 1,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +0000187
188 /// Global memory alignment for performance.
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000189 GlobalMemoryAlignment = 128,
Alexey Bataev09c9eea2018-11-09 16:18:04 +0000190
191 /// Maximal size of the shared memory buffer.
192 SharedMemorySize = 128,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000193};
194
Alexey Bataevf2f39be2018-11-16 19:38:21 +0000195static const ValueDecl *getPrivateItem(const Expr *RefExpr) {
196 RefExpr = RefExpr->IgnoreParens();
197 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr)) {
198 const Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
199 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
200 Base = TempASE->getBase()->IgnoreParenImpCasts();
201 RefExpr = Base;
202 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr)) {
203 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
204 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
205 Base = TempOASE->getBase()->IgnoreParenImpCasts();
206 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
207 Base = TempASE->getBase()->IgnoreParenImpCasts();
208 RefExpr = Base;
209 }
210 RefExpr = RefExpr->IgnoreParenImpCasts();
211 if (const auto *DE = dyn_cast<DeclRefExpr>(RefExpr))
212 return cast<ValueDecl>(DE->getDecl()->getCanonicalDecl());
213 const auto *ME = cast<MemberExpr>(RefExpr);
214 return cast<ValueDecl>(ME->getMemberDecl()->getCanonicalDecl());
215}
216
Alexey Bataev2adecff2018-09-21 14:22:53 +0000217typedef std::pair<CharUnits /*Align*/, const ValueDecl *> VarsDataTy;
218static bool stable_sort_comparator(const VarsDataTy P1, const VarsDataTy P2) {
219 return P1.first > P2.first;
220}
221
222static RecordDecl *buildRecordForGlobalizedVars(
223 ASTContext &C, ArrayRef<const ValueDecl *> EscapedDecls,
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000224 ArrayRef<const ValueDecl *> EscapedDeclsForTeams,
Alexey Bataev2adecff2018-09-21 14:22:53 +0000225 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
226 &MappedDeclsFields) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000227 if (EscapedDecls.empty() && EscapedDeclsForTeams.empty())
Alexey Bataev2adecff2018-09-21 14:22:53 +0000228 return nullptr;
229 SmallVector<VarsDataTy, 4> GlobalizedVars;
230 for (const ValueDecl *D : EscapedDecls)
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000231 GlobalizedVars.emplace_back(
232 CharUnits::fromQuantity(std::max(
233 C.getDeclAlign(D).getQuantity(),
234 static_cast<CharUnits::QuantityType>(GlobalMemoryAlignment))),
235 D);
236 for (const ValueDecl *D : EscapedDeclsForTeams)
Alexey Bataev2adecff2018-09-21 14:22:53 +0000237 GlobalizedVars.emplace_back(C.getDeclAlign(D), D);
238 std::stable_sort(GlobalizedVars.begin(), GlobalizedVars.end(),
239 stable_sort_comparator);
240 // Build struct _globalized_locals_ty {
Alexey Bataevff23bb62018-10-11 18:30:31 +0000241 // /* globalized vars */[WarSize] align (max(decl_align,
242 // GlobalMemoryAlignment))
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000243 // /* globalized vars */ for EscapedDeclsForTeams
Alexey Bataev2adecff2018-09-21 14:22:53 +0000244 // };
245 RecordDecl *GlobalizedRD = C.buildImplicitRecord("_globalized_locals_ty");
246 GlobalizedRD->startDefinition();
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000247 llvm::SmallPtrSet<const ValueDecl *, 16> SingleEscaped(
248 EscapedDeclsForTeams.begin(), EscapedDeclsForTeams.end());
Alexey Bataev2adecff2018-09-21 14:22:53 +0000249 for (const auto &Pair : GlobalizedVars) {
250 const ValueDecl *VD = Pair.second;
251 QualType Type = VD->getType();
252 if (Type->isLValueReferenceType())
253 Type = C.getPointerType(Type.getNonReferenceType());
254 else
255 Type = Type.getNonReferenceType();
256 SourceLocation Loc = VD->getLocation();
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000257 FieldDecl *Field;
258 if (SingleEscaped.count(VD)) {
259 Field = FieldDecl::Create(
260 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
261 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
262 /*BW=*/nullptr, /*Mutable=*/false,
263 /*InitStyle=*/ICIS_NoInit);
264 Field->setAccess(AS_public);
265 if (VD->hasAttrs()) {
266 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
267 E(VD->getAttrs().end());
268 I != E; ++I)
269 Field->addAttr(*I);
270 }
271 } else {
272 llvm::APInt ArraySize(32, WarpSize);
273 Type = C.getConstantArrayType(Type, ArraySize, ArrayType::Normal, 0);
274 Field = FieldDecl::Create(
275 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
276 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
277 /*BW=*/nullptr, /*Mutable=*/false,
278 /*InitStyle=*/ICIS_NoInit);
279 Field->setAccess(AS_public);
280 llvm::APInt Align(32, std::max(C.getDeclAlign(VD).getQuantity(),
281 static_cast<CharUnits::QuantityType>(
282 GlobalMemoryAlignment)));
283 Field->addAttr(AlignedAttr::CreateImplicit(
284 C, AlignedAttr::GNU_aligned, /*IsAlignmentExpr=*/true,
285 IntegerLiteral::Create(C, Align,
286 C.getIntTypeForBitwidth(32, /*Signed=*/0),
287 SourceLocation())));
Alexey Bataev2adecff2018-09-21 14:22:53 +0000288 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000289 GlobalizedRD->addDecl(Field);
Alexey Bataev2adecff2018-09-21 14:22:53 +0000290 MappedDeclsFields.try_emplace(VD, Field);
291 }
292 GlobalizedRD->completeDefinition();
293 return GlobalizedRD;
294}
295
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000296/// Get the list of variables that can escape their declaration context.
297class CheckVarsEscapingDeclContext final
298 : public ConstStmtVisitor<CheckVarsEscapingDeclContext> {
299 CodeGenFunction &CGF;
300 llvm::SetVector<const ValueDecl *> EscapedDecls;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000301 llvm::SetVector<const ValueDecl *> EscapedVariableLengthDecls;
Alexey Bataevc99042b2018-03-15 18:10:54 +0000302 llvm::SmallPtrSet<const Decl *, 4> EscapedParameters;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000303 RecordDecl *GlobalizedRD = nullptr;
304 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000305 bool AllEscaped = false;
Alexey Bataev91433f62018-06-26 17:24:03 +0000306 bool IsForCombinedParallelRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000307
308 void markAsEscaped(const ValueDecl *VD) {
Alexey Bataev03f270c2018-03-30 18:31:07 +0000309 // Do not globalize declare target variables.
Alexey Bataev97b72212018-08-14 18:31:20 +0000310 if (!isa<VarDecl>(VD) ||
311 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataev03f270c2018-03-30 18:31:07 +0000312 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000313 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataevc99042b2018-03-15 18:10:54 +0000314 // Variables captured by value must be globalized.
315 if (auto *CSI = CGF.CapturedStmtInfo) {
Mikael Holmen9f373a32018-03-16 07:27:57 +0000316 if (const FieldDecl *FD = CSI->lookup(cast<VarDecl>(VD))) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000317 // Check if need to capture the variable that was already captured by
318 // value in the outer region.
Alexey Bataev91433f62018-06-26 17:24:03 +0000319 if (!IsForCombinedParallelRegion) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000320 if (!FD->hasAttrs())
321 return;
322 const auto *Attr = FD->getAttr<OMPCaptureKindAttr>();
323 if (!Attr)
324 return;
Alexey Bataev6393eb72018-12-06 15:35:13 +0000325 if (((Attr->getCaptureKind() != OMPC_map) &&
326 !isOpenMPPrivate(
327 static_cast<OpenMPClauseKind>(Attr->getCaptureKind()))) ||
328 ((Attr->getCaptureKind() == OMPC_map) &&
329 !FD->getType()->isAnyPointerType()))
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000330 return;
331 }
332 if (!FD->getType()->isReferenceType()) {
333 assert(!VD->getType()->isVariablyModifiedType() &&
334 "Parameter captured by value with variably modified type");
335 EscapedParameters.insert(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000336 } else if (!IsForCombinedParallelRegion) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000337 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000338 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000339 }
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000340 }
341 if ((!CGF.CapturedStmtInfo ||
Alexey Bataev91433f62018-06-26 17:24:03 +0000342 (IsForCombinedParallelRegion && CGF.CapturedStmtInfo)) &&
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000343 VD->getType()->isReferenceType())
344 // Do not globalize variables with reference type.
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000345 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000346 if (VD->getType()->isVariablyModifiedType())
347 EscapedVariableLengthDecls.insert(VD);
348 else
349 EscapedDecls.insert(VD);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000350 }
351
352 void VisitValueDecl(const ValueDecl *VD) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000353 if (VD->getType()->isLValueReferenceType())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000354 markAsEscaped(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000355 if (const auto *VarD = dyn_cast<VarDecl>(VD)) {
356 if (!isa<ParmVarDecl>(VarD) && VarD->hasInit()) {
357 const bool SavedAllEscaped = AllEscaped;
358 AllEscaped = VD->getType()->isLValueReferenceType();
359 Visit(VarD->getInit());
360 AllEscaped = SavedAllEscaped;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000361 }
362 }
363 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000364 void VisitOpenMPCapturedStmt(const CapturedStmt *S,
365 ArrayRef<OMPClause *> Clauses,
366 bool IsCombinedParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000367 if (!S)
368 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000369 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000370 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
371 const ValueDecl *VD = C.getCapturedVar();
Alexey Bataev91433f62018-06-26 17:24:03 +0000372 bool SavedIsForCombinedParallelRegion = IsForCombinedParallelRegion;
373 if (IsCombinedParallelRegion) {
374 // Check if the variable is privatized in the combined construct and
375 // those private copies must be shared in the inner parallel
376 // directive.
377 IsForCombinedParallelRegion = false;
378 for (const OMPClause *C : Clauses) {
379 if (!isOpenMPPrivate(C->getClauseKind()) ||
380 C->getClauseKind() == OMPC_reduction ||
381 C->getClauseKind() == OMPC_linear ||
382 C->getClauseKind() == OMPC_private)
383 continue;
384 ArrayRef<const Expr *> Vars;
385 if (const auto *PC = dyn_cast<OMPFirstprivateClause>(C))
386 Vars = PC->getVarRefs();
387 else if (const auto *PC = dyn_cast<OMPLastprivateClause>(C))
388 Vars = PC->getVarRefs();
389 else
390 llvm_unreachable("Unexpected clause.");
391 for (const auto *E : Vars) {
392 const Decl *D =
393 cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
394 if (D == VD->getCanonicalDecl()) {
395 IsForCombinedParallelRegion = true;
396 break;
397 }
398 }
399 if (IsForCombinedParallelRegion)
400 break;
401 }
402 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000403 markAsEscaped(VD);
404 if (isa<OMPCapturedExprDecl>(VD))
405 VisitValueDecl(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000406 IsForCombinedParallelRegion = SavedIsForCombinedParallelRegion;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000407 }
408 }
409 }
410
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000411 void buildRecordForGlobalizedVars(bool IsInTTDRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000412 assert(!GlobalizedRD &&
413 "Record for globalized variables is built already.");
Alexey Bataevff23bb62018-10-11 18:30:31 +0000414 ArrayRef<const ValueDecl *> EscapedDeclsForParallel, EscapedDeclsForTeams;
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000415 if (IsInTTDRegion)
Alexey Bataevff23bb62018-10-11 18:30:31 +0000416 EscapedDeclsForTeams = EscapedDecls.getArrayRef();
417 else
418 EscapedDeclsForParallel = EscapedDecls.getArrayRef();
Alexey Bataev2adecff2018-09-21 14:22:53 +0000419 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataevff23bb62018-10-11 18:30:31 +0000420 CGF.getContext(), EscapedDeclsForParallel, EscapedDeclsForTeams,
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000421 MappedDeclsFields);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000422 }
423
424public:
Alexey Bataevf2f39be2018-11-16 19:38:21 +0000425 CheckVarsEscapingDeclContext(CodeGenFunction &CGF,
426 ArrayRef<const ValueDecl *> TeamsReductions)
427 : CGF(CGF), EscapedDecls(TeamsReductions.begin(), TeamsReductions.end()) {
428 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000429 virtual ~CheckVarsEscapingDeclContext() = default;
430 void VisitDeclStmt(const DeclStmt *S) {
431 if (!S)
432 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000433 for (const Decl *D : S->decls())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000434 if (const auto *VD = dyn_cast_or_null<ValueDecl>(D))
435 VisitValueDecl(VD);
436 }
437 void VisitOMPExecutableDirective(const OMPExecutableDirective *D) {
438 if (!D)
439 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000440 if (!D->hasAssociatedStmt())
441 return;
442 if (const auto *S =
443 dyn_cast_or_null<CapturedStmt>(D->getAssociatedStmt())) {
444 // Do not analyze directives that do not actually require capturing,
445 // like `omp for` or `omp simd` directives.
446 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
447 getOpenMPCaptureRegions(CaptureRegions, D->getDirectiveKind());
448 if (CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown) {
449 VisitStmt(S->getCapturedStmt());
450 return;
Alexey Bataev673110d2018-05-16 13:36:30 +0000451 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000452 VisitOpenMPCapturedStmt(
453 S, D->clauses(),
454 CaptureRegions.back() == OMPD_parallel &&
455 isOpenMPDistributeDirective(D->getDirectiveKind()));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000456 }
457 }
458 void VisitCapturedStmt(const CapturedStmt *S) {
459 if (!S)
460 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000461 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000462 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
463 const ValueDecl *VD = C.getCapturedVar();
464 markAsEscaped(VD);
465 if (isa<OMPCapturedExprDecl>(VD))
466 VisitValueDecl(VD);
467 }
468 }
469 }
470 void VisitLambdaExpr(const LambdaExpr *E) {
471 if (!E)
472 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000473 for (const LambdaCapture &C : E->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000474 if (C.capturesVariable()) {
475 if (C.getCaptureKind() == LCK_ByRef) {
476 const ValueDecl *VD = C.getCapturedVar();
477 markAsEscaped(VD);
478 if (E->isInitCapture(&C) || isa<OMPCapturedExprDecl>(VD))
479 VisitValueDecl(VD);
480 }
481 }
482 }
483 }
484 void VisitBlockExpr(const BlockExpr *E) {
485 if (!E)
486 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000487 for (const BlockDecl::Capture &C : E->getBlockDecl()->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000488 if (C.isByRef()) {
489 const VarDecl *VD = C.getVariable();
490 markAsEscaped(VD);
491 if (isa<OMPCapturedExprDecl>(VD) || VD->isInitCapture())
492 VisitValueDecl(VD);
493 }
494 }
495 }
496 void VisitCallExpr(const CallExpr *E) {
497 if (!E)
498 return;
499 for (const Expr *Arg : E->arguments()) {
500 if (!Arg)
501 continue;
502 if (Arg->isLValue()) {
503 const bool SavedAllEscaped = AllEscaped;
504 AllEscaped = true;
505 Visit(Arg);
506 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000507 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000508 Visit(Arg);
Alexey Bataev9ff80832018-04-16 20:16:21 +0000509 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000510 }
511 Visit(E->getCallee());
512 }
513 void VisitDeclRefExpr(const DeclRefExpr *E) {
514 if (!E)
515 return;
516 const ValueDecl *VD = E->getDecl();
517 if (AllEscaped)
518 markAsEscaped(VD);
519 if (isa<OMPCapturedExprDecl>(VD))
520 VisitValueDecl(VD);
521 else if (const auto *VarD = dyn_cast<VarDecl>(VD))
522 if (VarD->isInitCapture())
523 VisitValueDecl(VD);
524 }
525 void VisitUnaryOperator(const UnaryOperator *E) {
526 if (!E)
527 return;
528 if (E->getOpcode() == UO_AddrOf) {
529 const bool SavedAllEscaped = AllEscaped;
530 AllEscaped = true;
531 Visit(E->getSubExpr());
532 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000533 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000534 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000535 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000536 }
537 void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
538 if (!E)
539 return;
540 if (E->getCastKind() == CK_ArrayToPointerDecay) {
541 const bool SavedAllEscaped = AllEscaped;
542 AllEscaped = true;
543 Visit(E->getSubExpr());
544 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000545 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000546 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000547 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000548 }
549 void VisitExpr(const Expr *E) {
550 if (!E)
551 return;
552 bool SavedAllEscaped = AllEscaped;
553 if (!E->isLValue())
554 AllEscaped = false;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000555 for (const Stmt *Child : E->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000556 if (Child)
557 Visit(Child);
558 AllEscaped = SavedAllEscaped;
559 }
560 void VisitStmt(const Stmt *S) {
561 if (!S)
562 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000563 for (const Stmt *Child : S->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000564 if (Child)
565 Visit(Child);
566 }
567
Alexey Bataevc99042b2018-03-15 18:10:54 +0000568 /// Returns the record that handles all the escaped local variables and used
569 /// instead of their original storage.
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000570 const RecordDecl *getGlobalizedRecord(bool IsInTTDRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000571 if (!GlobalizedRD)
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000572 buildRecordForGlobalizedVars(IsInTTDRegion);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000573 return GlobalizedRD;
574 }
575
Alexey Bataevc99042b2018-03-15 18:10:54 +0000576 /// Returns the field in the globalized record for the escaped variable.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000577 const FieldDecl *getFieldForGlobalizedVar(const ValueDecl *VD) const {
578 assert(GlobalizedRD &&
579 "Record for globalized variables must be generated already.");
580 auto I = MappedDeclsFields.find(VD);
581 if (I == MappedDeclsFields.end())
582 return nullptr;
583 return I->getSecond();
584 }
585
Alexey Bataevc99042b2018-03-15 18:10:54 +0000586 /// Returns the list of the escaped local variables/parameters.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000587 ArrayRef<const ValueDecl *> getEscapedDecls() const {
588 return EscapedDecls.getArrayRef();
589 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000590
591 /// Checks if the escaped local variable is actually a parameter passed by
592 /// value.
593 const llvm::SmallPtrSetImpl<const Decl *> &getEscapedParameters() const {
594 return EscapedParameters;
595 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000596
597 /// Returns the list of the escaped variables with the variably modified
598 /// types.
599 ArrayRef<const ValueDecl *> getEscapedVariableLengthDecls() const {
600 return EscapedVariableLengthDecls.getArrayRef();
601 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000602};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000603} // anonymous namespace
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000604
605/// Get the GPU warp size.
606static llvm::Value *getNVPTXWarpSize(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000607 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000608 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000609 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_warpsize),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000610 "nvptx_warp_size");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000611}
612
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000613/// Get the id of the current thread on the GPU.
614static llvm::Value *getNVPTXThreadID(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000615 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000616 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000617 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_tid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000618 "nvptx_tid");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000619}
620
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000621/// Get the id of the warp in the block.
622/// We assume that the warp size is 32, which is always the case
623/// on the NVPTX device, to generate more efficient code.
624static llvm::Value *getNVPTXWarpID(CodeGenFunction &CGF) {
625 CGBuilderTy &Bld = CGF.Builder;
626 return Bld.CreateAShr(getNVPTXThreadID(CGF), LaneIDBits, "nvptx_warp_id");
627}
628
629/// Get the id of the current lane in the Warp.
630/// We assume that the warp size is 32, which is always the case
631/// on the NVPTX device, to generate more efficient code.
632static llvm::Value *getNVPTXLaneID(CodeGenFunction &CGF) {
633 CGBuilderTy &Bld = CGF.Builder;
634 return Bld.CreateAnd(getNVPTXThreadID(CGF), Bld.getInt32(LaneIDMask),
635 "nvptx_lane_id");
636}
637
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000638/// Get the maximum number of threads in a block of the GPU.
639static llvm::Value *getNVPTXNumThreads(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000640 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000641 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000642 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_ntid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000643 "nvptx_num_threads");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000644}
645
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000646/// Get the value of the thread_limit clause in the teams directive.
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000647/// For the 'generic' execution mode, the runtime encodes thread_limit in
648/// the launch parameters, always starting thread_limit+warpSize threads per
649/// CTA. The threads in the last warp are reserved for master execution.
650/// For the 'spmd' execution mode, all threads in a CTA are part of the team.
651static llvm::Value *getThreadLimit(CodeGenFunction &CGF,
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000652 bool IsInSPMDExecutionMode = false) {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000653 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000654 return IsInSPMDExecutionMode
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000655 ? getNVPTXNumThreads(CGF)
Alexey Bataeve290ec02018-04-06 16:03:36 +0000656 : Bld.CreateNUWSub(getNVPTXNumThreads(CGF), getNVPTXWarpSize(CGF),
657 "thread_limit");
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000658}
659
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000660/// Get the thread id of the OMP master thread.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000661/// The master thread id is the first thread (lane) of the last warp in the
662/// GPU block. Warp size is assumed to be some power of 2.
663/// Thread id is 0 indexed.
664/// E.g: If NumThreads is 33, master id is 32.
665/// If NumThreads is 64, master id is 32.
666/// If NumThreads is 1024, master id is 992.
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000667static llvm::Value *getMasterThreadID(CodeGenFunction &CGF) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000668 CGBuilderTy &Bld = CGF.Builder;
669 llvm::Value *NumThreads = getNVPTXNumThreads(CGF);
670
671 // We assume that the warp size is a power of 2.
Alexey Bataeve290ec02018-04-06 16:03:36 +0000672 llvm::Value *Mask = Bld.CreateNUWSub(getNVPTXWarpSize(CGF), Bld.getInt32(1));
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000673
Alexey Bataeve290ec02018-04-06 16:03:36 +0000674 return Bld.CreateAnd(Bld.CreateNUWSub(NumThreads, Bld.getInt32(1)),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000675 Bld.CreateNot(Mask), "master_tid");
676}
677
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000678CGOpenMPRuntimeNVPTX::WorkerFunctionState::WorkerFunctionState(
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000679 CodeGenModule &CGM, SourceLocation Loc)
Alexey Bataev9ff80832018-04-16 20:16:21 +0000680 : WorkerFn(nullptr), CGFI(CGM.getTypes().arrangeNullaryFunction()),
681 Loc(Loc) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000682 createWorkerFunction(CGM);
Vasileios Kalintirise5c09592016-03-22 10:41:20 +0000683}
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000684
685void CGOpenMPRuntimeNVPTX::WorkerFunctionState::createWorkerFunction(
686 CodeGenModule &CGM) {
687 // Create an worker function with no arguments.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000688
689 WorkerFn = llvm::Function::Create(
Alexey Bataev9ff80832018-04-16 20:16:21 +0000690 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataevaee93892018-01-08 20:09:47 +0000691 /*placeholder=*/"_worker", &CGM.getModule());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000692 CGM.SetInternalFunctionAttributes(GlobalDecl(), WorkerFn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +0000693 WorkerFn->setDoesNotRecurse();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000694}
695
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000696CGOpenMPRuntimeNVPTX::ExecutionMode
697CGOpenMPRuntimeNVPTX::getExecutionMode() const {
698 return CurrentExecutionMode;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000699}
700
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000701static CGOpenMPRuntimeNVPTX::DataSharingMode
702getDataSharingMode(CodeGenModule &CGM) {
703 return CGM.getLangOpts().OpenMPCUDAMode ? CGOpenMPRuntimeNVPTX::CUDA
704 : CGOpenMPRuntimeNVPTX::Generic;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000705}
706
Alexey Bataev7bb33532019-01-07 21:30:43 +0000707/// Checks if the expression is constant or does not have non-trivial function
708/// calls.
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000709static bool isTrivial(ASTContext &Ctx, const Expr * E) {
710 // We can skip constant expressions.
711 // We can skip expressions with trivial calls or simple expressions.
712 return (E->isEvaluatable(Ctx, Expr::SE_AllowUndefinedBehavior) ||
713 !E->hasNonTrivialCall(Ctx)) &&
714 !E->HasSideEffects(Ctx, /*IncludePossibleEffects=*/true);
715}
716
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000717/// Checks if the \p Body is the \a CompoundStmt and returns its child statement
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000718/// iff there is only one that is not evaluatable at the compile time.
719static const Stmt *getSingleCompoundChild(ASTContext &Ctx, const Stmt *Body) {
720 if (const auto *C = dyn_cast<CompoundStmt>(Body)) {
721 const Stmt *Child = nullptr;
722 for (const Stmt *S : C->body()) {
723 if (const auto *E = dyn_cast<Expr>(S)) {
724 if (isTrivial(Ctx, E))
725 continue;
726 }
727 // Some of the statements can be ignored.
728 if (isa<AsmStmt>(S) || isa<NullStmt>(S) || isa<OMPFlushDirective>(S) ||
729 isa<OMPBarrierDirective>(S) || isa<OMPTaskyieldDirective>(S))
730 continue;
731 // Analyze declarations.
732 if (const auto *DS = dyn_cast<DeclStmt>(S)) {
733 if (llvm::all_of(DS->decls(), [&Ctx](const Decl *D) {
734 if (isa<EmptyDecl>(D) || isa<DeclContext>(D) ||
735 isa<TypeDecl>(D) || isa<PragmaCommentDecl>(D) ||
736 isa<PragmaDetectMismatchDecl>(D) || isa<UsingDecl>(D) ||
737 isa<UsingDirectiveDecl>(D) ||
738 isa<OMPDeclareReductionDecl>(D) ||
739 isa<OMPThreadPrivateDecl>(D))
740 return true;
741 const auto *VD = dyn_cast<VarDecl>(D);
742 if (!VD)
743 return false;
744 return VD->isConstexpr() ||
745 ((VD->getType().isTrivialType(Ctx) ||
746 VD->getType()->isReferenceType()) &&
747 (!VD->hasInit() || isTrivial(Ctx, VD->getInit())));
748 }))
749 continue;
750 }
751 // Found multiple children - cannot get the one child only.
752 if (Child)
753 return Body;
754 Child = S;
755 }
756 if (Child)
757 return Child;
758 }
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000759 return Body;
760}
761
762/// Check if the parallel directive has an 'if' clause with non-constant or
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000763/// false condition. Also, check if the number of threads is strictly specified
764/// and run those directives in non-SPMD mode.
765static bool hasParallelIfNumThreadsClause(ASTContext &Ctx,
766 const OMPExecutableDirective &D) {
767 if (D.hasClausesOfKind<OMPNumThreadsClause>())
768 return true;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000769 for (const auto *C : D.getClausesOfKind<OMPIfClause>()) {
770 OpenMPDirectiveKind NameModifier = C->getNameModifier();
771 if (NameModifier != OMPD_parallel && NameModifier != OMPD_unknown)
772 continue;
773 const Expr *Cond = C->getCondition();
774 bool Result;
775 if (!Cond->EvaluateAsBooleanCondition(Result, Ctx) || !Result)
776 return true;
777 }
778 return false;
779}
780
781/// Check for inner (nested) SPMD construct, if any
782static bool hasNestedSPMDDirective(ASTContext &Ctx,
783 const OMPExecutableDirective &D) {
784 const auto *CS = D.getInnermostCapturedStmt();
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000785 const auto *Body =
786 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000787 const Stmt *ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000788
789 if (const auto *NestedDir = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
790 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000791 switch (D.getDirectiveKind()) {
792 case OMPD_target:
Alexey Bataevdf093e72018-05-11 19:45:14 +0000793 if (isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000794 !hasParallelIfNumThreadsClause(Ctx, *NestedDir))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000795 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000796 if (DKind == OMPD_teams) {
797 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
798 /*IgnoreCaptured=*/true);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000799 if (!Body)
800 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000801 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000802 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
803 DKind = NND->getDirectiveKind();
Alexey Bataevdf093e72018-05-11 19:45:14 +0000804 if (isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000805 !hasParallelIfNumThreadsClause(Ctx, *NND))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000806 return true;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000807 }
808 }
809 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000810 case OMPD_target_teams:
Alexey Bataevdf093e72018-05-11 19:45:14 +0000811 return isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000812 !hasParallelIfNumThreadsClause(Ctx, *NestedDir);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000813 case OMPD_target_simd:
814 case OMPD_target_parallel:
815 case OMPD_target_parallel_for:
816 case OMPD_target_parallel_for_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000817 case OMPD_target_teams_distribute:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000818 case OMPD_target_teams_distribute_simd:
819 case OMPD_target_teams_distribute_parallel_for:
820 case OMPD_target_teams_distribute_parallel_for_simd:
821 case OMPD_parallel:
822 case OMPD_for:
823 case OMPD_parallel_for:
824 case OMPD_parallel_sections:
825 case OMPD_for_simd:
826 case OMPD_parallel_for_simd:
827 case OMPD_cancel:
828 case OMPD_cancellation_point:
829 case OMPD_ordered:
830 case OMPD_threadprivate:
831 case OMPD_task:
832 case OMPD_simd:
833 case OMPD_sections:
834 case OMPD_section:
835 case OMPD_single:
836 case OMPD_master:
837 case OMPD_critical:
838 case OMPD_taskyield:
839 case OMPD_barrier:
840 case OMPD_taskwait:
841 case OMPD_taskgroup:
842 case OMPD_atomic:
843 case OMPD_flush:
844 case OMPD_teams:
845 case OMPD_target_data:
846 case OMPD_target_exit_data:
847 case OMPD_target_enter_data:
848 case OMPD_distribute:
849 case OMPD_distribute_simd:
850 case OMPD_distribute_parallel_for:
851 case OMPD_distribute_parallel_for_simd:
852 case OMPD_teams_distribute:
853 case OMPD_teams_distribute_simd:
854 case OMPD_teams_distribute_parallel_for:
855 case OMPD_teams_distribute_parallel_for_simd:
856 case OMPD_target_update:
857 case OMPD_declare_simd:
858 case OMPD_declare_target:
859 case OMPD_end_declare_target:
860 case OMPD_declare_reduction:
861 case OMPD_taskloop:
862 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000863 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000864 case OMPD_unknown:
865 llvm_unreachable("Unexpected directive.");
866 }
867 }
868
869 return false;
870}
871
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000872static bool supportsSPMDExecutionMode(ASTContext &Ctx,
873 const OMPExecutableDirective &D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000874 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
875 switch (DirectiveKind) {
876 case OMPD_target:
877 case OMPD_target_teams:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000878 return hasNestedSPMDDirective(Ctx, D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000879 case OMPD_target_parallel:
880 case OMPD_target_parallel_for:
881 case OMPD_target_parallel_for_simd:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000882 case OMPD_target_teams_distribute_parallel_for:
883 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev2adecff2018-09-21 14:22:53 +0000884 return !hasParallelIfNumThreadsClause(Ctx, D);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000885 case OMPD_target_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000886 case OMPD_target_teams_distribute:
887 case OMPD_target_teams_distribute_simd:
888 return false;
889 case OMPD_parallel:
890 case OMPD_for:
891 case OMPD_parallel_for:
892 case OMPD_parallel_sections:
893 case OMPD_for_simd:
894 case OMPD_parallel_for_simd:
895 case OMPD_cancel:
896 case OMPD_cancellation_point:
897 case OMPD_ordered:
898 case OMPD_threadprivate:
899 case OMPD_task:
900 case OMPD_simd:
901 case OMPD_sections:
902 case OMPD_section:
903 case OMPD_single:
904 case OMPD_master:
905 case OMPD_critical:
906 case OMPD_taskyield:
907 case OMPD_barrier:
908 case OMPD_taskwait:
909 case OMPD_taskgroup:
910 case OMPD_atomic:
911 case OMPD_flush:
912 case OMPD_teams:
913 case OMPD_target_data:
914 case OMPD_target_exit_data:
915 case OMPD_target_enter_data:
916 case OMPD_distribute:
917 case OMPD_distribute_simd:
918 case OMPD_distribute_parallel_for:
919 case OMPD_distribute_parallel_for_simd:
920 case OMPD_teams_distribute:
921 case OMPD_teams_distribute_simd:
922 case OMPD_teams_distribute_parallel_for:
923 case OMPD_teams_distribute_parallel_for_simd:
924 case OMPD_target_update:
925 case OMPD_declare_simd:
926 case OMPD_declare_target:
927 case OMPD_end_declare_target:
928 case OMPD_declare_reduction:
929 case OMPD_taskloop:
930 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000931 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000932 case OMPD_unknown:
933 break;
934 }
935 llvm_unreachable(
936 "Unknown programming model for OpenMP directive on NVPTX target.");
937}
938
939/// Check if the directive is loops based and has schedule clause at all or has
940/// static scheduling.
941static bool hasStaticScheduling(const OMPExecutableDirective &D) {
942 assert(isOpenMPWorksharingDirective(D.getDirectiveKind()) &&
943 isOpenMPLoopDirective(D.getDirectiveKind()) &&
944 "Expected loop-based directive.");
945 return !D.hasClausesOfKind<OMPOrderedClause>() &&
946 (!D.hasClausesOfKind<OMPScheduleClause>() ||
947 llvm::any_of(D.getClausesOfKind<OMPScheduleClause>(),
948 [](const OMPScheduleClause *C) {
949 return C->getScheduleKind() == OMPC_SCHEDULE_static;
950 }));
951}
952
953/// Check for inner (nested) lightweight runtime construct, if any
954static bool hasNestedLightweightDirective(ASTContext &Ctx,
955 const OMPExecutableDirective &D) {
956 assert(supportsSPMDExecutionMode(Ctx, D) && "Expected SPMD mode directive.");
957 const auto *CS = D.getInnermostCapturedStmt();
958 const auto *Body =
959 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000960 const Stmt *ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000961
962 if (const auto *NestedDir = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
963 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
964 switch (D.getDirectiveKind()) {
965 case OMPD_target:
966 if (isOpenMPParallelDirective(DKind) &&
967 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
968 hasStaticScheduling(*NestedDir))
969 return true;
970 if (DKind == OMPD_parallel) {
971 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
972 /*IgnoreCaptured=*/true);
973 if (!Body)
974 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000975 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000976 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
977 DKind = NND->getDirectiveKind();
978 if (isOpenMPWorksharingDirective(DKind) &&
979 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
980 return true;
981 }
982 } else if (DKind == OMPD_teams) {
983 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
984 /*IgnoreCaptured=*/true);
985 if (!Body)
986 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000987 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000988 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
989 DKind = NND->getDirectiveKind();
990 if (isOpenMPParallelDirective(DKind) &&
991 isOpenMPWorksharingDirective(DKind) &&
992 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
993 return true;
994 if (DKind == OMPD_parallel) {
995 Body = NND->getInnermostCapturedStmt()->IgnoreContainers(
996 /*IgnoreCaptured=*/true);
997 if (!Body)
998 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000999 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001000 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
1001 DKind = NND->getDirectiveKind();
1002 if (isOpenMPWorksharingDirective(DKind) &&
1003 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
1004 return true;
1005 }
1006 }
1007 }
1008 }
1009 return false;
1010 case OMPD_target_teams:
1011 if (isOpenMPParallelDirective(DKind) &&
1012 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
1013 hasStaticScheduling(*NestedDir))
1014 return true;
1015 if (DKind == OMPD_parallel) {
1016 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
1017 /*IgnoreCaptured=*/true);
1018 if (!Body)
1019 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001020 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001021 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
1022 DKind = NND->getDirectiveKind();
1023 if (isOpenMPWorksharingDirective(DKind) &&
1024 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
1025 return true;
1026 }
1027 }
1028 return false;
1029 case OMPD_target_parallel:
1030 return isOpenMPWorksharingDirective(DKind) &&
1031 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NestedDir);
1032 case OMPD_target_teams_distribute:
1033 case OMPD_target_simd:
1034 case OMPD_target_parallel_for:
1035 case OMPD_target_parallel_for_simd:
1036 case OMPD_target_teams_distribute_simd:
1037 case OMPD_target_teams_distribute_parallel_for:
1038 case OMPD_target_teams_distribute_parallel_for_simd:
1039 case OMPD_parallel:
1040 case OMPD_for:
1041 case OMPD_parallel_for:
1042 case OMPD_parallel_sections:
1043 case OMPD_for_simd:
1044 case OMPD_parallel_for_simd:
1045 case OMPD_cancel:
1046 case OMPD_cancellation_point:
1047 case OMPD_ordered:
1048 case OMPD_threadprivate:
1049 case OMPD_task:
1050 case OMPD_simd:
1051 case OMPD_sections:
1052 case OMPD_section:
1053 case OMPD_single:
1054 case OMPD_master:
1055 case OMPD_critical:
1056 case OMPD_taskyield:
1057 case OMPD_barrier:
1058 case OMPD_taskwait:
1059 case OMPD_taskgroup:
1060 case OMPD_atomic:
1061 case OMPD_flush:
1062 case OMPD_teams:
1063 case OMPD_target_data:
1064 case OMPD_target_exit_data:
1065 case OMPD_target_enter_data:
1066 case OMPD_distribute:
1067 case OMPD_distribute_simd:
1068 case OMPD_distribute_parallel_for:
1069 case OMPD_distribute_parallel_for_simd:
1070 case OMPD_teams_distribute:
1071 case OMPD_teams_distribute_simd:
1072 case OMPD_teams_distribute_parallel_for:
1073 case OMPD_teams_distribute_parallel_for_simd:
1074 case OMPD_target_update:
1075 case OMPD_declare_simd:
1076 case OMPD_declare_target:
1077 case OMPD_end_declare_target:
1078 case OMPD_declare_reduction:
1079 case OMPD_taskloop:
1080 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001081 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001082 case OMPD_unknown:
1083 llvm_unreachable("Unexpected directive.");
1084 }
1085 }
1086
1087 return false;
1088}
1089
1090/// Checks if the construct supports lightweight runtime. It must be SPMD
1091/// construct + inner loop-based construct with static scheduling.
1092static bool supportsLightweightRuntime(ASTContext &Ctx,
1093 const OMPExecutableDirective &D) {
1094 if (!supportsSPMDExecutionMode(Ctx, D))
1095 return false;
1096 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
1097 switch (DirectiveKind) {
1098 case OMPD_target:
1099 case OMPD_target_teams:
1100 case OMPD_target_parallel:
1101 return hasNestedLightweightDirective(Ctx, D);
1102 case OMPD_target_parallel_for:
1103 case OMPD_target_parallel_for_simd:
1104 case OMPD_target_teams_distribute_parallel_for:
1105 case OMPD_target_teams_distribute_parallel_for_simd:
1106 // (Last|First)-privates must be shared in parallel region.
1107 return hasStaticScheduling(D);
1108 case OMPD_target_simd:
1109 case OMPD_target_teams_distribute:
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001110 case OMPD_target_teams_distribute_simd:
Alexey Bataevdf093e72018-05-11 19:45:14 +00001111 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001112 case OMPD_parallel:
1113 case OMPD_for:
1114 case OMPD_parallel_for:
1115 case OMPD_parallel_sections:
1116 case OMPD_for_simd:
1117 case OMPD_parallel_for_simd:
1118 case OMPD_cancel:
1119 case OMPD_cancellation_point:
1120 case OMPD_ordered:
1121 case OMPD_threadprivate:
1122 case OMPD_task:
1123 case OMPD_simd:
1124 case OMPD_sections:
1125 case OMPD_section:
1126 case OMPD_single:
1127 case OMPD_master:
1128 case OMPD_critical:
1129 case OMPD_taskyield:
1130 case OMPD_barrier:
1131 case OMPD_taskwait:
1132 case OMPD_taskgroup:
1133 case OMPD_atomic:
1134 case OMPD_flush:
1135 case OMPD_teams:
1136 case OMPD_target_data:
1137 case OMPD_target_exit_data:
1138 case OMPD_target_enter_data:
1139 case OMPD_distribute:
1140 case OMPD_distribute_simd:
1141 case OMPD_distribute_parallel_for:
1142 case OMPD_distribute_parallel_for_simd:
1143 case OMPD_teams_distribute:
1144 case OMPD_teams_distribute_simd:
1145 case OMPD_teams_distribute_parallel_for:
1146 case OMPD_teams_distribute_parallel_for_simd:
1147 case OMPD_target_update:
1148 case OMPD_declare_simd:
1149 case OMPD_declare_target:
1150 case OMPD_end_declare_target:
1151 case OMPD_declare_reduction:
1152 case OMPD_taskloop:
1153 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001154 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001155 case OMPD_unknown:
1156 break;
1157 }
1158 llvm_unreachable(
1159 "Unknown programming model for OpenMP directive on NVPTX target.");
1160}
1161
1162void CGOpenMPRuntimeNVPTX::emitNonSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001163 StringRef ParentName,
1164 llvm::Function *&OutlinedFn,
1165 llvm::Constant *&OutlinedFnID,
1166 bool IsOffloadEntry,
1167 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001168 ExecutionRuntimeModesRAII ModeRAII(CurrentExecutionMode);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001169 EntryFunctionState EST;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001170 WorkerFunctionState WST(CGM, D.getBeginLoc());
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001171 Work.clear();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001172 WrapperFunctionsMap.clear();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001173
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001174 // Emit target region as a standalone region.
1175 class NVPTXPrePostActionTy : public PrePostActionTy {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001176 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1177 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001178
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001179 public:
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001180 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001181 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST)
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001182 : EST(EST), WST(WST) {}
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001183 void Enter(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001184 auto &RT =
1185 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001186 RT.emitNonSPMDEntryHeader(CGF, EST, WST);
1187 // Skip target region initialization.
1188 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001189 }
1190 void Exit(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001191 auto &RT =
1192 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001193 RT.clearLocThreadIdInsertPt(CGF);
1194 RT.emitNonSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001195 }
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001196 } Action(EST, WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001197 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001198 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001199 // Reserve place for the globalized memory.
1200 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001201 if (!KernelStaticGlobalized) {
1202 KernelStaticGlobalized = new llvm::GlobalVariable(
1203 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1204 llvm::GlobalValue::InternalLinkage,
1205 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1206 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1207 llvm::GlobalValue::NotThreadLocal,
1208 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1209 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001210 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1211 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001212 IsInTTDRegion = false;
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001213
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001214 // Now change the name of the worker function to correspond to this target
1215 // region's entry function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001216 WST.WorkerFn->setName(Twine(OutlinedFn->getName(), "_worker"));
Alexey Bataevaee93892018-01-08 20:09:47 +00001217
1218 // Create the worker function
1219 emitWorkerFunction(WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001220}
1221
1222// Setup NVPTX threads for master-worker OpenMP scheme.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001223void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryHeader(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001224 EntryFunctionState &EST,
1225 WorkerFunctionState &WST) {
1226 CGBuilderTy &Bld = CGF.Builder;
1227
1228 llvm::BasicBlock *WorkerBB = CGF.createBasicBlock(".worker");
1229 llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
1230 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
1231 EST.ExitBB = CGF.createBasicBlock(".exit");
1232
Alexey Bataev9ff80832018-04-16 20:16:21 +00001233 llvm::Value *IsWorker =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001234 Bld.CreateICmpULT(getNVPTXThreadID(CGF), getThreadLimit(CGF));
1235 Bld.CreateCondBr(IsWorker, WorkerBB, MasterCheckBB);
1236
1237 CGF.EmitBlock(WorkerBB);
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001238 emitCall(CGF, WST.Loc, WST.WorkerFn);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001239 CGF.EmitBranch(EST.ExitBB);
1240
1241 CGF.EmitBlock(MasterCheckBB);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001242 llvm::Value *IsMaster =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001243 Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
1244 Bld.CreateCondBr(IsMaster, MasterBB, EST.ExitBB);
1245
1246 CGF.EmitBlock(MasterBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001247 IsInTargetMasterThreadRegion = true;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001248 // SEQUENTIAL (MASTER) REGION START
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001249 // First action in sequential region:
1250 // Initialize the state of the OpenMP runtime library on the GPU.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001251 // TODO: Optimize runtime initialization and pass in correct value.
1252 llvm::Value *Args[] = {getThreadLimit(CGF),
1253 Bld.getInt16(/*RequiresOMPRuntime=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001254 CGF.EmitRuntimeCall(
1255 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_init), Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001256
1257 // For data sharing, we need to initialize the stack.
1258 CGF.EmitRuntimeCall(
1259 createNVPTXRuntimeFunction(
1260 OMPRTL_NVPTX__kmpc_data_sharing_init_stack));
1261
Alexey Bataevc99042b2018-03-15 18:10:54 +00001262 emitGenericVarsProlog(CGF, WST.Loc);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001263}
1264
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001265void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001266 EntryFunctionState &EST) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001267 IsInTargetMasterThreadRegion = false;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001268 if (!CGF.HaveInsertPoint())
1269 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001270
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001271 emitGenericVarsEpilog(CGF);
1272
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001273 if (!EST.ExitBB)
1274 EST.ExitBB = CGF.createBasicBlock(".exit");
1275
1276 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".termination.notifier");
1277 CGF.EmitBranch(TerminateBB);
1278
1279 CGF.EmitBlock(TerminateBB);
1280 // Signal termination condition.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001281 // TODO: Optimize runtime initialization and pass in correct value.
1282 llvm::Value *Args[] = {CGF.Builder.getInt16(/*IsOMPRuntimeInitialized=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001283 CGF.EmitRuntimeCall(
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001284 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_deinit), Args);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001285 // Barrier to terminate worker threads.
1286 syncCTAThreads(CGF);
1287 // Master thread jumps to exit point.
1288 CGF.EmitBranch(EST.ExitBB);
1289
1290 CGF.EmitBlock(EST.ExitBB);
1291 EST.ExitBB = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001292}
1293
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001294void CGOpenMPRuntimeNVPTX::emitSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001295 StringRef ParentName,
1296 llvm::Function *&OutlinedFn,
1297 llvm::Constant *&OutlinedFnID,
1298 bool IsOffloadEntry,
1299 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001300 ExecutionRuntimeModesRAII ModeRAII(
1301 CurrentExecutionMode, RequiresFullRuntime,
1302 CGM.getLangOpts().OpenMPCUDAForceFullRuntime ||
1303 !supportsLightweightRuntime(CGM.getContext(), D));
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001304 EntryFunctionState EST;
1305
1306 // Emit target region as a standalone region.
1307 class NVPTXPrePostActionTy : public PrePostActionTy {
1308 CGOpenMPRuntimeNVPTX &RT;
1309 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1310 const OMPExecutableDirective &D;
1311
1312 public:
1313 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT,
1314 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
1315 const OMPExecutableDirective &D)
1316 : RT(RT), EST(EST), D(D) {}
1317 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001318 RT.emitSPMDEntryHeader(CGF, EST, D);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001319 // Skip target region initialization.
1320 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001321 }
1322 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevfd006c42018-10-05 15:08:53 +00001323 RT.clearLocThreadIdInsertPt(CGF);
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001324 RT.emitSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001325 }
1326 } Action(*this, EST, D);
1327 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001328 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001329 // Reserve place for the globalized memory.
1330 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001331 if (!KernelStaticGlobalized) {
1332 KernelStaticGlobalized = new llvm::GlobalVariable(
1333 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1334 llvm::GlobalValue::InternalLinkage,
1335 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1336 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1337 llvm::GlobalValue::NotThreadLocal,
1338 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1339 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001340 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1341 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001342 IsInTTDRegion = false;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001343}
1344
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001345void CGOpenMPRuntimeNVPTX::emitSPMDEntryHeader(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001346 CodeGenFunction &CGF, EntryFunctionState &EST,
1347 const OMPExecutableDirective &D) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001348 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001349
1350 // Setup BBs in entry function.
1351 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute");
1352 EST.ExitBB = CGF.createBasicBlock(".exit");
1353
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001354 llvm::Value *Args[] = {getThreadLimit(CGF, /*IsInSPMDExecutionMode=*/true),
1355 /*RequiresOMPRuntime=*/
1356 Bld.getInt16(RequiresFullRuntime ? 1 : 0),
1357 /*RequiresDataSharing=*/Bld.getInt16(0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001358 CGF.EmitRuntimeCall(
1359 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_init), Args);
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001360
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001361 if (RequiresFullRuntime) {
1362 // For data sharing, we need to initialize the stack.
1363 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1364 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd));
1365 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001366
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001367 CGF.EmitBranch(ExecuteBB);
1368
1369 CGF.EmitBlock(ExecuteBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001370
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001371 IsInTargetMasterThreadRegion = true;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001372}
1373
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001374void CGOpenMPRuntimeNVPTX::emitSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001375 EntryFunctionState &EST) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001376 IsInTargetMasterThreadRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001377 if (!CGF.HaveInsertPoint())
1378 return;
1379
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001380 if (!EST.ExitBB)
1381 EST.ExitBB = CGF.createBasicBlock(".exit");
1382
1383 llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit");
1384 CGF.EmitBranch(OMPDeInitBB);
1385
1386 CGF.EmitBlock(OMPDeInitBB);
1387 // DeInitialize the OMP state in the runtime; called by all active threads.
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001388 llvm::Value *Args[] = {/*RequiresOMPRuntime=*/
1389 CGF.Builder.getInt16(RequiresFullRuntime ? 1 : 0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001390 CGF.EmitRuntimeCall(
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001391 createNVPTXRuntimeFunction(
1392 OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2), Args);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001393 CGF.EmitBranch(EST.ExitBB);
1394
1395 CGF.EmitBlock(EST.ExitBB);
1396 EST.ExitBB = nullptr;
1397}
1398
1399// Create a unique global variable to indicate the execution mode of this target
1400// region. The execution mode is either 'generic', or 'spmd' depending on the
1401// target directive. This variable is picked up by the offload library to setup
1402// the device appropriately before kernel launch. If the execution mode is
1403// 'generic', the runtime reserves one warp for the master, otherwise, all
1404// warps participate in parallel work.
1405static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001406 bool Mode) {
1407 auto *GVMode =
1408 new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
1409 llvm::GlobalValue::WeakAnyLinkage,
1410 llvm::ConstantInt::get(CGM.Int8Ty, Mode ? 0 : 1),
1411 Twine(Name, "_exec_mode"));
Alexey Bataev9ff80832018-04-16 20:16:21 +00001412 CGM.addCompilerUsedGlobal(GVMode);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001413}
1414
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001415void CGOpenMPRuntimeNVPTX::emitWorkerFunction(WorkerFunctionState &WST) {
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +00001416 ASTContext &Ctx = CGM.getContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001417
1418 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001419 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, WST.CGFI, {},
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001420 WST.Loc, WST.Loc);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001421 emitWorkerLoop(CGF, WST);
1422 CGF.FinishFunction();
1423}
1424
1425void CGOpenMPRuntimeNVPTX::emitWorkerLoop(CodeGenFunction &CGF,
1426 WorkerFunctionState &WST) {
1427 //
1428 // The workers enter this loop and wait for parallel work from the master.
1429 // When the master encounters a parallel region it sets up the work + variable
1430 // arguments, and wakes up the workers. The workers first check to see if
1431 // they are required for the parallel region, i.e., within the # of requested
1432 // parallel threads. The activated workers load the variable arguments and
1433 // execute the parallel work.
1434 //
1435
1436 CGBuilderTy &Bld = CGF.Builder;
1437
1438 llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work");
1439 llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers");
1440 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel");
1441 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel");
1442 llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel");
1443 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1444
1445 CGF.EmitBranch(AwaitBB);
1446
1447 // Workers wait for work from master.
1448 CGF.EmitBlock(AwaitBB);
1449 // Wait for parallel work
1450 syncCTAThreads(CGF);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001451
1452 Address WorkFn =
1453 CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn");
1454 Address ExecStatus =
1455 CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status");
1456 CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0));
1457 CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy));
1458
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001459 // TODO: Optimize runtime initialization and pass in correct value.
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001460 llvm::Value *Args[] = {WorkFn.getPointer(),
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001461 /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001462 llvm::Value *Ret = CGF.EmitRuntimeCall(
1463 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args);
1464 Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001465
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001466 // On termination condition (workid == 0), exit loop.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001467 llvm::Value *WorkID = Bld.CreateLoad(WorkFn);
1468 llvm::Value *ShouldTerminate = Bld.CreateIsNull(WorkID, "should_terminate");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001469 Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB);
1470
1471 // Activate requested workers.
1472 CGF.EmitBlock(SelectWorkersBB);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001473 llvm::Value *IsActive =
1474 Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active");
1475 Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001476
1477 // Signal start of parallel region.
1478 CGF.EmitBlock(ExecuteBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001479 // Skip initialization.
1480 setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001481
1482 // Process work items: outlined parallel functions.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001483 for (llvm::Function *W : Work) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001484 // Try to match this outlined function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001485 llvm::Value *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001486
1487 llvm::Value *WorkFnMatch =
1488 Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match");
1489
1490 llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn");
1491 llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next");
1492 Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB);
1493
1494 // Execute this outlined function.
1495 CGF.EmitBlock(ExecuteFNBB);
1496
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001497 // Insert call to work function via shared wrapper. The shared
1498 // wrapper takes two arguments:
1499 // - the parallelism level;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001500 // - the thread ID;
1501 emitCall(CGF, WST.Loc, W,
1502 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001503
1504 // Go to end of parallel region.
1505 CGF.EmitBranch(TerminateBB);
1506
1507 CGF.EmitBlock(CheckNextBB);
1508 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001509 // Default case: call to outlined function through pointer if the target
1510 // region makes a declare target call that may contain an orphaned parallel
1511 // directive.
1512 auto *ParallelFnTy =
1513 llvm::FunctionType::get(CGM.VoidTy, {CGM.Int16Ty, CGM.Int32Ty},
1514 /*isVarArg=*/false)
1515 ->getPointerTo();
1516 llvm::Value *WorkFnCast = Bld.CreateBitCast(WorkID, ParallelFnTy);
1517 // Insert call to work function via shared wrapper. The shared
1518 // wrapper takes two arguments:
1519 // - the parallelism level;
1520 // - the thread ID;
1521 emitCall(CGF, WST.Loc, WorkFnCast,
1522 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
1523 // Go to end of parallel region.
1524 CGF.EmitBranch(TerminateBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001525
1526 // Signal end of parallel region.
1527 CGF.EmitBlock(TerminateBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001528 CGF.EmitRuntimeCall(
1529 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_end_parallel),
1530 llvm::None);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001531 CGF.EmitBranch(BarrierBB);
1532
1533 // All active and inactive workers wait at a barrier after parallel region.
1534 CGF.EmitBlock(BarrierBB);
1535 // Barrier after parallel region.
1536 syncCTAThreads(CGF);
1537 CGF.EmitBranch(AwaitBB);
1538
1539 // Exit target region.
1540 CGF.EmitBlock(ExitBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001541 // Skip initialization.
1542 clearLocThreadIdInsertPt(CGF);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001543}
1544
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001545/// Returns specified OpenMP runtime function for the current OpenMP
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001546/// implementation. Specialized for the NVPTX device.
1547/// \param Function OpenMP runtime function.
1548/// \return Specified function.
1549llvm::Constant *
1550CGOpenMPRuntimeNVPTX::createNVPTXRuntimeFunction(unsigned Function) {
1551 llvm::Constant *RTLFn = nullptr;
1552 switch (static_cast<OpenMPRTLFunctionNVPTX>(Function)) {
1553 case OMPRTL_NVPTX__kmpc_kernel_init: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001554 // Build void __kmpc_kernel_init(kmp_int32 thread_limit, int16_t
1555 // RequiresOMPRuntime);
1556 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001557 auto *FnTy =
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001558 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1559 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_init");
1560 break;
1561 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001562 case OMPRTL_NVPTX__kmpc_kernel_deinit: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001563 // Build void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
1564 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001565 auto *FnTy =
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001566 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001567 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_deinit");
1568 break;
1569 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001570 case OMPRTL_NVPTX__kmpc_spmd_kernel_init: {
1571 // Build void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001572 // int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001573 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001574 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001575 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1576 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_init");
1577 break;
1578 }
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001579 case OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2: {
1580 // Build void __kmpc_spmd_kernel_deinit_v2(int16_t RequiresOMPRuntime);
1581 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001582 auto *FnTy =
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001583 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1584 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_deinit_v2");
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001585 break;
1586 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001587 case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: {
1588 /// Build void __kmpc_kernel_prepare_parallel(
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001589 /// void *outlined_function, int16_t IsOMPRuntimeInitialized);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001590 llvm::Type *TypeParams[] = {CGM.Int8PtrTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001591 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001592 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1593 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_prepare_parallel");
1594 break;
1595 }
1596 case OMPRTL_NVPTX__kmpc_kernel_parallel: {
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001597 /// Build bool __kmpc_kernel_parallel(void **outlined_function,
1598 /// int16_t IsOMPRuntimeInitialized);
1599 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy, CGM.Int16Ty};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001600 llvm::Type *RetTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001601 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001602 llvm::FunctionType::get(RetTy, TypeParams, /*isVarArg*/ false);
1603 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_parallel");
1604 break;
1605 }
1606 case OMPRTL_NVPTX__kmpc_kernel_end_parallel: {
1607 /// Build void __kmpc_kernel_end_parallel();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001608 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001609 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1610 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_end_parallel");
1611 break;
1612 }
1613 case OMPRTL_NVPTX__kmpc_serialized_parallel: {
1614 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1615 // global_tid);
1616 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001617 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001618 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1619 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1620 break;
1621 }
1622 case OMPRTL_NVPTX__kmpc_end_serialized_parallel: {
1623 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1624 // global_tid);
1625 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001626 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001627 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1628 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1629 break;
1630 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001631 case OMPRTL_NVPTX__kmpc_shuffle_int32: {
1632 // Build int32_t __kmpc_shuffle_int32(int32_t element,
1633 // int16_t lane_offset, int16_t warp_size);
1634 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001635 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001636 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1637 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int32");
1638 break;
1639 }
1640 case OMPRTL_NVPTX__kmpc_shuffle_int64: {
1641 // Build int64_t __kmpc_shuffle_int64(int64_t element,
1642 // int16_t lane_offset, int16_t warp_size);
1643 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001644 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001645 llvm::FunctionType::get(CGM.Int64Ty, TypeParams, /*isVarArg*/ false);
1646 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int64");
1647 break;
1648 }
Alexey Bataev8e009032019-01-04 17:25:09 +00001649 case OMPRTL_NVPTX__kmpc_parallel_reduce_nowait_v2: {
1650 // Build int32_t kmpc_nvptx_parallel_reduce_nowait_v2(ident_t *loc,
1651 // kmp_int32 global_tid, kmp_int32 num_vars, size_t reduce_size, void*
1652 // reduce_data, void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t
1653 // lane_id, int16_t lane_offset, int16_t Algorithm Version), void
1654 // (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001655 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1656 CGM.Int16Ty, CGM.Int16Ty};
1657 auto *ShuffleReduceFnTy =
1658 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1659 /*isVarArg=*/false);
1660 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1661 auto *InterWarpCopyFnTy =
1662 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1663 /*isVarArg=*/false);
Alexey Bataev8e009032019-01-04 17:25:09 +00001664 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1665 CGM.Int32Ty,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001666 CGM.Int32Ty,
1667 CGM.SizeTy,
1668 CGM.VoidPtrTy,
1669 ShuffleReduceFnTy->getPointerTo(),
1670 InterWarpCopyFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001671 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001672 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1673 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev8e009032019-01-04 17:25:09 +00001674 FnTy, /*Name=*/"__kmpc_nvptx_parallel_reduce_nowait_v2");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001675 break;
1676 }
1677 case OMPRTL_NVPTX__kmpc_end_reduce_nowait: {
1678 // Build __kmpc_end_reduce_nowait(kmp_int32 global_tid);
1679 llvm::Type *TypeParams[] = {CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001680 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001681 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1682 RTLFn = CGM.CreateRuntimeFunction(
1683 FnTy, /*Name=*/"__kmpc_nvptx_end_reduce_nowait");
1684 break;
1685 }
Alexey Bataeva1166022018-11-27 21:24:54 +00001686 case OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_simple: {
1687 // Build __kmpc_nvptx_teams_reduce_nowait_simple(ident_t *loc, kmp_int32
1688 // global_tid, kmp_critical_name *lck)
1689 llvm::Type *TypeParams[] = {
1690 getIdentTyPointerTy(), CGM.Int32Ty,
1691 llvm::PointerType::getUnqual(getKmpCriticalNameTy())};
1692 auto *FnTy =
1693 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1694 RTLFn = CGM.CreateRuntimeFunction(
1695 FnTy, /*Name=*/"__kmpc_nvptx_teams_reduce_nowait_simple");
1696 break;
1697 }
1698 case OMPRTL_NVPTX__kmpc_nvptx_teams_end_reduce_nowait_simple: {
1699 // Build __kmpc_nvptx_teams_end_reduce_nowait_simple(ident_t *loc, kmp_int32
1700 // global_tid, kmp_critical_name *lck)
1701 llvm::Type *TypeParams[] = {
1702 getIdentTyPointerTy(), CGM.Int32Ty,
1703 llvm::PointerType::getUnqual(getKmpCriticalNameTy())};
1704 auto *FnTy =
1705 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1706 RTLFn = CGM.CreateRuntimeFunction(
1707 FnTy, /*Name=*/"__kmpc_nvptx_teams_end_reduce_nowait_simple");
1708 break;
1709 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001710 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack: {
1711 /// Build void __kmpc_data_sharing_init_stack();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001712 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001713 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1714 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack");
1715 break;
1716 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001717 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd: {
1718 /// Build void __kmpc_data_sharing_init_stack_spmd();
1719 auto *FnTy =
1720 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001721 RTLFn =
1722 CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack_spmd");
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001723 break;
1724 }
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001725 case OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack: {
1726 // Build void *__kmpc_data_sharing_coalesced_push_stack(size_t size,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001727 // int16_t UseSharedMemory);
1728 llvm::Type *TypeParams[] = {CGM.SizeTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001729 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001730 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1731 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001732 FnTy, /*Name=*/"__kmpc_data_sharing_coalesced_push_stack");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001733 break;
1734 }
1735 case OMPRTL_NVPTX__kmpc_data_sharing_pop_stack: {
1736 // Build void __kmpc_data_sharing_pop_stack(void *a);
1737 llvm::Type *TypeParams[] = {CGM.VoidPtrTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001738 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001739 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1740 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1741 /*Name=*/"__kmpc_data_sharing_pop_stack");
1742 break;
1743 }
1744 case OMPRTL_NVPTX__kmpc_begin_sharing_variables: {
1745 /// Build void __kmpc_begin_sharing_variables(void ***args,
1746 /// size_t n_args);
1747 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo(), CGM.SizeTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001748 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001749 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1750 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_begin_sharing_variables");
1751 break;
1752 }
1753 case OMPRTL_NVPTX__kmpc_end_sharing_variables: {
1754 /// Build void __kmpc_end_sharing_variables();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001755 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001756 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1757 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_sharing_variables");
1758 break;
1759 }
1760 case OMPRTL_NVPTX__kmpc_get_shared_variables: {
1761 /// Build void __kmpc_get_shared_variables(void ***GlobalArgs);
1762 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001763 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001764 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1765 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_shared_variables");
1766 break;
1767 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001768 case OMPRTL_NVPTX__kmpc_parallel_level: {
1769 // Build uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32 global_tid);
1770 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1771 auto *FnTy =
1772 llvm::FunctionType::get(CGM.Int16Ty, TypeParams, /*isVarArg*/ false);
1773 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_parallel_level");
1774 break;
1775 }
Alexey Bataev673110d2018-05-16 13:36:30 +00001776 case OMPRTL_NVPTX__kmpc_is_spmd_exec_mode: {
1777 // Build int8_t __kmpc_is_spmd_exec_mode();
1778 auto *FnTy = llvm::FunctionType::get(CGM.Int8Ty, /*isVarArg=*/false);
1779 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_is_spmd_exec_mode");
1780 break;
1781 }
Alexey Bataeve4090182018-11-02 14:54:07 +00001782 case OMPRTL_NVPTX__kmpc_get_team_static_memory: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001783 // Build void __kmpc_get_team_static_memory(int16_t isSPMDExecutionMode,
1784 // const void *buf, size_t size, int16_t is_shared, const void **res);
1785 llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.VoidPtrTy, CGM.SizeTy,
1786 CGM.Int16Ty, CGM.VoidPtrPtrTy};
Alexey Bataeve4090182018-11-02 14:54:07 +00001787 auto *FnTy =
1788 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1789 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_team_static_memory");
1790 break;
1791 }
1792 case OMPRTL_NVPTX__kmpc_restore_team_static_memory: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001793 // Build void __kmpc_restore_team_static_memory(int16_t isSPMDExecutionMode,
1794 // int16_t is_shared);
1795 llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataeve4090182018-11-02 14:54:07 +00001796 auto *FnTy =
Alexey Bataev8e009032019-01-04 17:25:09 +00001797 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
Alexey Bataeve4090182018-11-02 14:54:07 +00001798 RTLFn =
1799 CGM.CreateRuntimeFunction(FnTy, "__kmpc_restore_team_static_memory");
1800 break;
1801 }
Alexey Bataevc3028ca2018-12-04 15:03:25 +00001802 case OMPRTL__kmpc_barrier: {
1803 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
1804 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1805 auto *FnTy =
1806 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1807 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1808 cast<llvm::Function>(RTLFn)->addFnAttr(llvm::Attribute::Convergent);
1809 break;
1810 }
Alexey Bataeva3924b52019-01-03 16:25:35 +00001811 case OMPRTL__kmpc_barrier_simple_spmd: {
1812 // Build void __kmpc_barrier_simple_spmd(ident_t *loc, kmp_int32
1813 // global_tid);
1814 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1815 auto *FnTy =
1816 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1817 RTLFn =
1818 CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier_simple_spmd");
1819 cast<llvm::Function>(RTLFn)->addFnAttr(llvm::Attribute::Convergent);
1820 break;
1821 }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001822 }
1823 return RTLFn;
1824}
1825
1826void CGOpenMPRuntimeNVPTX::createOffloadEntry(llvm::Constant *ID,
1827 llvm::Constant *Addr,
Alexey Bataev03f270c2018-03-30 18:31:07 +00001828 uint64_t Size, int32_t,
1829 llvm::GlobalValue::LinkageTypes) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001830 // TODO: Add support for global variables on the device after declare target
1831 // support.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001832 if (!isa<llvm::Function>(Addr))
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001833 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +00001834 llvm::Module &M = CGM.getModule();
1835 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001836
1837 // Get "nvvm.annotations" metadata node
Alexey Bataev9ff80832018-04-16 20:16:21 +00001838 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001839
1840 llvm::Metadata *MDVals[] = {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001841 llvm::ConstantAsMetadata::get(Addr), llvm::MDString::get(Ctx, "kernel"),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001842 llvm::ConstantAsMetadata::get(
1843 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))};
1844 // Append metadata to nvvm.annotations
1845 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
1846}
1847
1848void CGOpenMPRuntimeNVPTX::emitTargetOutlinedFunction(
1849 const OMPExecutableDirective &D, StringRef ParentName,
1850 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001851 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001852 if (!IsOffloadEntry) // Nothing to do.
1853 return;
1854
1855 assert(!ParentName.empty() && "Invalid target region parent name!");
1856
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001857 bool Mode = supportsSPMDExecutionMode(CGM.getContext(), D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001858 if (Mode)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001859 emitSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001860 CodeGen);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001861 else
1862 emitNonSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1863 CodeGen);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001864
1865 setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001866}
1867
Alexey Bataevceeaa482018-11-21 21:04:34 +00001868namespace {
1869LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
1870/// Enum for accesseing the reserved_2 field of the ident_t struct.
1871enum ModeFlagsTy : unsigned {
1872 /// Bit set to 1 when in SPMD mode.
1873 KMP_IDENT_SPMD_MODE = 0x01,
1874 /// Bit set to 1 when a simplified runtime is used.
1875 KMP_IDENT_SIMPLE_RT_MODE = 0x02,
1876 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/KMP_IDENT_SIMPLE_RT_MODE)
1877};
1878
1879/// Special mode Undefined. Is the combination of Non-SPMD mode + SimpleRuntime.
1880static const ModeFlagsTy UndefinedMode =
1881 (~KMP_IDENT_SPMD_MODE) & KMP_IDENT_SIMPLE_RT_MODE;
1882} // anonymous namespace
1883
1884unsigned CGOpenMPRuntimeNVPTX::getDefaultLocationReserved2Flags() const {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001885 switch (getExecutionMode()) {
1886 case EM_SPMD:
1887 if (requiresFullRuntime())
1888 return KMP_IDENT_SPMD_MODE & (~KMP_IDENT_SIMPLE_RT_MODE);
1889 return KMP_IDENT_SPMD_MODE | KMP_IDENT_SIMPLE_RT_MODE;
1890 case EM_NonSPMD:
1891 assert(requiresFullRuntime() && "Expected full runtime.");
1892 return (~KMP_IDENT_SPMD_MODE) & (~KMP_IDENT_SIMPLE_RT_MODE);
1893 case EM_Unknown:
1894 return UndefinedMode;
1895 }
1896 llvm_unreachable("Unknown flags are requested.");
Alexey Bataevceeaa482018-11-21 21:04:34 +00001897}
1898
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001899CGOpenMPRuntimeNVPTX::CGOpenMPRuntimeNVPTX(CodeGenModule &CGM)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001900 : CGOpenMPRuntime(CGM, "_", "$") {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001901 if (!CGM.getLangOpts().OpenMPIsDevice)
1902 llvm_unreachable("OpenMP NVPTX can only handle device code.");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001903}
Carlo Bertollic6872252016-04-04 15:55:02 +00001904
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001905void CGOpenMPRuntimeNVPTX::emitProcBindClause(CodeGenFunction &CGF,
1906 OpenMPProcBindClauseKind ProcBind,
1907 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001908 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001909 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001910 return;
1911
1912 CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc);
1913}
1914
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001915void CGOpenMPRuntimeNVPTX::emitNumThreadsClause(CodeGenFunction &CGF,
1916 llvm::Value *NumThreads,
1917 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001918 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001919 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001920 return;
1921
1922 CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc);
1923}
1924
Carlo Bertollic6872252016-04-04 15:55:02 +00001925void CGOpenMPRuntimeNVPTX::emitNumTeamsClause(CodeGenFunction &CGF,
1926 const Expr *NumTeams,
1927 const Expr *ThreadLimit,
1928 SourceLocation Loc) {}
1929
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001930llvm::Value *CGOpenMPRuntimeNVPTX::emitParallelOutlinedFunction(
1931 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1932 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00001933 // Emit target region as a standalone region.
1934 class NVPTXPrePostActionTy : public PrePostActionTy {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001935 bool &IsInParallelRegion;
1936 bool PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001937
1938 public:
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001939 NVPTXPrePostActionTy(bool &IsInParallelRegion)
1940 : IsInParallelRegion(IsInParallelRegion) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00001941 void Enter(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001942 PrevIsInParallelRegion = IsInParallelRegion;
1943 IsInParallelRegion = true;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001944 }
1945 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001946 IsInParallelRegion = PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001947 }
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001948 } Action(IsInParallelRegion);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001949 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001950 bool PrevIsInTTDRegion = IsInTTDRegion;
1951 IsInTTDRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001952 bool PrevIsInTargetMasterThreadRegion = IsInTargetMasterThreadRegion;
1953 IsInTargetMasterThreadRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001954 auto *OutlinedFun =
1955 cast<llvm::Function>(CGOpenMPRuntime::emitParallelOutlinedFunction(
1956 D, ThreadIDVar, InnermostKind, CodeGen));
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001957 IsInTargetMasterThreadRegion = PrevIsInTargetMasterThreadRegion;
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001958 IsInTTDRegion = PrevIsInTTDRegion;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001959 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD &&
1960 !IsInParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001961 llvm::Function *WrapperFun =
1962 createParallelDataSharingWrapper(OutlinedFun, D);
1963 WrapperFunctionsMap[OutlinedFun] = WrapperFun;
1964 }
1965
1966 return OutlinedFun;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001967}
1968
Alexey Bataev2adecff2018-09-21 14:22:53 +00001969/// Get list of lastprivate variables from the teams distribute ... or
1970/// teams {distribute ...} directives.
1971static void
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001972getDistributeLastprivateVars(ASTContext &Ctx, const OMPExecutableDirective &D,
Alexey Bataev2adecff2018-09-21 14:22:53 +00001973 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
1974 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
1975 "expected teams directive.");
1976 const OMPExecutableDirective *Dir = &D;
1977 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
1978 if (const Stmt *S = getSingleCompoundChild(
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001979 Ctx,
Alexey Bataev2adecff2018-09-21 14:22:53 +00001980 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
1981 /*IgnoreCaptured=*/true))) {
1982 Dir = dyn_cast<OMPExecutableDirective>(S);
1983 if (Dir && !isOpenMPDistributeDirective(Dir->getDirectiveKind()))
1984 Dir = nullptr;
1985 }
1986 }
1987 if (!Dir)
1988 return;
Alexey Bataev9ea3c382018-10-09 14:49:00 +00001989 for (const auto *C : Dir->getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00001990 for (const Expr *E : C->getVarRefs())
1991 Vars.push_back(getPrivateItem(E));
1992 }
1993}
1994
1995/// Get list of reduction variables from the teams ... directives.
1996static void
1997getTeamsReductionVars(ASTContext &Ctx, const OMPExecutableDirective &D,
1998 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
1999 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
2000 "expected teams directive.");
2001 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
2002 for (const Expr *E : C->privates())
2003 Vars.push_back(getPrivateItem(E));
Alexey Bataev2adecff2018-09-21 14:22:53 +00002004 }
2005}
2006
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002007llvm::Value *CGOpenMPRuntimeNVPTX::emitTeamsOutlinedFunction(
Carlo Bertollic6872252016-04-04 15:55:02 +00002008 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
2009 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002010 SourceLocation Loc = D.getBeginLoc();
Carlo Bertollic6872252016-04-04 15:55:02 +00002011
Alexey Bataev2adecff2018-09-21 14:22:53 +00002012 const RecordDecl *GlobalizedRD = nullptr;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002013 llvm::SmallVector<const ValueDecl *, 4> LastPrivatesReductions;
Alexey Bataev2adecff2018-09-21 14:22:53 +00002014 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002015 // Globalize team reductions variable unconditionally in all modes.
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,
2022 MappedDeclsFields);
2023 }
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 =
2052 llvm::make_unique<CodeGenFunction::OMPMapVars>();
2053 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);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002070 llvm::Value *OutlinedFunVal = CGOpenMPRuntime::emitTeamsOutlinedFunction(
2071 D, ThreadIDVar, InnermostKind, CodeGen);
2072 llvm::Function *OutlinedFun = cast<llvm::Function>(OutlinedFunVal);
2073 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00002074 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002075 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
Carlo Bertollic6872252016-04-04 15:55:02 +00002076
2077 return OutlinedFun;
2078}
2079
Alexey Bataevc99042b2018-03-15 18:10:54 +00002080void CGOpenMPRuntimeNVPTX::emitGenericVarsProlog(CodeGenFunction &CGF,
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002081 SourceLocation Loc,
2082 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002083 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2084 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002085 return;
2086
Alexey Bataevc99042b2018-03-15 18:10:54 +00002087 CGBuilderTy &Bld = CGF.Builder;
2088
2089 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
2090 if (I == FunctionGlobalizedDecls.end())
2091 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002092 if (const RecordDecl *GlobalizedVarsRecord = I->getSecond().GlobalRecord) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002093 QualType GlobalRecTy = CGM.getContext().getRecordType(GlobalizedVarsRecord);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002094 QualType SecGlobalRecTy;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002095
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002096 // Recover pointer to this function's global record. The runtime will
2097 // handle the specifics of the allocation of the memory.
2098 // Use actual memory size of the record including the padding
2099 // for alignment purposes.
2100 unsigned Alignment =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002101 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002102 unsigned GlobalRecordSize =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002103 CGM.getContext().getTypeSizeInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002104 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002105
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002106 llvm::PointerType *GlobalRecPtrTy =
2107 CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo();
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002108 llvm::Value *GlobalRecCastAddr;
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002109 llvm::Value *IsTTD = nullptr;
Alexey Bataeve4090182018-11-02 14:54:07 +00002110 if (!IsInTTDRegion &&
2111 (WithSPMDCheck ||
2112 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002113 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2114 llvm::BasicBlock *SPMDBB = CGF.createBasicBlock(".spmd");
2115 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002116 if (I->getSecond().SecondaryGlobalRecord.hasValue()) {
2117 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2118 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2119 llvm::Value *PL = CGF.EmitRuntimeCall(
2120 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2121 {RTLoc, ThreadID});
2122 IsTTD = Bld.CreateIsNull(PL);
2123 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002124 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2125 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
2126 Bld.CreateCondBr(IsSPMD, SPMDBB, NonSPMDBB);
2127 // There is no need to emit line number for unconditional branch.
2128 (void)ApplyDebugLocation::CreateEmpty(CGF);
2129 CGF.EmitBlock(SPMDBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002130 Address RecPtr = Address(llvm::ConstantPointerNull::get(GlobalRecPtrTy),
2131 CharUnits::fromQuantity(Alignment));
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002132 CGF.EmitBranch(ExitBB);
2133 // There is no need to emit line number for unconditional branch.
2134 (void)ApplyDebugLocation::CreateEmpty(CGF);
2135 CGF.EmitBlock(NonSPMDBB);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002136 llvm::Value *Size = llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize);
2137 if (const RecordDecl *SecGlobalizedVarsRecord =
2138 I->getSecond().SecondaryGlobalRecord.getValueOr(nullptr)) {
2139 SecGlobalRecTy =
2140 CGM.getContext().getRecordType(SecGlobalizedVarsRecord);
2141
2142 // Recover pointer to this function's global record. The runtime will
2143 // handle the specifics of the allocation of the memory.
2144 // Use actual memory size of the record including the padding
2145 // for alignment purposes.
2146 unsigned Alignment =
2147 CGM.getContext().getTypeAlignInChars(SecGlobalRecTy).getQuantity();
2148 unsigned GlobalRecordSize =
2149 CGM.getContext().getTypeSizeInChars(SecGlobalRecTy).getQuantity();
2150 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
2151 Size = Bld.CreateSelect(
2152 IsTTD, llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize), Size);
2153 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002154 // TODO: allow the usage of shared memory to be controlled by
2155 // the user, for now, default to global.
2156 llvm::Value *GlobalRecordSizeArg[] = {
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002157 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002158 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2159 createNVPTXRuntimeFunction(
2160 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2161 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002162 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002163 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002164 CGF.EmitBlock(ExitBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002165 auto *Phi = Bld.CreatePHI(GlobalRecPtrTy,
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002166 /*NumReservedValues=*/2, "_select_stack");
2167 Phi->addIncoming(RecPtr.getPointer(), SPMDBB);
2168 Phi->addIncoming(GlobalRecCastAddr, NonSPMDBB);
2169 GlobalRecCastAddr = Phi;
2170 I->getSecond().GlobalRecordAddr = Phi;
2171 I->getSecond().IsInSPMDModeFlag = IsSPMD;
Alexey Bataeve4090182018-11-02 14:54:07 +00002172 } else if (IsInTTDRegion) {
2173 assert(GlobalizedRecords.back().Records.size() < 2 &&
2174 "Expected less than 2 globalized records: one for target and one "
2175 "for teams.");
2176 unsigned Offset = 0;
2177 for (const RecordDecl *RD : GlobalizedRecords.back().Records) {
2178 QualType RDTy = CGM.getContext().getRecordType(RD);
2179 unsigned Alignment =
2180 CGM.getContext().getTypeAlignInChars(RDTy).getQuantity();
2181 unsigned Size = CGM.getContext().getTypeSizeInChars(RDTy).getQuantity();
2182 Offset =
2183 llvm::alignTo(llvm::alignTo(Offset, Alignment) + Size, Alignment);
2184 }
2185 unsigned Alignment =
2186 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
2187 Offset = llvm::alignTo(Offset, Alignment);
2188 GlobalizedRecords.back().Records.push_back(GlobalizedVarsRecord);
2189 ++GlobalizedRecords.back().RegionCounter;
2190 if (GlobalizedRecords.back().Records.size() == 1) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002191 assert(KernelStaticGlobalized &&
2192 "Kernel static pointer must be initialized already.");
2193 auto *UseSharedMemory = new llvm::GlobalVariable(
2194 CGM.getModule(), CGM.Int16Ty, /*isConstant=*/true,
2195 llvm::GlobalValue::InternalLinkage, nullptr,
2196 "_openmp_static_kernel$is_shared");
2197 UseSharedMemory->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2198 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2199 /*DestWidth=*/16, /*Signed=*/0);
2200 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2201 Address(UseSharedMemory,
2202 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2203 /*Volatile=*/false, Int16Ty, Loc);
2204 auto *StaticGlobalized = new llvm::GlobalVariable(
2205 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002206 llvm::GlobalValue::CommonLinkage, nullptr);
Alexey Bataeve4090182018-11-02 14:54:07 +00002207 auto *RecSize = new llvm::GlobalVariable(
2208 CGM.getModule(), CGM.SizeTy, /*isConstant=*/true,
2209 llvm::GlobalValue::InternalLinkage, nullptr,
2210 "_openmp_static_kernel$size");
2211 RecSize->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2212 llvm::Value *Ld = CGF.EmitLoadOfScalar(
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002213 Address(RecSize, CGM.getSizeAlign()), /*Volatile=*/false,
Alexey Bataeve4090182018-11-02 14:54:07 +00002214 CGM.getContext().getSizeType(), Loc);
2215 llvm::Value *ResAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2216 KernelStaticGlobalized, CGM.VoidPtrPtrTy);
Alexey Bataev8e009032019-01-04 17:25:09 +00002217 llvm::Value *GlobalRecordSizeArg[] = {
2218 llvm::ConstantInt::get(
2219 CGM.Int16Ty,
2220 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD ? 1 : 0),
2221 StaticGlobalized, Ld, IsInSharedMemory, ResAddr};
Alexey Bataeve4090182018-11-02 14:54:07 +00002222 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2223 OMPRTL_NVPTX__kmpc_get_team_static_memory),
2224 GlobalRecordSizeArg);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002225 GlobalizedRecords.back().Buffer = StaticGlobalized;
Alexey Bataeve4090182018-11-02 14:54:07 +00002226 GlobalizedRecords.back().RecSize = RecSize;
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002227 GlobalizedRecords.back().UseSharedMemory = UseSharedMemory;
2228 GlobalizedRecords.back().Loc = Loc;
Alexey Bataeve4090182018-11-02 14:54:07 +00002229 }
2230 assert(KernelStaticGlobalized && "Global address must be set already.");
2231 Address FrameAddr = CGF.EmitLoadOfPointer(
2232 Address(KernelStaticGlobalized, CGM.getPointerAlign()),
2233 CGM.getContext()
2234 .getPointerType(CGM.getContext().VoidPtrTy)
2235 .castAs<PointerType>());
2236 llvm::Value *GlobalRecValue =
2237 Bld.CreateConstInBoundsGEP(FrameAddr, Offset, CharUnits::One())
2238 .getPointer();
2239 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,
2431 llvm::Value *OutlinedFn,
2432 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(
2448 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2449 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) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002538 Address Dst = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
2539 CGF.getPointerSize());
2540 llvm::Value *PtrV;
Alexey Bataev17314212018-03-20 15:41:05 +00002541 if (V->getType()->isIntegerTy())
2542 PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
2543 else
2544 PtrV = Bld.CreatePointerBitCastOrAddrSpaceCast(V, CGF.VoidPtrTy);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002545 CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
2546 Ctx.getPointerType(Ctx.VoidPtrTy));
Alexey Bataevc99042b2018-03-15 18:10:54 +00002547 ++Idx;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002548 }
2549 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002550
2551 // Activate workers. This barrier is used by the master to signal
2552 // work for the workers.
2553 syncCTAThreads(CGF);
2554
2555 // OpenMP [2.5, Parallel Construct, p.49]
2556 // There is an implied barrier at the end of a parallel region. After the
2557 // end of a parallel region, only the master thread of the team resumes
2558 // execution of the enclosing task region.
2559 //
2560 // The master waits at this barrier until all workers are done.
2561 syncCTAThreads(CGF);
2562
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002563 if (!CapturedVars.empty())
2564 CGF.EmitRuntimeCall(
2565 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_sharing_variables));
2566
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002567 // Remember for post-processing in worker loop.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002568 Work.emplace_back(WFn);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002569 };
2570
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002571 auto &&LNParallelGen = [this, Loc, &SeqGen, &L0ParallelGen](
2572 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002573 if (IsInParallelRegion) {
2574 SeqGen(CGF, Action);
2575 } else if (IsInTargetMasterThreadRegion) {
2576 L0ParallelGen(CGF, Action);
2577 } else {
2578 // Check for master and then parallelism:
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002579 // if (__kmpc_is_spmd_exec_mode() || __kmpc_parallel_level(loc, gtid)) {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002580 // Serialized execution.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002581 // } else {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002582 // Worker call.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002583 // }
2584 CGBuilderTy &Bld = CGF.Builder;
2585 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002586 llvm::BasicBlock *SeqBB = CGF.createBasicBlock(".sequential");
2587 llvm::BasicBlock *ParallelCheckBB = CGF.createBasicBlock(".parcheck");
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002588 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
Alexey Bataev673110d2018-05-16 13:36:30 +00002589 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2590 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002591 Bld.CreateCondBr(IsSPMD, SeqBB, ParallelCheckBB);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002592 // There is no need to emit line number for unconditional branch.
2593 (void)ApplyDebugLocation::CreateEmpty(CGF);
2594 CGF.EmitBlock(ParallelCheckBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002595 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2596 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2597 llvm::Value *PL = CGF.EmitRuntimeCall(
2598 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2599 {RTLoc, ThreadID});
2600 llvm::Value *Res = Bld.CreateIsNotNull(PL);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002601 Bld.CreateCondBr(Res, SeqBB, MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002602 CGF.EmitBlock(SeqBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002603 SeqGen(CGF, Action);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002604 CGF.EmitBranch(ExitBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002605 // There is no need to emit line number for unconditional branch.
2606 (void)ApplyDebugLocation::CreateEmpty(CGF);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002607 CGF.EmitBlock(MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002608 L0ParallelGen(CGF, Action);
2609 CGF.EmitBranch(ExitBB);
2610 // There is no need to emit line number for unconditional branch.
2611 (void)ApplyDebugLocation::CreateEmpty(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002612 // Emit the continuation block for code after the if.
2613 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2614 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002615 };
2616
Alexey Bataev9ff80832018-04-16 20:16:21 +00002617 if (IfCond) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002618 emitOMPIfClause(CGF, IfCond, LNParallelGen, SeqGen);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002619 } else {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002620 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002621 RegionCodeGenTy ThenRCG(LNParallelGen);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002622 ThenRCG(CGF);
2623 }
2624}
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002625
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002626void CGOpenMPRuntimeNVPTX::emitSPMDParallelCall(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002627 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2628 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2629 // Just call the outlined function to execute the parallel region.
2630 // OutlinedFn(&GTid, &zero, CapturedStruct);
2631 //
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002632 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Carlo Bertolli79712092018-02-28 20:48:35 +00002633
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002634 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2635 /*DestWidth=*/32, /*Signed=*/1),
2636 ".zero.addr");
Carlo Bertolli79712092018-02-28 20:48:35 +00002637 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002638 // ThreadId for serialized parallels is 0.
2639 Address ThreadIDAddr = ZeroAddr;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002640 auto &&CodeGen = [this, OutlinedFn, CapturedVars, Loc, ZeroAddr,
Alexey Bataev8521ff62018-07-25 20:03:01 +00002641 &ThreadIDAddr](CodeGenFunction &CGF,
2642 PrePostActionTy &Action) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002643 Action.Enter(CGF);
2644
2645 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2646 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2647 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2648 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2649 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2650 };
2651 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2652 PrePostActionTy &) {
2653
2654 RegionCodeGenTy RCG(CodeGen);
2655 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2656 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2657 llvm::Value *Args[] = {RTLoc, ThreadID};
2658
2659 NVPTXActionTy Action(
2660 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2661 Args,
2662 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2663 Args);
2664 RCG.setAction(Action);
2665 RCG(CGF);
2666 };
2667
2668 if (IsInTargetMasterThreadRegion) {
Alexey Bataev8521ff62018-07-25 20:03:01 +00002669 // In the worker need to use the real thread id.
2670 ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002671 RegionCodeGenTy RCG(CodeGen);
2672 RCG(CGF);
2673 } else {
2674 // If we are not in the target region, it is definitely L2 parallelism or
2675 // more, because for SPMD mode we always has L1 parallel level, sowe don't
2676 // need to check for orphaned directives.
2677 RegionCodeGenTy RCG(SeqGen);
2678 RCG(CGF);
2679 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002680}
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002681
Alexey Bataeva3924b52019-01-03 16:25:35 +00002682void CGOpenMPRuntimeNVPTX::syncCTAThreads(CodeGenFunction &CGF) {
2683 // Always emit simple barriers!
2684 if (!CGF.HaveInsertPoint())
2685 return;
2686 // Build call __kmpc_barrier_simple_spmd(nullptr, 0);
2687 // This function does not use parameters, so we can emit just default values.
2688 llvm::Value *Args[] = {
2689 llvm::ConstantPointerNull::get(
2690 cast<llvm::PointerType>(getIdentTyPointerTy())),
2691 llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/0, /*isSigned=*/true)};
2692 CGF.EmitRuntimeCall(
2693 createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier_simple_spmd), Args);
2694}
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)};
2707 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier), Args);
2708}
2709
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002710void CGOpenMPRuntimeNVPTX::emitCriticalRegion(
2711 CodeGenFunction &CGF, StringRef CriticalName,
2712 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
2713 const Expr *Hint) {
2714 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
2715 llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
2716 llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
2717 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
2718 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
2719
2720 // Fetch team-local id of the thread.
2721 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
2722
2723 // Get the width of the team.
2724 llvm::Value *TeamWidth = getNVPTXNumThreads(CGF);
2725
2726 // Initialize the counter variable for the loop.
2727 QualType Int32Ty =
2728 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
2729 Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
2730 LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
2731 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
2732 /*isInit=*/true);
2733
2734 // Block checks if loop counter exceeds upper bound.
2735 CGF.EmitBlock(LoopBB);
2736 llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2737 llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
2738 CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
2739
2740 // Block tests which single thread should execute region, and which threads
2741 // should go straight to synchronisation point.
2742 CGF.EmitBlock(TestBB);
2743 CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2744 llvm::Value *CmpThreadToCounter =
2745 CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
2746 CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
2747
2748 // Block emits the body of the critical region.
2749 CGF.EmitBlock(BodyBB);
2750
2751 // Output the critical statement.
Alexey Bataev2c1ff9d2018-12-04 15:25:01 +00002752 CGOpenMPRuntime::emitCriticalRegion(CGF, CriticalName, CriticalOpGen, Loc,
2753 Hint);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002754
2755 // After the body surrounded by the critical region, the single executing
2756 // thread will jump to the synchronisation point.
2757 // Block waits for all threads in current team to finish then increments the
2758 // counter variable and returns to the loop.
2759 CGF.EmitBlock(SyncBB);
Alexey Bataev2c1ff9d2018-12-04 15:25:01 +00002760 emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false,
2761 /*ForceSimpleCall=*/true);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002762
2763 llvm::Value *IncCounterVal =
2764 CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
2765 CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
2766 CGF.EmitBranch(LoopBB);
2767
2768 // Block that is reached when all threads in the team complete the region.
2769 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2770}
2771
Alexey Bataevb2575932018-01-04 20:18:55 +00002772/// Cast value to the specified type.
Alexey Bataeva453f362018-03-19 17:53:56 +00002773static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
2774 QualType ValTy, QualType CastTy,
2775 SourceLocation Loc) {
2776 assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
2777 "Cast type must sized.");
2778 assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
2779 "Val type must sized.");
2780 llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
2781 if (ValTy == CastTy)
Alexey Bataevb2575932018-01-04 20:18:55 +00002782 return Val;
Alexey Bataeva453f362018-03-19 17:53:56 +00002783 if (CGF.getContext().getTypeSizeInChars(ValTy) ==
2784 CGF.getContext().getTypeSizeInChars(CastTy))
2785 return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
2786 if (CastTy->isIntegerType() && ValTy->isIntegerType())
2787 return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
2788 CastTy->hasSignedIntegerRepresentation());
2789 Address CastItem = CGF.CreateMemTemp(CastTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002790 Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2791 CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
Alexey Bataeva453f362018-03-19 17:53:56 +00002792 CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy);
2793 return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc);
Alexey Bataevb2575932018-01-04 20:18:55 +00002794}
2795
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002796/// This function creates calls to one of two shuffle functions to copy
2797/// variables between lanes in a warp.
2798static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002799 llvm::Value *Elem,
Alexey Bataeva453f362018-03-19 17:53:56 +00002800 QualType ElemType,
2801 llvm::Value *Offset,
2802 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002803 CodeGenModule &CGM = CGF.CGM;
2804 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002805 CGOpenMPRuntimeNVPTX &RT =
2806 *(static_cast<CGOpenMPRuntimeNVPTX *>(&CGM.getOpenMPRuntime()));
2807
Alexey Bataeva453f362018-03-19 17:53:56 +00002808 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2809 assert(Size.getQuantity() <= 8 &&
2810 "Unsupported bitwidth in shuffle instruction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002811
Alexey Bataeva453f362018-03-19 17:53:56 +00002812 OpenMPRTLFunctionNVPTX ShuffleFn = Size.getQuantity() <= 4
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002813 ? OMPRTL_NVPTX__kmpc_shuffle_int32
2814 : OMPRTL_NVPTX__kmpc_shuffle_int64;
2815
2816 // Cast all types to 32- or 64-bit values before calling shuffle routines.
Alexey Bataeva453f362018-03-19 17:53:56 +00002817 QualType CastTy = CGF.getContext().getIntTypeForBitwidth(
2818 Size.getQuantity() <= 4 ? 32 : 64, /*Signed=*/1);
2819 llvm::Value *ElemCast = castValueToType(CGF, Elem, ElemType, CastTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002820 llvm::Value *WarpSize =
Alexey Bataevb2575932018-01-04 20:18:55 +00002821 Bld.CreateIntCast(getNVPTXWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002822
Alexey Bataev9ff80832018-04-16 20:16:21 +00002823 llvm::Value *ShuffledVal = CGF.EmitRuntimeCall(
2824 RT.createNVPTXRuntimeFunction(ShuffleFn), {ElemCast, Offset, WarpSize});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002825
Alexey Bataeva453f362018-03-19 17:53:56 +00002826 return castValueToType(CGF, ShuffledVal, CastTy, ElemType, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002827}
2828
Alexey Bataev12c62902018-06-22 19:10:38 +00002829static void shuffleAndStore(CodeGenFunction &CGF, Address SrcAddr,
2830 Address DestAddr, QualType ElemType,
2831 llvm::Value *Offset, SourceLocation Loc) {
2832 CGBuilderTy &Bld = CGF.Builder;
2833
2834 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2835 // Create the loop over the big sized data.
2836 // ptr = (void*)Elem;
2837 // ptrEnd = (void*) Elem + 1;
2838 // Step = 8;
2839 // while (ptr + Step < ptrEnd)
2840 // shuffle((int64_t)*ptr);
2841 // Step = 4;
2842 // while (ptr + Step < ptrEnd)
2843 // shuffle((int32_t)*ptr);
2844 // ...
2845 Address ElemPtr = DestAddr;
2846 Address Ptr = SrcAddr;
2847 Address PtrEnd = Bld.CreatePointerBitCastOrAddrSpaceCast(
2848 Bld.CreateConstGEP(SrcAddr, 1, Size), CGF.VoidPtrTy);
2849 for (int IntSize = 8; IntSize >= 1; IntSize /= 2) {
2850 if (Size < CharUnits::fromQuantity(IntSize))
2851 continue;
2852 QualType IntType = CGF.getContext().getIntTypeForBitwidth(
2853 CGF.getContext().toBits(CharUnits::fromQuantity(IntSize)),
2854 /*Signed=*/1);
2855 llvm::Type *IntTy = CGF.ConvertTypeForMem(IntType);
2856 Ptr = Bld.CreatePointerBitCastOrAddrSpaceCast(Ptr, IntTy->getPointerTo());
2857 ElemPtr =
2858 Bld.CreatePointerBitCastOrAddrSpaceCast(ElemPtr, IntTy->getPointerTo());
2859 if (Size.getQuantity() / IntSize > 1) {
2860 llvm::BasicBlock *PreCondBB = CGF.createBasicBlock(".shuffle.pre_cond");
2861 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".shuffle.then");
2862 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".shuffle.exit");
2863 llvm::BasicBlock *CurrentBB = Bld.GetInsertBlock();
2864 CGF.EmitBlock(PreCondBB);
2865 llvm::PHINode *PhiSrc =
2866 Bld.CreatePHI(Ptr.getType(), /*NumReservedValues=*/2);
2867 PhiSrc->addIncoming(Ptr.getPointer(), CurrentBB);
2868 llvm::PHINode *PhiDest =
2869 Bld.CreatePHI(ElemPtr.getType(), /*NumReservedValues=*/2);
2870 PhiDest->addIncoming(ElemPtr.getPointer(), CurrentBB);
2871 Ptr = Address(PhiSrc, Ptr.getAlignment());
2872 ElemPtr = Address(PhiDest, ElemPtr.getAlignment());
2873 llvm::Value *PtrDiff = Bld.CreatePtrDiff(
2874 PtrEnd.getPointer(), Bld.CreatePointerBitCastOrAddrSpaceCast(
2875 Ptr.getPointer(), CGF.VoidPtrTy));
2876 Bld.CreateCondBr(Bld.CreateICmpSGT(PtrDiff, Bld.getInt64(IntSize - 1)),
2877 ThenBB, ExitBB);
2878 CGF.EmitBlock(ThenBB);
2879 llvm::Value *Res = createRuntimeShuffleFunction(
2880 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2881 IntType, Offset, Loc);
2882 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002883 Address LocalPtr =
2884 Bld.CreateConstGEP(Ptr, 1, CharUnits::fromQuantity(IntSize));
2885 Address LocalElemPtr =
Alexey Bataev12c62902018-06-22 19:10:38 +00002886 Bld.CreateConstGEP(ElemPtr, 1, CharUnits::fromQuantity(IntSize));
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002887 PhiSrc->addIncoming(LocalPtr.getPointer(), ThenBB);
2888 PhiDest->addIncoming(LocalElemPtr.getPointer(), ThenBB);
Alexey Bataev12c62902018-06-22 19:10:38 +00002889 CGF.EmitBranch(PreCondBB);
2890 CGF.EmitBlock(ExitBB);
2891 } else {
2892 llvm::Value *Res = createRuntimeShuffleFunction(
2893 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2894 IntType, Offset, Loc);
2895 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
2896 Ptr = Bld.CreateConstGEP(Ptr, 1, CharUnits::fromQuantity(IntSize));
2897 ElemPtr =
2898 Bld.CreateConstGEP(ElemPtr, 1, CharUnits::fromQuantity(IntSize));
2899 }
2900 Size = Size % IntSize;
2901 }
2902}
2903
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002904namespace {
2905enum CopyAction : unsigned {
2906 // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
2907 // the warp using shuffle instructions.
2908 RemoteLaneToThread,
2909 // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
2910 ThreadCopy,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002911 // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
2912 ThreadToScratchpad,
2913 // ScratchpadToThread: Copy from a scratchpad array in global memory
2914 // containing team-reduced data to a thread's stack.
2915 ScratchpadToThread,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002916};
2917} // namespace
2918
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002919struct CopyOptionsTy {
2920 llvm::Value *RemoteLaneOffset;
2921 llvm::Value *ScratchpadIndex;
2922 llvm::Value *ScratchpadWidth;
2923};
2924
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002925/// Emit instructions to copy a Reduce list, which contains partially
2926/// aggregated values, in the specified direction.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002927static void emitReductionListCopy(
2928 CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
2929 ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
2930 CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002931
Alexey Bataev9ff80832018-04-16 20:16:21 +00002932 CodeGenModule &CGM = CGF.CGM;
2933 ASTContext &C = CGM.getContext();
2934 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002935
Alexey Bataev9ff80832018-04-16 20:16:21 +00002936 llvm::Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
2937 llvm::Value *ScratchpadIndex = CopyOptions.ScratchpadIndex;
2938 llvm::Value *ScratchpadWidth = CopyOptions.ScratchpadWidth;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002939
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002940 // Iterates, element-by-element, through the source Reduce list and
2941 // make a copy.
2942 unsigned Idx = 0;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002943 unsigned Size = Privates.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00002944 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002945 Address SrcElementAddr = Address::invalid();
2946 Address DestElementAddr = Address::invalid();
2947 Address DestElementPtrAddr = Address::invalid();
2948 // Should we shuffle in an element from a remote lane?
2949 bool ShuffleInElement = false;
2950 // Set to true to update the pointer in the dest Reduce list to a
2951 // newly created element.
2952 bool UpdateDestListPtr = false;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002953 // Increment the src or dest pointer to the scratchpad, for each
2954 // new element.
2955 bool IncrScratchpadSrc = false;
2956 bool IncrScratchpadDest = false;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002957
2958 switch (Action) {
2959 case RemoteLaneToThread: {
2960 // Step 1.1: Get the address for the src element in the Reduce list.
2961 Address SrcElementPtrAddr =
2962 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002963 SrcElementAddr = CGF.EmitLoadOfPointer(
2964 SrcElementPtrAddr,
2965 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002966
2967 // Step 1.2: Create a temporary to store the element in the destination
2968 // Reduce list.
2969 DestElementPtrAddr =
2970 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
2971 DestElementAddr =
2972 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2973 ShuffleInElement = true;
2974 UpdateDestListPtr = true;
2975 break;
2976 }
2977 case ThreadCopy: {
2978 // Step 1.1: Get the address for the src element in the Reduce list.
2979 Address SrcElementPtrAddr =
2980 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
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.
2987 DestElementPtrAddr =
2988 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002989 DestElementAddr = CGF.EmitLoadOfPointer(
2990 DestElementPtrAddr,
2991 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002992 break;
2993 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002994 case ThreadToScratchpad: {
2995 // Step 1.1: Get the address for the src element in the Reduce list.
2996 Address SrcElementPtrAddr =
2997 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002998 SrcElementAddr = CGF.EmitLoadOfPointer(
2999 SrcElementPtrAddr,
3000 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003001
3002 // Step 1.2: Get the address for dest element:
3003 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00003004 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00003005 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003006 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003007 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003008 Bld.CreateNUWAdd(DestBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003009 ScratchPadElemAbsolutePtrVal =
3010 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00003011 DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
3012 C.getTypeAlignInChars(Private->getType()));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003013 IncrScratchpadDest = true;
3014 break;
3015 }
3016 case ScratchpadToThread: {
3017 // Step 1.1: Get the address for the src element in the scratchpad.
3018 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00003019 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00003020 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003021 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003022 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003023 Bld.CreateNUWAdd(SrcBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003024 ScratchPadElemAbsolutePtrVal =
3025 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
3026 SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
3027 C.getTypeAlignInChars(Private->getType()));
3028 IncrScratchpadSrc = true;
3029
3030 // Step 1.2: Create a temporary to store the element in the destination
3031 // Reduce list.
3032 DestElementPtrAddr =
3033 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
3034 DestElementAddr =
3035 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
3036 UpdateDestListPtr = true;
3037 break;
3038 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003039 }
3040
3041 // Regardless of src and dest of copy, we emit the load of src
3042 // element as this is required in all directions
3043 SrcElementAddr = Bld.CreateElementBitCast(
3044 SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
Alexey Bataev12c62902018-06-22 19:10:38 +00003045 DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
3046 SrcElementAddr.getElementType());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003047
3048 // Now that all active lanes have read the element in the
3049 // Reduce list, shuffle over the value from the remote lane.
Alexey Bataeva453f362018-03-19 17:53:56 +00003050 if (ShuffleInElement) {
Alexey Bataev12c62902018-06-22 19:10:38 +00003051 shuffleAndStore(CGF, SrcElementAddr, DestElementAddr, Private->getType(),
3052 RemoteLaneOffset, Private->getExprLoc());
3053 } else {
3054 if (Private->getType()->isScalarType()) {
3055 llvm::Value *Elem =
3056 CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false,
3057 Private->getType(), Private->getExprLoc());
3058 // Store the source element value to the dest element address.
3059 CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false,
3060 Private->getType());
3061 } else {
3062 CGF.EmitAggregateCopy(
3063 CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3064 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3065 Private->getType(), AggValueSlot::DoesNotOverlap);
3066 }
Alexey Bataeva453f362018-03-19 17:53:56 +00003067 }
Alexey Bataevb2575932018-01-04 20:18:55 +00003068
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003069 // Step 3.1: Modify reference in dest Reduce list as needed.
3070 // Modifying the reference in Reduce list to point to the newly
3071 // created element. The element is live in the current function
3072 // scope and that of functions it invokes (i.e., reduce_function).
3073 // RemoteReduceData[i] = (void*)&RemoteElem
3074 if (UpdateDestListPtr) {
3075 CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
3076 DestElementAddr.getPointer(), CGF.VoidPtrTy),
3077 DestElementPtrAddr, /*Volatile=*/false,
3078 C.VoidPtrTy);
3079 }
3080
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003081 // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
3082 // address of the next element in scratchpad memory, unless we're currently
3083 // processing the last one. Memory alignment is also taken care of here.
3084 if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
3085 llvm::Value *ScratchpadBasePtr =
3086 IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
Alexey Bataeve290ec02018-04-06 16:03:36 +00003087 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
3088 ScratchpadBasePtr = Bld.CreateNUWAdd(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003089 ScratchpadBasePtr,
Alexey Bataeve290ec02018-04-06 16:03:36 +00003090 Bld.CreateNUWMul(ScratchpadWidth, ElementSizeInChars));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003091
3092 // Take care of global memory alignment for performance
Alexey Bataeve290ec02018-04-06 16:03:36 +00003093 ScratchpadBasePtr = Bld.CreateNUWSub(
3094 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3095 ScratchpadBasePtr = Bld.CreateUDiv(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003096 ScratchpadBasePtr,
3097 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
Alexey Bataeve290ec02018-04-06 16:03:36 +00003098 ScratchpadBasePtr = Bld.CreateNUWAdd(
3099 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3100 ScratchpadBasePtr = Bld.CreateNUWMul(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003101 ScratchpadBasePtr,
3102 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
3103
3104 if (IncrScratchpadDest)
3105 DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3106 else /* IncrScratchpadSrc = true */
3107 SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3108 }
3109
Alexey Bataev9ff80832018-04-16 20:16:21 +00003110 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003111 }
3112}
3113
3114/// This function emits a helper that gathers Reduce lists from the first
3115/// lane of every active warp to lanes in the first warp.
3116///
3117/// void inter_warp_copy_func(void* reduce_data, num_warps)
3118/// shared smem[warp_size];
3119/// For all data entries D in reduce_data:
Alexey Bataev29d47fc2018-12-18 19:20:15 +00003120/// sync
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003121/// If (I am the first lane in each warp)
3122/// Copy my local D to smem[warp_id]
3123/// sync
3124/// if (I am the first warp)
3125/// Copy smem[thread_id] to my local D
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003126static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
3127 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003128 QualType ReductionArrayTy,
3129 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003130 ASTContext &C = CGM.getContext();
3131 llvm::Module &M = CGM.getModule();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003132
3133 // ReduceList: thread local Reduce list.
3134 // At the stage of the computation when this function is called, partially
3135 // aggregated values reside in the first lane of every active warp.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003136 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3137 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003138 // NumWarps: number of warps active in the parallel region. This could
3139 // be smaller than 32 (max warps in a CTA) for partial block reduction.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003140 ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00003141 C.getIntTypeForBitwidth(32, /* Signed */ true),
3142 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003143 FunctionArgList Args;
3144 Args.push_back(&ReduceListArg);
3145 Args.push_back(&NumWarpsArg);
3146
Alexey Bataev9ff80832018-04-16 20:16:21 +00003147 const CGFunctionInfo &CGFI =
3148 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003149 auto *Fn = llvm::Function::Create(
3150 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3151 "_omp_reduction_inter_warp_copy_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003152 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003153 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003154 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003155 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003156
Alexey Bataev9ff80832018-04-16 20:16:21 +00003157 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003158
3159 // This array is used as a medium to transfer, one reduce element at a time,
3160 // the data from the first lane of every warp to lanes in the first warp
3161 // in order to perform the final step of a reduction in a parallel region
3162 // (reduction across warps). The array is placed in NVPTX __shared__ memory
3163 // for reduced latency, as well as to have a distinct copy for concurrently
3164 // executing target regions. The array is declared with common linkage so
3165 // as to be shared across compilation units.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003166 StringRef TransferMediumName =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003167 "__openmp_nvptx_data_transfer_temporary_storage";
3168 llvm::GlobalVariable *TransferMedium =
3169 M.getGlobalVariable(TransferMediumName);
3170 if (!TransferMedium) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003171 auto *Ty = llvm::ArrayType::get(CGM.Int32Ty, WarpSize);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003172 unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
3173 TransferMedium = new llvm::GlobalVariable(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003174 M, Ty, /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003175 llvm::Constant::getNullValue(Ty), TransferMediumName,
3176 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3177 SharedAddressSpace);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003178 CGM.addCompilerUsedGlobal(TransferMedium);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003179 }
3180
3181 // Get the CUDA thread id of the current OpenMP thread on the GPU.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003182 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003183 // nvptx_lane_id = nvptx_id % warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003184 llvm::Value *LaneID = getNVPTXLaneID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003185 // nvptx_warp_id = nvptx_id / warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003186 llvm::Value *WarpID = getNVPTXWarpID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003187
3188 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3189 Address LocalReduceList(
3190 Bld.CreatePointerBitCastOrAddrSpaceCast(
3191 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003192 C.VoidPtrTy, Loc),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003193 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3194 CGF.getPointerAlign());
3195
3196 unsigned Idx = 0;
Alexey Bataev9ff80832018-04-16 20:16:21 +00003197 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003198 //
3199 // Warp master copies reduce element to transfer medium in __shared__
3200 // memory.
3201 //
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003202 unsigned RealTySize =
3203 C.getTypeSizeInChars(Private->getType())
3204 .alignTo(C.getTypeAlignInChars(Private->getType()))
3205 .getQuantity();
3206 for (unsigned TySize = 4; TySize > 0 && RealTySize > 0; TySize /=2) {
3207 unsigned NumIters = RealTySize / TySize;
3208 if (NumIters == 0)
3209 continue;
3210 QualType CType = C.getIntTypeForBitwidth(
3211 C.toBits(CharUnits::fromQuantity(TySize)), /*Signed=*/1);
3212 llvm::Type *CopyType = CGF.ConvertTypeForMem(CType);
3213 CharUnits Align = CharUnits::fromQuantity(TySize);
3214 llvm::Value *Cnt = nullptr;
3215 Address CntAddr = Address::invalid();
3216 llvm::BasicBlock *PrecondBB = nullptr;
3217 llvm::BasicBlock *ExitBB = nullptr;
3218 if (NumIters > 1) {
3219 CntAddr = CGF.CreateMemTemp(C.IntTy, ".cnt.addr");
3220 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.IntTy), CntAddr,
3221 /*Volatile=*/false, C.IntTy);
3222 PrecondBB = CGF.createBasicBlock("precond");
3223 ExitBB = CGF.createBasicBlock("exit");
3224 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("body");
3225 // There is no need to emit line number for unconditional branch.
3226 (void)ApplyDebugLocation::CreateEmpty(CGF);
3227 CGF.EmitBlock(PrecondBB);
3228 Cnt = CGF.EmitLoadOfScalar(CntAddr, /*Volatile=*/false, C.IntTy, Loc);
3229 llvm::Value *Cmp =
3230 Bld.CreateICmpULT(Cnt, llvm::ConstantInt::get(CGM.IntTy, NumIters));
3231 Bld.CreateCondBr(Cmp, BodyBB, ExitBB);
3232 CGF.EmitBlock(BodyBB);
3233 }
Alexey Bataev29d47fc2018-12-18 19:20:15 +00003234 // kmpc_barrier.
3235 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3236 /*EmitChecks=*/false,
3237 /*ForceSimpleCall=*/true);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003238 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3239 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3240 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003241
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003242 // if (lane_id == 0)
3243 llvm::Value *IsWarpMaster = Bld.CreateIsNull(LaneID, "warp_master");
3244 Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
3245 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003246
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003247 // Reduce element = LocalReduceList[i]
3248 Address ElemPtrPtrAddr =
3249 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
3250 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3251 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3252 // elemptr = ((CopyType*)(elemptrptr)) + I
3253 Address ElemPtr = Address(ElemPtrPtr, Align);
3254 ElemPtr = Bld.CreateElementBitCast(ElemPtr, CopyType);
3255 if (NumIters > 1) {
3256 ElemPtr = Address(Bld.CreateGEP(ElemPtr.getPointer(), Cnt),
3257 ElemPtr.getAlignment());
3258 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003259
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003260 // Get pointer to location in transfer medium.
3261 // MediumPtr = &medium[warp_id]
3262 llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
3263 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
3264 Address MediumPtr(MediumPtrVal, Align);
3265 // Casting to actual data type.
3266 // MediumPtr = (CopyType*)MediumPtrAddr;
3267 MediumPtr = Bld.CreateElementBitCast(MediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003268
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003269 // elem = *elemptr
3270 //*MediumPtr = elem
3271 llvm::Value *Elem =
3272 CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003273 // Store the source element value to the dest element address.
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003274 CGF.EmitStoreOfScalar(Elem, MediumPtr, /*Volatile=*/true, CType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003275
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003276 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003277
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003278 CGF.EmitBlock(ElseBB);
3279 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003280
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003281 CGF.EmitBlock(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003282
Alexey Bataevae51b962018-12-14 21:00:58 +00003283 // kmpc_barrier.
3284 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3285 /*EmitChecks=*/false,
3286 /*ForceSimpleCall=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003287
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003288 //
3289 // Warp 0 copies reduce element from transfer medium.
3290 //
3291 llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
3292 llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
3293 llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003294
Alexey Bataevae51b962018-12-14 21:00:58 +00003295 Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
3296 llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
3297 AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, Loc);
3298
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003299 // Up to 32 threads in warp 0 are active.
3300 llvm::Value *IsActiveThread =
3301 Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
3302 Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003303
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003304 CGF.EmitBlock(W0ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003305
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003306 // SrcMediumPtr = &medium[tid]
3307 llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
3308 TransferMedium,
3309 {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
3310 Address SrcMediumPtr(SrcMediumPtrVal, Align);
3311 // SrcMediumVal = *SrcMediumPtr;
3312 SrcMediumPtr = Bld.CreateElementBitCast(SrcMediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003313
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003314 // TargetElemPtr = (CopyType*)(SrcDataAddr[i]) + I
3315 Address TargetElemPtrPtr =
3316 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
3317 llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
3318 TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, Loc);
3319 Address TargetElemPtr = Address(TargetElemPtrVal, Align);
3320 TargetElemPtr = Bld.CreateElementBitCast(TargetElemPtr, CopyType);
3321 if (NumIters > 1) {
3322 TargetElemPtr = Address(Bld.CreateGEP(TargetElemPtr.getPointer(), Cnt),
3323 TargetElemPtr.getAlignment());
3324 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003325
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003326 // *TargetElemPtr = SrcMediumVal;
3327 llvm::Value *SrcMediumValue =
3328 CGF.EmitLoadOfScalar(SrcMediumPtr, /*Volatile=*/true, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003329 CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003330 CType);
3331 Bld.CreateBr(W0MergeBB);
3332
3333 CGF.EmitBlock(W0ElseBB);
3334 Bld.CreateBr(W0MergeBB);
3335
3336 CGF.EmitBlock(W0MergeBB);
3337
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003338 if (NumIters > 1) {
3339 Cnt = Bld.CreateNSWAdd(Cnt, llvm::ConstantInt::get(CGM.IntTy, /*V=*/1));
3340 CGF.EmitStoreOfScalar(Cnt, CntAddr, /*Volatile=*/false, C.IntTy);
3341 CGF.EmitBranch(PrecondBB);
3342 (void)ApplyDebugLocation::CreateEmpty(CGF);
3343 CGF.EmitBlock(ExitBB);
3344 }
3345 RealTySize %= TySize;
Alexey Bataev12c62902018-06-22 19:10:38 +00003346 }
Alexey Bataev9ff80832018-04-16 20:16:21 +00003347 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003348 }
3349
3350 CGF.FinishFunction();
3351 return Fn;
3352}
3353
3354/// Emit a helper that reduces data across two OpenMP threads (lanes)
3355/// in the same warp. It uses shuffle instructions to copy over data from
3356/// a remote lane's stack. The reduction algorithm performed is specified
3357/// by the fourth parameter.
3358///
3359/// Algorithm Versions.
3360/// Full Warp Reduce (argument value 0):
3361/// This algorithm assumes that all 32 lanes are active and gathers
3362/// data from these 32 lanes, producing a single resultant value.
3363/// Contiguous Partial Warp Reduce (argument value 1):
3364/// This algorithm assumes that only a *contiguous* subset of lanes
3365/// are active. This happens for the last warp in a parallel region
3366/// when the user specified num_threads is not an integer multiple of
3367/// 32. This contiguous subset always starts with the zeroth lane.
3368/// Partial Warp Reduce (argument value 2):
3369/// This algorithm gathers data from any number of lanes at any position.
3370/// All reduced values are stored in the lowest possible lane. The set
3371/// of problems every algorithm addresses is a super set of those
3372/// addressable by algorithms with a lower version number. Overhead
3373/// increases as algorithm version increases.
3374///
3375/// Terminology
3376/// Reduce element:
3377/// Reduce element refers to the individual data field with primitive
3378/// data types to be combined and reduced across threads.
3379/// Reduce list:
3380/// Reduce list refers to a collection of local, thread-private
3381/// reduce elements.
3382/// Remote Reduce list:
3383/// Remote Reduce list refers to a collection of remote (relative to
3384/// the current thread) reduce elements.
3385///
3386/// We distinguish between three states of threads that are important to
3387/// the implementation of this function.
3388/// Alive threads:
3389/// Threads in a warp executing the SIMT instruction, as distinguished from
3390/// threads that are inactive due to divergent control flow.
3391/// Active threads:
3392/// The minimal set of threads that has to be alive upon entry to this
3393/// function. The computation is correct iff active threads are alive.
3394/// Some threads are alive but they are not active because they do not
3395/// contribute to the computation in any useful manner. Turning them off
3396/// may introduce control flow overheads without any tangible benefits.
3397/// Effective threads:
3398/// In order to comply with the argument requirements of the shuffle
3399/// function, we must keep all lanes holding data alive. But at most
3400/// half of them perform value aggregation; we refer to this half of
3401/// threads as effective. The other half is simply handing off their
3402/// data.
3403///
3404/// Procedure
3405/// Value shuffle:
3406/// In this step active threads transfer data from higher lane positions
3407/// in the warp to lower lane positions, creating Remote Reduce list.
3408/// Value aggregation:
3409/// In this step, effective threads combine their thread local Reduce list
3410/// with Remote Reduce list and store the result in the thread local
3411/// Reduce list.
3412/// Value copy:
3413/// In this step, we deal with the assumption made by algorithm 2
3414/// (i.e. contiguity assumption). When we have an odd number of lanes
3415/// active, say 2k+1, only k threads will be effective and therefore k
3416/// new values will be produced. However, the Reduce list owned by the
3417/// (2k+1)th thread is ignored in the value aggregation. Therefore
3418/// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
3419/// that the contiguity assumption still holds.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003420static llvm::Value *emitShuffleAndReduceFunction(
3421 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3422 QualType ReductionArrayTy, llvm::Value *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003423 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003424
3425 // Thread local Reduce list used to host the values of data to be reduced.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003426 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3427 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003428 // Current lane id; could be logical.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003429 ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
3430 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003431 // Offset of the remote source lane relative to the current lane.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003432 ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3433 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003434 // Algorithm version. This is expected to be known at compile time.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003435 ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3436 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003437 FunctionArgList Args;
3438 Args.push_back(&ReduceListArg);
3439 Args.push_back(&LaneIDArg);
3440 Args.push_back(&RemoteLaneOffsetArg);
3441 Args.push_back(&AlgoVerArg);
3442
Alexey Bataev9ff80832018-04-16 20:16:21 +00003443 const CGFunctionInfo &CGFI =
3444 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003445 auto *Fn = llvm::Function::Create(
3446 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3447 "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003448 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003449 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003450 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003451 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003452
Alexey Bataev9ff80832018-04-16 20:16:21 +00003453 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003454
3455 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3456 Address LocalReduceList(
3457 Bld.CreatePointerBitCastOrAddrSpaceCast(
3458 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3459 C.VoidPtrTy, SourceLocation()),
3460 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3461 CGF.getPointerAlign());
3462
3463 Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
3464 llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
3465 AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3466
3467 Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
3468 llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
3469 AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3470
3471 Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
3472 llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
3473 AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3474
3475 // Create a local thread-private variable to host the Reduce list
3476 // from a remote lane.
3477 Address RemoteReduceList =
3478 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
3479
3480 // This loop iterates through the list of reduce elements and copies,
3481 // element by element, from a remote lane in the warp to RemoteReduceList,
3482 // hosted on the thread's stack.
3483 emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
3484 LocalReduceList, RemoteReduceList,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003485 {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
3486 /*ScratchpadIndex=*/nullptr,
3487 /*ScratchpadWidth=*/nullptr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003488
3489 // The actions to be performed on the Remote Reduce list is dependent
3490 // on the algorithm version.
3491 //
3492 // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
3493 // LaneId % 2 == 0 && Offset > 0):
3494 // do the reduction value aggregation
3495 //
3496 // The thread local variable Reduce list is mutated in place to host the
3497 // reduced data, which is the aggregated value produced from local and
3498 // remote lanes.
3499 //
3500 // Note that AlgoVer is expected to be a constant integer known at compile
3501 // time.
3502 // When AlgoVer==0, the first conjunction evaluates to true, making
3503 // the entire predicate true during compile time.
3504 // When AlgoVer==1, the second conjunction has only the second part to be
3505 // evaluated during runtime. Other conjunctions evaluates to false
3506 // during compile time.
3507 // When AlgoVer==2, the third conjunction has only the second part to be
3508 // evaluated during runtime. Other conjunctions evaluates to false
3509 // during compile time.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003510 llvm::Value *CondAlgo0 = Bld.CreateIsNull(AlgoVerArgVal);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003511
Alexey Bataev9ff80832018-04-16 20:16:21 +00003512 llvm::Value *Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
3513 llvm::Value *CondAlgo1 = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003514 Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
3515
Alexey Bataev9ff80832018-04-16 20:16:21 +00003516 llvm::Value *Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
3517 llvm::Value *CondAlgo2 = Bld.CreateAnd(
3518 Algo2, Bld.CreateIsNull(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1))));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003519 CondAlgo2 = Bld.CreateAnd(
3520 CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
3521
Alexey Bataev9ff80832018-04-16 20:16:21 +00003522 llvm::Value *CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003523 CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
3524
3525 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3526 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3527 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
3528 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
3529
3530 CGF.EmitBlock(ThenBB);
3531 // reduce_function(LocalReduceList, RemoteReduceList)
3532 llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3533 LocalReduceList.getPointer(), CGF.VoidPtrTy);
3534 llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3535 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003536 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3537 CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003538 Bld.CreateBr(MergeBB);
3539
3540 CGF.EmitBlock(ElseBB);
3541 Bld.CreateBr(MergeBB);
3542
3543 CGF.EmitBlock(MergeBB);
3544
3545 // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
3546 // Reduce list.
3547 Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
Alexey Bataev9ff80832018-04-16 20:16:21 +00003548 llvm::Value *CondCopy = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003549 Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
3550
3551 llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
3552 llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
3553 llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
3554 Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
3555
3556 CGF.EmitBlock(CpyThenBB);
3557 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
3558 RemoteReduceList, LocalReduceList);
3559 Bld.CreateBr(CpyMergeBB);
3560
3561 CGF.EmitBlock(CpyElseBB);
3562 Bld.CreateBr(CpyMergeBB);
3563
3564 CGF.EmitBlock(CpyMergeBB);
3565
3566 CGF.FinishFunction();
3567 return Fn;
3568}
3569
3570///
3571/// Design of OpenMP reductions on the GPU
3572///
3573/// Consider a typical OpenMP program with one or more reduction
3574/// clauses:
3575///
3576/// float foo;
3577/// double bar;
3578/// #pragma omp target teams distribute parallel for \
3579/// reduction(+:foo) reduction(*:bar)
3580/// for (int i = 0; i < N; i++) {
3581/// foo += A[i]; bar *= B[i];
3582/// }
3583///
3584/// where 'foo' and 'bar' are reduced across all OpenMP threads in
3585/// all teams. In our OpenMP implementation on the NVPTX device an
3586/// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
3587/// within a team are mapped to CUDA threads within a threadblock.
3588/// Our goal is to efficiently aggregate values across all OpenMP
3589/// threads such that:
3590///
3591/// - the compiler and runtime are logically concise, and
3592/// - the reduction is performed efficiently in a hierarchical
3593/// manner as follows: within OpenMP threads in the same warp,
3594/// across warps in a threadblock, and finally across teams on
3595/// the NVPTX device.
3596///
3597/// Introduction to Decoupling
3598///
3599/// We would like to decouple the compiler and the runtime so that the
3600/// latter is ignorant of the reduction variables (number, data types)
3601/// and the reduction operators. This allows a simpler interface
3602/// and implementation while still attaining good performance.
3603///
3604/// Pseudocode for the aforementioned OpenMP program generated by the
3605/// compiler is as follows:
3606///
3607/// 1. Create private copies of reduction variables on each OpenMP
3608/// thread: 'foo_private', 'bar_private'
3609/// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
3610/// to it and writes the result in 'foo_private' and 'bar_private'
3611/// respectively.
3612/// 3. Call the OpenMP runtime on the GPU to reduce within a team
3613/// and store the result on the team master:
3614///
Alexey Bataev8e009032019-01-04 17:25:09 +00003615/// __kmpc_nvptx_parallel_reduce_nowait_v2(...,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003616/// reduceData, shuffleReduceFn, interWarpCpyFn)
3617///
3618/// where:
3619/// struct ReduceData {
3620/// double *foo;
3621/// double *bar;
3622/// } reduceData
3623/// reduceData.foo = &foo_private
3624/// reduceData.bar = &bar_private
3625///
3626/// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
3627/// auxiliary functions generated by the compiler that operate on
3628/// variables of type 'ReduceData'. They aid the runtime perform
3629/// algorithmic steps in a data agnostic manner.
3630///
3631/// 'shuffleReduceFn' is a pointer to a function that reduces data
3632/// of type 'ReduceData' across two OpenMP threads (lanes) in the
3633/// same warp. It takes the following arguments as input:
3634///
3635/// a. variable of type 'ReduceData' on the calling lane,
3636/// b. its lane_id,
3637/// c. an offset relative to the current lane_id to generate a
3638/// remote_lane_id. The remote lane contains the second
3639/// variable of type 'ReduceData' that is to be reduced.
3640/// d. an algorithm version parameter determining which reduction
3641/// algorithm to use.
3642///
3643/// 'shuffleReduceFn' retrieves data from the remote lane using
3644/// efficient GPU shuffle intrinsics and reduces, using the
3645/// algorithm specified by the 4th parameter, the two operands
3646/// element-wise. The result is written to the first operand.
3647///
3648/// Different reduction algorithms are implemented in different
3649/// runtime functions, all calling 'shuffleReduceFn' to perform
3650/// the essential reduction step. Therefore, based on the 4th
3651/// parameter, this function behaves slightly differently to
3652/// cooperate with the runtime to ensure correctness under
3653/// different circumstances.
3654///
3655/// 'InterWarpCpyFn' is a pointer to a function that transfers
3656/// reduced variables across warps. It tunnels, through CUDA
3657/// shared memory, the thread-private data of type 'ReduceData'
3658/// from lane 0 of each warp to a lane in the first warp.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003659/// 4. Call the OpenMP runtime on the GPU to reduce across teams.
3660/// The last team writes the global reduced value to memory.
3661///
3662/// ret = __kmpc_nvptx_teams_reduce_nowait(...,
3663/// reduceData, shuffleReduceFn, interWarpCpyFn,
3664/// scratchpadCopyFn, loadAndReduceFn)
3665///
3666/// 'scratchpadCopyFn' is a helper that stores reduced
3667/// data from the team master to a scratchpad array in
3668/// global memory.
3669///
3670/// 'loadAndReduceFn' is a helper that loads data from
3671/// the scratchpad array and reduces it with the input
3672/// operand.
3673///
3674/// These compiler generated functions hide address
3675/// calculation and alignment information from the runtime.
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003676/// 5. if ret == 1:
3677/// The team master of the last team stores the reduced
3678/// result to the globals in memory.
3679/// foo += reduceData.foo; bar *= reduceData.bar
3680///
3681///
3682/// Warp Reduction Algorithms
3683///
3684/// On the warp level, we have three algorithms implemented in the
3685/// OpenMP runtime depending on the number of active lanes:
3686///
3687/// Full Warp Reduction
3688///
3689/// The reduce algorithm within a warp where all lanes are active
3690/// is implemented in the runtime as follows:
3691///
3692/// full_warp_reduce(void *reduce_data,
3693/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3694/// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
3695/// ShuffleReduceFn(reduce_data, 0, offset, 0);
3696/// }
3697///
3698/// The algorithm completes in log(2, WARPSIZE) steps.
3699///
3700/// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
3701/// not used therefore we save instructions by not retrieving lane_id
3702/// from the corresponding special registers. The 4th parameter, which
3703/// represents the version of the algorithm being used, is set to 0 to
3704/// signify full warp reduction.
3705///
3706/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3707///
3708/// #reduce_elem refers to an element in the local lane's data structure
3709/// #remote_elem is retrieved from a remote lane
3710/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3711/// reduce_elem = reduce_elem REDUCE_OP remote_elem;
3712///
3713/// Contiguous Partial Warp Reduction
3714///
3715/// This reduce algorithm is used within a warp where only the first
3716/// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
3717/// number of OpenMP threads in a parallel region is not a multiple of
3718/// WARPSIZE. The algorithm is implemented in the runtime as follows:
3719///
3720/// void
3721/// contiguous_partial_reduce(void *reduce_data,
3722/// kmp_ShuffleReductFctPtr ShuffleReduceFn,
3723/// int size, int lane_id) {
3724/// int curr_size;
3725/// int offset;
3726/// curr_size = size;
3727/// mask = curr_size/2;
3728/// while (offset>0) {
3729/// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
3730/// curr_size = (curr_size+1)/2;
3731/// offset = curr_size/2;
3732/// }
3733/// }
3734///
3735/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3736///
3737/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3738/// if (lane_id < offset)
3739/// reduce_elem = reduce_elem REDUCE_OP remote_elem
3740/// else
3741/// reduce_elem = remote_elem
3742///
3743/// This algorithm assumes that the data to be reduced are located in a
3744/// contiguous subset of lanes starting from the first. When there is
3745/// an odd number of active lanes, the data in the last lane is not
3746/// aggregated with any other lane's dat but is instead copied over.
3747///
3748/// Dispersed Partial Warp Reduction
3749///
3750/// This algorithm is used within a warp when any discontiguous subset of
3751/// lanes are active. It is used to implement the reduction operation
3752/// across lanes in an OpenMP simd region or in a nested parallel region.
3753///
3754/// void
3755/// dispersed_partial_reduce(void *reduce_data,
3756/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3757/// int size, remote_id;
3758/// int logical_lane_id = number_of_active_lanes_before_me() * 2;
3759/// do {
3760/// remote_id = next_active_lane_id_right_after_me();
3761/// # the above function returns 0 of no active lane
3762/// # is present right after the current lane.
3763/// size = number_of_active_lanes_in_this_warp();
3764/// logical_lane_id /= 2;
3765/// ShuffleReduceFn(reduce_data, logical_lane_id,
3766/// remote_id-1-threadIdx.x, 2);
3767/// } while (logical_lane_id % 2 == 0 && size > 1);
3768/// }
3769///
3770/// There is no assumption made about the initial state of the reduction.
3771/// Any number of lanes (>=1) could be active at any position. The reduction
3772/// result is returned in the first active lane.
3773///
3774/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3775///
3776/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3777/// if (lane_id % 2 == 0 && offset > 0)
3778/// reduce_elem = reduce_elem REDUCE_OP remote_elem
3779/// else
3780/// reduce_elem = remote_elem
3781///
3782///
3783/// Intra-Team Reduction
3784///
3785/// This function, as implemented in the runtime call
Alexey Bataev8e009032019-01-04 17:25:09 +00003786/// '__kmpc_nvptx_parallel_reduce_nowait_v2', aggregates data across OpenMP
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003787/// threads in a team. It first reduces within a warp using the
3788/// aforementioned algorithms. We then proceed to gather all such
3789/// reduced values at the first warp.
3790///
3791/// The runtime makes use of the function 'InterWarpCpyFn', which copies
3792/// data from each of the "warp master" (zeroth lane of each warp, where
3793/// warp-reduced data is held) to the zeroth warp. This step reduces (in
3794/// a mathematical sense) the problem of reduction across warp masters in
3795/// a block to the problem of warp reduction.
3796///
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003797///
3798/// Inter-Team Reduction
3799///
3800/// Once a team has reduced its data to a single value, it is stored in
3801/// a global scratchpad array. Since each team has a distinct slot, this
3802/// can be done without locking.
3803///
3804/// The last team to write to the scratchpad array proceeds to reduce the
3805/// scratchpad array. One or more workers in the last team use the helper
3806/// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
3807/// the k'th worker reduces every k'th element.
3808///
Alexey Bataev8e009032019-01-04 17:25:09 +00003809/// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait_v2' to
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003810/// reduce across workers and compute a globally reduced value.
3811///
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003812void CGOpenMPRuntimeNVPTX::emitReduction(
3813 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
3814 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
3815 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
3816 if (!CGF.HaveInsertPoint())
3817 return;
3818
3819 bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00003820#ifndef NDEBUG
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003821 bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00003822#endif
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003823
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00003824 if (Options.SimpleReduction) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003825 assert(!TeamsReduction && !ParallelReduction &&
3826 "Invalid reduction selection in emitReduction.");
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00003827 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
3828 ReductionOps, Options);
3829 return;
3830 }
3831
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003832 assert((TeamsReduction || ParallelReduction) &&
3833 "Invalid reduction selection in emitReduction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003834
Alexey Bataeva1166022018-11-27 21:24:54 +00003835 // Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003836 // RedList, shuffle_reduce_func, interwarp_copy_func);
Alexey Bataeva1166022018-11-27 21:24:54 +00003837 // or
3838 // Build res = __kmpc_reduce_teams_nowait_simple(<loc>, <gtid>, <lck>);
Alexey Bataev8e009032019-01-04 17:25:09 +00003839 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003840 llvm::Value *ThreadId = getThreadID(CGF, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003841
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003842 llvm::Value *Res;
3843 if (ParallelReduction) {
Alexey Bataeva1166022018-11-27 21:24:54 +00003844 ASTContext &C = CGM.getContext();
3845 // 1. Build a list of reduction variables.
3846 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3847 auto Size = RHSExprs.size();
3848 for (const Expr *E : Privates) {
3849 if (E->getType()->isVariablyModifiedType())
3850 // Reserve place for array size.
3851 ++Size;
3852 }
3853 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
3854 QualType ReductionArrayTy =
3855 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3856 /*IndexTypeQuals=*/0);
3857 Address ReductionList =
3858 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3859 auto IPriv = Privates.begin();
3860 unsigned Idx = 0;
3861 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
3862 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3863 CGF.getPointerSize());
3864 CGF.Builder.CreateStore(
3865 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3866 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
3867 Elem);
3868 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3869 // Store array size.
3870 ++Idx;
3871 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3872 CGF.getPointerSize());
3873 llvm::Value *Size = CGF.Builder.CreateIntCast(
3874 CGF.getVLASize(
3875 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3876 .NumElts,
3877 CGF.SizeTy, /*isSigned=*/false);
3878 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3879 Elem);
3880 }
3881 }
3882
3883 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
3884 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3885 ReductionList.getPointer(), CGF.VoidPtrTy);
3886 llvm::Value *ReductionFn = emitReductionFunction(
3887 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
3888 Privates, LHSExprs, RHSExprs, ReductionOps);
3889 llvm::Value *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
3890 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
3891 llvm::Value *InterWarpCopyFn =
3892 emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
3893
Alexey Bataev8e009032019-01-04 17:25:09 +00003894 llvm::Value *Args[] = {RTLoc,
3895 ThreadId,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003896 CGF.Builder.getInt32(RHSExprs.size()),
3897 ReductionArrayTySize,
3898 RL,
3899 ShuffleAndReduceFn,
3900 InterWarpCopyFn};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003901
Alexey Bataev8e009032019-01-04 17:25:09 +00003902 Res = CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
3903 OMPRTL_NVPTX__kmpc_parallel_reduce_nowait_v2),
3904 Args);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003905 } else {
3906 assert(TeamsReduction && "expected teams reduction.");
Alexey Bataeva1166022018-11-27 21:24:54 +00003907 std::string Name = getName({"reduction"});
3908 llvm::Value *Lock = getCriticalRegionLock(Name);
3909 llvm::Value *Args[] = {RTLoc, ThreadId, Lock};
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003910 Res = CGF.EmitRuntimeCall(
Alexey Bataeva1166022018-11-27 21:24:54 +00003911 createNVPTXRuntimeFunction(
3912 OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_simple),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003913 Args);
3914 }
3915
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003916 // 5. Build if (res == 1)
3917 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.reduction.done");
3918 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.then");
3919 llvm::Value *Cond = CGF.Builder.CreateICmpEQ(
3920 Res, llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1));
3921 CGF.Builder.CreateCondBr(Cond, ThenBB, ExitBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003922
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003923 // 6. Build then branch: where we have reduced values in the master
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003924 // thread in each team.
3925 // __kmpc_end_reduce{_nowait}(<gtid>);
3926 // break;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003927 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003928
3929 // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003930 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003931 this](CodeGenFunction &CGF, PrePostActionTy &Action) {
3932 auto IPriv = Privates.begin();
3933 auto ILHS = LHSExprs.begin();
3934 auto IRHS = RHSExprs.begin();
Alexey Bataev9ff80832018-04-16 20:16:21 +00003935 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003936 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
3937 cast<DeclRefExpr>(*IRHS));
3938 ++IPriv;
3939 ++ILHS;
3940 ++IRHS;
3941 }
3942 };
Alexey Bataeva1166022018-11-27 21:24:54 +00003943 if (ParallelReduction) {
3944 llvm::Value *EndArgs[] = {ThreadId};
3945 RegionCodeGenTy RCG(CodeGen);
3946 NVPTXActionTy Action(
3947 nullptr, llvm::None,
3948 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_reduce_nowait),
3949 EndArgs);
3950 RCG.setAction(Action);
3951 RCG(CGF);
3952 } else {
3953 assert(TeamsReduction && "expected teams reduction.");
3954 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
3955 std::string Name = getName({"reduction"});
3956 llvm::Value *Lock = getCriticalRegionLock(Name);
3957 llvm::Value *EndArgs[] = {RTLoc, ThreadId, Lock};
3958 RegionCodeGenTy RCG(CodeGen);
3959 NVPTXActionTy Action(
3960 nullptr, llvm::None,
3961 createNVPTXRuntimeFunction(
3962 OMPRTL_NVPTX__kmpc_nvptx_teams_end_reduce_nowait_simple),
3963 EndArgs);
3964 RCG.setAction(Action);
3965 RCG(CGF);
3966 }
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003967 // There is no need to emit line number for unconditional branch.
3968 (void)ApplyDebugLocation::CreateEmpty(CGF);
3969 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003970}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003971
3972const VarDecl *
3973CGOpenMPRuntimeNVPTX::translateParameter(const FieldDecl *FD,
3974 const VarDecl *NativeParam) const {
3975 if (!NativeParam->getType()->isReferenceType())
3976 return NativeParam;
3977 QualType ArgType = NativeParam->getType();
3978 QualifierCollector QC;
3979 const Type *NonQualTy = QC.strip(ArgType);
3980 QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
3981 if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
3982 if (Attr->getCaptureKind() == OMPC_map) {
3983 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
3984 LangAS::opencl_global);
3985 }
3986 }
3987 ArgType = CGM.getContext().getPointerType(PointeeTy);
3988 QC.addRestrict();
3989 enum { NVPTX_local_addr = 5 };
Alexander Richardson6d989432017-10-15 18:48:14 +00003990 QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003991 ArgType = QC.apply(CGM.getContext(), ArgType);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003992 if (isa<ImplicitParamDecl>(NativeParam))
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003993 return ImplicitParamDecl::Create(
3994 CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
3995 NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003996 return ParmVarDecl::Create(
3997 CGM.getContext(),
3998 const_cast<DeclContext *>(NativeParam->getDeclContext()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003999 NativeParam->getBeginLoc(), NativeParam->getLocation(),
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004000 NativeParam->getIdentifier(), ArgType,
4001 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004002}
4003
4004Address
4005CGOpenMPRuntimeNVPTX::getParameterAddress(CodeGenFunction &CGF,
4006 const VarDecl *NativeParam,
4007 const VarDecl *TargetParam) const {
4008 assert(NativeParam != TargetParam &&
4009 NativeParam->getType()->isReferenceType() &&
4010 "Native arg must not be the same as target arg.");
4011 Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
4012 QualType NativeParamType = NativeParam->getType();
4013 QualifierCollector QC;
4014 const Type *NonQualTy = QC.strip(NativeParamType);
4015 QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4016 unsigned NativePointeeAddrSpace =
Alexander Richardson6d989432017-10-15 18:48:14 +00004017 CGF.getContext().getTargetAddressSpace(NativePointeeTy);
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004018 QualType TargetTy = TargetParam->getType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004019 llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004020 LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004021 // First cast to generic.
4022 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4023 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4024 /*AddrSpace=*/0));
4025 // Cast from generic to native address space.
4026 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4027 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4028 NativePointeeAddrSpace));
4029 Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
4030 CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004031 NativeParamType);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004032 return NativeParamAddr;
4033}
4034
4035void CGOpenMPRuntimeNVPTX::emitOutlinedFunctionCall(
Alexey Bataev3c595a62017-08-14 15:01:03 +00004036 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004037 ArrayRef<llvm::Value *> Args) const {
4038 SmallVector<llvm::Value *, 4> TargetArgs;
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004039 TargetArgs.reserve(Args.size());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004040 auto *FnType =
4041 cast<llvm::FunctionType>(OutlinedFn->getType()->getPointerElementType());
4042 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004043 if (FnType->isVarArg() && FnType->getNumParams() <= I) {
4044 TargetArgs.append(std::next(Args.begin(), I), Args.end());
4045 break;
4046 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004047 llvm::Type *TargetType = FnType->getParamType(I);
4048 llvm::Value *NativeArg = Args[I];
4049 if (!TargetType->isPointerTy()) {
4050 TargetArgs.emplace_back(NativeArg);
4051 continue;
4052 }
4053 llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataevc99042b2018-03-15 18:10:54 +00004054 NativeArg,
4055 NativeArg->getType()->getPointerElementType()->getPointerTo());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004056 TargetArgs.emplace_back(
4057 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
4058 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00004059 CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004060}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004061
4062/// Emit function which wraps the outline parallel region
4063/// and controls the arguments which are passed to this function.
4064/// The wrapper ensures that the outlined function is called
4065/// with the correct arguments when data is shared.
4066llvm::Function *CGOpenMPRuntimeNVPTX::createParallelDataSharingWrapper(
4067 llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
4068 ASTContext &Ctx = CGM.getContext();
4069 const auto &CS = *D.getCapturedStmt(OMPD_parallel);
4070
4071 // Create a function that takes as argument the source thread.
4072 FunctionArgList WrapperArgs;
4073 QualType Int16QTy =
4074 Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
4075 QualType Int32QTy =
4076 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004077 ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004078 /*Id=*/nullptr, Int16QTy,
4079 ImplicitParamDecl::Other);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004080 ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004081 /*Id=*/nullptr, Int32QTy,
4082 ImplicitParamDecl::Other);
4083 WrapperArgs.emplace_back(&ParallelLevelArg);
4084 WrapperArgs.emplace_back(&WrapperArg);
4085
Alexey Bataev9ff80832018-04-16 20:16:21 +00004086 const CGFunctionInfo &CGFI =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004087 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
4088
4089 auto *Fn = llvm::Function::Create(
4090 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataev9ff80832018-04-16 20:16:21 +00004091 Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004092 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004093 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004094 Fn->setDoesNotRecurse();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004095
4096 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
4097 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004098 D.getBeginLoc(), D.getBeginLoc());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004099
4100 const auto *RD = CS.getCapturedRecordDecl();
4101 auto CurField = RD->field_begin();
4102
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004103 Address ZeroAddr = CGF.CreateMemTemp(
4104 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
4105 /*Name*/ ".zero.addr");
4106 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004107 // Get the array of arguments.
4108 SmallVector<llvm::Value *, 8> Args;
4109
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004110 Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).getPointer());
4111 Args.emplace_back(ZeroAddr.getPointer());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004112
4113 CGBuilderTy &Bld = CGF.Builder;
4114 auto CI = CS.capture_begin();
4115
4116 // Use global memory for data sharing.
4117 // Handle passing of global args to workers.
4118 Address GlobalArgs =
4119 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
4120 llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
4121 llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
4122 CGF.EmitRuntimeCall(
4123 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_get_shared_variables),
4124 DataSharingArgs);
4125
4126 // Retrieve the shared variables from the list of references returned
4127 // by the runtime. Pass the variables to the outlined function.
Alexey Bataev17314212018-03-20 15:41:05 +00004128 Address SharedArgListAddress = Address::invalid();
4129 if (CS.capture_size() > 0 ||
4130 isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4131 SharedArgListAddress = CGF.EmitLoadOfPointer(
4132 GlobalArgs, CGF.getContext()
4133 .getPointerType(CGF.getContext().getPointerType(
4134 CGF.getContext().VoidPtrTy))
4135 .castAs<PointerType>());
4136 }
4137 unsigned Idx = 0;
4138 if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4139 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
4140 CGF.getPointerSize());
4141 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4142 Src, CGF.SizeTy->getPointerTo());
4143 llvm::Value *LB = CGF.EmitLoadOfScalar(
4144 TypedAddress,
4145 /*Volatile=*/false,
4146 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4147 cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
4148 Args.emplace_back(LB);
4149 ++Idx;
4150 Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
4151 CGF.getPointerSize());
4152 TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4153 Src, CGF.SizeTy->getPointerTo());
4154 llvm::Value *UB = CGF.EmitLoadOfScalar(
4155 TypedAddress,
4156 /*Volatile=*/false,
4157 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4158 cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
4159 Args.emplace_back(UB);
4160 ++Idx;
4161 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004162 if (CS.capture_size() > 0) {
4163 ASTContext &CGFContext = CGF.getContext();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004164 for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
4165 QualType ElemTy = CurField->getType();
Alexey Bataev17314212018-03-20 15:41:05 +00004166 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx,
4167 CGF.getPointerSize());
4168 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004169 Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)));
4170 llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
4171 /*Volatile=*/false,
4172 CGFContext.getPointerType(ElemTy),
4173 CI->getLocation());
Alexey Bataev2091ca62018-04-23 17:33:41 +00004174 if (CI->capturesVariableByCopy() &&
4175 !CI->getCapturedVar()->getType()->isAnyPointerType()) {
Alexey Bataev17314212018-03-20 15:41:05 +00004176 Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
4177 CI->getLocation());
4178 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004179 Args.emplace_back(Arg);
4180 }
4181 }
4182
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004183 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedParallelFn, Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004184 CGF.FinishFunction();
4185 return Fn;
4186}
4187
4188void CGOpenMPRuntimeNVPTX::emitFunctionProlog(CodeGenFunction &CGF,
4189 const Decl *D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004190 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4191 return;
4192
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004193 assert(D && "Expected function or captured|block decl.");
4194 assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
4195 "Function is registered already.");
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004196 assert((!TeamAndReductions.first || TeamAndReductions.first == D) &&
4197 "Team is set but not processed.");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004198 const Stmt *Body = nullptr;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004199 bool NeedToDelayGlobalization = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004200 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4201 Body = FD->getBody();
4202 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
4203 Body = BD->getBody();
4204 } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
4205 Body = CD->getBody();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004206 NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
Alexey Bataev2adecff2018-09-21 14:22:53 +00004207 if (NeedToDelayGlobalization &&
4208 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
4209 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004210 }
4211 if (!Body)
4212 return;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004213 CheckVarsEscapingDeclContext VarChecker(CGF, TeamAndReductions.second);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004214 VarChecker.Visit(Body);
Alexey Bataevff23bb62018-10-11 18:30:31 +00004215 const RecordDecl *GlobalizedVarsRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004216 VarChecker.getGlobalizedRecord(IsInTTDRegion);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004217 TeamAndReductions.first = nullptr;
4218 TeamAndReductions.second.clear();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004219 ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
4220 VarChecker.getEscapedVariableLengthDecls();
4221 if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004222 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004223 auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
4224 I->getSecond().MappedParams =
4225 llvm::make_unique<CodeGenFunction::OMPMapVars>();
4226 I->getSecond().GlobalRecord = GlobalizedVarsRecord;
4227 I->getSecond().EscapedParameters.insert(
4228 VarChecker.getEscapedParameters().begin(),
4229 VarChecker.getEscapedParameters().end());
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004230 I->getSecond().EscapedVariableLengthDecls.append(
4231 EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004232 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004233 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004234 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004235 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004236 Data.insert(std::make_pair(VD, MappedVarData(FD, IsInTTDRegion)));
Alexey Bataevc99042b2018-03-15 18:10:54 +00004237 }
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004238 if (!IsInTTDRegion && !NeedToDelayGlobalization && !IsInParallelRegion) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004239 CheckVarsEscapingDeclContext VarChecker(CGF, llvm::None);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004240 VarChecker.Visit(Body);
4241 I->getSecond().SecondaryGlobalRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004242 VarChecker.getGlobalizedRecord(/*IsInTTDRegion=*/true);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004243 I->getSecond().SecondaryLocalVarData.emplace();
4244 DeclToAddrMapTy &Data = I->getSecond().SecondaryLocalVarData.getValue();
4245 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
4246 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
4247 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004248 Data.insert(
4249 std::make_pair(VD, MappedVarData(FD, /*IsInTTDRegion=*/true)));
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004250 }
4251 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00004252 if (!NeedToDelayGlobalization) {
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004253 emitGenericVarsProlog(CGF, D->getBeginLoc(), /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004254 struct GlobalizationScope final : EHScopeStack::Cleanup {
4255 GlobalizationScope() = default;
4256
4257 void Emit(CodeGenFunction &CGF, Flags flags) override {
4258 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004259 .emitGenericVarsEpilog(CGF, /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004260 }
4261 };
4262 CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004263 }
4264}
4265
4266Address CGOpenMPRuntimeNVPTX::getAddressOfLocalVariable(CodeGenFunction &CGF,
4267 const VarDecl *VD) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004268 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4269 return Address::invalid();
4270
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004271 VD = VD->getCanonicalDecl();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004272 auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
4273 if (I == FunctionGlobalizedDecls.end())
4274 return Address::invalid();
Alexey Bataevc99042b2018-03-15 18:10:54 +00004275 auto VDI = I->getSecond().LocalVarData.find(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004276 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004277 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004278 if (VD->hasAttrs()) {
4279 for (specific_attr_iterator<OMPReferencedVarAttr> IT(VD->attr_begin()),
4280 E(VD->attr_end());
4281 IT != E; ++IT) {
4282 auto VDI = I->getSecond().LocalVarData.find(
4283 cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
4284 ->getCanonicalDecl());
4285 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004286 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004287 }
4288 }
4289 return Address::invalid();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004290}
4291
4292void CGOpenMPRuntimeNVPTX::functionFinished(CodeGenFunction &CGF) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004293 FunctionGlobalizedDecls.erase(CGF.CurFn);
4294 CGOpenMPRuntime::functionFinished(CGF);
4295}
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004296
4297void CGOpenMPRuntimeNVPTX::getDefaultDistScheduleAndChunk(
4298 CodeGenFunction &CGF, const OMPLoopDirective &S,
4299 OpenMPDistScheduleClauseKind &ScheduleKind,
4300 llvm::Value *&Chunk) const {
4301 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
4302 ScheduleKind = OMPC_DIST_SCHEDULE_static;
4303 Chunk = CGF.EmitScalarConversion(getNVPTXNumThreads(CGF),
4304 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4305 S.getIterationVariable()->getType(), S.getBeginLoc());
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004306 return;
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004307 }
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004308 CGOpenMPRuntime::getDefaultDistScheduleAndChunk(
4309 CGF, S, ScheduleKind, Chunk);
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004310}
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004311
4312void CGOpenMPRuntimeNVPTX::getDefaultScheduleAndChunk(
4313 CodeGenFunction &CGF, const OMPLoopDirective &S,
4314 OpenMPScheduleClauseKind &ScheduleKind,
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004315 const Expr *&ChunkExpr) const {
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004316 ScheduleKind = OMPC_SCHEDULE_static;
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004317 // Chunk size is 1 in this case.
4318 llvm::APInt ChunkSize(32, 1);
4319 ChunkExpr = IntegerLiteral::Create(CGF.getContext(), ChunkSize,
4320 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4321 SourceLocation());
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004322}
Alexey Bataev60705422018-10-30 15:50:12 +00004323
4324void CGOpenMPRuntimeNVPTX::adjustTargetSpecificDataForLambdas(
4325 CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
4326 assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
4327 " Expected target-based directive.");
4328 const CapturedStmt *CS = D.getCapturedStmt(OMPD_target);
4329 for (const CapturedStmt::Capture &C : CS->captures()) {
4330 // Capture variables captured by reference in lambdas for target-based
4331 // directives.
4332 if (!C.capturesVariable())
4333 continue;
4334 const VarDecl *VD = C.getCapturedVar();
4335 const auto *RD = VD->getType()
4336 .getCanonicalType()
4337 .getNonReferenceType()
4338 ->getAsCXXRecordDecl();
4339 if (!RD || !RD->isLambda())
4340 continue;
4341 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4342 LValue VDLVal;
4343 if (VD->getType().getCanonicalType()->isReferenceType())
4344 VDLVal = CGF.EmitLoadOfReferenceLValue(VDAddr, VD->getType());
4345 else
4346 VDLVal = CGF.MakeAddrLValue(
4347 VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
4348 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4349 FieldDecl *ThisCapture = nullptr;
4350 RD->getCaptureFields(Captures, ThisCapture);
4351 if (ThisCapture && CGF.CapturedStmtInfo->isCXXThisExprCaptured()) {
4352 LValue ThisLVal =
4353 CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
4354 llvm::Value *CXXThis = CGF.LoadCXXThis();
4355 CGF.EmitStoreOfScalar(CXXThis, ThisLVal);
4356 }
4357 for (const LambdaCapture &LC : RD->captures()) {
4358 if (LC.getCaptureKind() != LCK_ByRef)
4359 continue;
4360 const VarDecl *VD = LC.getCapturedVar();
4361 if (!CS->capturesVariable(VD))
4362 continue;
4363 auto It = Captures.find(VD);
4364 assert(It != Captures.end() && "Found lambda capture without field.");
4365 LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
4366 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4367 if (VD->getType().getCanonicalType()->isReferenceType())
4368 VDAddr = CGF.EmitLoadOfReferenceLValue(VDAddr,
4369 VD->getType().getCanonicalType())
4370 .getAddress();
4371 CGF.EmitStoreOfScalar(VDAddr.getPointer(), VarLVal);
4372 }
4373 }
4374}
4375
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004376// Get current CudaArch and ignore any unknown values
4377static CudaArch getCudaArch(CodeGenModule &CGM) {
4378 if (!CGM.getTarget().hasFeature("ptx"))
4379 return CudaArch::UNKNOWN;
4380 llvm::StringMap<bool> Features;
4381 CGM.getTarget().initFeatureMap(Features, CGM.getDiags(),
4382 CGM.getTarget().getTargetOpts().CPU,
4383 CGM.getTarget().getTargetOpts().Features);
4384 for (const auto &Feature : Features) {
4385 if (Feature.getValue()) {
4386 CudaArch Arch = StringToCudaArch(Feature.getKey());
4387 if (Arch != CudaArch::UNKNOWN)
4388 return Arch;
4389 }
4390 }
4391 return CudaArch::UNKNOWN;
4392}
4393
4394/// Check to see if target architecture supports unified addressing which is
4395/// a restriction for OpenMP requires clause "unified_shared_memory".
4396void CGOpenMPRuntimeNVPTX::checkArchForUnifiedAddressing(
4397 CodeGenModule &CGM, const OMPRequiresDecl *D) const {
4398 for (const OMPClause *Clause : D->clauselists()) {
4399 if (Clause->getClauseKind() == OMPC_unified_shared_memory) {
4400 switch (getCudaArch(CGM)) {
4401 case CudaArch::SM_20:
4402 case CudaArch::SM_21:
4403 case CudaArch::SM_30:
4404 case CudaArch::SM_32:
4405 case CudaArch::SM_35:
4406 case CudaArch::SM_37:
4407 case CudaArch::SM_50:
4408 case CudaArch::SM_52:
4409 case CudaArch::SM_53:
4410 case CudaArch::SM_60:
4411 case CudaArch::SM_61:
4412 case CudaArch::SM_62:
4413 CGM.Error(Clause->getBeginLoc(),
4414 "Target architecture does not support unified addressing");
4415 return;
4416 case CudaArch::SM_70:
4417 case CudaArch::SM_72:
4418 case CudaArch::SM_75:
4419 case CudaArch::GFX600:
4420 case CudaArch::GFX601:
4421 case CudaArch::GFX700:
4422 case CudaArch::GFX701:
4423 case CudaArch::GFX702:
4424 case CudaArch::GFX703:
4425 case CudaArch::GFX704:
4426 case CudaArch::GFX801:
4427 case CudaArch::GFX802:
4428 case CudaArch::GFX803:
4429 case CudaArch::GFX810:
4430 case CudaArch::GFX900:
4431 case CudaArch::GFX902:
4432 case CudaArch::GFX904:
4433 case CudaArch::GFX906:
4434 case CudaArch::GFX909:
4435 case CudaArch::UNKNOWN:
4436 break;
4437 case CudaArch::LAST:
4438 llvm_unreachable("Unexpected Cuda arch.");
4439 }
4440 }
4441 }
4442}
4443
Alexey Bataeve4090182018-11-02 14:54:07 +00004444/// Get number of SMs and number of blocks per SM.
4445static std::pair<unsigned, unsigned> getSMsBlocksPerSM(CodeGenModule &CGM) {
4446 std::pair<unsigned, unsigned> Data;
4447 if (CGM.getLangOpts().OpenMPCUDANumSMs)
4448 Data.first = CGM.getLangOpts().OpenMPCUDANumSMs;
4449 if (CGM.getLangOpts().OpenMPCUDABlocksPerSM)
4450 Data.second = CGM.getLangOpts().OpenMPCUDABlocksPerSM;
4451 if (Data.first && Data.second)
4452 return Data;
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004453 switch (getCudaArch(CGM)) {
4454 case CudaArch::SM_20:
4455 case CudaArch::SM_21:
4456 case CudaArch::SM_30:
4457 case CudaArch::SM_32:
4458 case CudaArch::SM_35:
4459 case CudaArch::SM_37:
4460 case CudaArch::SM_50:
4461 case CudaArch::SM_52:
4462 case CudaArch::SM_53:
4463 return {16, 16};
4464 case CudaArch::SM_60:
4465 case CudaArch::SM_61:
4466 case CudaArch::SM_62:
4467 return {56, 32};
4468 case CudaArch::SM_70:
4469 case CudaArch::SM_72:
4470 case CudaArch::SM_75:
4471 return {84, 32};
4472 case CudaArch::GFX600:
4473 case CudaArch::GFX601:
4474 case CudaArch::GFX700:
4475 case CudaArch::GFX701:
4476 case CudaArch::GFX702:
4477 case CudaArch::GFX703:
4478 case CudaArch::GFX704:
4479 case CudaArch::GFX801:
4480 case CudaArch::GFX802:
4481 case CudaArch::GFX803:
4482 case CudaArch::GFX810:
4483 case CudaArch::GFX900:
4484 case CudaArch::GFX902:
4485 case CudaArch::GFX904:
4486 case CudaArch::GFX906:
4487 case CudaArch::GFX909:
4488 case CudaArch::UNKNOWN:
4489 break;
4490 case CudaArch::LAST:
4491 llvm_unreachable("Unexpected Cuda arch.");
Alexey Bataeve4090182018-11-02 14:54:07 +00004492 }
4493 llvm_unreachable("Unexpected NVPTX target without ptx feature.");
4494}
4495
4496void CGOpenMPRuntimeNVPTX::clear() {
4497 if (!GlobalizedRecords.empty()) {
4498 ASTContext &C = CGM.getContext();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004499 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> GlobalRecs;
4500 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> SharedRecs;
Alexey Bataeve4090182018-11-02 14:54:07 +00004501 RecordDecl *StaticRD = C.buildImplicitRecord(
4502 "_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
4503 StaticRD->startDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004504 RecordDecl *SharedStaticRD = C.buildImplicitRecord(
4505 "_shared_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
4506 SharedStaticRD->startDefinition();
Alexey Bataeve4090182018-11-02 14:54:07 +00004507 for (const GlobalPtrSizeRecsTy &Records : GlobalizedRecords) {
4508 if (Records.Records.empty())
4509 continue;
4510 unsigned Size = 0;
4511 unsigned RecAlignment = 0;
4512 for (const RecordDecl *RD : Records.Records) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004513 QualType RDTy = C.getRecordType(RD);
4514 unsigned Alignment = C.getTypeAlignInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00004515 RecAlignment = std::max(RecAlignment, Alignment);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004516 unsigned RecSize = C.getTypeSizeInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00004517 Size =
4518 llvm::alignTo(llvm::alignTo(Size, Alignment) + RecSize, Alignment);
4519 }
4520 Size = llvm::alignTo(Size, RecAlignment);
4521 llvm::APInt ArySize(/*numBits=*/64, Size);
4522 QualType SubTy = C.getConstantArrayType(
4523 C.CharTy, ArySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004524 const bool UseSharedMemory = Size <= SharedMemorySize;
4525 auto *Field =
4526 FieldDecl::Create(C, UseSharedMemory ? SharedStaticRD : StaticRD,
4527 SourceLocation(), SourceLocation(), nullptr, SubTy,
4528 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
4529 /*BW=*/nullptr, /*Mutable=*/false,
4530 /*InitStyle=*/ICIS_NoInit);
Alexey Bataeve4090182018-11-02 14:54:07 +00004531 Field->setAccess(AS_public);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004532 if (UseSharedMemory) {
4533 SharedStaticRD->addDecl(Field);
4534 SharedRecs.push_back(&Records);
4535 } else {
4536 StaticRD->addDecl(Field);
4537 GlobalRecs.push_back(&Records);
4538 }
Alexey Bataeve4090182018-11-02 14:54:07 +00004539 Records.RecSize->setInitializer(llvm::ConstantInt::get(CGM.SizeTy, Size));
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004540 Records.UseSharedMemory->setInitializer(
4541 llvm::ConstantInt::get(CGM.Int16Ty, UseSharedMemory ? 1 : 0));
4542 }
Alexey Bataev6a1b06b2018-12-18 21:01:42 +00004543 // Allocate SharedMemorySize buffer for the shared memory.
4544 // FIXME: nvlink does not handle weak linkage correctly (object with the
4545 // different size are reported as erroneous).
4546 // Restore this code as sson as nvlink is fixed.
4547 if (!SharedStaticRD->field_empty()) {
4548 llvm::APInt ArySize(/*numBits=*/64, SharedMemorySize);
4549 QualType SubTy = C.getConstantArrayType(
4550 C.CharTy, ArySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
4551 auto *Field = FieldDecl::Create(
4552 C, SharedStaticRD, SourceLocation(), SourceLocation(), nullptr, SubTy,
4553 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
4554 /*BW=*/nullptr, /*Mutable=*/false,
4555 /*InitStyle=*/ICIS_NoInit);
4556 Field->setAccess(AS_public);
4557 SharedStaticRD->addDecl(Field);
4558 }
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004559 SharedStaticRD->completeDefinition();
4560 if (!SharedStaticRD->field_empty()) {
4561 QualType StaticTy = C.getRecordType(SharedStaticRD);
4562 llvm::Type *LLVMStaticTy = CGM.getTypes().ConvertTypeForMem(StaticTy);
4563 auto *GV = new llvm::GlobalVariable(
4564 CGM.getModule(), LLVMStaticTy,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004565 /*isConstant=*/false, llvm::GlobalValue::CommonLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004566 llvm::Constant::getNullValue(LLVMStaticTy),
4567 "_openmp_shared_static_glob_rd_$_", /*InsertBefore=*/nullptr,
4568 llvm::GlobalValue::NotThreadLocal,
4569 C.getTargetAddressSpace(LangAS::cuda_shared));
4570 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
4571 GV, CGM.VoidPtrTy);
4572 for (const GlobalPtrSizeRecsTy *Rec : SharedRecs) {
4573 Rec->Buffer->replaceAllUsesWith(Replacement);
4574 Rec->Buffer->eraseFromParent();
4575 }
Alexey Bataeve4090182018-11-02 14:54:07 +00004576 }
4577 StaticRD->completeDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004578 if (!StaticRD->field_empty()) {
4579 QualType StaticTy = C.getRecordType(StaticRD);
4580 std::pair<unsigned, unsigned> SMsBlockPerSM = getSMsBlocksPerSM(CGM);
4581 llvm::APInt Size1(32, SMsBlockPerSM.second);
4582 QualType Arr1Ty =
4583 C.getConstantArrayType(StaticTy, Size1, ArrayType::Normal,
4584 /*IndexTypeQuals=*/0);
4585 llvm::APInt Size2(32, SMsBlockPerSM.first);
4586 QualType Arr2Ty = C.getConstantArrayType(Arr1Ty, Size2, ArrayType::Normal,
4587 /*IndexTypeQuals=*/0);
4588 llvm::Type *LLVMArr2Ty = CGM.getTypes().ConvertTypeForMem(Arr2Ty);
4589 auto *GV = new llvm::GlobalVariable(
4590 CGM.getModule(), LLVMArr2Ty,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004591 /*isConstant=*/false, llvm::GlobalValue::CommonLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004592 llvm::Constant::getNullValue(LLVMArr2Ty),
4593 "_openmp_static_glob_rd_$_");
4594 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
4595 GV, CGM.VoidPtrTy);
4596 for (const GlobalPtrSizeRecsTy *Rec : GlobalRecs) {
4597 Rec->Buffer->replaceAllUsesWith(Replacement);
4598 Rec->Buffer->eraseFromParent();
4599 }
4600 }
Alexey Bataeve4090182018-11-02 14:54:07 +00004601 }
4602 CGOpenMPRuntime::clear();
4603}