blob: ca9673096ecdbbdd821fe47b245b62621467d483 [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:
Michael Kruse251e1482019-02-01 20:25:04 +0000861 case OMPD_declare_mapper:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000862 case OMPD_taskloop:
863 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000864 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000865 case OMPD_unknown:
866 llvm_unreachable("Unexpected directive.");
867 }
868 }
869
870 return false;
871}
872
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000873static bool supportsSPMDExecutionMode(ASTContext &Ctx,
874 const OMPExecutableDirective &D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000875 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
876 switch (DirectiveKind) {
877 case OMPD_target:
878 case OMPD_target_teams:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000879 return hasNestedSPMDDirective(Ctx, D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000880 case OMPD_target_parallel:
881 case OMPD_target_parallel_for:
882 case OMPD_target_parallel_for_simd:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000883 case OMPD_target_teams_distribute_parallel_for:
884 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev2adecff2018-09-21 14:22:53 +0000885 return !hasParallelIfNumThreadsClause(Ctx, D);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000886 case OMPD_target_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000887 case OMPD_target_teams_distribute:
888 case OMPD_target_teams_distribute_simd:
889 return false;
890 case OMPD_parallel:
891 case OMPD_for:
892 case OMPD_parallel_for:
893 case OMPD_parallel_sections:
894 case OMPD_for_simd:
895 case OMPD_parallel_for_simd:
896 case OMPD_cancel:
897 case OMPD_cancellation_point:
898 case OMPD_ordered:
899 case OMPD_threadprivate:
900 case OMPD_task:
901 case OMPD_simd:
902 case OMPD_sections:
903 case OMPD_section:
904 case OMPD_single:
905 case OMPD_master:
906 case OMPD_critical:
907 case OMPD_taskyield:
908 case OMPD_barrier:
909 case OMPD_taskwait:
910 case OMPD_taskgroup:
911 case OMPD_atomic:
912 case OMPD_flush:
913 case OMPD_teams:
914 case OMPD_target_data:
915 case OMPD_target_exit_data:
916 case OMPD_target_enter_data:
917 case OMPD_distribute:
918 case OMPD_distribute_simd:
919 case OMPD_distribute_parallel_for:
920 case OMPD_distribute_parallel_for_simd:
921 case OMPD_teams_distribute:
922 case OMPD_teams_distribute_simd:
923 case OMPD_teams_distribute_parallel_for:
924 case OMPD_teams_distribute_parallel_for_simd:
925 case OMPD_target_update:
926 case OMPD_declare_simd:
927 case OMPD_declare_target:
928 case OMPD_end_declare_target:
929 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +0000930 case OMPD_declare_mapper:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000931 case OMPD_taskloop:
932 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000933 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000934 case OMPD_unknown:
935 break;
936 }
937 llvm_unreachable(
938 "Unknown programming model for OpenMP directive on NVPTX target.");
939}
940
941/// Check if the directive is loops based and has schedule clause at all or has
942/// static scheduling.
943static bool hasStaticScheduling(const OMPExecutableDirective &D) {
944 assert(isOpenMPWorksharingDirective(D.getDirectiveKind()) &&
945 isOpenMPLoopDirective(D.getDirectiveKind()) &&
946 "Expected loop-based directive.");
947 return !D.hasClausesOfKind<OMPOrderedClause>() &&
948 (!D.hasClausesOfKind<OMPScheduleClause>() ||
949 llvm::any_of(D.getClausesOfKind<OMPScheduleClause>(),
950 [](const OMPScheduleClause *C) {
951 return C->getScheduleKind() == OMPC_SCHEDULE_static;
952 }));
953}
954
955/// Check for inner (nested) lightweight runtime construct, if any
956static bool hasNestedLightweightDirective(ASTContext &Ctx,
957 const OMPExecutableDirective &D) {
958 assert(supportsSPMDExecutionMode(Ctx, D) && "Expected SPMD mode directive.");
959 const auto *CS = D.getInnermostCapturedStmt();
960 const auto *Body =
961 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000962 const Stmt *ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000963
964 if (const auto *NestedDir = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
965 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
966 switch (D.getDirectiveKind()) {
967 case OMPD_target:
968 if (isOpenMPParallelDirective(DKind) &&
969 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
970 hasStaticScheduling(*NestedDir))
971 return true;
972 if (DKind == OMPD_parallel) {
973 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
974 /*IgnoreCaptured=*/true);
975 if (!Body)
976 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000977 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000978 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
979 DKind = NND->getDirectiveKind();
980 if (isOpenMPWorksharingDirective(DKind) &&
981 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
982 return true;
983 }
984 } else if (DKind == OMPD_teams) {
985 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
986 /*IgnoreCaptured=*/true);
987 if (!Body)
988 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000989 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000990 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
991 DKind = NND->getDirectiveKind();
992 if (isOpenMPParallelDirective(DKind) &&
993 isOpenMPWorksharingDirective(DKind) &&
994 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
995 return true;
996 if (DKind == OMPD_parallel) {
997 Body = NND->getInnermostCapturedStmt()->IgnoreContainers(
998 /*IgnoreCaptured=*/true);
999 if (!Body)
1000 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001001 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001002 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
1003 DKind = NND->getDirectiveKind();
1004 if (isOpenMPWorksharingDirective(DKind) &&
1005 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
1006 return true;
1007 }
1008 }
1009 }
1010 }
1011 return false;
1012 case OMPD_target_teams:
1013 if (isOpenMPParallelDirective(DKind) &&
1014 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
1015 hasStaticScheduling(*NestedDir))
1016 return true;
1017 if (DKind == OMPD_parallel) {
1018 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
1019 /*IgnoreCaptured=*/true);
1020 if (!Body)
1021 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001022 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001023 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
1024 DKind = NND->getDirectiveKind();
1025 if (isOpenMPWorksharingDirective(DKind) &&
1026 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
1027 return true;
1028 }
1029 }
1030 return false;
1031 case OMPD_target_parallel:
1032 return isOpenMPWorksharingDirective(DKind) &&
1033 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NestedDir);
1034 case OMPD_target_teams_distribute:
1035 case OMPD_target_simd:
1036 case OMPD_target_parallel_for:
1037 case OMPD_target_parallel_for_simd:
1038 case OMPD_target_teams_distribute_simd:
1039 case OMPD_target_teams_distribute_parallel_for:
1040 case OMPD_target_teams_distribute_parallel_for_simd:
1041 case OMPD_parallel:
1042 case OMPD_for:
1043 case OMPD_parallel_for:
1044 case OMPD_parallel_sections:
1045 case OMPD_for_simd:
1046 case OMPD_parallel_for_simd:
1047 case OMPD_cancel:
1048 case OMPD_cancellation_point:
1049 case OMPD_ordered:
1050 case OMPD_threadprivate:
1051 case OMPD_task:
1052 case OMPD_simd:
1053 case OMPD_sections:
1054 case OMPD_section:
1055 case OMPD_single:
1056 case OMPD_master:
1057 case OMPD_critical:
1058 case OMPD_taskyield:
1059 case OMPD_barrier:
1060 case OMPD_taskwait:
1061 case OMPD_taskgroup:
1062 case OMPD_atomic:
1063 case OMPD_flush:
1064 case OMPD_teams:
1065 case OMPD_target_data:
1066 case OMPD_target_exit_data:
1067 case OMPD_target_enter_data:
1068 case OMPD_distribute:
1069 case OMPD_distribute_simd:
1070 case OMPD_distribute_parallel_for:
1071 case OMPD_distribute_parallel_for_simd:
1072 case OMPD_teams_distribute:
1073 case OMPD_teams_distribute_simd:
1074 case OMPD_teams_distribute_parallel_for:
1075 case OMPD_teams_distribute_parallel_for_simd:
1076 case OMPD_target_update:
1077 case OMPD_declare_simd:
1078 case OMPD_declare_target:
1079 case OMPD_end_declare_target:
1080 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00001081 case OMPD_declare_mapper:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001082 case OMPD_taskloop:
1083 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001084 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001085 case OMPD_unknown:
1086 llvm_unreachable("Unexpected directive.");
1087 }
1088 }
1089
1090 return false;
1091}
1092
1093/// Checks if the construct supports lightweight runtime. It must be SPMD
1094/// construct + inner loop-based construct with static scheduling.
1095static bool supportsLightweightRuntime(ASTContext &Ctx,
1096 const OMPExecutableDirective &D) {
1097 if (!supportsSPMDExecutionMode(Ctx, D))
1098 return false;
1099 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
1100 switch (DirectiveKind) {
1101 case OMPD_target:
1102 case OMPD_target_teams:
1103 case OMPD_target_parallel:
1104 return hasNestedLightweightDirective(Ctx, D);
1105 case OMPD_target_parallel_for:
1106 case OMPD_target_parallel_for_simd:
1107 case OMPD_target_teams_distribute_parallel_for:
1108 case OMPD_target_teams_distribute_parallel_for_simd:
1109 // (Last|First)-privates must be shared in parallel region.
1110 return hasStaticScheduling(D);
1111 case OMPD_target_simd:
1112 case OMPD_target_teams_distribute:
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001113 case OMPD_target_teams_distribute_simd:
Alexey Bataevdf093e72018-05-11 19:45:14 +00001114 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001115 case OMPD_parallel:
1116 case OMPD_for:
1117 case OMPD_parallel_for:
1118 case OMPD_parallel_sections:
1119 case OMPD_for_simd:
1120 case OMPD_parallel_for_simd:
1121 case OMPD_cancel:
1122 case OMPD_cancellation_point:
1123 case OMPD_ordered:
1124 case OMPD_threadprivate:
1125 case OMPD_task:
1126 case OMPD_simd:
1127 case OMPD_sections:
1128 case OMPD_section:
1129 case OMPD_single:
1130 case OMPD_master:
1131 case OMPD_critical:
1132 case OMPD_taskyield:
1133 case OMPD_barrier:
1134 case OMPD_taskwait:
1135 case OMPD_taskgroup:
1136 case OMPD_atomic:
1137 case OMPD_flush:
1138 case OMPD_teams:
1139 case OMPD_target_data:
1140 case OMPD_target_exit_data:
1141 case OMPD_target_enter_data:
1142 case OMPD_distribute:
1143 case OMPD_distribute_simd:
1144 case OMPD_distribute_parallel_for:
1145 case OMPD_distribute_parallel_for_simd:
1146 case OMPD_teams_distribute:
1147 case OMPD_teams_distribute_simd:
1148 case OMPD_teams_distribute_parallel_for:
1149 case OMPD_teams_distribute_parallel_for_simd:
1150 case OMPD_target_update:
1151 case OMPD_declare_simd:
1152 case OMPD_declare_target:
1153 case OMPD_end_declare_target:
1154 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00001155 case OMPD_declare_mapper:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001156 case OMPD_taskloop:
1157 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001158 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001159 case OMPD_unknown:
1160 break;
1161 }
1162 llvm_unreachable(
1163 "Unknown programming model for OpenMP directive on NVPTX target.");
1164}
1165
1166void CGOpenMPRuntimeNVPTX::emitNonSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001167 StringRef ParentName,
1168 llvm::Function *&OutlinedFn,
1169 llvm::Constant *&OutlinedFnID,
1170 bool IsOffloadEntry,
1171 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001172 ExecutionRuntimeModesRAII ModeRAII(CurrentExecutionMode);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001173 EntryFunctionState EST;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001174 WorkerFunctionState WST(CGM, D.getBeginLoc());
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001175 Work.clear();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001176 WrapperFunctionsMap.clear();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001177
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001178 // Emit target region as a standalone region.
1179 class NVPTXPrePostActionTy : public PrePostActionTy {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001180 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1181 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001182
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001183 public:
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001184 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001185 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST)
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001186 : EST(EST), WST(WST) {}
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001187 void Enter(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001188 auto &RT =
1189 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001190 RT.emitNonSPMDEntryHeader(CGF, EST, WST);
1191 // Skip target region initialization.
1192 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001193 }
1194 void Exit(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001195 auto &RT =
1196 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001197 RT.clearLocThreadIdInsertPt(CGF);
1198 RT.emitNonSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001199 }
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001200 } Action(EST, WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001201 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001202 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001203 // Reserve place for the globalized memory.
1204 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001205 if (!KernelStaticGlobalized) {
1206 KernelStaticGlobalized = new llvm::GlobalVariable(
1207 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1208 llvm::GlobalValue::InternalLinkage,
1209 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1210 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1211 llvm::GlobalValue::NotThreadLocal,
1212 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1213 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001214 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1215 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001216 IsInTTDRegion = false;
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001217
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001218 // Now change the name of the worker function to correspond to this target
1219 // region's entry function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001220 WST.WorkerFn->setName(Twine(OutlinedFn->getName(), "_worker"));
Alexey Bataevaee93892018-01-08 20:09:47 +00001221
1222 // Create the worker function
1223 emitWorkerFunction(WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001224}
1225
1226// Setup NVPTX threads for master-worker OpenMP scheme.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001227void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryHeader(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001228 EntryFunctionState &EST,
1229 WorkerFunctionState &WST) {
1230 CGBuilderTy &Bld = CGF.Builder;
1231
1232 llvm::BasicBlock *WorkerBB = CGF.createBasicBlock(".worker");
1233 llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
1234 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
1235 EST.ExitBB = CGF.createBasicBlock(".exit");
1236
Alexey Bataev9ff80832018-04-16 20:16:21 +00001237 llvm::Value *IsWorker =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001238 Bld.CreateICmpULT(getNVPTXThreadID(CGF), getThreadLimit(CGF));
1239 Bld.CreateCondBr(IsWorker, WorkerBB, MasterCheckBB);
1240
1241 CGF.EmitBlock(WorkerBB);
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001242 emitCall(CGF, WST.Loc, WST.WorkerFn);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001243 CGF.EmitBranch(EST.ExitBB);
1244
1245 CGF.EmitBlock(MasterCheckBB);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001246 llvm::Value *IsMaster =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001247 Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
1248 Bld.CreateCondBr(IsMaster, MasterBB, EST.ExitBB);
1249
1250 CGF.EmitBlock(MasterBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001251 IsInTargetMasterThreadRegion = true;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001252 // SEQUENTIAL (MASTER) REGION START
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001253 // First action in sequential region:
1254 // Initialize the state of the OpenMP runtime library on the GPU.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001255 // TODO: Optimize runtime initialization and pass in correct value.
1256 llvm::Value *Args[] = {getThreadLimit(CGF),
1257 Bld.getInt16(/*RequiresOMPRuntime=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001258 CGF.EmitRuntimeCall(
1259 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_init), Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001260
1261 // For data sharing, we need to initialize the stack.
1262 CGF.EmitRuntimeCall(
1263 createNVPTXRuntimeFunction(
1264 OMPRTL_NVPTX__kmpc_data_sharing_init_stack));
1265
Alexey Bataevc99042b2018-03-15 18:10:54 +00001266 emitGenericVarsProlog(CGF, WST.Loc);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001267}
1268
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001269void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001270 EntryFunctionState &EST) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001271 IsInTargetMasterThreadRegion = false;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001272 if (!CGF.HaveInsertPoint())
1273 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001274
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001275 emitGenericVarsEpilog(CGF);
1276
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001277 if (!EST.ExitBB)
1278 EST.ExitBB = CGF.createBasicBlock(".exit");
1279
1280 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".termination.notifier");
1281 CGF.EmitBranch(TerminateBB);
1282
1283 CGF.EmitBlock(TerminateBB);
1284 // Signal termination condition.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001285 // TODO: Optimize runtime initialization and pass in correct value.
1286 llvm::Value *Args[] = {CGF.Builder.getInt16(/*IsOMPRuntimeInitialized=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001287 CGF.EmitRuntimeCall(
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001288 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_deinit), Args);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001289 // Barrier to terminate worker threads.
1290 syncCTAThreads(CGF);
1291 // Master thread jumps to exit point.
1292 CGF.EmitBranch(EST.ExitBB);
1293
1294 CGF.EmitBlock(EST.ExitBB);
1295 EST.ExitBB = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001296}
1297
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001298void CGOpenMPRuntimeNVPTX::emitSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001299 StringRef ParentName,
1300 llvm::Function *&OutlinedFn,
1301 llvm::Constant *&OutlinedFnID,
1302 bool IsOffloadEntry,
1303 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001304 ExecutionRuntimeModesRAII ModeRAII(
1305 CurrentExecutionMode, RequiresFullRuntime,
1306 CGM.getLangOpts().OpenMPCUDAForceFullRuntime ||
1307 !supportsLightweightRuntime(CGM.getContext(), D));
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001308 EntryFunctionState EST;
1309
1310 // Emit target region as a standalone region.
1311 class NVPTXPrePostActionTy : public PrePostActionTy {
1312 CGOpenMPRuntimeNVPTX &RT;
1313 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1314 const OMPExecutableDirective &D;
1315
1316 public:
1317 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT,
1318 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
1319 const OMPExecutableDirective &D)
1320 : RT(RT), EST(EST), D(D) {}
1321 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001322 RT.emitSPMDEntryHeader(CGF, EST, D);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001323 // Skip target region initialization.
1324 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001325 }
1326 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevfd006c42018-10-05 15:08:53 +00001327 RT.clearLocThreadIdInsertPt(CGF);
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001328 RT.emitSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001329 }
1330 } Action(*this, EST, D);
1331 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001332 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001333 // Reserve place for the globalized memory.
1334 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001335 if (!KernelStaticGlobalized) {
1336 KernelStaticGlobalized = new llvm::GlobalVariable(
1337 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1338 llvm::GlobalValue::InternalLinkage,
1339 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1340 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1341 llvm::GlobalValue::NotThreadLocal,
1342 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1343 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001344 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1345 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001346 IsInTTDRegion = false;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001347}
1348
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001349void CGOpenMPRuntimeNVPTX::emitSPMDEntryHeader(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001350 CodeGenFunction &CGF, EntryFunctionState &EST,
1351 const OMPExecutableDirective &D) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001352 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001353
1354 // Setup BBs in entry function.
1355 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute");
1356 EST.ExitBB = CGF.createBasicBlock(".exit");
1357
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001358 llvm::Value *Args[] = {getThreadLimit(CGF, /*IsInSPMDExecutionMode=*/true),
1359 /*RequiresOMPRuntime=*/
1360 Bld.getInt16(RequiresFullRuntime ? 1 : 0),
1361 /*RequiresDataSharing=*/Bld.getInt16(0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001362 CGF.EmitRuntimeCall(
1363 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_init), Args);
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001364
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001365 if (RequiresFullRuntime) {
1366 // For data sharing, we need to initialize the stack.
1367 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1368 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd));
1369 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001370
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001371 CGF.EmitBranch(ExecuteBB);
1372
1373 CGF.EmitBlock(ExecuteBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001374
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001375 IsInTargetMasterThreadRegion = true;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001376}
1377
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001378void CGOpenMPRuntimeNVPTX::emitSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001379 EntryFunctionState &EST) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001380 IsInTargetMasterThreadRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001381 if (!CGF.HaveInsertPoint())
1382 return;
1383
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001384 if (!EST.ExitBB)
1385 EST.ExitBB = CGF.createBasicBlock(".exit");
1386
1387 llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit");
1388 CGF.EmitBranch(OMPDeInitBB);
1389
1390 CGF.EmitBlock(OMPDeInitBB);
1391 // DeInitialize the OMP state in the runtime; called by all active threads.
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001392 llvm::Value *Args[] = {/*RequiresOMPRuntime=*/
1393 CGF.Builder.getInt16(RequiresFullRuntime ? 1 : 0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001394 CGF.EmitRuntimeCall(
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001395 createNVPTXRuntimeFunction(
1396 OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2), Args);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001397 CGF.EmitBranch(EST.ExitBB);
1398
1399 CGF.EmitBlock(EST.ExitBB);
1400 EST.ExitBB = nullptr;
1401}
1402
1403// Create a unique global variable to indicate the execution mode of this target
1404// region. The execution mode is either 'generic', or 'spmd' depending on the
1405// target directive. This variable is picked up by the offload library to setup
1406// the device appropriately before kernel launch. If the execution mode is
1407// 'generic', the runtime reserves one warp for the master, otherwise, all
1408// warps participate in parallel work.
1409static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001410 bool Mode) {
1411 auto *GVMode =
1412 new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
1413 llvm::GlobalValue::WeakAnyLinkage,
1414 llvm::ConstantInt::get(CGM.Int8Ty, Mode ? 0 : 1),
1415 Twine(Name, "_exec_mode"));
Alexey Bataev9ff80832018-04-16 20:16:21 +00001416 CGM.addCompilerUsedGlobal(GVMode);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001417}
1418
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001419void CGOpenMPRuntimeNVPTX::emitWorkerFunction(WorkerFunctionState &WST) {
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +00001420 ASTContext &Ctx = CGM.getContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001421
1422 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001423 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, WST.CGFI, {},
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001424 WST.Loc, WST.Loc);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001425 emitWorkerLoop(CGF, WST);
1426 CGF.FinishFunction();
1427}
1428
1429void CGOpenMPRuntimeNVPTX::emitWorkerLoop(CodeGenFunction &CGF,
1430 WorkerFunctionState &WST) {
1431 //
1432 // The workers enter this loop and wait for parallel work from the master.
1433 // When the master encounters a parallel region it sets up the work + variable
1434 // arguments, and wakes up the workers. The workers first check to see if
1435 // they are required for the parallel region, i.e., within the # of requested
1436 // parallel threads. The activated workers load the variable arguments and
1437 // execute the parallel work.
1438 //
1439
1440 CGBuilderTy &Bld = CGF.Builder;
1441
1442 llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work");
1443 llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers");
1444 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel");
1445 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel");
1446 llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel");
1447 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1448
1449 CGF.EmitBranch(AwaitBB);
1450
1451 // Workers wait for work from master.
1452 CGF.EmitBlock(AwaitBB);
1453 // Wait for parallel work
1454 syncCTAThreads(CGF);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001455
1456 Address WorkFn =
1457 CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn");
1458 Address ExecStatus =
1459 CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status");
1460 CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0));
1461 CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy));
1462
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001463 // TODO: Optimize runtime initialization and pass in correct value.
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001464 llvm::Value *Args[] = {WorkFn.getPointer(),
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001465 /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001466 llvm::Value *Ret = CGF.EmitRuntimeCall(
1467 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args);
1468 Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001469
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001470 // On termination condition (workid == 0), exit loop.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001471 llvm::Value *WorkID = Bld.CreateLoad(WorkFn);
1472 llvm::Value *ShouldTerminate = Bld.CreateIsNull(WorkID, "should_terminate");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001473 Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB);
1474
1475 // Activate requested workers.
1476 CGF.EmitBlock(SelectWorkersBB);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001477 llvm::Value *IsActive =
1478 Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active");
1479 Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001480
1481 // Signal start of parallel region.
1482 CGF.EmitBlock(ExecuteBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001483 // Skip initialization.
1484 setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001485
1486 // Process work items: outlined parallel functions.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001487 for (llvm::Function *W : Work) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001488 // Try to match this outlined function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001489 llvm::Value *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001490
1491 llvm::Value *WorkFnMatch =
1492 Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match");
1493
1494 llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn");
1495 llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next");
1496 Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB);
1497
1498 // Execute this outlined function.
1499 CGF.EmitBlock(ExecuteFNBB);
1500
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001501 // Insert call to work function via shared wrapper. The shared
1502 // wrapper takes two arguments:
1503 // - the parallelism level;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001504 // - the thread ID;
1505 emitCall(CGF, WST.Loc, W,
1506 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001507
1508 // Go to end of parallel region.
1509 CGF.EmitBranch(TerminateBB);
1510
1511 CGF.EmitBlock(CheckNextBB);
1512 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001513 // Default case: call to outlined function through pointer if the target
1514 // region makes a declare target call that may contain an orphaned parallel
1515 // directive.
1516 auto *ParallelFnTy =
1517 llvm::FunctionType::get(CGM.VoidTy, {CGM.Int16Ty, CGM.Int32Ty},
1518 /*isVarArg=*/false)
1519 ->getPointerTo();
1520 llvm::Value *WorkFnCast = Bld.CreateBitCast(WorkID, ParallelFnTy);
1521 // Insert call to work function via shared wrapper. The shared
1522 // wrapper takes two arguments:
1523 // - the parallelism level;
1524 // - the thread ID;
1525 emitCall(CGF, WST.Loc, WorkFnCast,
1526 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
1527 // Go to end of parallel region.
1528 CGF.EmitBranch(TerminateBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001529
1530 // Signal end of parallel region.
1531 CGF.EmitBlock(TerminateBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001532 CGF.EmitRuntimeCall(
1533 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_end_parallel),
1534 llvm::None);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001535 CGF.EmitBranch(BarrierBB);
1536
1537 // All active and inactive workers wait at a barrier after parallel region.
1538 CGF.EmitBlock(BarrierBB);
1539 // Barrier after parallel region.
1540 syncCTAThreads(CGF);
1541 CGF.EmitBranch(AwaitBB);
1542
1543 // Exit target region.
1544 CGF.EmitBlock(ExitBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001545 // Skip initialization.
1546 clearLocThreadIdInsertPt(CGF);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001547}
1548
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001549/// Returns specified OpenMP runtime function for the current OpenMP
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001550/// implementation. Specialized for the NVPTX device.
1551/// \param Function OpenMP runtime function.
1552/// \return Specified function.
1553llvm::Constant *
1554CGOpenMPRuntimeNVPTX::createNVPTXRuntimeFunction(unsigned Function) {
1555 llvm::Constant *RTLFn = nullptr;
1556 switch (static_cast<OpenMPRTLFunctionNVPTX>(Function)) {
1557 case OMPRTL_NVPTX__kmpc_kernel_init: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001558 // Build void __kmpc_kernel_init(kmp_int32 thread_limit, int16_t
1559 // RequiresOMPRuntime);
1560 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001561 auto *FnTy =
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001562 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1563 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_init");
1564 break;
1565 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001566 case OMPRTL_NVPTX__kmpc_kernel_deinit: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001567 // Build void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
1568 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001569 auto *FnTy =
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001570 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001571 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_deinit");
1572 break;
1573 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001574 case OMPRTL_NVPTX__kmpc_spmd_kernel_init: {
1575 // Build void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001576 // int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001577 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001578 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001579 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1580 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_init");
1581 break;
1582 }
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001583 case OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2: {
1584 // Build void __kmpc_spmd_kernel_deinit_v2(int16_t RequiresOMPRuntime);
1585 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001586 auto *FnTy =
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001587 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1588 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_deinit_v2");
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001589 break;
1590 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001591 case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: {
1592 /// Build void __kmpc_kernel_prepare_parallel(
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001593 /// void *outlined_function, int16_t IsOMPRuntimeInitialized);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001594 llvm::Type *TypeParams[] = {CGM.Int8PtrTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001595 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001596 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1597 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_prepare_parallel");
1598 break;
1599 }
1600 case OMPRTL_NVPTX__kmpc_kernel_parallel: {
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001601 /// Build bool __kmpc_kernel_parallel(void **outlined_function,
1602 /// int16_t IsOMPRuntimeInitialized);
1603 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy, CGM.Int16Ty};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001604 llvm::Type *RetTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001605 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001606 llvm::FunctionType::get(RetTy, TypeParams, /*isVarArg*/ false);
1607 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_parallel");
1608 break;
1609 }
1610 case OMPRTL_NVPTX__kmpc_kernel_end_parallel: {
1611 /// Build void __kmpc_kernel_end_parallel();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001612 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001613 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1614 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_end_parallel");
1615 break;
1616 }
1617 case OMPRTL_NVPTX__kmpc_serialized_parallel: {
1618 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1619 // global_tid);
1620 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001621 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001622 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1623 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1624 break;
1625 }
1626 case OMPRTL_NVPTX__kmpc_end_serialized_parallel: {
1627 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1628 // global_tid);
1629 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001630 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001631 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1632 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1633 break;
1634 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001635 case OMPRTL_NVPTX__kmpc_shuffle_int32: {
1636 // Build int32_t __kmpc_shuffle_int32(int32_t element,
1637 // int16_t lane_offset, int16_t warp_size);
1638 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001639 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001640 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1641 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int32");
1642 break;
1643 }
1644 case OMPRTL_NVPTX__kmpc_shuffle_int64: {
1645 // Build int64_t __kmpc_shuffle_int64(int64_t element,
1646 // int16_t lane_offset, int16_t warp_size);
1647 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001648 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001649 llvm::FunctionType::get(CGM.Int64Ty, TypeParams, /*isVarArg*/ false);
1650 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int64");
1651 break;
1652 }
Alexey Bataev8e009032019-01-04 17:25:09 +00001653 case OMPRTL_NVPTX__kmpc_parallel_reduce_nowait_v2: {
1654 // Build int32_t kmpc_nvptx_parallel_reduce_nowait_v2(ident_t *loc,
1655 // kmp_int32 global_tid, kmp_int32 num_vars, size_t reduce_size, void*
1656 // reduce_data, void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t
1657 // lane_id, int16_t lane_offset, int16_t Algorithm Version), void
1658 // (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001659 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1660 CGM.Int16Ty, CGM.Int16Ty};
1661 auto *ShuffleReduceFnTy =
1662 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1663 /*isVarArg=*/false);
1664 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1665 auto *InterWarpCopyFnTy =
1666 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1667 /*isVarArg=*/false);
Alexey Bataev8e009032019-01-04 17:25:09 +00001668 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1669 CGM.Int32Ty,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001670 CGM.Int32Ty,
1671 CGM.SizeTy,
1672 CGM.VoidPtrTy,
1673 ShuffleReduceFnTy->getPointerTo(),
1674 InterWarpCopyFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001675 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001676 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1677 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev8e009032019-01-04 17:25:09 +00001678 FnTy, /*Name=*/"__kmpc_nvptx_parallel_reduce_nowait_v2");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001679 break;
1680 }
1681 case OMPRTL_NVPTX__kmpc_end_reduce_nowait: {
1682 // Build __kmpc_end_reduce_nowait(kmp_int32 global_tid);
1683 llvm::Type *TypeParams[] = {CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001684 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001685 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1686 RTLFn = CGM.CreateRuntimeFunction(
1687 FnTy, /*Name=*/"__kmpc_nvptx_end_reduce_nowait");
1688 break;
1689 }
Alexey Bataeva1166022018-11-27 21:24:54 +00001690 case OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_simple: {
1691 // Build __kmpc_nvptx_teams_reduce_nowait_simple(ident_t *loc, kmp_int32
1692 // global_tid, kmp_critical_name *lck)
1693 llvm::Type *TypeParams[] = {
1694 getIdentTyPointerTy(), CGM.Int32Ty,
1695 llvm::PointerType::getUnqual(getKmpCriticalNameTy())};
1696 auto *FnTy =
1697 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1698 RTLFn = CGM.CreateRuntimeFunction(
1699 FnTy, /*Name=*/"__kmpc_nvptx_teams_reduce_nowait_simple");
1700 break;
1701 }
1702 case OMPRTL_NVPTX__kmpc_nvptx_teams_end_reduce_nowait_simple: {
1703 // Build __kmpc_nvptx_teams_end_reduce_nowait_simple(ident_t *loc, kmp_int32
1704 // global_tid, kmp_critical_name *lck)
1705 llvm::Type *TypeParams[] = {
1706 getIdentTyPointerTy(), CGM.Int32Ty,
1707 llvm::PointerType::getUnqual(getKmpCriticalNameTy())};
1708 auto *FnTy =
1709 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1710 RTLFn = CGM.CreateRuntimeFunction(
1711 FnTy, /*Name=*/"__kmpc_nvptx_teams_end_reduce_nowait_simple");
1712 break;
1713 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001714 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack: {
1715 /// Build void __kmpc_data_sharing_init_stack();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001716 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001717 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1718 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack");
1719 break;
1720 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001721 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd: {
1722 /// Build void __kmpc_data_sharing_init_stack_spmd();
1723 auto *FnTy =
1724 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001725 RTLFn =
1726 CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack_spmd");
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001727 break;
1728 }
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001729 case OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack: {
1730 // Build void *__kmpc_data_sharing_coalesced_push_stack(size_t size,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001731 // int16_t UseSharedMemory);
1732 llvm::Type *TypeParams[] = {CGM.SizeTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001733 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001734 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1735 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001736 FnTy, /*Name=*/"__kmpc_data_sharing_coalesced_push_stack");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001737 break;
1738 }
1739 case OMPRTL_NVPTX__kmpc_data_sharing_pop_stack: {
1740 // Build void __kmpc_data_sharing_pop_stack(void *a);
1741 llvm::Type *TypeParams[] = {CGM.VoidPtrTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001742 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001743 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1744 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1745 /*Name=*/"__kmpc_data_sharing_pop_stack");
1746 break;
1747 }
1748 case OMPRTL_NVPTX__kmpc_begin_sharing_variables: {
1749 /// Build void __kmpc_begin_sharing_variables(void ***args,
1750 /// size_t n_args);
1751 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo(), CGM.SizeTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001752 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001753 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1754 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_begin_sharing_variables");
1755 break;
1756 }
1757 case OMPRTL_NVPTX__kmpc_end_sharing_variables: {
1758 /// Build void __kmpc_end_sharing_variables();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001759 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001760 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1761 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_sharing_variables");
1762 break;
1763 }
1764 case OMPRTL_NVPTX__kmpc_get_shared_variables: {
1765 /// Build void __kmpc_get_shared_variables(void ***GlobalArgs);
1766 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001767 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001768 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1769 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_shared_variables");
1770 break;
1771 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001772 case OMPRTL_NVPTX__kmpc_parallel_level: {
1773 // Build uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32 global_tid);
1774 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1775 auto *FnTy =
1776 llvm::FunctionType::get(CGM.Int16Ty, TypeParams, /*isVarArg*/ false);
1777 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_parallel_level");
1778 break;
1779 }
Alexey Bataev673110d2018-05-16 13:36:30 +00001780 case OMPRTL_NVPTX__kmpc_is_spmd_exec_mode: {
1781 // Build int8_t __kmpc_is_spmd_exec_mode();
1782 auto *FnTy = llvm::FunctionType::get(CGM.Int8Ty, /*isVarArg=*/false);
1783 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_is_spmd_exec_mode");
1784 break;
1785 }
Alexey Bataeve4090182018-11-02 14:54:07 +00001786 case OMPRTL_NVPTX__kmpc_get_team_static_memory: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001787 // Build void __kmpc_get_team_static_memory(int16_t isSPMDExecutionMode,
1788 // const void *buf, size_t size, int16_t is_shared, const void **res);
1789 llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.VoidPtrTy, CGM.SizeTy,
1790 CGM.Int16Ty, CGM.VoidPtrPtrTy};
Alexey Bataeve4090182018-11-02 14:54:07 +00001791 auto *FnTy =
1792 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1793 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_team_static_memory");
1794 break;
1795 }
1796 case OMPRTL_NVPTX__kmpc_restore_team_static_memory: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001797 // Build void __kmpc_restore_team_static_memory(int16_t isSPMDExecutionMode,
1798 // int16_t is_shared);
1799 llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataeve4090182018-11-02 14:54:07 +00001800 auto *FnTy =
Alexey Bataev8e009032019-01-04 17:25:09 +00001801 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
Alexey Bataeve4090182018-11-02 14:54:07 +00001802 RTLFn =
1803 CGM.CreateRuntimeFunction(FnTy, "__kmpc_restore_team_static_memory");
1804 break;
1805 }
Alexey Bataevc3028ca2018-12-04 15:03:25 +00001806 case OMPRTL__kmpc_barrier: {
1807 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
1808 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1809 auto *FnTy =
1810 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1811 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1812 cast<llvm::Function>(RTLFn)->addFnAttr(llvm::Attribute::Convergent);
1813 break;
1814 }
Alexey Bataeva3924b52019-01-03 16:25:35 +00001815 case OMPRTL__kmpc_barrier_simple_spmd: {
1816 // Build void __kmpc_barrier_simple_spmd(ident_t *loc, kmp_int32
1817 // global_tid);
1818 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1819 auto *FnTy =
1820 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1821 RTLFn =
1822 CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier_simple_spmd");
1823 cast<llvm::Function>(RTLFn)->addFnAttr(llvm::Attribute::Convergent);
1824 break;
1825 }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001826 }
1827 return RTLFn;
1828}
1829
1830void CGOpenMPRuntimeNVPTX::createOffloadEntry(llvm::Constant *ID,
1831 llvm::Constant *Addr,
Alexey Bataev03f270c2018-03-30 18:31:07 +00001832 uint64_t Size, int32_t,
1833 llvm::GlobalValue::LinkageTypes) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001834 // TODO: Add support for global variables on the device after declare target
1835 // support.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001836 if (!isa<llvm::Function>(Addr))
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001837 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +00001838 llvm::Module &M = CGM.getModule();
1839 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001840
1841 // Get "nvvm.annotations" metadata node
Alexey Bataev9ff80832018-04-16 20:16:21 +00001842 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001843
1844 llvm::Metadata *MDVals[] = {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001845 llvm::ConstantAsMetadata::get(Addr), llvm::MDString::get(Ctx, "kernel"),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001846 llvm::ConstantAsMetadata::get(
1847 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))};
1848 // Append metadata to nvvm.annotations
1849 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
1850}
1851
1852void CGOpenMPRuntimeNVPTX::emitTargetOutlinedFunction(
1853 const OMPExecutableDirective &D, StringRef ParentName,
1854 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001855 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001856 if (!IsOffloadEntry) // Nothing to do.
1857 return;
1858
1859 assert(!ParentName.empty() && "Invalid target region parent name!");
1860
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001861 bool Mode = supportsSPMDExecutionMode(CGM.getContext(), D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001862 if (Mode)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001863 emitSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001864 CodeGen);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001865 else
1866 emitNonSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1867 CodeGen);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001868
1869 setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001870}
1871
Alexey Bataevceeaa482018-11-21 21:04:34 +00001872namespace {
1873LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
1874/// Enum for accesseing the reserved_2 field of the ident_t struct.
1875enum ModeFlagsTy : unsigned {
1876 /// Bit set to 1 when in SPMD mode.
1877 KMP_IDENT_SPMD_MODE = 0x01,
1878 /// Bit set to 1 when a simplified runtime is used.
1879 KMP_IDENT_SIMPLE_RT_MODE = 0x02,
1880 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/KMP_IDENT_SIMPLE_RT_MODE)
1881};
1882
1883/// Special mode Undefined. Is the combination of Non-SPMD mode + SimpleRuntime.
1884static const ModeFlagsTy UndefinedMode =
1885 (~KMP_IDENT_SPMD_MODE) & KMP_IDENT_SIMPLE_RT_MODE;
1886} // anonymous namespace
1887
1888unsigned CGOpenMPRuntimeNVPTX::getDefaultLocationReserved2Flags() const {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001889 switch (getExecutionMode()) {
1890 case EM_SPMD:
1891 if (requiresFullRuntime())
1892 return KMP_IDENT_SPMD_MODE & (~KMP_IDENT_SIMPLE_RT_MODE);
1893 return KMP_IDENT_SPMD_MODE | KMP_IDENT_SIMPLE_RT_MODE;
1894 case EM_NonSPMD:
1895 assert(requiresFullRuntime() && "Expected full runtime.");
1896 return (~KMP_IDENT_SPMD_MODE) & (~KMP_IDENT_SIMPLE_RT_MODE);
1897 case EM_Unknown:
1898 return UndefinedMode;
1899 }
1900 llvm_unreachable("Unknown flags are requested.");
Alexey Bataevceeaa482018-11-21 21:04:34 +00001901}
1902
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001903CGOpenMPRuntimeNVPTX::CGOpenMPRuntimeNVPTX(CodeGenModule &CGM)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001904 : CGOpenMPRuntime(CGM, "_", "$") {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001905 if (!CGM.getLangOpts().OpenMPIsDevice)
1906 llvm_unreachable("OpenMP NVPTX can only handle device code.");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001907}
Carlo Bertollic6872252016-04-04 15:55:02 +00001908
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001909void CGOpenMPRuntimeNVPTX::emitProcBindClause(CodeGenFunction &CGF,
1910 OpenMPProcBindClauseKind ProcBind,
1911 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001912 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001913 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001914 return;
1915
1916 CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc);
1917}
1918
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001919void CGOpenMPRuntimeNVPTX::emitNumThreadsClause(CodeGenFunction &CGF,
1920 llvm::Value *NumThreads,
1921 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001922 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001923 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001924 return;
1925
1926 CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc);
1927}
1928
Carlo Bertollic6872252016-04-04 15:55:02 +00001929void CGOpenMPRuntimeNVPTX::emitNumTeamsClause(CodeGenFunction &CGF,
1930 const Expr *NumTeams,
1931 const Expr *ThreadLimit,
1932 SourceLocation Loc) {}
1933
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001934llvm::Value *CGOpenMPRuntimeNVPTX::emitParallelOutlinedFunction(
1935 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1936 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00001937 // Emit target region as a standalone region.
1938 class NVPTXPrePostActionTy : public PrePostActionTy {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001939 bool &IsInParallelRegion;
1940 bool PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001941
1942 public:
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001943 NVPTXPrePostActionTy(bool &IsInParallelRegion)
1944 : IsInParallelRegion(IsInParallelRegion) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00001945 void Enter(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001946 PrevIsInParallelRegion = IsInParallelRegion;
1947 IsInParallelRegion = true;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001948 }
1949 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001950 IsInParallelRegion = PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001951 }
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001952 } Action(IsInParallelRegion);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001953 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001954 bool PrevIsInTTDRegion = IsInTTDRegion;
1955 IsInTTDRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001956 bool PrevIsInTargetMasterThreadRegion = IsInTargetMasterThreadRegion;
1957 IsInTargetMasterThreadRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001958 auto *OutlinedFun =
1959 cast<llvm::Function>(CGOpenMPRuntime::emitParallelOutlinedFunction(
1960 D, ThreadIDVar, InnermostKind, CodeGen));
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001961 IsInTargetMasterThreadRegion = PrevIsInTargetMasterThreadRegion;
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001962 IsInTTDRegion = PrevIsInTTDRegion;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001963 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD &&
1964 !IsInParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001965 llvm::Function *WrapperFun =
1966 createParallelDataSharingWrapper(OutlinedFun, D);
1967 WrapperFunctionsMap[OutlinedFun] = WrapperFun;
1968 }
1969
1970 return OutlinedFun;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001971}
1972
Alexey Bataev2adecff2018-09-21 14:22:53 +00001973/// Get list of lastprivate variables from the teams distribute ... or
1974/// teams {distribute ...} directives.
1975static void
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001976getDistributeLastprivateVars(ASTContext &Ctx, const OMPExecutableDirective &D,
Alexey Bataev2adecff2018-09-21 14:22:53 +00001977 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
1978 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
1979 "expected teams directive.");
1980 const OMPExecutableDirective *Dir = &D;
1981 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
1982 if (const Stmt *S = getSingleCompoundChild(
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001983 Ctx,
Alexey Bataev2adecff2018-09-21 14:22:53 +00001984 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
1985 /*IgnoreCaptured=*/true))) {
1986 Dir = dyn_cast<OMPExecutableDirective>(S);
1987 if (Dir && !isOpenMPDistributeDirective(Dir->getDirectiveKind()))
1988 Dir = nullptr;
1989 }
1990 }
1991 if (!Dir)
1992 return;
Alexey Bataev9ea3c382018-10-09 14:49:00 +00001993 for (const auto *C : Dir->getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00001994 for (const Expr *E : C->getVarRefs())
1995 Vars.push_back(getPrivateItem(E));
1996 }
1997}
1998
1999/// Get list of reduction variables from the teams ... directives.
2000static void
2001getTeamsReductionVars(ASTContext &Ctx, const OMPExecutableDirective &D,
2002 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
2003 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
2004 "expected teams directive.");
2005 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
2006 for (const Expr *E : C->privates())
2007 Vars.push_back(getPrivateItem(E));
Alexey Bataev2adecff2018-09-21 14:22:53 +00002008 }
2009}
2010
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002011llvm::Value *CGOpenMPRuntimeNVPTX::emitTeamsOutlinedFunction(
Carlo Bertollic6872252016-04-04 15:55:02 +00002012 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
2013 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002014 SourceLocation Loc = D.getBeginLoc();
Carlo Bertollic6872252016-04-04 15:55:02 +00002015
Alexey Bataev2adecff2018-09-21 14:22:53 +00002016 const RecordDecl *GlobalizedRD = nullptr;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002017 llvm::SmallVector<const ValueDecl *, 4> LastPrivatesReductions;
Alexey Bataev2adecff2018-09-21 14:22:53 +00002018 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002019 // Globalize team reductions variable unconditionally in all modes.
2020 getTeamsReductionVars(CGM.getContext(), D, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002021 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002022 getDistributeLastprivateVars(CGM.getContext(), D, LastPrivatesReductions);
2023 if (!LastPrivatesReductions.empty()) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002024 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002025 CGM.getContext(), llvm::None, LastPrivatesReductions,
2026 MappedDeclsFields);
2027 }
2028 } else if (!LastPrivatesReductions.empty()) {
2029 assert(!TeamAndReductions.first &&
2030 "Previous team declaration is not expected.");
2031 TeamAndReductions.first = D.getCapturedStmt(OMPD_teams)->getCapturedDecl();
2032 std::swap(TeamAndReductions.second, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002033 }
2034
Alexey Bataevc99042b2018-03-15 18:10:54 +00002035 // Emit target region as a standalone region.
2036 class NVPTXPrePostActionTy : public PrePostActionTy {
2037 SourceLocation &Loc;
Alexey Bataev2adecff2018-09-21 14:22:53 +00002038 const RecordDecl *GlobalizedRD;
2039 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2040 &MappedDeclsFields;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002041
2042 public:
Alexey Bataev2adecff2018-09-21 14:22:53 +00002043 NVPTXPrePostActionTy(
2044 SourceLocation &Loc, const RecordDecl *GlobalizedRD,
2045 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2046 &MappedDeclsFields)
2047 : Loc(Loc), GlobalizedRD(GlobalizedRD),
2048 MappedDeclsFields(MappedDeclsFields) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00002049 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002050 auto &Rt =
2051 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
2052 if (GlobalizedRD) {
2053 auto I = Rt.FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
2054 I->getSecond().GlobalRecord = GlobalizedRD;
2055 I->getSecond().MappedParams =
2056 llvm::make_unique<CodeGenFunction::OMPMapVars>();
2057 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
2058 for (const auto &Pair : MappedDeclsFields) {
2059 assert(Pair.getFirst()->isCanonicalDecl() &&
2060 "Expected canonical declaration");
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002061 Data.insert(std::make_pair(Pair.getFirst(),
2062 MappedVarData(Pair.getSecond(),
2063 /*IsOnePerTeam=*/true)));
Alexey Bataev2adecff2018-09-21 14:22:53 +00002064 }
2065 }
2066 Rt.emitGenericVarsProlog(CGF, Loc);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002067 }
2068 void Exit(CodeGenFunction &CGF) override {
2069 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
2070 .emitGenericVarsEpilog(CGF);
2071 }
Alexey Bataev2adecff2018-09-21 14:22:53 +00002072 } Action(Loc, GlobalizedRD, MappedDeclsFields);
2073 CodeGen.setAction(Action);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002074 llvm::Value *OutlinedFunVal = CGOpenMPRuntime::emitTeamsOutlinedFunction(
2075 D, ThreadIDVar, InnermostKind, CodeGen);
2076 llvm::Function *OutlinedFun = cast<llvm::Function>(OutlinedFunVal);
2077 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00002078 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002079 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
Carlo Bertollic6872252016-04-04 15:55:02 +00002080
2081 return OutlinedFun;
2082}
2083
Alexey Bataevc99042b2018-03-15 18:10:54 +00002084void CGOpenMPRuntimeNVPTX::emitGenericVarsProlog(CodeGenFunction &CGF,
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002085 SourceLocation Loc,
2086 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002087 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2088 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002089 return;
2090
Alexey Bataevc99042b2018-03-15 18:10:54 +00002091 CGBuilderTy &Bld = CGF.Builder;
2092
2093 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
2094 if (I == FunctionGlobalizedDecls.end())
2095 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002096 if (const RecordDecl *GlobalizedVarsRecord = I->getSecond().GlobalRecord) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002097 QualType GlobalRecTy = CGM.getContext().getRecordType(GlobalizedVarsRecord);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002098 QualType SecGlobalRecTy;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002099
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002100 // Recover pointer to this function's global record. The runtime will
2101 // handle the specifics of the allocation of the memory.
2102 // Use actual memory size of the record including the padding
2103 // for alignment purposes.
2104 unsigned Alignment =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002105 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002106 unsigned GlobalRecordSize =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002107 CGM.getContext().getTypeSizeInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002108 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002109
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002110 llvm::PointerType *GlobalRecPtrTy =
2111 CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo();
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002112 llvm::Value *GlobalRecCastAddr;
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002113 llvm::Value *IsTTD = nullptr;
Alexey Bataeve4090182018-11-02 14:54:07 +00002114 if (!IsInTTDRegion &&
2115 (WithSPMDCheck ||
2116 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002117 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2118 llvm::BasicBlock *SPMDBB = CGF.createBasicBlock(".spmd");
2119 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002120 if (I->getSecond().SecondaryGlobalRecord.hasValue()) {
2121 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2122 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2123 llvm::Value *PL = CGF.EmitRuntimeCall(
2124 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2125 {RTLoc, ThreadID});
2126 IsTTD = Bld.CreateIsNull(PL);
2127 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002128 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2129 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
2130 Bld.CreateCondBr(IsSPMD, SPMDBB, NonSPMDBB);
2131 // There is no need to emit line number for unconditional branch.
2132 (void)ApplyDebugLocation::CreateEmpty(CGF);
2133 CGF.EmitBlock(SPMDBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002134 Address RecPtr = Address(llvm::ConstantPointerNull::get(GlobalRecPtrTy),
2135 CharUnits::fromQuantity(Alignment));
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002136 CGF.EmitBranch(ExitBB);
2137 // There is no need to emit line number for unconditional branch.
2138 (void)ApplyDebugLocation::CreateEmpty(CGF);
2139 CGF.EmitBlock(NonSPMDBB);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002140 llvm::Value *Size = llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize);
2141 if (const RecordDecl *SecGlobalizedVarsRecord =
2142 I->getSecond().SecondaryGlobalRecord.getValueOr(nullptr)) {
2143 SecGlobalRecTy =
2144 CGM.getContext().getRecordType(SecGlobalizedVarsRecord);
2145
2146 // Recover pointer to this function's global record. The runtime will
2147 // handle the specifics of the allocation of the memory.
2148 // Use actual memory size of the record including the padding
2149 // for alignment purposes.
2150 unsigned Alignment =
2151 CGM.getContext().getTypeAlignInChars(SecGlobalRecTy).getQuantity();
2152 unsigned GlobalRecordSize =
2153 CGM.getContext().getTypeSizeInChars(SecGlobalRecTy).getQuantity();
2154 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
2155 Size = Bld.CreateSelect(
2156 IsTTD, llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize), Size);
2157 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002158 // TODO: allow the usage of shared memory to be controlled by
2159 // the user, for now, default to global.
2160 llvm::Value *GlobalRecordSizeArg[] = {
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002161 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002162 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2163 createNVPTXRuntimeFunction(
2164 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2165 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002166 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002167 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002168 CGF.EmitBlock(ExitBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002169 auto *Phi = Bld.CreatePHI(GlobalRecPtrTy,
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002170 /*NumReservedValues=*/2, "_select_stack");
2171 Phi->addIncoming(RecPtr.getPointer(), SPMDBB);
2172 Phi->addIncoming(GlobalRecCastAddr, NonSPMDBB);
2173 GlobalRecCastAddr = Phi;
2174 I->getSecond().GlobalRecordAddr = Phi;
2175 I->getSecond().IsInSPMDModeFlag = IsSPMD;
Alexey Bataeve4090182018-11-02 14:54:07 +00002176 } else if (IsInTTDRegion) {
2177 assert(GlobalizedRecords.back().Records.size() < 2 &&
2178 "Expected less than 2 globalized records: one for target and one "
2179 "for teams.");
2180 unsigned Offset = 0;
2181 for (const RecordDecl *RD : GlobalizedRecords.back().Records) {
2182 QualType RDTy = CGM.getContext().getRecordType(RD);
2183 unsigned Alignment =
2184 CGM.getContext().getTypeAlignInChars(RDTy).getQuantity();
2185 unsigned Size = CGM.getContext().getTypeSizeInChars(RDTy).getQuantity();
2186 Offset =
2187 llvm::alignTo(llvm::alignTo(Offset, Alignment) + Size, Alignment);
2188 }
2189 unsigned Alignment =
2190 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
2191 Offset = llvm::alignTo(Offset, Alignment);
2192 GlobalizedRecords.back().Records.push_back(GlobalizedVarsRecord);
2193 ++GlobalizedRecords.back().RegionCounter;
2194 if (GlobalizedRecords.back().Records.size() == 1) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002195 assert(KernelStaticGlobalized &&
2196 "Kernel static pointer must be initialized already.");
2197 auto *UseSharedMemory = new llvm::GlobalVariable(
2198 CGM.getModule(), CGM.Int16Ty, /*isConstant=*/true,
2199 llvm::GlobalValue::InternalLinkage, nullptr,
2200 "_openmp_static_kernel$is_shared");
2201 UseSharedMemory->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2202 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2203 /*DestWidth=*/16, /*Signed=*/0);
2204 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2205 Address(UseSharedMemory,
2206 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2207 /*Volatile=*/false, Int16Ty, Loc);
2208 auto *StaticGlobalized = new llvm::GlobalVariable(
2209 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002210 llvm::GlobalValue::CommonLinkage, nullptr);
Alexey Bataeve4090182018-11-02 14:54:07 +00002211 auto *RecSize = new llvm::GlobalVariable(
2212 CGM.getModule(), CGM.SizeTy, /*isConstant=*/true,
2213 llvm::GlobalValue::InternalLinkage, nullptr,
2214 "_openmp_static_kernel$size");
2215 RecSize->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2216 llvm::Value *Ld = CGF.EmitLoadOfScalar(
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002217 Address(RecSize, CGM.getSizeAlign()), /*Volatile=*/false,
Alexey Bataeve4090182018-11-02 14:54:07 +00002218 CGM.getContext().getSizeType(), Loc);
2219 llvm::Value *ResAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2220 KernelStaticGlobalized, CGM.VoidPtrPtrTy);
Alexey Bataev8e009032019-01-04 17:25:09 +00002221 llvm::Value *GlobalRecordSizeArg[] = {
2222 llvm::ConstantInt::get(
2223 CGM.Int16Ty,
2224 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD ? 1 : 0),
2225 StaticGlobalized, Ld, IsInSharedMemory, ResAddr};
Alexey Bataeve4090182018-11-02 14:54:07 +00002226 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2227 OMPRTL_NVPTX__kmpc_get_team_static_memory),
2228 GlobalRecordSizeArg);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002229 GlobalizedRecords.back().Buffer = StaticGlobalized;
Alexey Bataeve4090182018-11-02 14:54:07 +00002230 GlobalizedRecords.back().RecSize = RecSize;
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002231 GlobalizedRecords.back().UseSharedMemory = UseSharedMemory;
2232 GlobalizedRecords.back().Loc = Loc;
Alexey Bataeve4090182018-11-02 14:54:07 +00002233 }
2234 assert(KernelStaticGlobalized && "Global address must be set already.");
2235 Address FrameAddr = CGF.EmitLoadOfPointer(
2236 Address(KernelStaticGlobalized, CGM.getPointerAlign()),
2237 CGM.getContext()
2238 .getPointerType(CGM.getContext().VoidPtrTy)
2239 .castAs<PointerType>());
2240 llvm::Value *GlobalRecValue =
2241 Bld.CreateConstInBoundsGEP(FrameAddr, Offset, CharUnits::One())
2242 .getPointer();
2243 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2244 I->getSecond().IsInSPMDModeFlag = nullptr;
2245 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2246 GlobalRecValue, CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo());
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002247 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002248 // TODO: allow the usage of shared memory to be controlled by
2249 // the user, for now, default to global.
2250 llvm::Value *GlobalRecordSizeArg[] = {
2251 llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize),
2252 CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002253 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2254 createNVPTXRuntimeFunction(
2255 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2256 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002257 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002258 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002259 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2260 I->getSecond().IsInSPMDModeFlag = nullptr;
2261 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002262 LValue Base =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002263 CGF.MakeNaturalAlignPointeeAddrLValue(GlobalRecCastAddr, GlobalRecTy);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002264
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002265 // Emit the "global alloca" which is a GEP from the global declaration
2266 // record using the pointer returned by the runtime.
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002267 LValue SecBase;
2268 decltype(I->getSecond().LocalVarData)::const_iterator SecIt;
2269 if (IsTTD) {
2270 SecIt = I->getSecond().SecondaryLocalVarData->begin();
2271 llvm::PointerType *SecGlobalRecPtrTy =
2272 CGF.ConvertTypeForMem(SecGlobalRecTy)->getPointerTo();
2273 SecBase = CGF.MakeNaturalAlignPointeeAddrLValue(
2274 Bld.CreatePointerBitCastOrAddrSpaceCast(
2275 I->getSecond().GlobalRecordAddr, SecGlobalRecPtrTy),
2276 SecGlobalRecTy);
2277 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002278 for (auto &Rec : I->getSecond().LocalVarData) {
2279 bool EscapedParam = I->getSecond().EscapedParameters.count(Rec.first);
2280 llvm::Value *ParValue;
2281 if (EscapedParam) {
2282 const auto *VD = cast<VarDecl>(Rec.first);
2283 LValue ParLVal =
2284 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
2285 ParValue = CGF.EmitLoadOfScalar(ParLVal, Loc);
2286 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002287 LValue VarAddr = CGF.EmitLValueForField(Base, Rec.second.FD);
2288 // Emit VarAddr basing on lane-id if required.
2289 QualType VarTy;
2290 if (Rec.second.IsOnePerTeam) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002291 VarTy = Rec.second.FD->getType();
2292 } else {
2293 llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(
2294 VarAddr.getAddress().getPointer(),
2295 {Bld.getInt32(0), getNVPTXLaneID(CGF)});
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002296 VarTy =
2297 Rec.second.FD->getType()->castAsArrayTypeUnsafe()->getElementType();
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002298 VarAddr = CGF.MakeAddrLValue(
2299 Address(Ptr, CGM.getContext().getDeclAlign(Rec.first)), VarTy,
2300 AlignmentSource::Decl);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002301 }
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002302 Rec.second.PrivateAddr = VarAddr.getAddress();
Alexey Bataeve4090182018-11-02 14:54:07 +00002303 if (!IsInTTDRegion &&
2304 (WithSPMDCheck ||
2305 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002306 assert(I->getSecond().IsInSPMDModeFlag &&
2307 "Expected unknown execution mode or required SPMD check.");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002308 if (IsTTD) {
2309 assert(SecIt->second.IsOnePerTeam &&
2310 "Secondary glob data must be one per team.");
2311 LValue SecVarAddr = CGF.EmitLValueForField(SecBase, SecIt->second.FD);
2312 VarAddr.setAddress(
2313 Address(Bld.CreateSelect(IsTTD, SecVarAddr.getPointer(),
2314 VarAddr.getPointer()),
2315 VarAddr.getAlignment()));
2316 Rec.second.PrivateAddr = VarAddr.getAddress();
2317 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002318 Address GlobalPtr = Rec.second.PrivateAddr;
2319 Address LocalAddr = CGF.CreateMemTemp(VarTy, Rec.second.FD->getName());
2320 Rec.second.PrivateAddr = Address(
2321 Bld.CreateSelect(I->getSecond().IsInSPMDModeFlag,
2322 LocalAddr.getPointer(), GlobalPtr.getPointer()),
2323 LocalAddr.getAlignment());
2324 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002325 if (EscapedParam) {
2326 const auto *VD = cast<VarDecl>(Rec.first);
2327 CGF.EmitStoreOfScalar(ParValue, VarAddr);
2328 I->getSecond().MappedParams->setVarAddr(CGF, VD, VarAddr.getAddress());
2329 }
Alexey Bataev93a38d62018-10-16 00:09:06 +00002330 if (IsTTD)
2331 ++SecIt;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002332 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002333 }
2334 for (const ValueDecl *VD : I->getSecond().EscapedVariableLengthDecls) {
2335 // Recover pointer to this function's global record. The runtime will
2336 // handle the specifics of the allocation of the memory.
2337 // Use actual memory size of the record including the padding
2338 // for alignment purposes.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002339 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002340 llvm::Value *Size = CGF.getTypeSize(VD->getType());
2341 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2342 Size = Bld.CreateNUWAdd(
2343 Size, llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity() - 1));
2344 llvm::Value *AlignVal =
2345 llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity());
2346 Size = Bld.CreateUDiv(Size, AlignVal);
2347 Size = Bld.CreateNUWMul(Size, AlignVal);
2348 // TODO: allow the usage of shared memory to be controlled by
2349 // the user, for now, default to global.
2350 llvm::Value *GlobalRecordSizeArg[] = {
2351 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
2352 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002353 createNVPTXRuntimeFunction(
2354 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002355 GlobalRecordSizeArg);
2356 llvm::Value *GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2357 GlobalRecValue, CGF.ConvertTypeForMem(VD->getType())->getPointerTo());
2358 LValue Base = CGF.MakeAddrLValue(GlobalRecCastAddr, VD->getType(),
2359 CGM.getContext().getDeclAlign(VD),
2360 AlignmentSource::Decl);
2361 I->getSecond().MappedParams->setVarAddr(CGF, cast<VarDecl>(VD),
2362 Base.getAddress());
2363 I->getSecond().EscapedVariableLengthDeclsAddrs.emplace_back(GlobalRecValue);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002364 }
2365 I->getSecond().MappedParams->apply(CGF);
2366}
2367
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002368void CGOpenMPRuntimeNVPTX::emitGenericVarsEpilog(CodeGenFunction &CGF,
2369 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002370 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2371 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002372 return;
2373
Alexey Bataevc99042b2018-03-15 18:10:54 +00002374 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002375 if (I != FunctionGlobalizedDecls.end()) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00002376 I->getSecond().MappedParams->restore(CGF);
2377 if (!CGF.HaveInsertPoint())
2378 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002379 for (llvm::Value *Addr :
2380 llvm::reverse(I->getSecond().EscapedVariableLengthDeclsAddrs)) {
2381 CGF.EmitRuntimeCall(
2382 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2383 Addr);
2384 }
2385 if (I->getSecond().GlobalRecordAddr) {
Alexey Bataeve4090182018-11-02 14:54:07 +00002386 if (!IsInTTDRegion &&
2387 (WithSPMDCheck ||
2388 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002389 CGBuilderTy &Bld = CGF.Builder;
2390 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2391 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
2392 Bld.CreateCondBr(I->getSecond().IsInSPMDModeFlag, ExitBB, NonSPMDBB);
2393 // There is no need to emit line number for unconditional branch.
2394 (void)ApplyDebugLocation::CreateEmpty(CGF);
2395 CGF.EmitBlock(NonSPMDBB);
2396 CGF.EmitRuntimeCall(
2397 createNVPTXRuntimeFunction(
2398 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2399 CGF.EmitCastToVoidPtr(I->getSecond().GlobalRecordAddr));
2400 CGF.EmitBlock(ExitBB);
Alexey Bataeve4090182018-11-02 14:54:07 +00002401 } else if (IsInTTDRegion) {
2402 assert(GlobalizedRecords.back().RegionCounter > 0 &&
2403 "region counter must be > 0.");
2404 --GlobalizedRecords.back().RegionCounter;
2405 // Emit the restore function only in the target region.
2406 if (GlobalizedRecords.back().RegionCounter == 0) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002407 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2408 /*DestWidth=*/16, /*Signed=*/0);
2409 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2410 Address(GlobalizedRecords.back().UseSharedMemory,
2411 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2412 /*Volatile=*/false, Int16Ty, GlobalizedRecords.back().Loc);
Alexey Bataev8e009032019-01-04 17:25:09 +00002413 llvm::Value *Args[] = {
2414 llvm::ConstantInt::get(
2415 CGM.Int16Ty,
2416 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD ? 1 : 0),
2417 IsInSharedMemory};
Alexey Bataeve4090182018-11-02 14:54:07 +00002418 CGF.EmitRuntimeCall(
2419 createNVPTXRuntimeFunction(
2420 OMPRTL_NVPTX__kmpc_restore_team_static_memory),
Alexey Bataev8e009032019-01-04 17:25:09 +00002421 Args);
Alexey Bataeve4090182018-11-02 14:54:07 +00002422 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002423 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002424 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2425 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2426 I->getSecond().GlobalRecordAddr);
2427 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002428 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00002429 }
2430}
2431
Carlo Bertollic6872252016-04-04 15:55:02 +00002432void CGOpenMPRuntimeNVPTX::emitTeamsCall(CodeGenFunction &CGF,
2433 const OMPExecutableDirective &D,
2434 SourceLocation Loc,
2435 llvm::Value *OutlinedFn,
2436 ArrayRef<llvm::Value *> CapturedVars) {
2437 if (!CGF.HaveInsertPoint())
2438 return;
2439
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002440 Address ZeroAddr = CGF.CreateMemTemp(
2441 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2442 /*Name*/ ".zero.addr");
Carlo Bertollic6872252016-04-04 15:55:02 +00002443 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2444 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002445 OutlinedFnArgs.push_back(emitThreadIDAddress(CGF, Loc).getPointer());
Carlo Bertollic6872252016-04-04 15:55:02 +00002446 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2447 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002448 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Carlo Bertollic6872252016-04-04 15:55:02 +00002449}
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002450
2451void CGOpenMPRuntimeNVPTX::emitParallelCall(
2452 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2453 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2454 if (!CGF.HaveInsertPoint())
2455 return;
2456
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002457 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002458 emitSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002459 else
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002460 emitNonSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002461}
2462
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002463void CGOpenMPRuntimeNVPTX::emitNonSPMDParallelCall(
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002464 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2465 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2466 llvm::Function *Fn = cast<llvm::Function>(OutlinedFn);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002467
2468 // Force inline this outlined function at its call site.
2469 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
2470
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002471 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2472 /*DestWidth=*/32, /*Signed=*/1),
2473 ".zero.addr");
2474 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002475 // ThreadId for serialized parallels is 0.
2476 Address ThreadIDAddr = ZeroAddr;
2477 auto &&CodeGen = [this, Fn, CapturedVars, Loc, ZeroAddr, &ThreadIDAddr](
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002478 CodeGenFunction &CGF, PrePostActionTy &Action) {
2479 Action.Enter(CGF);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002480
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002481 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2482 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2483 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2484 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2485 emitOutlinedFunctionCall(CGF, Loc, Fn, OutlinedFnArgs);
2486 };
2487 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2488 PrePostActionTy &) {
2489
2490 RegionCodeGenTy RCG(CodeGen);
2491 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2492 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2493 llvm::Value *Args[] = {RTLoc, ThreadID};
2494
2495 NVPTXActionTy Action(
2496 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2497 Args,
2498 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2499 Args);
2500 RCG.setAction(Action);
2501 RCG(CGF);
2502 };
2503
2504 auto &&L0ParallelGen = [this, CapturedVars, Fn](CodeGenFunction &CGF,
2505 PrePostActionTy &Action) {
2506 CGBuilderTy &Bld = CGF.Builder;
2507 llvm::Function *WFn = WrapperFunctionsMap[Fn];
2508 assert(WFn && "Wrapper function does not exist!");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002509 llvm::Value *ID = Bld.CreateBitOrPointerCast(WFn, CGM.Int8PtrTy);
2510
2511 // Prepare for parallel region. Indicate the outlined function.
2512 llvm::Value *Args[] = {ID, /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002513 CGF.EmitRuntimeCall(
2514 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_prepare_parallel),
2515 Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002516
2517 // Create a private scope that will globalize the arguments
2518 // passed from the outside of the target region.
2519 CodeGenFunction::OMPPrivateScope PrivateArgScope(CGF);
2520
Raphael Isemannb23ccec2018-12-10 12:37:46 +00002521 // There's something to share.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002522 if (!CapturedVars.empty()) {
2523 // Prepare for parallel region. Indicate the outlined function.
2524 Address SharedArgs =
2525 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "shared_arg_refs");
2526 llvm::Value *SharedArgsPtr = SharedArgs.getPointer();
2527
2528 llvm::Value *DataSharingArgs[] = {
2529 SharedArgsPtr,
2530 llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size())};
2531 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2532 OMPRTL_NVPTX__kmpc_begin_sharing_variables),
2533 DataSharingArgs);
2534
2535 // Store variable address in a list of references to pass to workers.
2536 unsigned Idx = 0;
2537 ASTContext &Ctx = CGF.getContext();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002538 Address SharedArgListAddress = CGF.EmitLoadOfPointer(
2539 SharedArgs, Ctx.getPointerType(Ctx.getPointerType(Ctx.VoidPtrTy))
2540 .castAs<PointerType>());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002541 for (llvm::Value *V : CapturedVars) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002542 Address Dst = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
2543 CGF.getPointerSize());
2544 llvm::Value *PtrV;
Alexey Bataev17314212018-03-20 15:41:05 +00002545 if (V->getType()->isIntegerTy())
2546 PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
2547 else
2548 PtrV = Bld.CreatePointerBitCastOrAddrSpaceCast(V, CGF.VoidPtrTy);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002549 CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
2550 Ctx.getPointerType(Ctx.VoidPtrTy));
Alexey Bataevc99042b2018-03-15 18:10:54 +00002551 ++Idx;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002552 }
2553 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002554
2555 // Activate workers. This barrier is used by the master to signal
2556 // work for the workers.
2557 syncCTAThreads(CGF);
2558
2559 // OpenMP [2.5, Parallel Construct, p.49]
2560 // There is an implied barrier at the end of a parallel region. After the
2561 // end of a parallel region, only the master thread of the team resumes
2562 // execution of the enclosing task region.
2563 //
2564 // The master waits at this barrier until all workers are done.
2565 syncCTAThreads(CGF);
2566
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002567 if (!CapturedVars.empty())
2568 CGF.EmitRuntimeCall(
2569 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_sharing_variables));
2570
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002571 // Remember for post-processing in worker loop.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002572 Work.emplace_back(WFn);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002573 };
2574
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002575 auto &&LNParallelGen = [this, Loc, &SeqGen, &L0ParallelGen](
2576 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002577 if (IsInParallelRegion) {
2578 SeqGen(CGF, Action);
2579 } else if (IsInTargetMasterThreadRegion) {
2580 L0ParallelGen(CGF, Action);
2581 } else {
2582 // Check for master and then parallelism:
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002583 // if (__kmpc_is_spmd_exec_mode() || __kmpc_parallel_level(loc, gtid)) {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002584 // Serialized execution.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002585 // } else {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002586 // Worker call.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002587 // }
2588 CGBuilderTy &Bld = CGF.Builder;
2589 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002590 llvm::BasicBlock *SeqBB = CGF.createBasicBlock(".sequential");
2591 llvm::BasicBlock *ParallelCheckBB = CGF.createBasicBlock(".parcheck");
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002592 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
Alexey Bataev673110d2018-05-16 13:36:30 +00002593 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2594 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002595 Bld.CreateCondBr(IsSPMD, SeqBB, ParallelCheckBB);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002596 // There is no need to emit line number for unconditional branch.
2597 (void)ApplyDebugLocation::CreateEmpty(CGF);
2598 CGF.EmitBlock(ParallelCheckBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002599 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2600 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2601 llvm::Value *PL = CGF.EmitRuntimeCall(
2602 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2603 {RTLoc, ThreadID});
2604 llvm::Value *Res = Bld.CreateIsNotNull(PL);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002605 Bld.CreateCondBr(Res, SeqBB, MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002606 CGF.EmitBlock(SeqBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002607 SeqGen(CGF, Action);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002608 CGF.EmitBranch(ExitBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002609 // There is no need to emit line number for unconditional branch.
2610 (void)ApplyDebugLocation::CreateEmpty(CGF);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002611 CGF.EmitBlock(MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002612 L0ParallelGen(CGF, Action);
2613 CGF.EmitBranch(ExitBB);
2614 // There is no need to emit line number for unconditional branch.
2615 (void)ApplyDebugLocation::CreateEmpty(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002616 // Emit the continuation block for code after the if.
2617 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2618 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002619 };
2620
Alexey Bataev9ff80832018-04-16 20:16:21 +00002621 if (IfCond) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002622 emitOMPIfClause(CGF, IfCond, LNParallelGen, SeqGen);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002623 } else {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002624 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002625 RegionCodeGenTy ThenRCG(LNParallelGen);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002626 ThenRCG(CGF);
2627 }
2628}
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002629
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002630void CGOpenMPRuntimeNVPTX::emitSPMDParallelCall(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002631 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2632 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2633 // Just call the outlined function to execute the parallel region.
2634 // OutlinedFn(&GTid, &zero, CapturedStruct);
2635 //
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002636 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Carlo Bertolli79712092018-02-28 20:48:35 +00002637
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002638 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2639 /*DestWidth=*/32, /*Signed=*/1),
2640 ".zero.addr");
Carlo Bertolli79712092018-02-28 20:48:35 +00002641 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002642 // ThreadId for serialized parallels is 0.
2643 Address ThreadIDAddr = ZeroAddr;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002644 auto &&CodeGen = [this, OutlinedFn, CapturedVars, Loc, ZeroAddr,
Alexey Bataev8521ff62018-07-25 20:03:01 +00002645 &ThreadIDAddr](CodeGenFunction &CGF,
2646 PrePostActionTy &Action) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002647 Action.Enter(CGF);
2648
2649 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2650 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2651 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2652 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2653 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2654 };
2655 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2656 PrePostActionTy &) {
2657
2658 RegionCodeGenTy RCG(CodeGen);
2659 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2660 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2661 llvm::Value *Args[] = {RTLoc, ThreadID};
2662
2663 NVPTXActionTy Action(
2664 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2665 Args,
2666 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2667 Args);
2668 RCG.setAction(Action);
2669 RCG(CGF);
2670 };
2671
2672 if (IsInTargetMasterThreadRegion) {
Alexey Bataev8521ff62018-07-25 20:03:01 +00002673 // In the worker need to use the real thread id.
2674 ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002675 RegionCodeGenTy RCG(CodeGen);
2676 RCG(CGF);
2677 } else {
2678 // If we are not in the target region, it is definitely L2 parallelism or
2679 // more, because for SPMD mode we always has L1 parallel level, sowe don't
2680 // need to check for orphaned directives.
2681 RegionCodeGenTy RCG(SeqGen);
2682 RCG(CGF);
2683 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002684}
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002685
Alexey Bataeva3924b52019-01-03 16:25:35 +00002686void CGOpenMPRuntimeNVPTX::syncCTAThreads(CodeGenFunction &CGF) {
2687 // Always emit simple barriers!
2688 if (!CGF.HaveInsertPoint())
2689 return;
2690 // Build call __kmpc_barrier_simple_spmd(nullptr, 0);
2691 // This function does not use parameters, so we can emit just default values.
2692 llvm::Value *Args[] = {
2693 llvm::ConstantPointerNull::get(
2694 cast<llvm::PointerType>(getIdentTyPointerTy())),
2695 llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/0, /*isSigned=*/true)};
2696 CGF.EmitRuntimeCall(
2697 createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier_simple_spmd), Args);
2698}
2699
Alexey Bataevc3028ca2018-12-04 15:03:25 +00002700void CGOpenMPRuntimeNVPTX::emitBarrierCall(CodeGenFunction &CGF,
2701 SourceLocation Loc,
2702 OpenMPDirectiveKind Kind, bool,
2703 bool) {
2704 // Always emit simple barriers!
2705 if (!CGF.HaveInsertPoint())
2706 return;
2707 // Build call __kmpc_cancel_barrier(loc, thread_id);
2708 unsigned Flags = getDefaultFlagsForBarriers(Kind);
2709 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2710 getThreadID(CGF, Loc)};
2711 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier), Args);
2712}
2713
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002714void CGOpenMPRuntimeNVPTX::emitCriticalRegion(
2715 CodeGenFunction &CGF, StringRef CriticalName,
2716 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
2717 const Expr *Hint) {
2718 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
2719 llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
2720 llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
2721 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
2722 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
2723
2724 // Fetch team-local id of the thread.
2725 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
2726
2727 // Get the width of the team.
2728 llvm::Value *TeamWidth = getNVPTXNumThreads(CGF);
2729
2730 // Initialize the counter variable for the loop.
2731 QualType Int32Ty =
2732 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
2733 Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
2734 LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
2735 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
2736 /*isInit=*/true);
2737
2738 // Block checks if loop counter exceeds upper bound.
2739 CGF.EmitBlock(LoopBB);
2740 llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2741 llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
2742 CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
2743
2744 // Block tests which single thread should execute region, and which threads
2745 // should go straight to synchronisation point.
2746 CGF.EmitBlock(TestBB);
2747 CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2748 llvm::Value *CmpThreadToCounter =
2749 CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
2750 CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
2751
2752 // Block emits the body of the critical region.
2753 CGF.EmitBlock(BodyBB);
2754
2755 // Output the critical statement.
Alexey Bataev2c1ff9d2018-12-04 15:25:01 +00002756 CGOpenMPRuntime::emitCriticalRegion(CGF, CriticalName, CriticalOpGen, Loc,
2757 Hint);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002758
2759 // After the body surrounded by the critical region, the single executing
2760 // thread will jump to the synchronisation point.
2761 // Block waits for all threads in current team to finish then increments the
2762 // counter variable and returns to the loop.
2763 CGF.EmitBlock(SyncBB);
Alexey Bataev2c1ff9d2018-12-04 15:25:01 +00002764 emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false,
2765 /*ForceSimpleCall=*/true);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002766
2767 llvm::Value *IncCounterVal =
2768 CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
2769 CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
2770 CGF.EmitBranch(LoopBB);
2771
2772 // Block that is reached when all threads in the team complete the region.
2773 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2774}
2775
Alexey Bataevb2575932018-01-04 20:18:55 +00002776/// Cast value to the specified type.
Alexey Bataeva453f362018-03-19 17:53:56 +00002777static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
2778 QualType ValTy, QualType CastTy,
2779 SourceLocation Loc) {
2780 assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
2781 "Cast type must sized.");
2782 assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
2783 "Val type must sized.");
2784 llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
2785 if (ValTy == CastTy)
Alexey Bataevb2575932018-01-04 20:18:55 +00002786 return Val;
Alexey Bataeva453f362018-03-19 17:53:56 +00002787 if (CGF.getContext().getTypeSizeInChars(ValTy) ==
2788 CGF.getContext().getTypeSizeInChars(CastTy))
2789 return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
2790 if (CastTy->isIntegerType() && ValTy->isIntegerType())
2791 return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
2792 CastTy->hasSignedIntegerRepresentation());
2793 Address CastItem = CGF.CreateMemTemp(CastTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002794 Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2795 CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
Alexey Bataeva453f362018-03-19 17:53:56 +00002796 CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy);
2797 return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc);
Alexey Bataevb2575932018-01-04 20:18:55 +00002798}
2799
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002800/// This function creates calls to one of two shuffle functions to copy
2801/// variables between lanes in a warp.
2802static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002803 llvm::Value *Elem,
Alexey Bataeva453f362018-03-19 17:53:56 +00002804 QualType ElemType,
2805 llvm::Value *Offset,
2806 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002807 CodeGenModule &CGM = CGF.CGM;
2808 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002809 CGOpenMPRuntimeNVPTX &RT =
2810 *(static_cast<CGOpenMPRuntimeNVPTX *>(&CGM.getOpenMPRuntime()));
2811
Alexey Bataeva453f362018-03-19 17:53:56 +00002812 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2813 assert(Size.getQuantity() <= 8 &&
2814 "Unsupported bitwidth in shuffle instruction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002815
Alexey Bataeva453f362018-03-19 17:53:56 +00002816 OpenMPRTLFunctionNVPTX ShuffleFn = Size.getQuantity() <= 4
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002817 ? OMPRTL_NVPTX__kmpc_shuffle_int32
2818 : OMPRTL_NVPTX__kmpc_shuffle_int64;
2819
2820 // Cast all types to 32- or 64-bit values before calling shuffle routines.
Alexey Bataeva453f362018-03-19 17:53:56 +00002821 QualType CastTy = CGF.getContext().getIntTypeForBitwidth(
2822 Size.getQuantity() <= 4 ? 32 : 64, /*Signed=*/1);
2823 llvm::Value *ElemCast = castValueToType(CGF, Elem, ElemType, CastTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002824 llvm::Value *WarpSize =
Alexey Bataevb2575932018-01-04 20:18:55 +00002825 Bld.CreateIntCast(getNVPTXWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002826
Alexey Bataev9ff80832018-04-16 20:16:21 +00002827 llvm::Value *ShuffledVal = CGF.EmitRuntimeCall(
2828 RT.createNVPTXRuntimeFunction(ShuffleFn), {ElemCast, Offset, WarpSize});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002829
Alexey Bataeva453f362018-03-19 17:53:56 +00002830 return castValueToType(CGF, ShuffledVal, CastTy, ElemType, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002831}
2832
Alexey Bataev12c62902018-06-22 19:10:38 +00002833static void shuffleAndStore(CodeGenFunction &CGF, Address SrcAddr,
2834 Address DestAddr, QualType ElemType,
2835 llvm::Value *Offset, SourceLocation Loc) {
2836 CGBuilderTy &Bld = CGF.Builder;
2837
2838 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2839 // Create the loop over the big sized data.
2840 // ptr = (void*)Elem;
2841 // ptrEnd = (void*) Elem + 1;
2842 // Step = 8;
2843 // while (ptr + Step < ptrEnd)
2844 // shuffle((int64_t)*ptr);
2845 // Step = 4;
2846 // while (ptr + Step < ptrEnd)
2847 // shuffle((int32_t)*ptr);
2848 // ...
2849 Address ElemPtr = DestAddr;
2850 Address Ptr = SrcAddr;
2851 Address PtrEnd = Bld.CreatePointerBitCastOrAddrSpaceCast(
2852 Bld.CreateConstGEP(SrcAddr, 1, Size), CGF.VoidPtrTy);
2853 for (int IntSize = 8; IntSize >= 1; IntSize /= 2) {
2854 if (Size < CharUnits::fromQuantity(IntSize))
2855 continue;
2856 QualType IntType = CGF.getContext().getIntTypeForBitwidth(
2857 CGF.getContext().toBits(CharUnits::fromQuantity(IntSize)),
2858 /*Signed=*/1);
2859 llvm::Type *IntTy = CGF.ConvertTypeForMem(IntType);
2860 Ptr = Bld.CreatePointerBitCastOrAddrSpaceCast(Ptr, IntTy->getPointerTo());
2861 ElemPtr =
2862 Bld.CreatePointerBitCastOrAddrSpaceCast(ElemPtr, IntTy->getPointerTo());
2863 if (Size.getQuantity() / IntSize > 1) {
2864 llvm::BasicBlock *PreCondBB = CGF.createBasicBlock(".shuffle.pre_cond");
2865 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".shuffle.then");
2866 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".shuffle.exit");
2867 llvm::BasicBlock *CurrentBB = Bld.GetInsertBlock();
2868 CGF.EmitBlock(PreCondBB);
2869 llvm::PHINode *PhiSrc =
2870 Bld.CreatePHI(Ptr.getType(), /*NumReservedValues=*/2);
2871 PhiSrc->addIncoming(Ptr.getPointer(), CurrentBB);
2872 llvm::PHINode *PhiDest =
2873 Bld.CreatePHI(ElemPtr.getType(), /*NumReservedValues=*/2);
2874 PhiDest->addIncoming(ElemPtr.getPointer(), CurrentBB);
2875 Ptr = Address(PhiSrc, Ptr.getAlignment());
2876 ElemPtr = Address(PhiDest, ElemPtr.getAlignment());
2877 llvm::Value *PtrDiff = Bld.CreatePtrDiff(
2878 PtrEnd.getPointer(), Bld.CreatePointerBitCastOrAddrSpaceCast(
2879 Ptr.getPointer(), CGF.VoidPtrTy));
2880 Bld.CreateCondBr(Bld.CreateICmpSGT(PtrDiff, Bld.getInt64(IntSize - 1)),
2881 ThenBB, ExitBB);
2882 CGF.EmitBlock(ThenBB);
2883 llvm::Value *Res = createRuntimeShuffleFunction(
2884 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2885 IntType, Offset, Loc);
2886 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002887 Address LocalPtr =
2888 Bld.CreateConstGEP(Ptr, 1, CharUnits::fromQuantity(IntSize));
2889 Address LocalElemPtr =
Alexey Bataev12c62902018-06-22 19:10:38 +00002890 Bld.CreateConstGEP(ElemPtr, 1, CharUnits::fromQuantity(IntSize));
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002891 PhiSrc->addIncoming(LocalPtr.getPointer(), ThenBB);
2892 PhiDest->addIncoming(LocalElemPtr.getPointer(), ThenBB);
Alexey Bataev12c62902018-06-22 19:10:38 +00002893 CGF.EmitBranch(PreCondBB);
2894 CGF.EmitBlock(ExitBB);
2895 } else {
2896 llvm::Value *Res = createRuntimeShuffleFunction(
2897 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2898 IntType, Offset, Loc);
2899 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
2900 Ptr = Bld.CreateConstGEP(Ptr, 1, CharUnits::fromQuantity(IntSize));
2901 ElemPtr =
2902 Bld.CreateConstGEP(ElemPtr, 1, CharUnits::fromQuantity(IntSize));
2903 }
2904 Size = Size % IntSize;
2905 }
2906}
2907
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002908namespace {
2909enum CopyAction : unsigned {
2910 // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
2911 // the warp using shuffle instructions.
2912 RemoteLaneToThread,
2913 // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
2914 ThreadCopy,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002915 // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
2916 ThreadToScratchpad,
2917 // ScratchpadToThread: Copy from a scratchpad array in global memory
2918 // containing team-reduced data to a thread's stack.
2919 ScratchpadToThread,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002920};
2921} // namespace
2922
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002923struct CopyOptionsTy {
2924 llvm::Value *RemoteLaneOffset;
2925 llvm::Value *ScratchpadIndex;
2926 llvm::Value *ScratchpadWidth;
2927};
2928
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002929/// Emit instructions to copy a Reduce list, which contains partially
2930/// aggregated values, in the specified direction.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002931static void emitReductionListCopy(
2932 CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
2933 ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
2934 CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002935
Alexey Bataev9ff80832018-04-16 20:16:21 +00002936 CodeGenModule &CGM = CGF.CGM;
2937 ASTContext &C = CGM.getContext();
2938 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002939
Alexey Bataev9ff80832018-04-16 20:16:21 +00002940 llvm::Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
2941 llvm::Value *ScratchpadIndex = CopyOptions.ScratchpadIndex;
2942 llvm::Value *ScratchpadWidth = CopyOptions.ScratchpadWidth;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002943
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002944 // Iterates, element-by-element, through the source Reduce list and
2945 // make a copy.
2946 unsigned Idx = 0;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002947 unsigned Size = Privates.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00002948 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002949 Address SrcElementAddr = Address::invalid();
2950 Address DestElementAddr = Address::invalid();
2951 Address DestElementPtrAddr = Address::invalid();
2952 // Should we shuffle in an element from a remote lane?
2953 bool ShuffleInElement = false;
2954 // Set to true to update the pointer in the dest Reduce list to a
2955 // newly created element.
2956 bool UpdateDestListPtr = false;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002957 // Increment the src or dest pointer to the scratchpad, for each
2958 // new element.
2959 bool IncrScratchpadSrc = false;
2960 bool IncrScratchpadDest = false;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002961
2962 switch (Action) {
2963 case RemoteLaneToThread: {
2964 // Step 1.1: Get the address for the src element in the Reduce list.
2965 Address SrcElementPtrAddr =
2966 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002967 SrcElementAddr = CGF.EmitLoadOfPointer(
2968 SrcElementPtrAddr,
2969 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002970
2971 // Step 1.2: Create a temporary to store the element in the destination
2972 // Reduce list.
2973 DestElementPtrAddr =
2974 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
2975 DestElementAddr =
2976 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2977 ShuffleInElement = true;
2978 UpdateDestListPtr = true;
2979 break;
2980 }
2981 case ThreadCopy: {
2982 // Step 1.1: Get the address for the src element in the Reduce list.
2983 Address SrcElementPtrAddr =
2984 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002985 SrcElementAddr = CGF.EmitLoadOfPointer(
2986 SrcElementPtrAddr,
2987 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002988
2989 // Step 1.2: Get the address for dest element. The destination
2990 // element has already been created on the thread's stack.
2991 DestElementPtrAddr =
2992 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002993 DestElementAddr = CGF.EmitLoadOfPointer(
2994 DestElementPtrAddr,
2995 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002996 break;
2997 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002998 case ThreadToScratchpad: {
2999 // Step 1.1: Get the address for the src element in the Reduce list.
3000 Address SrcElementPtrAddr =
3001 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00003002 SrcElementAddr = CGF.EmitLoadOfPointer(
3003 SrcElementPtrAddr,
3004 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003005
3006 // Step 1.2: Get the address for dest element:
3007 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00003008 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00003009 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003010 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003011 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003012 Bld.CreateNUWAdd(DestBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003013 ScratchPadElemAbsolutePtrVal =
3014 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00003015 DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
3016 C.getTypeAlignInChars(Private->getType()));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003017 IncrScratchpadDest = true;
3018 break;
3019 }
3020 case ScratchpadToThread: {
3021 // Step 1.1: Get the address for the src element in the scratchpad.
3022 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00003023 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00003024 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003025 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003026 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003027 Bld.CreateNUWAdd(SrcBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003028 ScratchPadElemAbsolutePtrVal =
3029 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
3030 SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
3031 C.getTypeAlignInChars(Private->getType()));
3032 IncrScratchpadSrc = true;
3033
3034 // Step 1.2: Create a temporary to store the element in the destination
3035 // Reduce list.
3036 DestElementPtrAddr =
3037 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
3038 DestElementAddr =
3039 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
3040 UpdateDestListPtr = true;
3041 break;
3042 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003043 }
3044
3045 // Regardless of src and dest of copy, we emit the load of src
3046 // element as this is required in all directions
3047 SrcElementAddr = Bld.CreateElementBitCast(
3048 SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
Alexey Bataev12c62902018-06-22 19:10:38 +00003049 DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
3050 SrcElementAddr.getElementType());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003051
3052 // Now that all active lanes have read the element in the
3053 // Reduce list, shuffle over the value from the remote lane.
Alexey Bataeva453f362018-03-19 17:53:56 +00003054 if (ShuffleInElement) {
Alexey Bataev12c62902018-06-22 19:10:38 +00003055 shuffleAndStore(CGF, SrcElementAddr, DestElementAddr, Private->getType(),
3056 RemoteLaneOffset, Private->getExprLoc());
3057 } else {
3058 if (Private->getType()->isScalarType()) {
3059 llvm::Value *Elem =
3060 CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false,
3061 Private->getType(), Private->getExprLoc());
3062 // Store the source element value to the dest element address.
3063 CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false,
3064 Private->getType());
3065 } else {
3066 CGF.EmitAggregateCopy(
3067 CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3068 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3069 Private->getType(), AggValueSlot::DoesNotOverlap);
3070 }
Alexey Bataeva453f362018-03-19 17:53:56 +00003071 }
Alexey Bataevb2575932018-01-04 20:18:55 +00003072
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003073 // Step 3.1: Modify reference in dest Reduce list as needed.
3074 // Modifying the reference in Reduce list to point to the newly
3075 // created element. The element is live in the current function
3076 // scope and that of functions it invokes (i.e., reduce_function).
3077 // RemoteReduceData[i] = (void*)&RemoteElem
3078 if (UpdateDestListPtr) {
3079 CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
3080 DestElementAddr.getPointer(), CGF.VoidPtrTy),
3081 DestElementPtrAddr, /*Volatile=*/false,
3082 C.VoidPtrTy);
3083 }
3084
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003085 // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
3086 // address of the next element in scratchpad memory, unless we're currently
3087 // processing the last one. Memory alignment is also taken care of here.
3088 if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
3089 llvm::Value *ScratchpadBasePtr =
3090 IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
Alexey Bataeve290ec02018-04-06 16:03:36 +00003091 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
3092 ScratchpadBasePtr = Bld.CreateNUWAdd(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003093 ScratchpadBasePtr,
Alexey Bataeve290ec02018-04-06 16:03:36 +00003094 Bld.CreateNUWMul(ScratchpadWidth, ElementSizeInChars));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003095
3096 // Take care of global memory alignment for performance
Alexey Bataeve290ec02018-04-06 16:03:36 +00003097 ScratchpadBasePtr = Bld.CreateNUWSub(
3098 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3099 ScratchpadBasePtr = Bld.CreateUDiv(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003100 ScratchpadBasePtr,
3101 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
Alexey Bataeve290ec02018-04-06 16:03:36 +00003102 ScratchpadBasePtr = Bld.CreateNUWAdd(
3103 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3104 ScratchpadBasePtr = Bld.CreateNUWMul(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003105 ScratchpadBasePtr,
3106 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
3107
3108 if (IncrScratchpadDest)
3109 DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3110 else /* IncrScratchpadSrc = true */
3111 SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3112 }
3113
Alexey Bataev9ff80832018-04-16 20:16:21 +00003114 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003115 }
3116}
3117
3118/// This function emits a helper that gathers Reduce lists from the first
3119/// lane of every active warp to lanes in the first warp.
3120///
3121/// void inter_warp_copy_func(void* reduce_data, num_warps)
3122/// shared smem[warp_size];
3123/// For all data entries D in reduce_data:
Alexey Bataev29d47fc2018-12-18 19:20:15 +00003124/// sync
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003125/// If (I am the first lane in each warp)
3126/// Copy my local D to smem[warp_id]
3127/// sync
3128/// if (I am the first warp)
3129/// Copy smem[thread_id] to my local D
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003130static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
3131 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003132 QualType ReductionArrayTy,
3133 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003134 ASTContext &C = CGM.getContext();
3135 llvm::Module &M = CGM.getModule();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003136
3137 // ReduceList: thread local Reduce list.
3138 // At the stage of the computation when this function is called, partially
3139 // aggregated values reside in the first lane of every active warp.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003140 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3141 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003142 // NumWarps: number of warps active in the parallel region. This could
3143 // be smaller than 32 (max warps in a CTA) for partial block reduction.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003144 ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00003145 C.getIntTypeForBitwidth(32, /* Signed */ true),
3146 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003147 FunctionArgList Args;
3148 Args.push_back(&ReduceListArg);
3149 Args.push_back(&NumWarpsArg);
3150
Alexey Bataev9ff80832018-04-16 20:16:21 +00003151 const CGFunctionInfo &CGFI =
3152 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003153 auto *Fn = llvm::Function::Create(
3154 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3155 "_omp_reduction_inter_warp_copy_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003156 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003157 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003158 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003159 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003160
Alexey Bataev9ff80832018-04-16 20:16:21 +00003161 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003162
3163 // This array is used as a medium to transfer, one reduce element at a time,
3164 // the data from the first lane of every warp to lanes in the first warp
3165 // in order to perform the final step of a reduction in a parallel region
3166 // (reduction across warps). The array is placed in NVPTX __shared__ memory
3167 // for reduced latency, as well as to have a distinct copy for concurrently
3168 // executing target regions. The array is declared with common linkage so
3169 // as to be shared across compilation units.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003170 StringRef TransferMediumName =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003171 "__openmp_nvptx_data_transfer_temporary_storage";
3172 llvm::GlobalVariable *TransferMedium =
3173 M.getGlobalVariable(TransferMediumName);
3174 if (!TransferMedium) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003175 auto *Ty = llvm::ArrayType::get(CGM.Int32Ty, WarpSize);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003176 unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
3177 TransferMedium = new llvm::GlobalVariable(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003178 M, Ty, /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003179 llvm::Constant::getNullValue(Ty), TransferMediumName,
3180 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3181 SharedAddressSpace);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003182 CGM.addCompilerUsedGlobal(TransferMedium);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003183 }
3184
3185 // Get the CUDA thread id of the current OpenMP thread on the GPU.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003186 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003187 // nvptx_lane_id = nvptx_id % warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003188 llvm::Value *LaneID = getNVPTXLaneID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003189 // nvptx_warp_id = nvptx_id / warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003190 llvm::Value *WarpID = getNVPTXWarpID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003191
3192 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3193 Address LocalReduceList(
3194 Bld.CreatePointerBitCastOrAddrSpaceCast(
3195 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003196 C.VoidPtrTy, Loc),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003197 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3198 CGF.getPointerAlign());
3199
3200 unsigned Idx = 0;
Alexey Bataev9ff80832018-04-16 20:16:21 +00003201 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003202 //
3203 // Warp master copies reduce element to transfer medium in __shared__
3204 // memory.
3205 //
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003206 unsigned RealTySize =
3207 C.getTypeSizeInChars(Private->getType())
3208 .alignTo(C.getTypeAlignInChars(Private->getType()))
3209 .getQuantity();
3210 for (unsigned TySize = 4; TySize > 0 && RealTySize > 0; TySize /=2) {
3211 unsigned NumIters = RealTySize / TySize;
3212 if (NumIters == 0)
3213 continue;
3214 QualType CType = C.getIntTypeForBitwidth(
3215 C.toBits(CharUnits::fromQuantity(TySize)), /*Signed=*/1);
3216 llvm::Type *CopyType = CGF.ConvertTypeForMem(CType);
3217 CharUnits Align = CharUnits::fromQuantity(TySize);
3218 llvm::Value *Cnt = nullptr;
3219 Address CntAddr = Address::invalid();
3220 llvm::BasicBlock *PrecondBB = nullptr;
3221 llvm::BasicBlock *ExitBB = nullptr;
3222 if (NumIters > 1) {
3223 CntAddr = CGF.CreateMemTemp(C.IntTy, ".cnt.addr");
3224 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.IntTy), CntAddr,
3225 /*Volatile=*/false, C.IntTy);
3226 PrecondBB = CGF.createBasicBlock("precond");
3227 ExitBB = CGF.createBasicBlock("exit");
3228 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("body");
3229 // There is no need to emit line number for unconditional branch.
3230 (void)ApplyDebugLocation::CreateEmpty(CGF);
3231 CGF.EmitBlock(PrecondBB);
3232 Cnt = CGF.EmitLoadOfScalar(CntAddr, /*Volatile=*/false, C.IntTy, Loc);
3233 llvm::Value *Cmp =
3234 Bld.CreateICmpULT(Cnt, llvm::ConstantInt::get(CGM.IntTy, NumIters));
3235 Bld.CreateCondBr(Cmp, BodyBB, ExitBB);
3236 CGF.EmitBlock(BodyBB);
3237 }
Alexey Bataev29d47fc2018-12-18 19:20:15 +00003238 // kmpc_barrier.
3239 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3240 /*EmitChecks=*/false,
3241 /*ForceSimpleCall=*/true);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003242 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3243 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3244 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003245
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003246 // if (lane_id == 0)
3247 llvm::Value *IsWarpMaster = Bld.CreateIsNull(LaneID, "warp_master");
3248 Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
3249 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003250
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003251 // Reduce element = LocalReduceList[i]
3252 Address ElemPtrPtrAddr =
3253 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
3254 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3255 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3256 // elemptr = ((CopyType*)(elemptrptr)) + I
3257 Address ElemPtr = Address(ElemPtrPtr, Align);
3258 ElemPtr = Bld.CreateElementBitCast(ElemPtr, CopyType);
3259 if (NumIters > 1) {
3260 ElemPtr = Address(Bld.CreateGEP(ElemPtr.getPointer(), Cnt),
3261 ElemPtr.getAlignment());
3262 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003263
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003264 // Get pointer to location in transfer medium.
3265 // MediumPtr = &medium[warp_id]
3266 llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
3267 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
3268 Address MediumPtr(MediumPtrVal, Align);
3269 // Casting to actual data type.
3270 // MediumPtr = (CopyType*)MediumPtrAddr;
3271 MediumPtr = Bld.CreateElementBitCast(MediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003272
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003273 // elem = *elemptr
3274 //*MediumPtr = elem
3275 llvm::Value *Elem =
3276 CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003277 // Store the source element value to the dest element address.
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003278 CGF.EmitStoreOfScalar(Elem, MediumPtr, /*Volatile=*/true, CType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003279
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003280 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003281
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003282 CGF.EmitBlock(ElseBB);
3283 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003284
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003285 CGF.EmitBlock(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003286
Alexey Bataevae51b962018-12-14 21:00:58 +00003287 // kmpc_barrier.
3288 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3289 /*EmitChecks=*/false,
3290 /*ForceSimpleCall=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003291
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003292 //
3293 // Warp 0 copies reduce element from transfer medium.
3294 //
3295 llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
3296 llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
3297 llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003298
Alexey Bataevae51b962018-12-14 21:00:58 +00003299 Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
3300 llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
3301 AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, Loc);
3302
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003303 // Up to 32 threads in warp 0 are active.
3304 llvm::Value *IsActiveThread =
3305 Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
3306 Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003307
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003308 CGF.EmitBlock(W0ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003309
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003310 // SrcMediumPtr = &medium[tid]
3311 llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
3312 TransferMedium,
3313 {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
3314 Address SrcMediumPtr(SrcMediumPtrVal, Align);
3315 // SrcMediumVal = *SrcMediumPtr;
3316 SrcMediumPtr = Bld.CreateElementBitCast(SrcMediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003317
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003318 // TargetElemPtr = (CopyType*)(SrcDataAddr[i]) + I
3319 Address TargetElemPtrPtr =
3320 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
3321 llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
3322 TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, Loc);
3323 Address TargetElemPtr = Address(TargetElemPtrVal, Align);
3324 TargetElemPtr = Bld.CreateElementBitCast(TargetElemPtr, CopyType);
3325 if (NumIters > 1) {
3326 TargetElemPtr = Address(Bld.CreateGEP(TargetElemPtr.getPointer(), Cnt),
3327 TargetElemPtr.getAlignment());
3328 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003329
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003330 // *TargetElemPtr = SrcMediumVal;
3331 llvm::Value *SrcMediumValue =
3332 CGF.EmitLoadOfScalar(SrcMediumPtr, /*Volatile=*/true, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003333 CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003334 CType);
3335 Bld.CreateBr(W0MergeBB);
3336
3337 CGF.EmitBlock(W0ElseBB);
3338 Bld.CreateBr(W0MergeBB);
3339
3340 CGF.EmitBlock(W0MergeBB);
3341
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003342 if (NumIters > 1) {
3343 Cnt = Bld.CreateNSWAdd(Cnt, llvm::ConstantInt::get(CGM.IntTy, /*V=*/1));
3344 CGF.EmitStoreOfScalar(Cnt, CntAddr, /*Volatile=*/false, C.IntTy);
3345 CGF.EmitBranch(PrecondBB);
3346 (void)ApplyDebugLocation::CreateEmpty(CGF);
3347 CGF.EmitBlock(ExitBB);
3348 }
3349 RealTySize %= TySize;
Alexey Bataev12c62902018-06-22 19:10:38 +00003350 }
Alexey Bataev9ff80832018-04-16 20:16:21 +00003351 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003352 }
3353
3354 CGF.FinishFunction();
3355 return Fn;
3356}
3357
3358/// Emit a helper that reduces data across two OpenMP threads (lanes)
3359/// in the same warp. It uses shuffle instructions to copy over data from
3360/// a remote lane's stack. The reduction algorithm performed is specified
3361/// by the fourth parameter.
3362///
3363/// Algorithm Versions.
3364/// Full Warp Reduce (argument value 0):
3365/// This algorithm assumes that all 32 lanes are active and gathers
3366/// data from these 32 lanes, producing a single resultant value.
3367/// Contiguous Partial Warp Reduce (argument value 1):
3368/// This algorithm assumes that only a *contiguous* subset of lanes
3369/// are active. This happens for the last warp in a parallel region
3370/// when the user specified num_threads is not an integer multiple of
3371/// 32. This contiguous subset always starts with the zeroth lane.
3372/// Partial Warp Reduce (argument value 2):
3373/// This algorithm gathers data from any number of lanes at any position.
3374/// All reduced values are stored in the lowest possible lane. The set
3375/// of problems every algorithm addresses is a super set of those
3376/// addressable by algorithms with a lower version number. Overhead
3377/// increases as algorithm version increases.
3378///
3379/// Terminology
3380/// Reduce element:
3381/// Reduce element refers to the individual data field with primitive
3382/// data types to be combined and reduced across threads.
3383/// Reduce list:
3384/// Reduce list refers to a collection of local, thread-private
3385/// reduce elements.
3386/// Remote Reduce list:
3387/// Remote Reduce list refers to a collection of remote (relative to
3388/// the current thread) reduce elements.
3389///
3390/// We distinguish between three states of threads that are important to
3391/// the implementation of this function.
3392/// Alive threads:
3393/// Threads in a warp executing the SIMT instruction, as distinguished from
3394/// threads that are inactive due to divergent control flow.
3395/// Active threads:
3396/// The minimal set of threads that has to be alive upon entry to this
3397/// function. The computation is correct iff active threads are alive.
3398/// Some threads are alive but they are not active because they do not
3399/// contribute to the computation in any useful manner. Turning them off
3400/// may introduce control flow overheads without any tangible benefits.
3401/// Effective threads:
3402/// In order to comply with the argument requirements of the shuffle
3403/// function, we must keep all lanes holding data alive. But at most
3404/// half of them perform value aggregation; we refer to this half of
3405/// threads as effective. The other half is simply handing off their
3406/// data.
3407///
3408/// Procedure
3409/// Value shuffle:
3410/// In this step active threads transfer data from higher lane positions
3411/// in the warp to lower lane positions, creating Remote Reduce list.
3412/// Value aggregation:
3413/// In this step, effective threads combine their thread local Reduce list
3414/// with Remote Reduce list and store the result in the thread local
3415/// Reduce list.
3416/// Value copy:
3417/// In this step, we deal with the assumption made by algorithm 2
3418/// (i.e. contiguity assumption). When we have an odd number of lanes
3419/// active, say 2k+1, only k threads will be effective and therefore k
3420/// new values will be produced. However, the Reduce list owned by the
3421/// (2k+1)th thread is ignored in the value aggregation. Therefore
3422/// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
3423/// that the contiguity assumption still holds.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003424static llvm::Value *emitShuffleAndReduceFunction(
3425 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3426 QualType ReductionArrayTy, llvm::Value *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003427 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003428
3429 // Thread local Reduce list used to host the values of data to be reduced.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003430 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3431 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003432 // Current lane id; could be logical.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003433 ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
3434 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003435 // Offset of the remote source lane relative to the current lane.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003436 ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3437 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003438 // Algorithm version. This is expected to be known at compile time.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003439 ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3440 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003441 FunctionArgList Args;
3442 Args.push_back(&ReduceListArg);
3443 Args.push_back(&LaneIDArg);
3444 Args.push_back(&RemoteLaneOffsetArg);
3445 Args.push_back(&AlgoVerArg);
3446
Alexey Bataev9ff80832018-04-16 20:16:21 +00003447 const CGFunctionInfo &CGFI =
3448 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003449 auto *Fn = llvm::Function::Create(
3450 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3451 "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003452 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003453 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003454 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003455 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003456
Alexey Bataev9ff80832018-04-16 20:16:21 +00003457 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003458
3459 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3460 Address LocalReduceList(
3461 Bld.CreatePointerBitCastOrAddrSpaceCast(
3462 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3463 C.VoidPtrTy, SourceLocation()),
3464 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3465 CGF.getPointerAlign());
3466
3467 Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
3468 llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
3469 AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3470
3471 Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
3472 llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
3473 AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3474
3475 Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
3476 llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
3477 AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3478
3479 // Create a local thread-private variable to host the Reduce list
3480 // from a remote lane.
3481 Address RemoteReduceList =
3482 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
3483
3484 // This loop iterates through the list of reduce elements and copies,
3485 // element by element, from a remote lane in the warp to RemoteReduceList,
3486 // hosted on the thread's stack.
3487 emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
3488 LocalReduceList, RemoteReduceList,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003489 {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
3490 /*ScratchpadIndex=*/nullptr,
3491 /*ScratchpadWidth=*/nullptr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003492
3493 // The actions to be performed on the Remote Reduce list is dependent
3494 // on the algorithm version.
3495 //
3496 // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
3497 // LaneId % 2 == 0 && Offset > 0):
3498 // do the reduction value aggregation
3499 //
3500 // The thread local variable Reduce list is mutated in place to host the
3501 // reduced data, which is the aggregated value produced from local and
3502 // remote lanes.
3503 //
3504 // Note that AlgoVer is expected to be a constant integer known at compile
3505 // time.
3506 // When AlgoVer==0, the first conjunction evaluates to true, making
3507 // the entire predicate true during compile time.
3508 // When AlgoVer==1, the second conjunction has only the second part to be
3509 // evaluated during runtime. Other conjunctions evaluates to false
3510 // during compile time.
3511 // When AlgoVer==2, the third conjunction has only the second part to be
3512 // evaluated during runtime. Other conjunctions evaluates to false
3513 // during compile time.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003514 llvm::Value *CondAlgo0 = Bld.CreateIsNull(AlgoVerArgVal);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003515
Alexey Bataev9ff80832018-04-16 20:16:21 +00003516 llvm::Value *Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
3517 llvm::Value *CondAlgo1 = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003518 Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
3519
Alexey Bataev9ff80832018-04-16 20:16:21 +00003520 llvm::Value *Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
3521 llvm::Value *CondAlgo2 = Bld.CreateAnd(
3522 Algo2, Bld.CreateIsNull(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1))));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003523 CondAlgo2 = Bld.CreateAnd(
3524 CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
3525
Alexey Bataev9ff80832018-04-16 20:16:21 +00003526 llvm::Value *CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003527 CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
3528
3529 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3530 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3531 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
3532 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
3533
3534 CGF.EmitBlock(ThenBB);
3535 // reduce_function(LocalReduceList, RemoteReduceList)
3536 llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3537 LocalReduceList.getPointer(), CGF.VoidPtrTy);
3538 llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3539 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003540 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3541 CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003542 Bld.CreateBr(MergeBB);
3543
3544 CGF.EmitBlock(ElseBB);
3545 Bld.CreateBr(MergeBB);
3546
3547 CGF.EmitBlock(MergeBB);
3548
3549 // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
3550 // Reduce list.
3551 Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
Alexey Bataev9ff80832018-04-16 20:16:21 +00003552 llvm::Value *CondCopy = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003553 Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
3554
3555 llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
3556 llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
3557 llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
3558 Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
3559
3560 CGF.EmitBlock(CpyThenBB);
3561 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
3562 RemoteReduceList, LocalReduceList);
3563 Bld.CreateBr(CpyMergeBB);
3564
3565 CGF.EmitBlock(CpyElseBB);
3566 Bld.CreateBr(CpyMergeBB);
3567
3568 CGF.EmitBlock(CpyMergeBB);
3569
3570 CGF.FinishFunction();
3571 return Fn;
3572}
3573
3574///
3575/// Design of OpenMP reductions on the GPU
3576///
3577/// Consider a typical OpenMP program with one or more reduction
3578/// clauses:
3579///
3580/// float foo;
3581/// double bar;
3582/// #pragma omp target teams distribute parallel for \
3583/// reduction(+:foo) reduction(*:bar)
3584/// for (int i = 0; i < N; i++) {
3585/// foo += A[i]; bar *= B[i];
3586/// }
3587///
3588/// where 'foo' and 'bar' are reduced across all OpenMP threads in
3589/// all teams. In our OpenMP implementation on the NVPTX device an
3590/// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
3591/// within a team are mapped to CUDA threads within a threadblock.
3592/// Our goal is to efficiently aggregate values across all OpenMP
3593/// threads such that:
3594///
3595/// - the compiler and runtime are logically concise, and
3596/// - the reduction is performed efficiently in a hierarchical
3597/// manner as follows: within OpenMP threads in the same warp,
3598/// across warps in a threadblock, and finally across teams on
3599/// the NVPTX device.
3600///
3601/// Introduction to Decoupling
3602///
3603/// We would like to decouple the compiler and the runtime so that the
3604/// latter is ignorant of the reduction variables (number, data types)
3605/// and the reduction operators. This allows a simpler interface
3606/// and implementation while still attaining good performance.
3607///
3608/// Pseudocode for the aforementioned OpenMP program generated by the
3609/// compiler is as follows:
3610///
3611/// 1. Create private copies of reduction variables on each OpenMP
3612/// thread: 'foo_private', 'bar_private'
3613/// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
3614/// to it and writes the result in 'foo_private' and 'bar_private'
3615/// respectively.
3616/// 3. Call the OpenMP runtime on the GPU to reduce within a team
3617/// and store the result on the team master:
3618///
Alexey Bataev8e009032019-01-04 17:25:09 +00003619/// __kmpc_nvptx_parallel_reduce_nowait_v2(...,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003620/// reduceData, shuffleReduceFn, interWarpCpyFn)
3621///
3622/// where:
3623/// struct ReduceData {
3624/// double *foo;
3625/// double *bar;
3626/// } reduceData
3627/// reduceData.foo = &foo_private
3628/// reduceData.bar = &bar_private
3629///
3630/// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
3631/// auxiliary functions generated by the compiler that operate on
3632/// variables of type 'ReduceData'. They aid the runtime perform
3633/// algorithmic steps in a data agnostic manner.
3634///
3635/// 'shuffleReduceFn' is a pointer to a function that reduces data
3636/// of type 'ReduceData' across two OpenMP threads (lanes) in the
3637/// same warp. It takes the following arguments as input:
3638///
3639/// a. variable of type 'ReduceData' on the calling lane,
3640/// b. its lane_id,
3641/// c. an offset relative to the current lane_id to generate a
3642/// remote_lane_id. The remote lane contains the second
3643/// variable of type 'ReduceData' that is to be reduced.
3644/// d. an algorithm version parameter determining which reduction
3645/// algorithm to use.
3646///
3647/// 'shuffleReduceFn' retrieves data from the remote lane using
3648/// efficient GPU shuffle intrinsics and reduces, using the
3649/// algorithm specified by the 4th parameter, the two operands
3650/// element-wise. The result is written to the first operand.
3651///
3652/// Different reduction algorithms are implemented in different
3653/// runtime functions, all calling 'shuffleReduceFn' to perform
3654/// the essential reduction step. Therefore, based on the 4th
3655/// parameter, this function behaves slightly differently to
3656/// cooperate with the runtime to ensure correctness under
3657/// different circumstances.
3658///
3659/// 'InterWarpCpyFn' is a pointer to a function that transfers
3660/// reduced variables across warps. It tunnels, through CUDA
3661/// shared memory, the thread-private data of type 'ReduceData'
3662/// from lane 0 of each warp to a lane in the first warp.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003663/// 4. Call the OpenMP runtime on the GPU to reduce across teams.
3664/// The last team writes the global reduced value to memory.
3665///
3666/// ret = __kmpc_nvptx_teams_reduce_nowait(...,
3667/// reduceData, shuffleReduceFn, interWarpCpyFn,
3668/// scratchpadCopyFn, loadAndReduceFn)
3669///
3670/// 'scratchpadCopyFn' is a helper that stores reduced
3671/// data from the team master to a scratchpad array in
3672/// global memory.
3673///
3674/// 'loadAndReduceFn' is a helper that loads data from
3675/// the scratchpad array and reduces it with the input
3676/// operand.
3677///
3678/// These compiler generated functions hide address
3679/// calculation and alignment information from the runtime.
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003680/// 5. if ret == 1:
3681/// The team master of the last team stores the reduced
3682/// result to the globals in memory.
3683/// foo += reduceData.foo; bar *= reduceData.bar
3684///
3685///
3686/// Warp Reduction Algorithms
3687///
3688/// On the warp level, we have three algorithms implemented in the
3689/// OpenMP runtime depending on the number of active lanes:
3690///
3691/// Full Warp Reduction
3692///
3693/// The reduce algorithm within a warp where all lanes are active
3694/// is implemented in the runtime as follows:
3695///
3696/// full_warp_reduce(void *reduce_data,
3697/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3698/// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
3699/// ShuffleReduceFn(reduce_data, 0, offset, 0);
3700/// }
3701///
3702/// The algorithm completes in log(2, WARPSIZE) steps.
3703///
3704/// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
3705/// not used therefore we save instructions by not retrieving lane_id
3706/// from the corresponding special registers. The 4th parameter, which
3707/// represents the version of the algorithm being used, is set to 0 to
3708/// signify full warp reduction.
3709///
3710/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3711///
3712/// #reduce_elem refers to an element in the local lane's data structure
3713/// #remote_elem is retrieved from a remote lane
3714/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3715/// reduce_elem = reduce_elem REDUCE_OP remote_elem;
3716///
3717/// Contiguous Partial Warp Reduction
3718///
3719/// This reduce algorithm is used within a warp where only the first
3720/// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
3721/// number of OpenMP threads in a parallel region is not a multiple of
3722/// WARPSIZE. The algorithm is implemented in the runtime as follows:
3723///
3724/// void
3725/// contiguous_partial_reduce(void *reduce_data,
3726/// kmp_ShuffleReductFctPtr ShuffleReduceFn,
3727/// int size, int lane_id) {
3728/// int curr_size;
3729/// int offset;
3730/// curr_size = size;
3731/// mask = curr_size/2;
3732/// while (offset>0) {
3733/// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
3734/// curr_size = (curr_size+1)/2;
3735/// offset = curr_size/2;
3736/// }
3737/// }
3738///
3739/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3740///
3741/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3742/// if (lane_id < offset)
3743/// reduce_elem = reduce_elem REDUCE_OP remote_elem
3744/// else
3745/// reduce_elem = remote_elem
3746///
3747/// This algorithm assumes that the data to be reduced are located in a
3748/// contiguous subset of lanes starting from the first. When there is
3749/// an odd number of active lanes, the data in the last lane is not
3750/// aggregated with any other lane's dat but is instead copied over.
3751///
3752/// Dispersed Partial Warp Reduction
3753///
3754/// This algorithm is used within a warp when any discontiguous subset of
3755/// lanes are active. It is used to implement the reduction operation
3756/// across lanes in an OpenMP simd region or in a nested parallel region.
3757///
3758/// void
3759/// dispersed_partial_reduce(void *reduce_data,
3760/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3761/// int size, remote_id;
3762/// int logical_lane_id = number_of_active_lanes_before_me() * 2;
3763/// do {
3764/// remote_id = next_active_lane_id_right_after_me();
3765/// # the above function returns 0 of no active lane
3766/// # is present right after the current lane.
3767/// size = number_of_active_lanes_in_this_warp();
3768/// logical_lane_id /= 2;
3769/// ShuffleReduceFn(reduce_data, logical_lane_id,
3770/// remote_id-1-threadIdx.x, 2);
3771/// } while (logical_lane_id % 2 == 0 && size > 1);
3772/// }
3773///
3774/// There is no assumption made about the initial state of the reduction.
3775/// Any number of lanes (>=1) could be active at any position. The reduction
3776/// result is returned in the first active lane.
3777///
3778/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3779///
3780/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3781/// if (lane_id % 2 == 0 && offset > 0)
3782/// reduce_elem = reduce_elem REDUCE_OP remote_elem
3783/// else
3784/// reduce_elem = remote_elem
3785///
3786///
3787/// Intra-Team Reduction
3788///
3789/// This function, as implemented in the runtime call
Alexey Bataev8e009032019-01-04 17:25:09 +00003790/// '__kmpc_nvptx_parallel_reduce_nowait_v2', aggregates data across OpenMP
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003791/// threads in a team. It first reduces within a warp using the
3792/// aforementioned algorithms. We then proceed to gather all such
3793/// reduced values at the first warp.
3794///
3795/// The runtime makes use of the function 'InterWarpCpyFn', which copies
3796/// data from each of the "warp master" (zeroth lane of each warp, where
3797/// warp-reduced data is held) to the zeroth warp. This step reduces (in
3798/// a mathematical sense) the problem of reduction across warp masters in
3799/// a block to the problem of warp reduction.
3800///
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003801///
3802/// Inter-Team Reduction
3803///
3804/// Once a team has reduced its data to a single value, it is stored in
3805/// a global scratchpad array. Since each team has a distinct slot, this
3806/// can be done without locking.
3807///
3808/// The last team to write to the scratchpad array proceeds to reduce the
3809/// scratchpad array. One or more workers in the last team use the helper
3810/// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
3811/// the k'th worker reduces every k'th element.
3812///
Alexey Bataev8e009032019-01-04 17:25:09 +00003813/// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait_v2' to
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003814/// reduce across workers and compute a globally reduced value.
3815///
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003816void CGOpenMPRuntimeNVPTX::emitReduction(
3817 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
3818 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
3819 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
3820 if (!CGF.HaveInsertPoint())
3821 return;
3822
3823 bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00003824#ifndef NDEBUG
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003825 bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00003826#endif
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003827
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00003828 if (Options.SimpleReduction) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003829 assert(!TeamsReduction && !ParallelReduction &&
3830 "Invalid reduction selection in emitReduction.");
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00003831 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
3832 ReductionOps, Options);
3833 return;
3834 }
3835
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003836 assert((TeamsReduction || ParallelReduction) &&
3837 "Invalid reduction selection in emitReduction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003838
Alexey Bataeva1166022018-11-27 21:24:54 +00003839 // Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003840 // RedList, shuffle_reduce_func, interwarp_copy_func);
Alexey Bataeva1166022018-11-27 21:24:54 +00003841 // or
3842 // Build res = __kmpc_reduce_teams_nowait_simple(<loc>, <gtid>, <lck>);
Alexey Bataev8e009032019-01-04 17:25:09 +00003843 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003844 llvm::Value *ThreadId = getThreadID(CGF, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003845
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003846 llvm::Value *Res;
3847 if (ParallelReduction) {
Alexey Bataeva1166022018-11-27 21:24:54 +00003848 ASTContext &C = CGM.getContext();
3849 // 1. Build a list of reduction variables.
3850 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3851 auto Size = RHSExprs.size();
3852 for (const Expr *E : Privates) {
3853 if (E->getType()->isVariablyModifiedType())
3854 // Reserve place for array size.
3855 ++Size;
3856 }
3857 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
3858 QualType ReductionArrayTy =
3859 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3860 /*IndexTypeQuals=*/0);
3861 Address ReductionList =
3862 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3863 auto IPriv = Privates.begin();
3864 unsigned Idx = 0;
3865 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
3866 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3867 CGF.getPointerSize());
3868 CGF.Builder.CreateStore(
3869 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3870 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
3871 Elem);
3872 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3873 // Store array size.
3874 ++Idx;
3875 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3876 CGF.getPointerSize());
3877 llvm::Value *Size = CGF.Builder.CreateIntCast(
3878 CGF.getVLASize(
3879 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3880 .NumElts,
3881 CGF.SizeTy, /*isSigned=*/false);
3882 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3883 Elem);
3884 }
3885 }
3886
3887 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
3888 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3889 ReductionList.getPointer(), CGF.VoidPtrTy);
3890 llvm::Value *ReductionFn = emitReductionFunction(
3891 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
3892 Privates, LHSExprs, RHSExprs, ReductionOps);
3893 llvm::Value *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
3894 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
3895 llvm::Value *InterWarpCopyFn =
3896 emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
3897
Alexey Bataev8e009032019-01-04 17:25:09 +00003898 llvm::Value *Args[] = {RTLoc,
3899 ThreadId,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003900 CGF.Builder.getInt32(RHSExprs.size()),
3901 ReductionArrayTySize,
3902 RL,
3903 ShuffleAndReduceFn,
3904 InterWarpCopyFn};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003905
Alexey Bataev8e009032019-01-04 17:25:09 +00003906 Res = CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
3907 OMPRTL_NVPTX__kmpc_parallel_reduce_nowait_v2),
3908 Args);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003909 } else {
3910 assert(TeamsReduction && "expected teams reduction.");
Alexey Bataeva1166022018-11-27 21:24:54 +00003911 std::string Name = getName({"reduction"});
3912 llvm::Value *Lock = getCriticalRegionLock(Name);
3913 llvm::Value *Args[] = {RTLoc, ThreadId, Lock};
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003914 Res = CGF.EmitRuntimeCall(
Alexey Bataeva1166022018-11-27 21:24:54 +00003915 createNVPTXRuntimeFunction(
3916 OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_simple),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003917 Args);
3918 }
3919
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003920 // 5. Build if (res == 1)
3921 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.reduction.done");
3922 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.then");
3923 llvm::Value *Cond = CGF.Builder.CreateICmpEQ(
3924 Res, llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1));
3925 CGF.Builder.CreateCondBr(Cond, ThenBB, ExitBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003926
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003927 // 6. Build then branch: where we have reduced values in the master
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003928 // thread in each team.
3929 // __kmpc_end_reduce{_nowait}(<gtid>);
3930 // break;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003931 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003932
3933 // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003934 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003935 this](CodeGenFunction &CGF, PrePostActionTy &Action) {
3936 auto IPriv = Privates.begin();
3937 auto ILHS = LHSExprs.begin();
3938 auto IRHS = RHSExprs.begin();
Alexey Bataev9ff80832018-04-16 20:16:21 +00003939 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003940 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
3941 cast<DeclRefExpr>(*IRHS));
3942 ++IPriv;
3943 ++ILHS;
3944 ++IRHS;
3945 }
3946 };
Alexey Bataeva1166022018-11-27 21:24:54 +00003947 if (ParallelReduction) {
3948 llvm::Value *EndArgs[] = {ThreadId};
3949 RegionCodeGenTy RCG(CodeGen);
3950 NVPTXActionTy Action(
3951 nullptr, llvm::None,
3952 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_reduce_nowait),
3953 EndArgs);
3954 RCG.setAction(Action);
3955 RCG(CGF);
3956 } else {
3957 assert(TeamsReduction && "expected teams reduction.");
3958 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
3959 std::string Name = getName({"reduction"});
3960 llvm::Value *Lock = getCriticalRegionLock(Name);
3961 llvm::Value *EndArgs[] = {RTLoc, ThreadId, Lock};
3962 RegionCodeGenTy RCG(CodeGen);
3963 NVPTXActionTy Action(
3964 nullptr, llvm::None,
3965 createNVPTXRuntimeFunction(
3966 OMPRTL_NVPTX__kmpc_nvptx_teams_end_reduce_nowait_simple),
3967 EndArgs);
3968 RCG.setAction(Action);
3969 RCG(CGF);
3970 }
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003971 // There is no need to emit line number for unconditional branch.
3972 (void)ApplyDebugLocation::CreateEmpty(CGF);
3973 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003974}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003975
3976const VarDecl *
3977CGOpenMPRuntimeNVPTX::translateParameter(const FieldDecl *FD,
3978 const VarDecl *NativeParam) const {
3979 if (!NativeParam->getType()->isReferenceType())
3980 return NativeParam;
3981 QualType ArgType = NativeParam->getType();
3982 QualifierCollector QC;
3983 const Type *NonQualTy = QC.strip(ArgType);
3984 QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
3985 if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
3986 if (Attr->getCaptureKind() == OMPC_map) {
3987 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
3988 LangAS::opencl_global);
3989 }
3990 }
3991 ArgType = CGM.getContext().getPointerType(PointeeTy);
3992 QC.addRestrict();
3993 enum { NVPTX_local_addr = 5 };
Alexander Richardson6d989432017-10-15 18:48:14 +00003994 QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003995 ArgType = QC.apply(CGM.getContext(), ArgType);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003996 if (isa<ImplicitParamDecl>(NativeParam))
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003997 return ImplicitParamDecl::Create(
3998 CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
3999 NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004000 return ParmVarDecl::Create(
4001 CGM.getContext(),
4002 const_cast<DeclContext *>(NativeParam->getDeclContext()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004003 NativeParam->getBeginLoc(), NativeParam->getLocation(),
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004004 NativeParam->getIdentifier(), ArgType,
4005 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004006}
4007
4008Address
4009CGOpenMPRuntimeNVPTX::getParameterAddress(CodeGenFunction &CGF,
4010 const VarDecl *NativeParam,
4011 const VarDecl *TargetParam) const {
4012 assert(NativeParam != TargetParam &&
4013 NativeParam->getType()->isReferenceType() &&
4014 "Native arg must not be the same as target arg.");
4015 Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
4016 QualType NativeParamType = NativeParam->getType();
4017 QualifierCollector QC;
4018 const Type *NonQualTy = QC.strip(NativeParamType);
4019 QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4020 unsigned NativePointeeAddrSpace =
Alexander Richardson6d989432017-10-15 18:48:14 +00004021 CGF.getContext().getTargetAddressSpace(NativePointeeTy);
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004022 QualType TargetTy = TargetParam->getType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004023 llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004024 LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004025 // First cast to generic.
4026 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4027 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4028 /*AddrSpace=*/0));
4029 // Cast from generic to native address space.
4030 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4031 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4032 NativePointeeAddrSpace));
4033 Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
4034 CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004035 NativeParamType);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004036 return NativeParamAddr;
4037}
4038
4039void CGOpenMPRuntimeNVPTX::emitOutlinedFunctionCall(
Alexey Bataev3c595a62017-08-14 15:01:03 +00004040 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004041 ArrayRef<llvm::Value *> Args) const {
4042 SmallVector<llvm::Value *, 4> TargetArgs;
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004043 TargetArgs.reserve(Args.size());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004044 auto *FnType =
4045 cast<llvm::FunctionType>(OutlinedFn->getType()->getPointerElementType());
4046 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004047 if (FnType->isVarArg() && FnType->getNumParams() <= I) {
4048 TargetArgs.append(std::next(Args.begin(), I), Args.end());
4049 break;
4050 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004051 llvm::Type *TargetType = FnType->getParamType(I);
4052 llvm::Value *NativeArg = Args[I];
4053 if (!TargetType->isPointerTy()) {
4054 TargetArgs.emplace_back(NativeArg);
4055 continue;
4056 }
4057 llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataevc99042b2018-03-15 18:10:54 +00004058 NativeArg,
4059 NativeArg->getType()->getPointerElementType()->getPointerTo());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004060 TargetArgs.emplace_back(
4061 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
4062 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00004063 CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004064}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004065
4066/// Emit function which wraps the outline parallel region
4067/// and controls the arguments which are passed to this function.
4068/// The wrapper ensures that the outlined function is called
4069/// with the correct arguments when data is shared.
4070llvm::Function *CGOpenMPRuntimeNVPTX::createParallelDataSharingWrapper(
4071 llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
4072 ASTContext &Ctx = CGM.getContext();
4073 const auto &CS = *D.getCapturedStmt(OMPD_parallel);
4074
4075 // Create a function that takes as argument the source thread.
4076 FunctionArgList WrapperArgs;
4077 QualType Int16QTy =
4078 Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
4079 QualType Int32QTy =
4080 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004081 ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004082 /*Id=*/nullptr, Int16QTy,
4083 ImplicitParamDecl::Other);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004084 ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004085 /*Id=*/nullptr, Int32QTy,
4086 ImplicitParamDecl::Other);
4087 WrapperArgs.emplace_back(&ParallelLevelArg);
4088 WrapperArgs.emplace_back(&WrapperArg);
4089
Alexey Bataev9ff80832018-04-16 20:16:21 +00004090 const CGFunctionInfo &CGFI =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004091 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
4092
4093 auto *Fn = llvm::Function::Create(
4094 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataev9ff80832018-04-16 20:16:21 +00004095 Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004096 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004097 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004098 Fn->setDoesNotRecurse();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004099
4100 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
4101 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004102 D.getBeginLoc(), D.getBeginLoc());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004103
4104 const auto *RD = CS.getCapturedRecordDecl();
4105 auto CurField = RD->field_begin();
4106
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004107 Address ZeroAddr = CGF.CreateMemTemp(
4108 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
4109 /*Name*/ ".zero.addr");
4110 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004111 // Get the array of arguments.
4112 SmallVector<llvm::Value *, 8> Args;
4113
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004114 Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).getPointer());
4115 Args.emplace_back(ZeroAddr.getPointer());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004116
4117 CGBuilderTy &Bld = CGF.Builder;
4118 auto CI = CS.capture_begin();
4119
4120 // Use global memory for data sharing.
4121 // Handle passing of global args to workers.
4122 Address GlobalArgs =
4123 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
4124 llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
4125 llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
4126 CGF.EmitRuntimeCall(
4127 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_get_shared_variables),
4128 DataSharingArgs);
4129
4130 // Retrieve the shared variables from the list of references returned
4131 // by the runtime. Pass the variables to the outlined function.
Alexey Bataev17314212018-03-20 15:41:05 +00004132 Address SharedArgListAddress = Address::invalid();
4133 if (CS.capture_size() > 0 ||
4134 isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4135 SharedArgListAddress = CGF.EmitLoadOfPointer(
4136 GlobalArgs, CGF.getContext()
4137 .getPointerType(CGF.getContext().getPointerType(
4138 CGF.getContext().VoidPtrTy))
4139 .castAs<PointerType>());
4140 }
4141 unsigned Idx = 0;
4142 if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4143 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
4144 CGF.getPointerSize());
4145 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4146 Src, CGF.SizeTy->getPointerTo());
4147 llvm::Value *LB = CGF.EmitLoadOfScalar(
4148 TypedAddress,
4149 /*Volatile=*/false,
4150 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4151 cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
4152 Args.emplace_back(LB);
4153 ++Idx;
4154 Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
4155 CGF.getPointerSize());
4156 TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4157 Src, CGF.SizeTy->getPointerTo());
4158 llvm::Value *UB = CGF.EmitLoadOfScalar(
4159 TypedAddress,
4160 /*Volatile=*/false,
4161 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4162 cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
4163 Args.emplace_back(UB);
4164 ++Idx;
4165 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004166 if (CS.capture_size() > 0) {
4167 ASTContext &CGFContext = CGF.getContext();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004168 for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
4169 QualType ElemTy = CurField->getType();
Alexey Bataev17314212018-03-20 15:41:05 +00004170 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx,
4171 CGF.getPointerSize());
4172 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004173 Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)));
4174 llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
4175 /*Volatile=*/false,
4176 CGFContext.getPointerType(ElemTy),
4177 CI->getLocation());
Alexey Bataev2091ca62018-04-23 17:33:41 +00004178 if (CI->capturesVariableByCopy() &&
4179 !CI->getCapturedVar()->getType()->isAnyPointerType()) {
Alexey Bataev17314212018-03-20 15:41:05 +00004180 Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
4181 CI->getLocation());
4182 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004183 Args.emplace_back(Arg);
4184 }
4185 }
4186
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004187 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedParallelFn, Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004188 CGF.FinishFunction();
4189 return Fn;
4190}
4191
4192void CGOpenMPRuntimeNVPTX::emitFunctionProlog(CodeGenFunction &CGF,
4193 const Decl *D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004194 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4195 return;
4196
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004197 assert(D && "Expected function or captured|block decl.");
4198 assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
4199 "Function is registered already.");
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004200 assert((!TeamAndReductions.first || TeamAndReductions.first == D) &&
4201 "Team is set but not processed.");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004202 const Stmt *Body = nullptr;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004203 bool NeedToDelayGlobalization = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004204 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4205 Body = FD->getBody();
4206 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
4207 Body = BD->getBody();
4208 } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
4209 Body = CD->getBody();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004210 NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
Alexey Bataev2adecff2018-09-21 14:22:53 +00004211 if (NeedToDelayGlobalization &&
4212 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
4213 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004214 }
4215 if (!Body)
4216 return;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004217 CheckVarsEscapingDeclContext VarChecker(CGF, TeamAndReductions.second);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004218 VarChecker.Visit(Body);
Alexey Bataevff23bb62018-10-11 18:30:31 +00004219 const RecordDecl *GlobalizedVarsRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004220 VarChecker.getGlobalizedRecord(IsInTTDRegion);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004221 TeamAndReductions.first = nullptr;
4222 TeamAndReductions.second.clear();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004223 ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
4224 VarChecker.getEscapedVariableLengthDecls();
4225 if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004226 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004227 auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
4228 I->getSecond().MappedParams =
4229 llvm::make_unique<CodeGenFunction::OMPMapVars>();
4230 I->getSecond().GlobalRecord = GlobalizedVarsRecord;
4231 I->getSecond().EscapedParameters.insert(
4232 VarChecker.getEscapedParameters().begin(),
4233 VarChecker.getEscapedParameters().end());
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004234 I->getSecond().EscapedVariableLengthDecls.append(
4235 EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004236 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004237 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004238 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004239 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004240 Data.insert(std::make_pair(VD, MappedVarData(FD, IsInTTDRegion)));
Alexey Bataevc99042b2018-03-15 18:10:54 +00004241 }
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004242 if (!IsInTTDRegion && !NeedToDelayGlobalization && !IsInParallelRegion) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004243 CheckVarsEscapingDeclContext VarChecker(CGF, llvm::None);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004244 VarChecker.Visit(Body);
4245 I->getSecond().SecondaryGlobalRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004246 VarChecker.getGlobalizedRecord(/*IsInTTDRegion=*/true);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004247 I->getSecond().SecondaryLocalVarData.emplace();
4248 DeclToAddrMapTy &Data = I->getSecond().SecondaryLocalVarData.getValue();
4249 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
4250 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
4251 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004252 Data.insert(
4253 std::make_pair(VD, MappedVarData(FD, /*IsInTTDRegion=*/true)));
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004254 }
4255 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00004256 if (!NeedToDelayGlobalization) {
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004257 emitGenericVarsProlog(CGF, D->getBeginLoc(), /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004258 struct GlobalizationScope final : EHScopeStack::Cleanup {
4259 GlobalizationScope() = default;
4260
4261 void Emit(CodeGenFunction &CGF, Flags flags) override {
4262 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004263 .emitGenericVarsEpilog(CGF, /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004264 }
4265 };
4266 CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004267 }
4268}
4269
4270Address CGOpenMPRuntimeNVPTX::getAddressOfLocalVariable(CodeGenFunction &CGF,
4271 const VarDecl *VD) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004272 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4273 return Address::invalid();
4274
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004275 VD = VD->getCanonicalDecl();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004276 auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
4277 if (I == FunctionGlobalizedDecls.end())
4278 return Address::invalid();
Alexey Bataevc99042b2018-03-15 18:10:54 +00004279 auto VDI = I->getSecond().LocalVarData.find(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004280 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004281 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004282 if (VD->hasAttrs()) {
4283 for (specific_attr_iterator<OMPReferencedVarAttr> IT(VD->attr_begin()),
4284 E(VD->attr_end());
4285 IT != E; ++IT) {
4286 auto VDI = I->getSecond().LocalVarData.find(
4287 cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
4288 ->getCanonicalDecl());
4289 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004290 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004291 }
4292 }
4293 return Address::invalid();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004294}
4295
4296void CGOpenMPRuntimeNVPTX::functionFinished(CodeGenFunction &CGF) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004297 FunctionGlobalizedDecls.erase(CGF.CurFn);
4298 CGOpenMPRuntime::functionFinished(CGF);
4299}
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004300
4301void CGOpenMPRuntimeNVPTX::getDefaultDistScheduleAndChunk(
4302 CodeGenFunction &CGF, const OMPLoopDirective &S,
4303 OpenMPDistScheduleClauseKind &ScheduleKind,
4304 llvm::Value *&Chunk) const {
4305 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
4306 ScheduleKind = OMPC_DIST_SCHEDULE_static;
4307 Chunk = CGF.EmitScalarConversion(getNVPTXNumThreads(CGF),
4308 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4309 S.getIterationVariable()->getType(), S.getBeginLoc());
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004310 return;
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004311 }
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004312 CGOpenMPRuntime::getDefaultDistScheduleAndChunk(
4313 CGF, S, ScheduleKind, Chunk);
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004314}
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004315
4316void CGOpenMPRuntimeNVPTX::getDefaultScheduleAndChunk(
4317 CodeGenFunction &CGF, const OMPLoopDirective &S,
4318 OpenMPScheduleClauseKind &ScheduleKind,
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004319 const Expr *&ChunkExpr) const {
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004320 ScheduleKind = OMPC_SCHEDULE_static;
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004321 // Chunk size is 1 in this case.
4322 llvm::APInt ChunkSize(32, 1);
4323 ChunkExpr = IntegerLiteral::Create(CGF.getContext(), ChunkSize,
4324 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4325 SourceLocation());
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004326}
Alexey Bataev60705422018-10-30 15:50:12 +00004327
4328void CGOpenMPRuntimeNVPTX::adjustTargetSpecificDataForLambdas(
4329 CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
4330 assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
4331 " Expected target-based directive.");
4332 const CapturedStmt *CS = D.getCapturedStmt(OMPD_target);
4333 for (const CapturedStmt::Capture &C : CS->captures()) {
4334 // Capture variables captured by reference in lambdas for target-based
4335 // directives.
4336 if (!C.capturesVariable())
4337 continue;
4338 const VarDecl *VD = C.getCapturedVar();
4339 const auto *RD = VD->getType()
4340 .getCanonicalType()
4341 .getNonReferenceType()
4342 ->getAsCXXRecordDecl();
4343 if (!RD || !RD->isLambda())
4344 continue;
4345 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4346 LValue VDLVal;
4347 if (VD->getType().getCanonicalType()->isReferenceType())
4348 VDLVal = CGF.EmitLoadOfReferenceLValue(VDAddr, VD->getType());
4349 else
4350 VDLVal = CGF.MakeAddrLValue(
4351 VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
4352 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4353 FieldDecl *ThisCapture = nullptr;
4354 RD->getCaptureFields(Captures, ThisCapture);
4355 if (ThisCapture && CGF.CapturedStmtInfo->isCXXThisExprCaptured()) {
4356 LValue ThisLVal =
4357 CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
4358 llvm::Value *CXXThis = CGF.LoadCXXThis();
4359 CGF.EmitStoreOfScalar(CXXThis, ThisLVal);
4360 }
4361 for (const LambdaCapture &LC : RD->captures()) {
4362 if (LC.getCaptureKind() != LCK_ByRef)
4363 continue;
4364 const VarDecl *VD = LC.getCapturedVar();
4365 if (!CS->capturesVariable(VD))
4366 continue;
4367 auto It = Captures.find(VD);
4368 assert(It != Captures.end() && "Found lambda capture without field.");
4369 LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
4370 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4371 if (VD->getType().getCanonicalType()->isReferenceType())
4372 VDAddr = CGF.EmitLoadOfReferenceLValue(VDAddr,
4373 VD->getType().getCanonicalType())
4374 .getAddress();
4375 CGF.EmitStoreOfScalar(VDAddr.getPointer(), VarLVal);
4376 }
4377 }
4378}
4379
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004380// Get current CudaArch and ignore any unknown values
4381static CudaArch getCudaArch(CodeGenModule &CGM) {
4382 if (!CGM.getTarget().hasFeature("ptx"))
4383 return CudaArch::UNKNOWN;
4384 llvm::StringMap<bool> Features;
4385 CGM.getTarget().initFeatureMap(Features, CGM.getDiags(),
4386 CGM.getTarget().getTargetOpts().CPU,
4387 CGM.getTarget().getTargetOpts().Features);
4388 for (const auto &Feature : Features) {
4389 if (Feature.getValue()) {
4390 CudaArch Arch = StringToCudaArch(Feature.getKey());
4391 if (Arch != CudaArch::UNKNOWN)
4392 return Arch;
4393 }
4394 }
4395 return CudaArch::UNKNOWN;
4396}
4397
4398/// Check to see if target architecture supports unified addressing which is
4399/// a restriction for OpenMP requires clause "unified_shared_memory".
4400void CGOpenMPRuntimeNVPTX::checkArchForUnifiedAddressing(
4401 CodeGenModule &CGM, const OMPRequiresDecl *D) const {
4402 for (const OMPClause *Clause : D->clauselists()) {
4403 if (Clause->getClauseKind() == OMPC_unified_shared_memory) {
4404 switch (getCudaArch(CGM)) {
4405 case CudaArch::SM_20:
4406 case CudaArch::SM_21:
4407 case CudaArch::SM_30:
4408 case CudaArch::SM_32:
4409 case CudaArch::SM_35:
4410 case CudaArch::SM_37:
4411 case CudaArch::SM_50:
4412 case CudaArch::SM_52:
4413 case CudaArch::SM_53:
4414 case CudaArch::SM_60:
4415 case CudaArch::SM_61:
4416 case CudaArch::SM_62:
4417 CGM.Error(Clause->getBeginLoc(),
4418 "Target architecture does not support unified addressing");
4419 return;
4420 case CudaArch::SM_70:
4421 case CudaArch::SM_72:
4422 case CudaArch::SM_75:
4423 case CudaArch::GFX600:
4424 case CudaArch::GFX601:
4425 case CudaArch::GFX700:
4426 case CudaArch::GFX701:
4427 case CudaArch::GFX702:
4428 case CudaArch::GFX703:
4429 case CudaArch::GFX704:
4430 case CudaArch::GFX801:
4431 case CudaArch::GFX802:
4432 case CudaArch::GFX803:
4433 case CudaArch::GFX810:
4434 case CudaArch::GFX900:
4435 case CudaArch::GFX902:
4436 case CudaArch::GFX904:
4437 case CudaArch::GFX906:
4438 case CudaArch::GFX909:
4439 case CudaArch::UNKNOWN:
4440 break;
4441 case CudaArch::LAST:
4442 llvm_unreachable("Unexpected Cuda arch.");
4443 }
4444 }
4445 }
4446}
4447
Alexey Bataeve4090182018-11-02 14:54:07 +00004448/// Get number of SMs and number of blocks per SM.
4449static std::pair<unsigned, unsigned> getSMsBlocksPerSM(CodeGenModule &CGM) {
4450 std::pair<unsigned, unsigned> Data;
4451 if (CGM.getLangOpts().OpenMPCUDANumSMs)
4452 Data.first = CGM.getLangOpts().OpenMPCUDANumSMs;
4453 if (CGM.getLangOpts().OpenMPCUDABlocksPerSM)
4454 Data.second = CGM.getLangOpts().OpenMPCUDABlocksPerSM;
4455 if (Data.first && Data.second)
4456 return Data;
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004457 switch (getCudaArch(CGM)) {
4458 case CudaArch::SM_20:
4459 case CudaArch::SM_21:
4460 case CudaArch::SM_30:
4461 case CudaArch::SM_32:
4462 case CudaArch::SM_35:
4463 case CudaArch::SM_37:
4464 case CudaArch::SM_50:
4465 case CudaArch::SM_52:
4466 case CudaArch::SM_53:
4467 return {16, 16};
4468 case CudaArch::SM_60:
4469 case CudaArch::SM_61:
4470 case CudaArch::SM_62:
4471 return {56, 32};
4472 case CudaArch::SM_70:
4473 case CudaArch::SM_72:
4474 case CudaArch::SM_75:
4475 return {84, 32};
4476 case CudaArch::GFX600:
4477 case CudaArch::GFX601:
4478 case CudaArch::GFX700:
4479 case CudaArch::GFX701:
4480 case CudaArch::GFX702:
4481 case CudaArch::GFX703:
4482 case CudaArch::GFX704:
4483 case CudaArch::GFX801:
4484 case CudaArch::GFX802:
4485 case CudaArch::GFX803:
4486 case CudaArch::GFX810:
4487 case CudaArch::GFX900:
4488 case CudaArch::GFX902:
4489 case CudaArch::GFX904:
4490 case CudaArch::GFX906:
4491 case CudaArch::GFX909:
4492 case CudaArch::UNKNOWN:
4493 break;
4494 case CudaArch::LAST:
4495 llvm_unreachable("Unexpected Cuda arch.");
Alexey Bataeve4090182018-11-02 14:54:07 +00004496 }
4497 llvm_unreachable("Unexpected NVPTX target without ptx feature.");
4498}
4499
4500void CGOpenMPRuntimeNVPTX::clear() {
Alexey Bataeve4e9ba22019-01-28 20:03:02 +00004501 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
4502 if (CGM.getCodeGenOpts().getDebugInfo() >=
4503 codegenoptions::LimitedDebugInfo) {
4504 ASTContext &C = CGM.getContext();
4505 auto *VD = VarDecl::Create(
4506 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(),
4507 &C.Idents.get("_$_"), C.IntTy, /*TInfo=*/nullptr, SC_Static);
4508 auto *Var = cast<llvm::GlobalVariable>(
4509 CGM.CreateRuntimeVariable(CGM.IntTy, "_$_"));
4510 Var->setInitializer(llvm::ConstantInt::getNullValue(CGM.IntTy));
4511 Var->setLinkage(llvm::GlobalVariable::CommonLinkage);
4512 CGM.addCompilerUsedGlobal(Var);
4513 DI->EmitGlobalVariable(Var, VD);
4514 }
Alexey Bataeve4090182018-11-02 14:54:07 +00004515 if (!GlobalizedRecords.empty()) {
4516 ASTContext &C = CGM.getContext();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004517 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> GlobalRecs;
4518 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> SharedRecs;
Alexey Bataeve4090182018-11-02 14:54:07 +00004519 RecordDecl *StaticRD = C.buildImplicitRecord(
4520 "_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
4521 StaticRD->startDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004522 RecordDecl *SharedStaticRD = C.buildImplicitRecord(
4523 "_shared_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
4524 SharedStaticRD->startDefinition();
Alexey Bataeve4090182018-11-02 14:54:07 +00004525 for (const GlobalPtrSizeRecsTy &Records : GlobalizedRecords) {
4526 if (Records.Records.empty())
4527 continue;
4528 unsigned Size = 0;
4529 unsigned RecAlignment = 0;
4530 for (const RecordDecl *RD : Records.Records) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004531 QualType RDTy = C.getRecordType(RD);
4532 unsigned Alignment = C.getTypeAlignInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00004533 RecAlignment = std::max(RecAlignment, Alignment);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004534 unsigned RecSize = C.getTypeSizeInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00004535 Size =
4536 llvm::alignTo(llvm::alignTo(Size, Alignment) + RecSize, Alignment);
4537 }
4538 Size = llvm::alignTo(Size, RecAlignment);
4539 llvm::APInt ArySize(/*numBits=*/64, Size);
4540 QualType SubTy = C.getConstantArrayType(
4541 C.CharTy, ArySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004542 const bool UseSharedMemory = Size <= SharedMemorySize;
4543 auto *Field =
4544 FieldDecl::Create(C, UseSharedMemory ? SharedStaticRD : StaticRD,
4545 SourceLocation(), SourceLocation(), nullptr, SubTy,
4546 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
4547 /*BW=*/nullptr, /*Mutable=*/false,
4548 /*InitStyle=*/ICIS_NoInit);
Alexey Bataeve4090182018-11-02 14:54:07 +00004549 Field->setAccess(AS_public);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004550 if (UseSharedMemory) {
4551 SharedStaticRD->addDecl(Field);
4552 SharedRecs.push_back(&Records);
4553 } else {
4554 StaticRD->addDecl(Field);
4555 GlobalRecs.push_back(&Records);
4556 }
Alexey Bataeve4090182018-11-02 14:54:07 +00004557 Records.RecSize->setInitializer(llvm::ConstantInt::get(CGM.SizeTy, Size));
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004558 Records.UseSharedMemory->setInitializer(
4559 llvm::ConstantInt::get(CGM.Int16Ty, UseSharedMemory ? 1 : 0));
4560 }
Alexey Bataev6a1b06b2018-12-18 21:01:42 +00004561 // Allocate SharedMemorySize buffer for the shared memory.
4562 // FIXME: nvlink does not handle weak linkage correctly (object with the
4563 // different size are reported as erroneous).
4564 // Restore this code as sson as nvlink is fixed.
4565 if (!SharedStaticRD->field_empty()) {
4566 llvm::APInt ArySize(/*numBits=*/64, SharedMemorySize);
4567 QualType SubTy = C.getConstantArrayType(
4568 C.CharTy, ArySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
4569 auto *Field = FieldDecl::Create(
4570 C, SharedStaticRD, SourceLocation(), SourceLocation(), nullptr, SubTy,
4571 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
4572 /*BW=*/nullptr, /*Mutable=*/false,
4573 /*InitStyle=*/ICIS_NoInit);
4574 Field->setAccess(AS_public);
4575 SharedStaticRD->addDecl(Field);
4576 }
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004577 SharedStaticRD->completeDefinition();
4578 if (!SharedStaticRD->field_empty()) {
4579 QualType StaticTy = C.getRecordType(SharedStaticRD);
4580 llvm::Type *LLVMStaticTy = CGM.getTypes().ConvertTypeForMem(StaticTy);
4581 auto *GV = new llvm::GlobalVariable(
4582 CGM.getModule(), LLVMStaticTy,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004583 /*isConstant=*/false, llvm::GlobalValue::CommonLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004584 llvm::Constant::getNullValue(LLVMStaticTy),
4585 "_openmp_shared_static_glob_rd_$_", /*InsertBefore=*/nullptr,
4586 llvm::GlobalValue::NotThreadLocal,
4587 C.getTargetAddressSpace(LangAS::cuda_shared));
4588 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
4589 GV, CGM.VoidPtrTy);
4590 for (const GlobalPtrSizeRecsTy *Rec : SharedRecs) {
4591 Rec->Buffer->replaceAllUsesWith(Replacement);
4592 Rec->Buffer->eraseFromParent();
4593 }
Alexey Bataeve4090182018-11-02 14:54:07 +00004594 }
4595 StaticRD->completeDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004596 if (!StaticRD->field_empty()) {
4597 QualType StaticTy = C.getRecordType(StaticRD);
4598 std::pair<unsigned, unsigned> SMsBlockPerSM = getSMsBlocksPerSM(CGM);
4599 llvm::APInt Size1(32, SMsBlockPerSM.second);
4600 QualType Arr1Ty =
4601 C.getConstantArrayType(StaticTy, Size1, ArrayType::Normal,
4602 /*IndexTypeQuals=*/0);
4603 llvm::APInt Size2(32, SMsBlockPerSM.first);
4604 QualType Arr2Ty = C.getConstantArrayType(Arr1Ty, Size2, ArrayType::Normal,
4605 /*IndexTypeQuals=*/0);
4606 llvm::Type *LLVMArr2Ty = CGM.getTypes().ConvertTypeForMem(Arr2Ty);
4607 auto *GV = new llvm::GlobalVariable(
4608 CGM.getModule(), LLVMArr2Ty,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004609 /*isConstant=*/false, llvm::GlobalValue::CommonLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004610 llvm::Constant::getNullValue(LLVMArr2Ty),
4611 "_openmp_static_glob_rd_$_");
4612 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
4613 GV, CGM.VoidPtrTy);
4614 for (const GlobalPtrSizeRecsTy *Rec : GlobalRecs) {
4615 Rec->Buffer->replaceAllUsesWith(Replacement);
4616 Rec->Buffer->eraseFromParent();
4617 }
4618 }
Alexey Bataeve4090182018-11-02 14:54:07 +00004619 }
4620 CGOpenMPRuntime::clear();
4621}