blob: cf814a4b203b4cde7d91a365a168e7da07667b98 [file] [log] [blame]
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001//===---- CGOpenMPRuntimeNVPTX.cpp - Interface to OpenMP NVPTX Runtimes ---===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides a class for OpenMP runtime code generation specialized to NVPTX
11// targets.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CGOpenMPRuntimeNVPTX.h"
Carlo Bertollic6872252016-04-04 15:55:02 +000016#include "CodeGenFunction.h"
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000017#include "clang/AST/DeclOpenMP.h"
Carlo Bertollic6872252016-04-04 15:55:02 +000018#include "clang/AST/StmtOpenMP.h"
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000019#include "clang/AST/StmtVisitor.h"
Alexey Bataeve4090182018-11-02 14:54:07 +000020#include "clang/Basic/Cuda.h"
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000021#include "llvm/ADT/SmallPtrSet.h"
Samuel Antao45bfe4c2016-02-08 15:59:20 +000022
23using namespace clang;
24using namespace CodeGen;
25
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +000026namespace {
27enum OpenMPRTLFunctionNVPTX {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000028 /// Call to void __kmpc_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +000029 /// int16_t RequiresOMPRuntime);
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +000030 OMPRTL_NVPTX__kmpc_kernel_init,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000031 /// Call to void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +000032 OMPRTL_NVPTX__kmpc_kernel_deinit,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000033 /// Call to void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +000034 /// int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +000035 OMPRTL_NVPTX__kmpc_spmd_kernel_init,
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +000036 /// Call to void __kmpc_spmd_kernel_deinit_v2(int16_t RequiresOMPRuntime);
37 OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000038 /// Call to void __kmpc_kernel_prepare_parallel(void
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +000039 /// *outlined_function, int16_t
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +000040 /// IsOMPRuntimeInitialized);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000041 OMPRTL_NVPTX__kmpc_kernel_prepare_parallel,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000042 /// Call to bool __kmpc_kernel_parallel(void **outlined_function,
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +000043 /// int16_t IsOMPRuntimeInitialized);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000044 OMPRTL_NVPTX__kmpc_kernel_parallel,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000045 /// Call to void __kmpc_kernel_end_parallel();
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000046 OMPRTL_NVPTX__kmpc_kernel_end_parallel,
47 /// Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
48 /// global_tid);
49 OMPRTL_NVPTX__kmpc_serialized_parallel,
50 /// Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
51 /// global_tid);
52 OMPRTL_NVPTX__kmpc_end_serialized_parallel,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000053 /// Call to int32_t __kmpc_shuffle_int32(int32_t element,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000054 /// int16_t lane_offset, int16_t warp_size);
55 OMPRTL_NVPTX__kmpc_shuffle_int32,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000056 /// Call to int64_t __kmpc_shuffle_int64(int64_t element,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000057 /// int16_t lane_offset, int16_t warp_size);
58 OMPRTL_NVPTX__kmpc_shuffle_int64,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000059 /// Call to __kmpc_nvptx_parallel_reduce_nowait(kmp_int32
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000060 /// global_tid, kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
61 /// void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
62 /// lane_offset, int16_t shortCircuit),
63 /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num));
64 OMPRTL_NVPTX__kmpc_parallel_reduce_nowait,
Alexey Bataeva1166022018-11-27 21:24:54 +000065 /// Call to __kmpc_nvptx_teams_reduce_nowait_simple(ident_t *loc, kmp_int32
66 /// global_tid, kmp_critical_name *lck)
67 OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_simple,
68 /// Call to __kmpc_nvptx_teams_end_reduce_nowait_simple(ident_t *loc,
69 /// kmp_int32 global_tid, kmp_critical_name *lck)
70 OMPRTL_NVPTX__kmpc_nvptx_teams_end_reduce_nowait_simple,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000071 /// Call to __kmpc_nvptx_end_reduce_nowait(int32_t global_tid);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000072 OMPRTL_NVPTX__kmpc_end_reduce_nowait,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000073 /// Call to void __kmpc_data_sharing_init_stack();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000074 OMPRTL_NVPTX__kmpc_data_sharing_init_stack,
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +000075 /// Call to void __kmpc_data_sharing_init_stack_spmd();
76 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd,
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +000077 /// Call to void* __kmpc_data_sharing_coalesced_push_stack(size_t size,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000078 /// int16_t UseSharedMemory);
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +000079 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000080 /// Call to void __kmpc_data_sharing_pop_stack(void *a);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000081 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000082 /// Call to void __kmpc_begin_sharing_variables(void ***args,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000083 /// size_t n_args);
84 OMPRTL_NVPTX__kmpc_begin_sharing_variables,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000085 /// Call to void __kmpc_end_sharing_variables();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000086 OMPRTL_NVPTX__kmpc_end_sharing_variables,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000087 /// Call to void __kmpc_get_shared_variables(void ***GlobalArgs)
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000088 OMPRTL_NVPTX__kmpc_get_shared_variables,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +000089 /// Call to uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32
90 /// global_tid);
91 OMPRTL_NVPTX__kmpc_parallel_level,
Alexey Bataev673110d2018-05-16 13:36:30 +000092 /// Call to int8_t __kmpc_is_spmd_exec_mode();
93 OMPRTL_NVPTX__kmpc_is_spmd_exec_mode,
Alexey Bataeve4090182018-11-02 14:54:07 +000094 /// Call to void __kmpc_get_team_static_memory(const void *buf, size_t size,
95 /// int16_t is_shared, const void **res);
96 OMPRTL_NVPTX__kmpc_get_team_static_memory,
97 /// Call to void __kmpc_restore_team_static_memory(int16_t is_shared);
98 OMPRTL_NVPTX__kmpc_restore_team_static_memory,
Alexey Bataevc3028ca2018-12-04 15:03:25 +000099 // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
100 OMPRTL__kmpc_barrier,
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000101};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000102
103/// Pre(post)-action for different OpenMP constructs specialized for NVPTX.
104class NVPTXActionTy final : public PrePostActionTy {
Alexey Bataev9ff80832018-04-16 20:16:21 +0000105 llvm::Value *EnterCallee = nullptr;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000106 ArrayRef<llvm::Value *> EnterArgs;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000107 llvm::Value *ExitCallee = nullptr;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000108 ArrayRef<llvm::Value *> ExitArgs;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000109 bool Conditional = false;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000110 llvm::BasicBlock *ContBlock = nullptr;
111
112public:
113 NVPTXActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
114 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
115 bool Conditional = false)
116 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
117 ExitArgs(ExitArgs), Conditional(Conditional) {}
118 void Enter(CodeGenFunction &CGF) override {
119 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
120 if (Conditional) {
121 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
122 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
123 ContBlock = CGF.createBasicBlock("omp_if.end");
124 // Generate the branch (If-stmt)
125 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
126 CGF.EmitBlock(ThenBlock);
127 }
128 }
129 void Done(CodeGenFunction &CGF) {
130 // Emit the rest of blocks/branches
131 CGF.EmitBranch(ContBlock);
132 CGF.EmitBlock(ContBlock, true);
133 }
134 void Exit(CodeGenFunction &CGF) override {
135 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
136 }
137};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000138
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000139/// A class to track the execution mode when codegening directives within
140/// a target region. The appropriate mode (SPMD|NON-SPMD) is set on entry
141/// to the target region and used by containing directives such as 'parallel'
142/// to emit optimized code.
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000143class ExecutionRuntimeModesRAII {
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000144private:
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000145 CGOpenMPRuntimeNVPTX::ExecutionMode SavedExecMode =
146 CGOpenMPRuntimeNVPTX::EM_Unknown;
147 CGOpenMPRuntimeNVPTX::ExecutionMode &ExecMode;
148 bool SavedRuntimeMode = false;
149 bool *RuntimeMode = nullptr;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000150
151public:
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000152 /// Constructor for Non-SPMD mode.
153 ExecutionRuntimeModesRAII(CGOpenMPRuntimeNVPTX::ExecutionMode &ExecMode)
154 : ExecMode(ExecMode) {
155 SavedExecMode = ExecMode;
156 ExecMode = CGOpenMPRuntimeNVPTX::EM_NonSPMD;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000157 }
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000158 /// Constructor for SPMD mode.
159 ExecutionRuntimeModesRAII(CGOpenMPRuntimeNVPTX::ExecutionMode &ExecMode,
160 bool &RuntimeMode, bool FullRuntimeMode)
161 : ExecMode(ExecMode), RuntimeMode(&RuntimeMode) {
162 SavedExecMode = ExecMode;
163 SavedRuntimeMode = RuntimeMode;
164 ExecMode = CGOpenMPRuntimeNVPTX::EM_SPMD;
165 RuntimeMode = FullRuntimeMode;
166 }
167 ~ExecutionRuntimeModesRAII() {
168 ExecMode = SavedExecMode;
169 if (RuntimeMode)
170 *RuntimeMode = SavedRuntimeMode;
171 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000172};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000173
174/// GPU Configuration: This information can be derived from cuda registers,
175/// however, providing compile time constants helps generate more efficient
176/// code. For all practical purposes this is fine because the configuration
177/// is the same for all known NVPTX architectures.
178enum MachineConfiguration : unsigned {
179 WarpSize = 32,
180 /// Number of bits required to represent a lane identifier, which is
181 /// computed as log_2(WarpSize).
182 LaneIDBits = 5,
183 LaneIDMask = WarpSize - 1,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +0000184
185 /// Global memory alignment for performance.
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000186 GlobalMemoryAlignment = 128,
Alexey Bataev09c9eea2018-11-09 16:18:04 +0000187
188 /// Maximal size of the shared memory buffer.
189 SharedMemorySize = 128,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000190};
191
192enum NamedBarrier : unsigned {
193 /// Synchronize on this barrier #ID using a named barrier primitive.
194 /// Only the subset of active threads in a parallel region arrive at the
195 /// barrier.
196 NB_Parallel = 1,
197};
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000198
Alexey Bataevf2f39be2018-11-16 19:38:21 +0000199static const ValueDecl *getPrivateItem(const Expr *RefExpr) {
200 RefExpr = RefExpr->IgnoreParens();
201 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr)) {
202 const Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
203 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
204 Base = TempASE->getBase()->IgnoreParenImpCasts();
205 RefExpr = Base;
206 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr)) {
207 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
208 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
209 Base = TempOASE->getBase()->IgnoreParenImpCasts();
210 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
211 Base = TempASE->getBase()->IgnoreParenImpCasts();
212 RefExpr = Base;
213 }
214 RefExpr = RefExpr->IgnoreParenImpCasts();
215 if (const auto *DE = dyn_cast<DeclRefExpr>(RefExpr))
216 return cast<ValueDecl>(DE->getDecl()->getCanonicalDecl());
217 const auto *ME = cast<MemberExpr>(RefExpr);
218 return cast<ValueDecl>(ME->getMemberDecl()->getCanonicalDecl());
219}
220
Alexey Bataev2adecff2018-09-21 14:22:53 +0000221typedef std::pair<CharUnits /*Align*/, const ValueDecl *> VarsDataTy;
222static bool stable_sort_comparator(const VarsDataTy P1, const VarsDataTy P2) {
223 return P1.first > P2.first;
224}
225
226static RecordDecl *buildRecordForGlobalizedVars(
227 ASTContext &C, ArrayRef<const ValueDecl *> EscapedDecls,
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000228 ArrayRef<const ValueDecl *> EscapedDeclsForTeams,
Alexey Bataev2adecff2018-09-21 14:22:53 +0000229 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
230 &MappedDeclsFields) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000231 if (EscapedDecls.empty() && EscapedDeclsForTeams.empty())
Alexey Bataev2adecff2018-09-21 14:22:53 +0000232 return nullptr;
233 SmallVector<VarsDataTy, 4> GlobalizedVars;
234 for (const ValueDecl *D : EscapedDecls)
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000235 GlobalizedVars.emplace_back(
236 CharUnits::fromQuantity(std::max(
237 C.getDeclAlign(D).getQuantity(),
238 static_cast<CharUnits::QuantityType>(GlobalMemoryAlignment))),
239 D);
240 for (const ValueDecl *D : EscapedDeclsForTeams)
Alexey Bataev2adecff2018-09-21 14:22:53 +0000241 GlobalizedVars.emplace_back(C.getDeclAlign(D), D);
242 std::stable_sort(GlobalizedVars.begin(), GlobalizedVars.end(),
243 stable_sort_comparator);
244 // Build struct _globalized_locals_ty {
Alexey Bataevff23bb62018-10-11 18:30:31 +0000245 // /* globalized vars */[WarSize] align (max(decl_align,
246 // GlobalMemoryAlignment))
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000247 // /* globalized vars */ for EscapedDeclsForTeams
Alexey Bataev2adecff2018-09-21 14:22:53 +0000248 // };
249 RecordDecl *GlobalizedRD = C.buildImplicitRecord("_globalized_locals_ty");
250 GlobalizedRD->startDefinition();
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000251 llvm::SmallPtrSet<const ValueDecl *, 16> SingleEscaped(
252 EscapedDeclsForTeams.begin(), EscapedDeclsForTeams.end());
Alexey Bataev2adecff2018-09-21 14:22:53 +0000253 for (const auto &Pair : GlobalizedVars) {
254 const ValueDecl *VD = Pair.second;
255 QualType Type = VD->getType();
256 if (Type->isLValueReferenceType())
257 Type = C.getPointerType(Type.getNonReferenceType());
258 else
259 Type = Type.getNonReferenceType();
260 SourceLocation Loc = VD->getLocation();
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000261 FieldDecl *Field;
262 if (SingleEscaped.count(VD)) {
263 Field = FieldDecl::Create(
264 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
265 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
266 /*BW=*/nullptr, /*Mutable=*/false,
267 /*InitStyle=*/ICIS_NoInit);
268 Field->setAccess(AS_public);
269 if (VD->hasAttrs()) {
270 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
271 E(VD->getAttrs().end());
272 I != E; ++I)
273 Field->addAttr(*I);
274 }
275 } else {
276 llvm::APInt ArraySize(32, WarpSize);
277 Type = C.getConstantArrayType(Type, ArraySize, ArrayType::Normal, 0);
278 Field = FieldDecl::Create(
279 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
280 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
281 /*BW=*/nullptr, /*Mutable=*/false,
282 /*InitStyle=*/ICIS_NoInit);
283 Field->setAccess(AS_public);
284 llvm::APInt Align(32, std::max(C.getDeclAlign(VD).getQuantity(),
285 static_cast<CharUnits::QuantityType>(
286 GlobalMemoryAlignment)));
287 Field->addAttr(AlignedAttr::CreateImplicit(
288 C, AlignedAttr::GNU_aligned, /*IsAlignmentExpr=*/true,
289 IntegerLiteral::Create(C, Align,
290 C.getIntTypeForBitwidth(32, /*Signed=*/0),
291 SourceLocation())));
Alexey Bataev2adecff2018-09-21 14:22:53 +0000292 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000293 GlobalizedRD->addDecl(Field);
Alexey Bataev2adecff2018-09-21 14:22:53 +0000294 MappedDeclsFields.try_emplace(VD, Field);
295 }
296 GlobalizedRD->completeDefinition();
297 return GlobalizedRD;
298}
299
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000300/// Get the list of variables that can escape their declaration context.
301class CheckVarsEscapingDeclContext final
302 : public ConstStmtVisitor<CheckVarsEscapingDeclContext> {
303 CodeGenFunction &CGF;
304 llvm::SetVector<const ValueDecl *> EscapedDecls;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000305 llvm::SetVector<const ValueDecl *> EscapedVariableLengthDecls;
Alexey Bataevc99042b2018-03-15 18:10:54 +0000306 llvm::SmallPtrSet<const Decl *, 4> EscapedParameters;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000307 RecordDecl *GlobalizedRD = nullptr;
308 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000309 bool AllEscaped = false;
Alexey Bataev91433f62018-06-26 17:24:03 +0000310 bool IsForCombinedParallelRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000311
312 void markAsEscaped(const ValueDecl *VD) {
Alexey Bataev03f270c2018-03-30 18:31:07 +0000313 // Do not globalize declare target variables.
Alexey Bataev97b72212018-08-14 18:31:20 +0000314 if (!isa<VarDecl>(VD) ||
315 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataev03f270c2018-03-30 18:31:07 +0000316 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000317 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataevc99042b2018-03-15 18:10:54 +0000318 // Variables captured by value must be globalized.
319 if (auto *CSI = CGF.CapturedStmtInfo) {
Mikael Holmen9f373a32018-03-16 07:27:57 +0000320 if (const FieldDecl *FD = CSI->lookup(cast<VarDecl>(VD))) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000321 // Check if need to capture the variable that was already captured by
322 // value in the outer region.
Alexey Bataev91433f62018-06-26 17:24:03 +0000323 if (!IsForCombinedParallelRegion) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000324 if (!FD->hasAttrs())
325 return;
326 const auto *Attr = FD->getAttr<OMPCaptureKindAttr>();
327 if (!Attr)
328 return;
329 if (!isOpenMPPrivate(
330 static_cast<OpenMPClauseKind>(Attr->getCaptureKind())) ||
331 Attr->getCaptureKind() == OMPC_map)
332 return;
333 }
334 if (!FD->getType()->isReferenceType()) {
335 assert(!VD->getType()->isVariablyModifiedType() &&
336 "Parameter captured by value with variably modified type");
337 EscapedParameters.insert(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000338 } else if (!IsForCombinedParallelRegion) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000339 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000340 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000341 }
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000342 }
343 if ((!CGF.CapturedStmtInfo ||
Alexey Bataev91433f62018-06-26 17:24:03 +0000344 (IsForCombinedParallelRegion && CGF.CapturedStmtInfo)) &&
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000345 VD->getType()->isReferenceType())
346 // Do not globalize variables with reference type.
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000347 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000348 if (VD->getType()->isVariablyModifiedType())
349 EscapedVariableLengthDecls.insert(VD);
350 else
351 EscapedDecls.insert(VD);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000352 }
353
354 void VisitValueDecl(const ValueDecl *VD) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000355 if (VD->getType()->isLValueReferenceType())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000356 markAsEscaped(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000357 if (const auto *VarD = dyn_cast<VarDecl>(VD)) {
358 if (!isa<ParmVarDecl>(VarD) && VarD->hasInit()) {
359 const bool SavedAllEscaped = AllEscaped;
360 AllEscaped = VD->getType()->isLValueReferenceType();
361 Visit(VarD->getInit());
362 AllEscaped = SavedAllEscaped;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000363 }
364 }
365 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000366 void VisitOpenMPCapturedStmt(const CapturedStmt *S,
367 ArrayRef<OMPClause *> Clauses,
368 bool IsCombinedParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000369 if (!S)
370 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000371 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000372 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
373 const ValueDecl *VD = C.getCapturedVar();
Alexey Bataev91433f62018-06-26 17:24:03 +0000374 bool SavedIsForCombinedParallelRegion = IsForCombinedParallelRegion;
375 if (IsCombinedParallelRegion) {
376 // Check if the variable is privatized in the combined construct and
377 // those private copies must be shared in the inner parallel
378 // directive.
379 IsForCombinedParallelRegion = false;
380 for (const OMPClause *C : Clauses) {
381 if (!isOpenMPPrivate(C->getClauseKind()) ||
382 C->getClauseKind() == OMPC_reduction ||
383 C->getClauseKind() == OMPC_linear ||
384 C->getClauseKind() == OMPC_private)
385 continue;
386 ArrayRef<const Expr *> Vars;
387 if (const auto *PC = dyn_cast<OMPFirstprivateClause>(C))
388 Vars = PC->getVarRefs();
389 else if (const auto *PC = dyn_cast<OMPLastprivateClause>(C))
390 Vars = PC->getVarRefs();
391 else
392 llvm_unreachable("Unexpected clause.");
393 for (const auto *E : Vars) {
394 const Decl *D =
395 cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
396 if (D == VD->getCanonicalDecl()) {
397 IsForCombinedParallelRegion = true;
398 break;
399 }
400 }
401 if (IsForCombinedParallelRegion)
402 break;
403 }
404 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000405 markAsEscaped(VD);
406 if (isa<OMPCapturedExprDecl>(VD))
407 VisitValueDecl(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000408 IsForCombinedParallelRegion = SavedIsForCombinedParallelRegion;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000409 }
410 }
411 }
412
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000413 void buildRecordForGlobalizedVars(bool IsInTTDRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000414 assert(!GlobalizedRD &&
415 "Record for globalized variables is built already.");
Alexey Bataevff23bb62018-10-11 18:30:31 +0000416 ArrayRef<const ValueDecl *> EscapedDeclsForParallel, EscapedDeclsForTeams;
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000417 if (IsInTTDRegion)
Alexey Bataevff23bb62018-10-11 18:30:31 +0000418 EscapedDeclsForTeams = EscapedDecls.getArrayRef();
419 else
420 EscapedDeclsForParallel = EscapedDecls.getArrayRef();
Alexey Bataev2adecff2018-09-21 14:22:53 +0000421 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataevff23bb62018-10-11 18:30:31 +0000422 CGF.getContext(), EscapedDeclsForParallel, EscapedDeclsForTeams,
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000423 MappedDeclsFields);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000424 }
425
426public:
Alexey Bataevf2f39be2018-11-16 19:38:21 +0000427 CheckVarsEscapingDeclContext(CodeGenFunction &CGF,
428 ArrayRef<const ValueDecl *> TeamsReductions)
429 : CGF(CGF), EscapedDecls(TeamsReductions.begin(), TeamsReductions.end()) {
430 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000431 virtual ~CheckVarsEscapingDeclContext() = default;
432 void VisitDeclStmt(const DeclStmt *S) {
433 if (!S)
434 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000435 for (const Decl *D : S->decls())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000436 if (const auto *VD = dyn_cast_or_null<ValueDecl>(D))
437 VisitValueDecl(VD);
438 }
439 void VisitOMPExecutableDirective(const OMPExecutableDirective *D) {
440 if (!D)
441 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000442 if (!D->hasAssociatedStmt())
443 return;
444 if (const auto *S =
445 dyn_cast_or_null<CapturedStmt>(D->getAssociatedStmt())) {
446 // Do not analyze directives that do not actually require capturing,
447 // like `omp for` or `omp simd` directives.
448 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
449 getOpenMPCaptureRegions(CaptureRegions, D->getDirectiveKind());
450 if (CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown) {
451 VisitStmt(S->getCapturedStmt());
452 return;
Alexey Bataev673110d2018-05-16 13:36:30 +0000453 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000454 VisitOpenMPCapturedStmt(
455 S, D->clauses(),
456 CaptureRegions.back() == OMPD_parallel &&
457 isOpenMPDistributeDirective(D->getDirectiveKind()));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000458 }
459 }
460 void VisitCapturedStmt(const CapturedStmt *S) {
461 if (!S)
462 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000463 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000464 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
465 const ValueDecl *VD = C.getCapturedVar();
466 markAsEscaped(VD);
467 if (isa<OMPCapturedExprDecl>(VD))
468 VisitValueDecl(VD);
469 }
470 }
471 }
472 void VisitLambdaExpr(const LambdaExpr *E) {
473 if (!E)
474 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000475 for (const LambdaCapture &C : E->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000476 if (C.capturesVariable()) {
477 if (C.getCaptureKind() == LCK_ByRef) {
478 const ValueDecl *VD = C.getCapturedVar();
479 markAsEscaped(VD);
480 if (E->isInitCapture(&C) || isa<OMPCapturedExprDecl>(VD))
481 VisitValueDecl(VD);
482 }
483 }
484 }
485 }
486 void VisitBlockExpr(const BlockExpr *E) {
487 if (!E)
488 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000489 for (const BlockDecl::Capture &C : E->getBlockDecl()->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000490 if (C.isByRef()) {
491 const VarDecl *VD = C.getVariable();
492 markAsEscaped(VD);
493 if (isa<OMPCapturedExprDecl>(VD) || VD->isInitCapture())
494 VisitValueDecl(VD);
495 }
496 }
497 }
498 void VisitCallExpr(const CallExpr *E) {
499 if (!E)
500 return;
501 for (const Expr *Arg : E->arguments()) {
502 if (!Arg)
503 continue;
504 if (Arg->isLValue()) {
505 const bool SavedAllEscaped = AllEscaped;
506 AllEscaped = true;
507 Visit(Arg);
508 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000509 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000510 Visit(Arg);
Alexey Bataev9ff80832018-04-16 20:16:21 +0000511 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000512 }
513 Visit(E->getCallee());
514 }
515 void VisitDeclRefExpr(const DeclRefExpr *E) {
516 if (!E)
517 return;
518 const ValueDecl *VD = E->getDecl();
519 if (AllEscaped)
520 markAsEscaped(VD);
521 if (isa<OMPCapturedExprDecl>(VD))
522 VisitValueDecl(VD);
523 else if (const auto *VarD = dyn_cast<VarDecl>(VD))
524 if (VarD->isInitCapture())
525 VisitValueDecl(VD);
526 }
527 void VisitUnaryOperator(const UnaryOperator *E) {
528 if (!E)
529 return;
530 if (E->getOpcode() == UO_AddrOf) {
531 const bool SavedAllEscaped = AllEscaped;
532 AllEscaped = true;
533 Visit(E->getSubExpr());
534 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000535 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000536 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000537 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000538 }
539 void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
540 if (!E)
541 return;
542 if (E->getCastKind() == CK_ArrayToPointerDecay) {
543 const bool SavedAllEscaped = AllEscaped;
544 AllEscaped = true;
545 Visit(E->getSubExpr());
546 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000547 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000548 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000549 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000550 }
551 void VisitExpr(const Expr *E) {
552 if (!E)
553 return;
554 bool SavedAllEscaped = AllEscaped;
555 if (!E->isLValue())
556 AllEscaped = false;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000557 for (const Stmt *Child : E->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000558 if (Child)
559 Visit(Child);
560 AllEscaped = SavedAllEscaped;
561 }
562 void VisitStmt(const Stmt *S) {
563 if (!S)
564 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000565 for (const Stmt *Child : S->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000566 if (Child)
567 Visit(Child);
568 }
569
Alexey Bataevc99042b2018-03-15 18:10:54 +0000570 /// Returns the record that handles all the escaped local variables and used
571 /// instead of their original storage.
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000572 const RecordDecl *getGlobalizedRecord(bool IsInTTDRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000573 if (!GlobalizedRD)
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000574 buildRecordForGlobalizedVars(IsInTTDRegion);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000575 return GlobalizedRD;
576 }
577
Alexey Bataevc99042b2018-03-15 18:10:54 +0000578 /// Returns the field in the globalized record for the escaped variable.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000579 const FieldDecl *getFieldForGlobalizedVar(const ValueDecl *VD) const {
580 assert(GlobalizedRD &&
581 "Record for globalized variables must be generated already.");
582 auto I = MappedDeclsFields.find(VD);
583 if (I == MappedDeclsFields.end())
584 return nullptr;
585 return I->getSecond();
586 }
587
Alexey Bataevc99042b2018-03-15 18:10:54 +0000588 /// Returns the list of the escaped local variables/parameters.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000589 ArrayRef<const ValueDecl *> getEscapedDecls() const {
590 return EscapedDecls.getArrayRef();
591 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000592
593 /// Checks if the escaped local variable is actually a parameter passed by
594 /// value.
595 const llvm::SmallPtrSetImpl<const Decl *> &getEscapedParameters() const {
596 return EscapedParameters;
597 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000598
599 /// Returns the list of the escaped variables with the variably modified
600 /// types.
601 ArrayRef<const ValueDecl *> getEscapedVariableLengthDecls() const {
602 return EscapedVariableLengthDecls.getArrayRef();
603 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000604};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000605} // anonymous namespace
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000606
607/// Get the GPU warp size.
608static llvm::Value *getNVPTXWarpSize(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000609 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000610 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000611 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_warpsize),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000612 "nvptx_warp_size");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000613}
614
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000615/// Get the id of the current thread on the GPU.
616static llvm::Value *getNVPTXThreadID(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000617 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000618 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000619 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_tid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000620 "nvptx_tid");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000621}
622
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000623/// Get the id of the warp in the block.
624/// We assume that the warp size is 32, which is always the case
625/// on the NVPTX device, to generate more efficient code.
626static llvm::Value *getNVPTXWarpID(CodeGenFunction &CGF) {
627 CGBuilderTy &Bld = CGF.Builder;
628 return Bld.CreateAShr(getNVPTXThreadID(CGF), LaneIDBits, "nvptx_warp_id");
629}
630
631/// Get the id of the current lane in the Warp.
632/// We assume that the warp size is 32, which is always the case
633/// on the NVPTX device, to generate more efficient code.
634static llvm::Value *getNVPTXLaneID(CodeGenFunction &CGF) {
635 CGBuilderTy &Bld = CGF.Builder;
636 return Bld.CreateAnd(getNVPTXThreadID(CGF), Bld.getInt32(LaneIDMask),
637 "nvptx_lane_id");
638}
639
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000640/// Get the maximum number of threads in a block of the GPU.
641static llvm::Value *getNVPTXNumThreads(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000642 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000643 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000644 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_ntid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000645 "nvptx_num_threads");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000646}
647
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000648/// Get barrier to synchronize all threads in a block.
649static void getNVPTXCTABarrier(CodeGenFunction &CGF) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +0000650 llvm::Function *F = llvm::Intrinsic::getDeclaration(
651 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_barrier0);
652 F->addFnAttr(llvm::Attribute::Convergent);
653 CGF.EmitRuntimeCall(F);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000654}
655
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000656/// Get barrier #ID to synchronize selected (multiple of warp size) threads in
657/// a CTA.
658static void getNVPTXBarrier(CodeGenFunction &CGF, int ID,
659 llvm::Value *NumThreads) {
660 CGBuilderTy &Bld = CGF.Builder;
661 llvm::Value *Args[] = {Bld.getInt32(ID), NumThreads};
Alexey Bataevf2f39be2018-11-16 19:38:21 +0000662 llvm::Function *F = llvm::Intrinsic::getDeclaration(
663 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_barrier);
664 F->addFnAttr(llvm::Attribute::Convergent);
665 CGF.EmitRuntimeCall(F, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000666}
667
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000668/// Synchronize all GPU threads in a block.
669static void syncCTAThreads(CodeGenFunction &CGF) { getNVPTXCTABarrier(CGF); }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000670
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000671/// Synchronize worker threads in a parallel region.
672static void syncParallelThreads(CodeGenFunction &CGF, llvm::Value *NumThreads) {
673 return getNVPTXBarrier(CGF, NB_Parallel, NumThreads);
674}
675
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000676/// Get the value of the thread_limit clause in the teams directive.
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000677/// For the 'generic' execution mode, the runtime encodes thread_limit in
678/// the launch parameters, always starting thread_limit+warpSize threads per
679/// CTA. The threads in the last warp are reserved for master execution.
680/// For the 'spmd' execution mode, all threads in a CTA are part of the team.
681static llvm::Value *getThreadLimit(CodeGenFunction &CGF,
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000682 bool IsInSPMDExecutionMode = false) {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000683 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000684 return IsInSPMDExecutionMode
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000685 ? getNVPTXNumThreads(CGF)
Alexey Bataeve290ec02018-04-06 16:03:36 +0000686 : Bld.CreateNUWSub(getNVPTXNumThreads(CGF), getNVPTXWarpSize(CGF),
687 "thread_limit");
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000688}
689
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000690/// Get the thread id of the OMP master thread.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000691/// The master thread id is the first thread (lane) of the last warp in the
692/// GPU block. Warp size is assumed to be some power of 2.
693/// Thread id is 0 indexed.
694/// E.g: If NumThreads is 33, master id is 32.
695/// If NumThreads is 64, master id is 32.
696/// If NumThreads is 1024, master id is 992.
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000697static llvm::Value *getMasterThreadID(CodeGenFunction &CGF) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000698 CGBuilderTy &Bld = CGF.Builder;
699 llvm::Value *NumThreads = getNVPTXNumThreads(CGF);
700
701 // We assume that the warp size is a power of 2.
Alexey Bataeve290ec02018-04-06 16:03:36 +0000702 llvm::Value *Mask = Bld.CreateNUWSub(getNVPTXWarpSize(CGF), Bld.getInt32(1));
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000703
Alexey Bataeve290ec02018-04-06 16:03:36 +0000704 return Bld.CreateAnd(Bld.CreateNUWSub(NumThreads, Bld.getInt32(1)),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000705 Bld.CreateNot(Mask), "master_tid");
706}
707
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000708CGOpenMPRuntimeNVPTX::WorkerFunctionState::WorkerFunctionState(
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000709 CodeGenModule &CGM, SourceLocation Loc)
Alexey Bataev9ff80832018-04-16 20:16:21 +0000710 : WorkerFn(nullptr), CGFI(CGM.getTypes().arrangeNullaryFunction()),
711 Loc(Loc) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000712 createWorkerFunction(CGM);
Vasileios Kalintirise5c09592016-03-22 10:41:20 +0000713}
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000714
715void CGOpenMPRuntimeNVPTX::WorkerFunctionState::createWorkerFunction(
716 CodeGenModule &CGM) {
717 // Create an worker function with no arguments.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000718
719 WorkerFn = llvm::Function::Create(
Alexey Bataev9ff80832018-04-16 20:16:21 +0000720 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataevaee93892018-01-08 20:09:47 +0000721 /*placeholder=*/"_worker", &CGM.getModule());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000722 CGM.SetInternalFunctionAttributes(GlobalDecl(), WorkerFn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +0000723 WorkerFn->setDoesNotRecurse();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000724}
725
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000726CGOpenMPRuntimeNVPTX::ExecutionMode
727CGOpenMPRuntimeNVPTX::getExecutionMode() const {
728 return CurrentExecutionMode;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000729}
730
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000731static CGOpenMPRuntimeNVPTX::DataSharingMode
732getDataSharingMode(CodeGenModule &CGM) {
733 return CGM.getLangOpts().OpenMPCUDAMode ? CGOpenMPRuntimeNVPTX::CUDA
734 : CGOpenMPRuntimeNVPTX::Generic;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000735}
736
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000737// Checks if the expression is constant or does not have non-trivial function
738// calls.
739static bool isTrivial(ASTContext &Ctx, const Expr * E) {
740 // We can skip constant expressions.
741 // We can skip expressions with trivial calls or simple expressions.
742 return (E->isEvaluatable(Ctx, Expr::SE_AllowUndefinedBehavior) ||
743 !E->hasNonTrivialCall(Ctx)) &&
744 !E->HasSideEffects(Ctx, /*IncludePossibleEffects=*/true);
745}
746
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000747/// Checks if the \p Body is the \a CompoundStmt and returns its child statement
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000748/// iff there is only one that is not evaluatable at the compile time.
749static const Stmt *getSingleCompoundChild(ASTContext &Ctx, const Stmt *Body) {
750 if (const auto *C = dyn_cast<CompoundStmt>(Body)) {
751 const Stmt *Child = nullptr;
752 for (const Stmt *S : C->body()) {
753 if (const auto *E = dyn_cast<Expr>(S)) {
754 if (isTrivial(Ctx, E))
755 continue;
756 }
757 // Some of the statements can be ignored.
758 if (isa<AsmStmt>(S) || isa<NullStmt>(S) || isa<OMPFlushDirective>(S) ||
759 isa<OMPBarrierDirective>(S) || isa<OMPTaskyieldDirective>(S))
760 continue;
761 // Analyze declarations.
762 if (const auto *DS = dyn_cast<DeclStmt>(S)) {
763 if (llvm::all_of(DS->decls(), [&Ctx](const Decl *D) {
764 if (isa<EmptyDecl>(D) || isa<DeclContext>(D) ||
765 isa<TypeDecl>(D) || isa<PragmaCommentDecl>(D) ||
766 isa<PragmaDetectMismatchDecl>(D) || isa<UsingDecl>(D) ||
767 isa<UsingDirectiveDecl>(D) ||
768 isa<OMPDeclareReductionDecl>(D) ||
769 isa<OMPThreadPrivateDecl>(D))
770 return true;
771 const auto *VD = dyn_cast<VarDecl>(D);
772 if (!VD)
773 return false;
774 return VD->isConstexpr() ||
775 ((VD->getType().isTrivialType(Ctx) ||
776 VD->getType()->isReferenceType()) &&
777 (!VD->hasInit() || isTrivial(Ctx, VD->getInit())));
778 }))
779 continue;
780 }
781 // Found multiple children - cannot get the one child only.
782 if (Child)
783 return Body;
784 Child = S;
785 }
786 if (Child)
787 return Child;
788 }
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000789 return Body;
790}
791
792/// Check if the parallel directive has an 'if' clause with non-constant or
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000793/// false condition. Also, check if the number of threads is strictly specified
794/// and run those directives in non-SPMD mode.
795static bool hasParallelIfNumThreadsClause(ASTContext &Ctx,
796 const OMPExecutableDirective &D) {
797 if (D.hasClausesOfKind<OMPNumThreadsClause>())
798 return true;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000799 for (const auto *C : D.getClausesOfKind<OMPIfClause>()) {
800 OpenMPDirectiveKind NameModifier = C->getNameModifier();
801 if (NameModifier != OMPD_parallel && NameModifier != OMPD_unknown)
802 continue;
803 const Expr *Cond = C->getCondition();
804 bool Result;
805 if (!Cond->EvaluateAsBooleanCondition(Result, Ctx) || !Result)
806 return true;
807 }
808 return false;
809}
810
811/// Check for inner (nested) SPMD construct, if any
812static bool hasNestedSPMDDirective(ASTContext &Ctx,
813 const OMPExecutableDirective &D) {
814 const auto *CS = D.getInnermostCapturedStmt();
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000815 const auto *Body =
816 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000817 const Stmt *ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000818
819 if (const auto *NestedDir = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
820 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000821 switch (D.getDirectiveKind()) {
822 case OMPD_target:
Alexey Bataevdf093e72018-05-11 19:45:14 +0000823 if (isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000824 !hasParallelIfNumThreadsClause(Ctx, *NestedDir))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000825 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000826 if (DKind == OMPD_teams) {
827 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
828 /*IgnoreCaptured=*/true);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000829 if (!Body)
830 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000831 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000832 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
833 DKind = NND->getDirectiveKind();
Alexey Bataevdf093e72018-05-11 19:45:14 +0000834 if (isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000835 !hasParallelIfNumThreadsClause(Ctx, *NND))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000836 return true;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000837 }
838 }
839 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000840 case OMPD_target_teams:
Alexey Bataevdf093e72018-05-11 19:45:14 +0000841 return isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000842 !hasParallelIfNumThreadsClause(Ctx, *NestedDir);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000843 case OMPD_target_simd:
844 case OMPD_target_parallel:
845 case OMPD_target_parallel_for:
846 case OMPD_target_parallel_for_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000847 case OMPD_target_teams_distribute:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000848 case OMPD_target_teams_distribute_simd:
849 case OMPD_target_teams_distribute_parallel_for:
850 case OMPD_target_teams_distribute_parallel_for_simd:
851 case OMPD_parallel:
852 case OMPD_for:
853 case OMPD_parallel_for:
854 case OMPD_parallel_sections:
855 case OMPD_for_simd:
856 case OMPD_parallel_for_simd:
857 case OMPD_cancel:
858 case OMPD_cancellation_point:
859 case OMPD_ordered:
860 case OMPD_threadprivate:
861 case OMPD_task:
862 case OMPD_simd:
863 case OMPD_sections:
864 case OMPD_section:
865 case OMPD_single:
866 case OMPD_master:
867 case OMPD_critical:
868 case OMPD_taskyield:
869 case OMPD_barrier:
870 case OMPD_taskwait:
871 case OMPD_taskgroup:
872 case OMPD_atomic:
873 case OMPD_flush:
874 case OMPD_teams:
875 case OMPD_target_data:
876 case OMPD_target_exit_data:
877 case OMPD_target_enter_data:
878 case OMPD_distribute:
879 case OMPD_distribute_simd:
880 case OMPD_distribute_parallel_for:
881 case OMPD_distribute_parallel_for_simd:
882 case OMPD_teams_distribute:
883 case OMPD_teams_distribute_simd:
884 case OMPD_teams_distribute_parallel_for:
885 case OMPD_teams_distribute_parallel_for_simd:
886 case OMPD_target_update:
887 case OMPD_declare_simd:
888 case OMPD_declare_target:
889 case OMPD_end_declare_target:
890 case OMPD_declare_reduction:
891 case OMPD_taskloop:
892 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000893 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000894 case OMPD_unknown:
895 llvm_unreachable("Unexpected directive.");
896 }
897 }
898
899 return false;
900}
901
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000902static bool supportsSPMDExecutionMode(ASTContext &Ctx,
903 const OMPExecutableDirective &D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000904 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
905 switch (DirectiveKind) {
906 case OMPD_target:
907 case OMPD_target_teams:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000908 return hasNestedSPMDDirective(Ctx, D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000909 case OMPD_target_parallel:
910 case OMPD_target_parallel_for:
911 case OMPD_target_parallel_for_simd:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000912 case OMPD_target_teams_distribute_parallel_for:
913 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev2adecff2018-09-21 14:22:53 +0000914 return !hasParallelIfNumThreadsClause(Ctx, D);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000915 case OMPD_target_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000916 case OMPD_target_teams_distribute:
917 case OMPD_target_teams_distribute_simd:
918 return false;
919 case OMPD_parallel:
920 case OMPD_for:
921 case OMPD_parallel_for:
922 case OMPD_parallel_sections:
923 case OMPD_for_simd:
924 case OMPD_parallel_for_simd:
925 case OMPD_cancel:
926 case OMPD_cancellation_point:
927 case OMPD_ordered:
928 case OMPD_threadprivate:
929 case OMPD_task:
930 case OMPD_simd:
931 case OMPD_sections:
932 case OMPD_section:
933 case OMPD_single:
934 case OMPD_master:
935 case OMPD_critical:
936 case OMPD_taskyield:
937 case OMPD_barrier:
938 case OMPD_taskwait:
939 case OMPD_taskgroup:
940 case OMPD_atomic:
941 case OMPD_flush:
942 case OMPD_teams:
943 case OMPD_target_data:
944 case OMPD_target_exit_data:
945 case OMPD_target_enter_data:
946 case OMPD_distribute:
947 case OMPD_distribute_simd:
948 case OMPD_distribute_parallel_for:
949 case OMPD_distribute_parallel_for_simd:
950 case OMPD_teams_distribute:
951 case OMPD_teams_distribute_simd:
952 case OMPD_teams_distribute_parallel_for:
953 case OMPD_teams_distribute_parallel_for_simd:
954 case OMPD_target_update:
955 case OMPD_declare_simd:
956 case OMPD_declare_target:
957 case OMPD_end_declare_target:
958 case OMPD_declare_reduction:
959 case OMPD_taskloop:
960 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000961 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000962 case OMPD_unknown:
963 break;
964 }
965 llvm_unreachable(
966 "Unknown programming model for OpenMP directive on NVPTX target.");
967}
968
969/// Check if the directive is loops based and has schedule clause at all or has
970/// static scheduling.
971static bool hasStaticScheduling(const OMPExecutableDirective &D) {
972 assert(isOpenMPWorksharingDirective(D.getDirectiveKind()) &&
973 isOpenMPLoopDirective(D.getDirectiveKind()) &&
974 "Expected loop-based directive.");
975 return !D.hasClausesOfKind<OMPOrderedClause>() &&
976 (!D.hasClausesOfKind<OMPScheduleClause>() ||
977 llvm::any_of(D.getClausesOfKind<OMPScheduleClause>(),
978 [](const OMPScheduleClause *C) {
979 return C->getScheduleKind() == OMPC_SCHEDULE_static;
980 }));
981}
982
983/// Check for inner (nested) lightweight runtime construct, if any
984static bool hasNestedLightweightDirective(ASTContext &Ctx,
985 const OMPExecutableDirective &D) {
986 assert(supportsSPMDExecutionMode(Ctx, D) && "Expected SPMD mode directive.");
987 const auto *CS = D.getInnermostCapturedStmt();
988 const auto *Body =
989 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000990 const Stmt *ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000991
992 if (const auto *NestedDir = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
993 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
994 switch (D.getDirectiveKind()) {
995 case OMPD_target:
996 if (isOpenMPParallelDirective(DKind) &&
997 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
998 hasStaticScheduling(*NestedDir))
999 return true;
1000 if (DKind == OMPD_parallel) {
1001 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
1002 /*IgnoreCaptured=*/true);
1003 if (!Body)
1004 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001005 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001006 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
1007 DKind = NND->getDirectiveKind();
1008 if (isOpenMPWorksharingDirective(DKind) &&
1009 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
1010 return true;
1011 }
1012 } else if (DKind == OMPD_teams) {
1013 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
1014 /*IgnoreCaptured=*/true);
1015 if (!Body)
1016 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001017 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001018 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
1019 DKind = NND->getDirectiveKind();
1020 if (isOpenMPParallelDirective(DKind) &&
1021 isOpenMPWorksharingDirective(DKind) &&
1022 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
1023 return true;
1024 if (DKind == OMPD_parallel) {
1025 Body = NND->getInnermostCapturedStmt()->IgnoreContainers(
1026 /*IgnoreCaptured=*/true);
1027 if (!Body)
1028 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001029 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001030 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
1031 DKind = NND->getDirectiveKind();
1032 if (isOpenMPWorksharingDirective(DKind) &&
1033 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
1034 return true;
1035 }
1036 }
1037 }
1038 }
1039 return false;
1040 case OMPD_target_teams:
1041 if (isOpenMPParallelDirective(DKind) &&
1042 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
1043 hasStaticScheduling(*NestedDir))
1044 return true;
1045 if (DKind == OMPD_parallel) {
1046 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
1047 /*IgnoreCaptured=*/true);
1048 if (!Body)
1049 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001050 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001051 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
1052 DKind = NND->getDirectiveKind();
1053 if (isOpenMPWorksharingDirective(DKind) &&
1054 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
1055 return true;
1056 }
1057 }
1058 return false;
1059 case OMPD_target_parallel:
1060 return isOpenMPWorksharingDirective(DKind) &&
1061 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NestedDir);
1062 case OMPD_target_teams_distribute:
1063 case OMPD_target_simd:
1064 case OMPD_target_parallel_for:
1065 case OMPD_target_parallel_for_simd:
1066 case OMPD_target_teams_distribute_simd:
1067 case OMPD_target_teams_distribute_parallel_for:
1068 case OMPD_target_teams_distribute_parallel_for_simd:
1069 case OMPD_parallel:
1070 case OMPD_for:
1071 case OMPD_parallel_for:
1072 case OMPD_parallel_sections:
1073 case OMPD_for_simd:
1074 case OMPD_parallel_for_simd:
1075 case OMPD_cancel:
1076 case OMPD_cancellation_point:
1077 case OMPD_ordered:
1078 case OMPD_threadprivate:
1079 case OMPD_task:
1080 case OMPD_simd:
1081 case OMPD_sections:
1082 case OMPD_section:
1083 case OMPD_single:
1084 case OMPD_master:
1085 case OMPD_critical:
1086 case OMPD_taskyield:
1087 case OMPD_barrier:
1088 case OMPD_taskwait:
1089 case OMPD_taskgroup:
1090 case OMPD_atomic:
1091 case OMPD_flush:
1092 case OMPD_teams:
1093 case OMPD_target_data:
1094 case OMPD_target_exit_data:
1095 case OMPD_target_enter_data:
1096 case OMPD_distribute:
1097 case OMPD_distribute_simd:
1098 case OMPD_distribute_parallel_for:
1099 case OMPD_distribute_parallel_for_simd:
1100 case OMPD_teams_distribute:
1101 case OMPD_teams_distribute_simd:
1102 case OMPD_teams_distribute_parallel_for:
1103 case OMPD_teams_distribute_parallel_for_simd:
1104 case OMPD_target_update:
1105 case OMPD_declare_simd:
1106 case OMPD_declare_target:
1107 case OMPD_end_declare_target:
1108 case OMPD_declare_reduction:
1109 case OMPD_taskloop:
1110 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001111 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001112 case OMPD_unknown:
1113 llvm_unreachable("Unexpected directive.");
1114 }
1115 }
1116
1117 return false;
1118}
1119
1120/// Checks if the construct supports lightweight runtime. It must be SPMD
1121/// construct + inner loop-based construct with static scheduling.
1122static bool supportsLightweightRuntime(ASTContext &Ctx,
1123 const OMPExecutableDirective &D) {
1124 if (!supportsSPMDExecutionMode(Ctx, D))
1125 return false;
1126 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
1127 switch (DirectiveKind) {
1128 case OMPD_target:
1129 case OMPD_target_teams:
1130 case OMPD_target_parallel:
1131 return hasNestedLightweightDirective(Ctx, D);
1132 case OMPD_target_parallel_for:
1133 case OMPD_target_parallel_for_simd:
1134 case OMPD_target_teams_distribute_parallel_for:
1135 case OMPD_target_teams_distribute_parallel_for_simd:
1136 // (Last|First)-privates must be shared in parallel region.
1137 return hasStaticScheduling(D);
1138 case OMPD_target_simd:
1139 case OMPD_target_teams_distribute:
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001140 case OMPD_target_teams_distribute_simd:
Alexey Bataevdf093e72018-05-11 19:45:14 +00001141 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001142 case OMPD_parallel:
1143 case OMPD_for:
1144 case OMPD_parallel_for:
1145 case OMPD_parallel_sections:
1146 case OMPD_for_simd:
1147 case OMPD_parallel_for_simd:
1148 case OMPD_cancel:
1149 case OMPD_cancellation_point:
1150 case OMPD_ordered:
1151 case OMPD_threadprivate:
1152 case OMPD_task:
1153 case OMPD_simd:
1154 case OMPD_sections:
1155 case OMPD_section:
1156 case OMPD_single:
1157 case OMPD_master:
1158 case OMPD_critical:
1159 case OMPD_taskyield:
1160 case OMPD_barrier:
1161 case OMPD_taskwait:
1162 case OMPD_taskgroup:
1163 case OMPD_atomic:
1164 case OMPD_flush:
1165 case OMPD_teams:
1166 case OMPD_target_data:
1167 case OMPD_target_exit_data:
1168 case OMPD_target_enter_data:
1169 case OMPD_distribute:
1170 case OMPD_distribute_simd:
1171 case OMPD_distribute_parallel_for:
1172 case OMPD_distribute_parallel_for_simd:
1173 case OMPD_teams_distribute:
1174 case OMPD_teams_distribute_simd:
1175 case OMPD_teams_distribute_parallel_for:
1176 case OMPD_teams_distribute_parallel_for_simd:
1177 case OMPD_target_update:
1178 case OMPD_declare_simd:
1179 case OMPD_declare_target:
1180 case OMPD_end_declare_target:
1181 case OMPD_declare_reduction:
1182 case OMPD_taskloop:
1183 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001184 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001185 case OMPD_unknown:
1186 break;
1187 }
1188 llvm_unreachable(
1189 "Unknown programming model for OpenMP directive on NVPTX target.");
1190}
1191
1192void CGOpenMPRuntimeNVPTX::emitNonSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001193 StringRef ParentName,
1194 llvm::Function *&OutlinedFn,
1195 llvm::Constant *&OutlinedFnID,
1196 bool IsOffloadEntry,
1197 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001198 ExecutionRuntimeModesRAII ModeRAII(CurrentExecutionMode);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001199 EntryFunctionState EST;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001200 WorkerFunctionState WST(CGM, D.getBeginLoc());
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001201 Work.clear();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001202 WrapperFunctionsMap.clear();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001203
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001204 // Emit target region as a standalone region.
1205 class NVPTXPrePostActionTy : public PrePostActionTy {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001206 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1207 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001208
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001209 public:
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001210 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001211 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST)
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001212 : EST(EST), WST(WST) {}
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001213 void Enter(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001214 auto &RT =
1215 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001216 RT.emitNonSPMDEntryHeader(CGF, EST, WST);
1217 // Skip target region initialization.
1218 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001219 }
1220 void Exit(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001221 auto &RT =
1222 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001223 RT.clearLocThreadIdInsertPt(CGF);
1224 RT.emitNonSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001225 }
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001226 } Action(EST, WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001227 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001228 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001229 // Reserve place for the globalized memory.
1230 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001231 if (!KernelStaticGlobalized) {
1232 KernelStaticGlobalized = new llvm::GlobalVariable(
1233 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1234 llvm::GlobalValue::InternalLinkage,
1235 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1236 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1237 llvm::GlobalValue::NotThreadLocal,
1238 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1239 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001240 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1241 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001242 IsInTTDRegion = false;
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001243
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001244 // Now change the name of the worker function to correspond to this target
1245 // region's entry function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001246 WST.WorkerFn->setName(Twine(OutlinedFn->getName(), "_worker"));
Alexey Bataevaee93892018-01-08 20:09:47 +00001247
1248 // Create the worker function
1249 emitWorkerFunction(WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001250}
1251
1252// Setup NVPTX threads for master-worker OpenMP scheme.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001253void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryHeader(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001254 EntryFunctionState &EST,
1255 WorkerFunctionState &WST) {
1256 CGBuilderTy &Bld = CGF.Builder;
1257
1258 llvm::BasicBlock *WorkerBB = CGF.createBasicBlock(".worker");
1259 llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
1260 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
1261 EST.ExitBB = CGF.createBasicBlock(".exit");
1262
Alexey Bataev9ff80832018-04-16 20:16:21 +00001263 llvm::Value *IsWorker =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001264 Bld.CreateICmpULT(getNVPTXThreadID(CGF), getThreadLimit(CGF));
1265 Bld.CreateCondBr(IsWorker, WorkerBB, MasterCheckBB);
1266
1267 CGF.EmitBlock(WorkerBB);
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001268 emitCall(CGF, WST.Loc, WST.WorkerFn);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001269 CGF.EmitBranch(EST.ExitBB);
1270
1271 CGF.EmitBlock(MasterCheckBB);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001272 llvm::Value *IsMaster =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001273 Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
1274 Bld.CreateCondBr(IsMaster, MasterBB, EST.ExitBB);
1275
1276 CGF.EmitBlock(MasterBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001277 IsInTargetMasterThreadRegion = true;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001278 // SEQUENTIAL (MASTER) REGION START
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001279 // First action in sequential region:
1280 // Initialize the state of the OpenMP runtime library on the GPU.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001281 // TODO: Optimize runtime initialization and pass in correct value.
1282 llvm::Value *Args[] = {getThreadLimit(CGF),
1283 Bld.getInt16(/*RequiresOMPRuntime=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001284 CGF.EmitRuntimeCall(
1285 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_init), Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001286
1287 // For data sharing, we need to initialize the stack.
1288 CGF.EmitRuntimeCall(
1289 createNVPTXRuntimeFunction(
1290 OMPRTL_NVPTX__kmpc_data_sharing_init_stack));
1291
Alexey Bataevc99042b2018-03-15 18:10:54 +00001292 emitGenericVarsProlog(CGF, WST.Loc);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001293}
1294
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001295void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001296 EntryFunctionState &EST) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001297 IsInTargetMasterThreadRegion = false;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001298 if (!CGF.HaveInsertPoint())
1299 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001300
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001301 emitGenericVarsEpilog(CGF);
1302
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001303 if (!EST.ExitBB)
1304 EST.ExitBB = CGF.createBasicBlock(".exit");
1305
1306 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".termination.notifier");
1307 CGF.EmitBranch(TerminateBB);
1308
1309 CGF.EmitBlock(TerminateBB);
1310 // Signal termination condition.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001311 // TODO: Optimize runtime initialization and pass in correct value.
1312 llvm::Value *Args[] = {CGF.Builder.getInt16(/*IsOMPRuntimeInitialized=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001313 CGF.EmitRuntimeCall(
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001314 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_deinit), Args);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001315 // Barrier to terminate worker threads.
1316 syncCTAThreads(CGF);
1317 // Master thread jumps to exit point.
1318 CGF.EmitBranch(EST.ExitBB);
1319
1320 CGF.EmitBlock(EST.ExitBB);
1321 EST.ExitBB = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001322}
1323
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001324void CGOpenMPRuntimeNVPTX::emitSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001325 StringRef ParentName,
1326 llvm::Function *&OutlinedFn,
1327 llvm::Constant *&OutlinedFnID,
1328 bool IsOffloadEntry,
1329 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001330 ExecutionRuntimeModesRAII ModeRAII(
1331 CurrentExecutionMode, RequiresFullRuntime,
1332 CGM.getLangOpts().OpenMPCUDAForceFullRuntime ||
1333 !supportsLightweightRuntime(CGM.getContext(), D));
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001334 EntryFunctionState EST;
1335
1336 // Emit target region as a standalone region.
1337 class NVPTXPrePostActionTy : public PrePostActionTy {
1338 CGOpenMPRuntimeNVPTX &RT;
1339 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1340 const OMPExecutableDirective &D;
1341
1342 public:
1343 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT,
1344 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
1345 const OMPExecutableDirective &D)
1346 : RT(RT), EST(EST), D(D) {}
1347 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001348 RT.emitSPMDEntryHeader(CGF, EST, D);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001349 // Skip target region initialization.
1350 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001351 }
1352 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevfd006c42018-10-05 15:08:53 +00001353 RT.clearLocThreadIdInsertPt(CGF);
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001354 RT.emitSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001355 }
1356 } Action(*this, EST, D);
1357 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001358 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001359 // Reserve place for the globalized memory.
1360 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001361 if (!KernelStaticGlobalized) {
1362 KernelStaticGlobalized = new llvm::GlobalVariable(
1363 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1364 llvm::GlobalValue::InternalLinkage,
1365 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1366 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1367 llvm::GlobalValue::NotThreadLocal,
1368 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1369 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001370 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1371 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001372 IsInTTDRegion = false;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001373}
1374
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001375void CGOpenMPRuntimeNVPTX::emitSPMDEntryHeader(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001376 CodeGenFunction &CGF, EntryFunctionState &EST,
1377 const OMPExecutableDirective &D) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001378 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001379
1380 // Setup BBs in entry function.
1381 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute");
1382 EST.ExitBB = CGF.createBasicBlock(".exit");
1383
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001384 llvm::Value *Args[] = {getThreadLimit(CGF, /*IsInSPMDExecutionMode=*/true),
1385 /*RequiresOMPRuntime=*/
1386 Bld.getInt16(RequiresFullRuntime ? 1 : 0),
1387 /*RequiresDataSharing=*/Bld.getInt16(0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001388 CGF.EmitRuntimeCall(
1389 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_init), Args);
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001390
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001391 if (RequiresFullRuntime) {
1392 // For data sharing, we need to initialize the stack.
1393 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1394 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd));
1395 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001396
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001397 CGF.EmitBranch(ExecuteBB);
1398
1399 CGF.EmitBlock(ExecuteBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001400
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001401 IsInTargetMasterThreadRegion = true;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001402}
1403
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001404void CGOpenMPRuntimeNVPTX::emitSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001405 EntryFunctionState &EST) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001406 IsInTargetMasterThreadRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001407 if (!CGF.HaveInsertPoint())
1408 return;
1409
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001410 if (!EST.ExitBB)
1411 EST.ExitBB = CGF.createBasicBlock(".exit");
1412
1413 llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit");
1414 CGF.EmitBranch(OMPDeInitBB);
1415
1416 CGF.EmitBlock(OMPDeInitBB);
1417 // DeInitialize the OMP state in the runtime; called by all active threads.
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001418 llvm::Value *Args[] = {/*RequiresOMPRuntime=*/
1419 CGF.Builder.getInt16(RequiresFullRuntime ? 1 : 0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001420 CGF.EmitRuntimeCall(
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001421 createNVPTXRuntimeFunction(
1422 OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2), Args);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001423 CGF.EmitBranch(EST.ExitBB);
1424
1425 CGF.EmitBlock(EST.ExitBB);
1426 EST.ExitBB = nullptr;
1427}
1428
1429// Create a unique global variable to indicate the execution mode of this target
1430// region. The execution mode is either 'generic', or 'spmd' depending on the
1431// target directive. This variable is picked up by the offload library to setup
1432// the device appropriately before kernel launch. If the execution mode is
1433// 'generic', the runtime reserves one warp for the master, otherwise, all
1434// warps participate in parallel work.
1435static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001436 bool Mode) {
1437 auto *GVMode =
1438 new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
1439 llvm::GlobalValue::WeakAnyLinkage,
1440 llvm::ConstantInt::get(CGM.Int8Ty, Mode ? 0 : 1),
1441 Twine(Name, "_exec_mode"));
Alexey Bataev9ff80832018-04-16 20:16:21 +00001442 CGM.addCompilerUsedGlobal(GVMode);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001443}
1444
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001445void CGOpenMPRuntimeNVPTX::emitWorkerFunction(WorkerFunctionState &WST) {
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +00001446 ASTContext &Ctx = CGM.getContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001447
1448 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001449 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, WST.CGFI, {},
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001450 WST.Loc, WST.Loc);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001451 emitWorkerLoop(CGF, WST);
1452 CGF.FinishFunction();
1453}
1454
1455void CGOpenMPRuntimeNVPTX::emitWorkerLoop(CodeGenFunction &CGF,
1456 WorkerFunctionState &WST) {
1457 //
1458 // The workers enter this loop and wait for parallel work from the master.
1459 // When the master encounters a parallel region it sets up the work + variable
1460 // arguments, and wakes up the workers. The workers first check to see if
1461 // they are required for the parallel region, i.e., within the # of requested
1462 // parallel threads. The activated workers load the variable arguments and
1463 // execute the parallel work.
1464 //
1465
1466 CGBuilderTy &Bld = CGF.Builder;
1467
1468 llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work");
1469 llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers");
1470 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel");
1471 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel");
1472 llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel");
1473 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1474
1475 CGF.EmitBranch(AwaitBB);
1476
1477 // Workers wait for work from master.
1478 CGF.EmitBlock(AwaitBB);
1479 // Wait for parallel work
1480 syncCTAThreads(CGF);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001481
1482 Address WorkFn =
1483 CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn");
1484 Address ExecStatus =
1485 CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status");
1486 CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0));
1487 CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy));
1488
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001489 // TODO: Optimize runtime initialization and pass in correct value.
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001490 llvm::Value *Args[] = {WorkFn.getPointer(),
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001491 /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001492 llvm::Value *Ret = CGF.EmitRuntimeCall(
1493 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args);
1494 Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001495
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001496 // On termination condition (workid == 0), exit loop.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001497 llvm::Value *WorkID = Bld.CreateLoad(WorkFn);
1498 llvm::Value *ShouldTerminate = Bld.CreateIsNull(WorkID, "should_terminate");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001499 Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB);
1500
1501 // Activate requested workers.
1502 CGF.EmitBlock(SelectWorkersBB);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001503 llvm::Value *IsActive =
1504 Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active");
1505 Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001506
1507 // Signal start of parallel region.
1508 CGF.EmitBlock(ExecuteBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001509 // Skip initialization.
1510 setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001511
1512 // Process work items: outlined parallel functions.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001513 for (llvm::Function *W : Work) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001514 // Try to match this outlined function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001515 llvm::Value *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001516
1517 llvm::Value *WorkFnMatch =
1518 Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match");
1519
1520 llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn");
1521 llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next");
1522 Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB);
1523
1524 // Execute this outlined function.
1525 CGF.EmitBlock(ExecuteFNBB);
1526
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001527 // Insert call to work function via shared wrapper. The shared
1528 // wrapper takes two arguments:
1529 // - the parallelism level;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001530 // - the thread ID;
1531 emitCall(CGF, WST.Loc, W,
1532 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001533
1534 // Go to end of parallel region.
1535 CGF.EmitBranch(TerminateBB);
1536
1537 CGF.EmitBlock(CheckNextBB);
1538 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001539 // Default case: call to outlined function through pointer if the target
1540 // region makes a declare target call that may contain an orphaned parallel
1541 // directive.
1542 auto *ParallelFnTy =
1543 llvm::FunctionType::get(CGM.VoidTy, {CGM.Int16Ty, CGM.Int32Ty},
1544 /*isVarArg=*/false)
1545 ->getPointerTo();
1546 llvm::Value *WorkFnCast = Bld.CreateBitCast(WorkID, ParallelFnTy);
1547 // Insert call to work function via shared wrapper. The shared
1548 // wrapper takes two arguments:
1549 // - the parallelism level;
1550 // - the thread ID;
1551 emitCall(CGF, WST.Loc, WorkFnCast,
1552 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
1553 // Go to end of parallel region.
1554 CGF.EmitBranch(TerminateBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001555
1556 // Signal end of parallel region.
1557 CGF.EmitBlock(TerminateBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001558 CGF.EmitRuntimeCall(
1559 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_end_parallel),
1560 llvm::None);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001561 CGF.EmitBranch(BarrierBB);
1562
1563 // All active and inactive workers wait at a barrier after parallel region.
1564 CGF.EmitBlock(BarrierBB);
1565 // Barrier after parallel region.
1566 syncCTAThreads(CGF);
1567 CGF.EmitBranch(AwaitBB);
1568
1569 // Exit target region.
1570 CGF.EmitBlock(ExitBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001571 // Skip initialization.
1572 clearLocThreadIdInsertPt(CGF);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001573}
1574
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001575/// Returns specified OpenMP runtime function for the current OpenMP
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001576/// implementation. Specialized for the NVPTX device.
1577/// \param Function OpenMP runtime function.
1578/// \return Specified function.
1579llvm::Constant *
1580CGOpenMPRuntimeNVPTX::createNVPTXRuntimeFunction(unsigned Function) {
1581 llvm::Constant *RTLFn = nullptr;
1582 switch (static_cast<OpenMPRTLFunctionNVPTX>(Function)) {
1583 case OMPRTL_NVPTX__kmpc_kernel_init: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001584 // Build void __kmpc_kernel_init(kmp_int32 thread_limit, int16_t
1585 // RequiresOMPRuntime);
1586 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001587 auto *FnTy =
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001588 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1589 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_init");
1590 break;
1591 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001592 case OMPRTL_NVPTX__kmpc_kernel_deinit: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001593 // Build void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
1594 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001595 auto *FnTy =
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001596 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001597 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_deinit");
1598 break;
1599 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001600 case OMPRTL_NVPTX__kmpc_spmd_kernel_init: {
1601 // Build void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001602 // int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001603 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001604 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001605 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1606 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_init");
1607 break;
1608 }
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001609 case OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2: {
1610 // Build void __kmpc_spmd_kernel_deinit_v2(int16_t RequiresOMPRuntime);
1611 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001612 auto *FnTy =
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001613 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1614 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_deinit_v2");
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001615 break;
1616 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001617 case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: {
1618 /// Build void __kmpc_kernel_prepare_parallel(
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001619 /// void *outlined_function, int16_t IsOMPRuntimeInitialized);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001620 llvm::Type *TypeParams[] = {CGM.Int8PtrTy, CGM.Int16Ty};
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_kernel_prepare_parallel");
1624 break;
1625 }
1626 case OMPRTL_NVPTX__kmpc_kernel_parallel: {
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001627 /// Build bool __kmpc_kernel_parallel(void **outlined_function,
1628 /// int16_t IsOMPRuntimeInitialized);
1629 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy, CGM.Int16Ty};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001630 llvm::Type *RetTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001631 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001632 llvm::FunctionType::get(RetTy, TypeParams, /*isVarArg*/ false);
1633 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_parallel");
1634 break;
1635 }
1636 case OMPRTL_NVPTX__kmpc_kernel_end_parallel: {
1637 /// Build void __kmpc_kernel_end_parallel();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001638 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001639 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1640 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_end_parallel");
1641 break;
1642 }
1643 case OMPRTL_NVPTX__kmpc_serialized_parallel: {
1644 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1645 // global_tid);
1646 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001647 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001648 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1649 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1650 break;
1651 }
1652 case OMPRTL_NVPTX__kmpc_end_serialized_parallel: {
1653 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1654 // global_tid);
1655 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001656 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001657 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1658 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1659 break;
1660 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001661 case OMPRTL_NVPTX__kmpc_shuffle_int32: {
1662 // Build int32_t __kmpc_shuffle_int32(int32_t element,
1663 // int16_t lane_offset, int16_t warp_size);
1664 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001665 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001666 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1667 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int32");
1668 break;
1669 }
1670 case OMPRTL_NVPTX__kmpc_shuffle_int64: {
1671 // Build int64_t __kmpc_shuffle_int64(int64_t element,
1672 // int16_t lane_offset, int16_t warp_size);
1673 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001674 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001675 llvm::FunctionType::get(CGM.Int64Ty, TypeParams, /*isVarArg*/ false);
1676 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int64");
1677 break;
1678 }
1679 case OMPRTL_NVPTX__kmpc_parallel_reduce_nowait: {
1680 // Build int32_t kmpc_nvptx_parallel_reduce_nowait(kmp_int32 global_tid,
1681 // kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
1682 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1683 // lane_offset, int16_t Algorithm Version),
1684 // void (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
1685 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1686 CGM.Int16Ty, CGM.Int16Ty};
1687 auto *ShuffleReduceFnTy =
1688 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1689 /*isVarArg=*/false);
1690 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1691 auto *InterWarpCopyFnTy =
1692 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1693 /*isVarArg=*/false);
1694 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1695 CGM.Int32Ty,
1696 CGM.SizeTy,
1697 CGM.VoidPtrTy,
1698 ShuffleReduceFnTy->getPointerTo(),
1699 InterWarpCopyFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001700 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001701 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1702 RTLFn = CGM.CreateRuntimeFunction(
1703 FnTy, /*Name=*/"__kmpc_nvptx_parallel_reduce_nowait");
1704 break;
1705 }
1706 case OMPRTL_NVPTX__kmpc_end_reduce_nowait: {
1707 // Build __kmpc_end_reduce_nowait(kmp_int32 global_tid);
1708 llvm::Type *TypeParams[] = {CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001709 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001710 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1711 RTLFn = CGM.CreateRuntimeFunction(
1712 FnTy, /*Name=*/"__kmpc_nvptx_end_reduce_nowait");
1713 break;
1714 }
Alexey Bataeva1166022018-11-27 21:24:54 +00001715 case OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_simple: {
1716 // Build __kmpc_nvptx_teams_reduce_nowait_simple(ident_t *loc, kmp_int32
1717 // global_tid, kmp_critical_name *lck)
1718 llvm::Type *TypeParams[] = {
1719 getIdentTyPointerTy(), CGM.Int32Ty,
1720 llvm::PointerType::getUnqual(getKmpCriticalNameTy())};
1721 auto *FnTy =
1722 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1723 RTLFn = CGM.CreateRuntimeFunction(
1724 FnTy, /*Name=*/"__kmpc_nvptx_teams_reduce_nowait_simple");
1725 break;
1726 }
1727 case OMPRTL_NVPTX__kmpc_nvptx_teams_end_reduce_nowait_simple: {
1728 // Build __kmpc_nvptx_teams_end_reduce_nowait_simple(ident_t *loc, kmp_int32
1729 // global_tid, kmp_critical_name *lck)
1730 llvm::Type *TypeParams[] = {
1731 getIdentTyPointerTy(), CGM.Int32Ty,
1732 llvm::PointerType::getUnqual(getKmpCriticalNameTy())};
1733 auto *FnTy =
1734 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1735 RTLFn = CGM.CreateRuntimeFunction(
1736 FnTy, /*Name=*/"__kmpc_nvptx_teams_end_reduce_nowait_simple");
1737 break;
1738 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001739 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack: {
1740 /// Build void __kmpc_data_sharing_init_stack();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001741 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001742 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1743 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack");
1744 break;
1745 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001746 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd: {
1747 /// Build void __kmpc_data_sharing_init_stack_spmd();
1748 auto *FnTy =
1749 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001750 RTLFn =
1751 CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack_spmd");
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001752 break;
1753 }
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001754 case OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack: {
1755 // Build void *__kmpc_data_sharing_coalesced_push_stack(size_t size,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001756 // int16_t UseSharedMemory);
1757 llvm::Type *TypeParams[] = {CGM.SizeTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001758 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001759 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1760 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001761 FnTy, /*Name=*/"__kmpc_data_sharing_coalesced_push_stack");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001762 break;
1763 }
1764 case OMPRTL_NVPTX__kmpc_data_sharing_pop_stack: {
1765 // Build void __kmpc_data_sharing_pop_stack(void *a);
1766 llvm::Type *TypeParams[] = {CGM.VoidPtrTy};
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,
1770 /*Name=*/"__kmpc_data_sharing_pop_stack");
1771 break;
1772 }
1773 case OMPRTL_NVPTX__kmpc_begin_sharing_variables: {
1774 /// Build void __kmpc_begin_sharing_variables(void ***args,
1775 /// size_t n_args);
1776 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo(), CGM.SizeTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001777 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001778 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1779 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_begin_sharing_variables");
1780 break;
1781 }
1782 case OMPRTL_NVPTX__kmpc_end_sharing_variables: {
1783 /// Build void __kmpc_end_sharing_variables();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001784 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001785 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1786 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_sharing_variables");
1787 break;
1788 }
1789 case OMPRTL_NVPTX__kmpc_get_shared_variables: {
1790 /// Build void __kmpc_get_shared_variables(void ***GlobalArgs);
1791 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001792 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001793 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1794 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_shared_variables");
1795 break;
1796 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001797 case OMPRTL_NVPTX__kmpc_parallel_level: {
1798 // Build uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32 global_tid);
1799 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1800 auto *FnTy =
1801 llvm::FunctionType::get(CGM.Int16Ty, TypeParams, /*isVarArg*/ false);
1802 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_parallel_level");
1803 break;
1804 }
Alexey Bataev673110d2018-05-16 13:36:30 +00001805 case OMPRTL_NVPTX__kmpc_is_spmd_exec_mode: {
1806 // Build int8_t __kmpc_is_spmd_exec_mode();
1807 auto *FnTy = llvm::FunctionType::get(CGM.Int8Ty, /*isVarArg=*/false);
1808 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_is_spmd_exec_mode");
1809 break;
1810 }
Alexey Bataeve4090182018-11-02 14:54:07 +00001811 case OMPRTL_NVPTX__kmpc_get_team_static_memory: {
1812 // Build void __kmpc_get_team_static_memory(const void *buf, size_t size,
1813 // int16_t is_shared, const void **res);
1814 llvm::Type *TypeParams[] = {CGM.VoidPtrTy, CGM.SizeTy, CGM.Int16Ty,
1815 CGM.VoidPtrPtrTy};
1816 auto *FnTy =
1817 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1818 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_team_static_memory");
1819 break;
1820 }
1821 case OMPRTL_NVPTX__kmpc_restore_team_static_memory: {
1822 // Build void __kmpc_restore_team_static_memory(int16_t is_shared);
1823 auto *FnTy =
1824 llvm::FunctionType::get(CGM.VoidTy, CGM.Int16Ty, /*isVarArg=*/false);
1825 RTLFn =
1826 CGM.CreateRuntimeFunction(FnTy, "__kmpc_restore_team_static_memory");
1827 break;
1828 }
Alexey Bataevc3028ca2018-12-04 15:03:25 +00001829 case OMPRTL__kmpc_barrier: {
1830 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
1831 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1832 auto *FnTy =
1833 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1834 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1835 cast<llvm::Function>(RTLFn)->addFnAttr(llvm::Attribute::Convergent);
1836 break;
1837 }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001838 }
1839 return RTLFn;
1840}
1841
1842void CGOpenMPRuntimeNVPTX::createOffloadEntry(llvm::Constant *ID,
1843 llvm::Constant *Addr,
Alexey Bataev03f270c2018-03-30 18:31:07 +00001844 uint64_t Size, int32_t,
1845 llvm::GlobalValue::LinkageTypes) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001846 // TODO: Add support for global variables on the device after declare target
1847 // support.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001848 if (!isa<llvm::Function>(Addr))
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001849 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +00001850 llvm::Module &M = CGM.getModule();
1851 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001852
1853 // Get "nvvm.annotations" metadata node
Alexey Bataev9ff80832018-04-16 20:16:21 +00001854 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001855
1856 llvm::Metadata *MDVals[] = {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001857 llvm::ConstantAsMetadata::get(Addr), llvm::MDString::get(Ctx, "kernel"),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001858 llvm::ConstantAsMetadata::get(
1859 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))};
1860 // Append metadata to nvvm.annotations
1861 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
1862}
1863
1864void CGOpenMPRuntimeNVPTX::emitTargetOutlinedFunction(
1865 const OMPExecutableDirective &D, StringRef ParentName,
1866 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001867 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001868 if (!IsOffloadEntry) // Nothing to do.
1869 return;
1870
1871 assert(!ParentName.empty() && "Invalid target region parent name!");
1872
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001873 bool Mode = supportsSPMDExecutionMode(CGM.getContext(), D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001874 if (Mode)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001875 emitSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001876 CodeGen);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001877 else
1878 emitNonSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1879 CodeGen);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001880
1881 setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001882}
1883
Alexey Bataevceeaa482018-11-21 21:04:34 +00001884namespace {
1885LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
1886/// Enum for accesseing the reserved_2 field of the ident_t struct.
1887enum ModeFlagsTy : unsigned {
1888 /// Bit set to 1 when in SPMD mode.
1889 KMP_IDENT_SPMD_MODE = 0x01,
1890 /// Bit set to 1 when a simplified runtime is used.
1891 KMP_IDENT_SIMPLE_RT_MODE = 0x02,
1892 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/KMP_IDENT_SIMPLE_RT_MODE)
1893};
1894
1895/// Special mode Undefined. Is the combination of Non-SPMD mode + SimpleRuntime.
1896static const ModeFlagsTy UndefinedMode =
1897 (~KMP_IDENT_SPMD_MODE) & KMP_IDENT_SIMPLE_RT_MODE;
1898} // anonymous namespace
1899
1900unsigned CGOpenMPRuntimeNVPTX::getDefaultLocationReserved2Flags() const {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001901 switch (getExecutionMode()) {
1902 case EM_SPMD:
1903 if (requiresFullRuntime())
1904 return KMP_IDENT_SPMD_MODE & (~KMP_IDENT_SIMPLE_RT_MODE);
1905 return KMP_IDENT_SPMD_MODE | KMP_IDENT_SIMPLE_RT_MODE;
1906 case EM_NonSPMD:
1907 assert(requiresFullRuntime() && "Expected full runtime.");
1908 return (~KMP_IDENT_SPMD_MODE) & (~KMP_IDENT_SIMPLE_RT_MODE);
1909 case EM_Unknown:
1910 return UndefinedMode;
1911 }
1912 llvm_unreachable("Unknown flags are requested.");
Alexey Bataevceeaa482018-11-21 21:04:34 +00001913}
1914
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001915CGOpenMPRuntimeNVPTX::CGOpenMPRuntimeNVPTX(CodeGenModule &CGM)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001916 : CGOpenMPRuntime(CGM, "_", "$") {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001917 if (!CGM.getLangOpts().OpenMPIsDevice)
1918 llvm_unreachable("OpenMP NVPTX can only handle device code.");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001919}
Carlo Bertollic6872252016-04-04 15:55:02 +00001920
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001921void CGOpenMPRuntimeNVPTX::emitProcBindClause(CodeGenFunction &CGF,
1922 OpenMPProcBindClauseKind ProcBind,
1923 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001924 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001925 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001926 return;
1927
1928 CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc);
1929}
1930
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001931void CGOpenMPRuntimeNVPTX::emitNumThreadsClause(CodeGenFunction &CGF,
1932 llvm::Value *NumThreads,
1933 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001934 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001935 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001936 return;
1937
1938 CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc);
1939}
1940
Carlo Bertollic6872252016-04-04 15:55:02 +00001941void CGOpenMPRuntimeNVPTX::emitNumTeamsClause(CodeGenFunction &CGF,
1942 const Expr *NumTeams,
1943 const Expr *ThreadLimit,
1944 SourceLocation Loc) {}
1945
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001946llvm::Value *CGOpenMPRuntimeNVPTX::emitParallelOutlinedFunction(
1947 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1948 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00001949 // Emit target region as a standalone region.
1950 class NVPTXPrePostActionTy : public PrePostActionTy {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001951 bool &IsInParallelRegion;
1952 bool PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001953
1954 public:
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001955 NVPTXPrePostActionTy(bool &IsInParallelRegion)
1956 : IsInParallelRegion(IsInParallelRegion) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00001957 void Enter(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001958 PrevIsInParallelRegion = IsInParallelRegion;
1959 IsInParallelRegion = true;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001960 }
1961 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001962 IsInParallelRegion = PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001963 }
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001964 } Action(IsInParallelRegion);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001965 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001966 bool PrevIsInTTDRegion = IsInTTDRegion;
1967 IsInTTDRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001968 bool PrevIsInTargetMasterThreadRegion = IsInTargetMasterThreadRegion;
1969 IsInTargetMasterThreadRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001970 auto *OutlinedFun =
1971 cast<llvm::Function>(CGOpenMPRuntime::emitParallelOutlinedFunction(
1972 D, ThreadIDVar, InnermostKind, CodeGen));
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001973 IsInTargetMasterThreadRegion = PrevIsInTargetMasterThreadRegion;
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001974 IsInTTDRegion = PrevIsInTTDRegion;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001975 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD &&
1976 !IsInParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001977 llvm::Function *WrapperFun =
1978 createParallelDataSharingWrapper(OutlinedFun, D);
1979 WrapperFunctionsMap[OutlinedFun] = WrapperFun;
1980 }
1981
1982 return OutlinedFun;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001983}
1984
Alexey Bataev2adecff2018-09-21 14:22:53 +00001985/// Get list of lastprivate variables from the teams distribute ... or
1986/// teams {distribute ...} directives.
1987static void
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001988getDistributeLastprivateVars(ASTContext &Ctx, const OMPExecutableDirective &D,
Alexey Bataev2adecff2018-09-21 14:22:53 +00001989 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
1990 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
1991 "expected teams directive.");
1992 const OMPExecutableDirective *Dir = &D;
1993 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
1994 if (const Stmt *S = getSingleCompoundChild(
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001995 Ctx,
Alexey Bataev2adecff2018-09-21 14:22:53 +00001996 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
1997 /*IgnoreCaptured=*/true))) {
1998 Dir = dyn_cast<OMPExecutableDirective>(S);
1999 if (Dir && !isOpenMPDistributeDirective(Dir->getDirectiveKind()))
2000 Dir = nullptr;
2001 }
2002 }
2003 if (!Dir)
2004 return;
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002005 for (const auto *C : Dir->getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002006 for (const Expr *E : C->getVarRefs())
2007 Vars.push_back(getPrivateItem(E));
2008 }
2009}
2010
2011/// Get list of reduction variables from the teams ... directives.
2012static void
2013getTeamsReductionVars(ASTContext &Ctx, const OMPExecutableDirective &D,
2014 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
2015 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
2016 "expected teams directive.");
2017 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
2018 for (const Expr *E : C->privates())
2019 Vars.push_back(getPrivateItem(E));
Alexey Bataev2adecff2018-09-21 14:22:53 +00002020 }
2021}
2022
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002023llvm::Value *CGOpenMPRuntimeNVPTX::emitTeamsOutlinedFunction(
Carlo Bertollic6872252016-04-04 15:55:02 +00002024 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
2025 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002026 SourceLocation Loc = D.getBeginLoc();
Carlo Bertollic6872252016-04-04 15:55:02 +00002027
Alexey Bataev2adecff2018-09-21 14:22:53 +00002028 const RecordDecl *GlobalizedRD = nullptr;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002029 llvm::SmallVector<const ValueDecl *, 4> LastPrivatesReductions;
Alexey Bataev2adecff2018-09-21 14:22:53 +00002030 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002031 // Globalize team reductions variable unconditionally in all modes.
2032 getTeamsReductionVars(CGM.getContext(), D, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002033 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002034 getDistributeLastprivateVars(CGM.getContext(), D, LastPrivatesReductions);
2035 if (!LastPrivatesReductions.empty()) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002036 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002037 CGM.getContext(), llvm::None, LastPrivatesReductions,
2038 MappedDeclsFields);
2039 }
2040 } else if (!LastPrivatesReductions.empty()) {
2041 assert(!TeamAndReductions.first &&
2042 "Previous team declaration is not expected.");
2043 TeamAndReductions.first = D.getCapturedStmt(OMPD_teams)->getCapturedDecl();
2044 std::swap(TeamAndReductions.second, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002045 }
2046
Alexey Bataevc99042b2018-03-15 18:10:54 +00002047 // Emit target region as a standalone region.
2048 class NVPTXPrePostActionTy : public PrePostActionTy {
2049 SourceLocation &Loc;
Alexey Bataev2adecff2018-09-21 14:22:53 +00002050 const RecordDecl *GlobalizedRD;
2051 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2052 &MappedDeclsFields;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002053
2054 public:
Alexey Bataev2adecff2018-09-21 14:22:53 +00002055 NVPTXPrePostActionTy(
2056 SourceLocation &Loc, const RecordDecl *GlobalizedRD,
2057 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2058 &MappedDeclsFields)
2059 : Loc(Loc), GlobalizedRD(GlobalizedRD),
2060 MappedDeclsFields(MappedDeclsFields) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00002061 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002062 auto &Rt =
2063 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
2064 if (GlobalizedRD) {
2065 auto I = Rt.FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
2066 I->getSecond().GlobalRecord = GlobalizedRD;
2067 I->getSecond().MappedParams =
2068 llvm::make_unique<CodeGenFunction::OMPMapVars>();
2069 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
2070 for (const auto &Pair : MappedDeclsFields) {
2071 assert(Pair.getFirst()->isCanonicalDecl() &&
2072 "Expected canonical declaration");
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002073 Data.insert(std::make_pair(Pair.getFirst(),
2074 MappedVarData(Pair.getSecond(),
2075 /*IsOnePerTeam=*/true)));
Alexey Bataev2adecff2018-09-21 14:22:53 +00002076 }
2077 }
2078 Rt.emitGenericVarsProlog(CGF, Loc);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002079 }
2080 void Exit(CodeGenFunction &CGF) override {
2081 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
2082 .emitGenericVarsEpilog(CGF);
2083 }
Alexey Bataev2adecff2018-09-21 14:22:53 +00002084 } Action(Loc, GlobalizedRD, MappedDeclsFields);
2085 CodeGen.setAction(Action);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002086 llvm::Value *OutlinedFunVal = CGOpenMPRuntime::emitTeamsOutlinedFunction(
2087 D, ThreadIDVar, InnermostKind, CodeGen);
2088 llvm::Function *OutlinedFun = cast<llvm::Function>(OutlinedFunVal);
2089 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00002090 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002091 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
Carlo Bertollic6872252016-04-04 15:55:02 +00002092
2093 return OutlinedFun;
2094}
2095
Alexey Bataevc99042b2018-03-15 18:10:54 +00002096void CGOpenMPRuntimeNVPTX::emitGenericVarsProlog(CodeGenFunction &CGF,
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002097 SourceLocation Loc,
2098 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002099 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2100 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002101 return;
2102
Alexey Bataevc99042b2018-03-15 18:10:54 +00002103 CGBuilderTy &Bld = CGF.Builder;
2104
2105 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
2106 if (I == FunctionGlobalizedDecls.end())
2107 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002108 if (const RecordDecl *GlobalizedVarsRecord = I->getSecond().GlobalRecord) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002109 QualType GlobalRecTy = CGM.getContext().getRecordType(GlobalizedVarsRecord);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002110 QualType SecGlobalRecTy;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002111
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002112 // Recover pointer to this function's global record. The runtime will
2113 // handle the specifics of the allocation of the memory.
2114 // Use actual memory size of the record including the padding
2115 // for alignment purposes.
2116 unsigned Alignment =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002117 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002118 unsigned GlobalRecordSize =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002119 CGM.getContext().getTypeSizeInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002120 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002121
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002122 llvm::PointerType *GlobalRecPtrTy =
2123 CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo();
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002124 llvm::Value *GlobalRecCastAddr;
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002125 llvm::Value *IsTTD = nullptr;
Alexey Bataeve4090182018-11-02 14:54:07 +00002126 if (!IsInTTDRegion &&
2127 (WithSPMDCheck ||
2128 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002129 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2130 llvm::BasicBlock *SPMDBB = CGF.createBasicBlock(".spmd");
2131 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002132 if (I->getSecond().SecondaryGlobalRecord.hasValue()) {
2133 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2134 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2135 llvm::Value *PL = CGF.EmitRuntimeCall(
2136 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2137 {RTLoc, ThreadID});
2138 IsTTD = Bld.CreateIsNull(PL);
2139 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002140 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2141 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
2142 Bld.CreateCondBr(IsSPMD, SPMDBB, NonSPMDBB);
2143 // There is no need to emit line number for unconditional branch.
2144 (void)ApplyDebugLocation::CreateEmpty(CGF);
2145 CGF.EmitBlock(SPMDBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002146 Address RecPtr = Address(llvm::ConstantPointerNull::get(GlobalRecPtrTy),
2147 CharUnits::fromQuantity(Alignment));
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002148 CGF.EmitBranch(ExitBB);
2149 // There is no need to emit line number for unconditional branch.
2150 (void)ApplyDebugLocation::CreateEmpty(CGF);
2151 CGF.EmitBlock(NonSPMDBB);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002152 llvm::Value *Size = llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize);
2153 if (const RecordDecl *SecGlobalizedVarsRecord =
2154 I->getSecond().SecondaryGlobalRecord.getValueOr(nullptr)) {
2155 SecGlobalRecTy =
2156 CGM.getContext().getRecordType(SecGlobalizedVarsRecord);
2157
2158 // Recover pointer to this function's global record. The runtime will
2159 // handle the specifics of the allocation of the memory.
2160 // Use actual memory size of the record including the padding
2161 // for alignment purposes.
2162 unsigned Alignment =
2163 CGM.getContext().getTypeAlignInChars(SecGlobalRecTy).getQuantity();
2164 unsigned GlobalRecordSize =
2165 CGM.getContext().getTypeSizeInChars(SecGlobalRecTy).getQuantity();
2166 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
2167 Size = Bld.CreateSelect(
2168 IsTTD, llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize), Size);
2169 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002170 // TODO: allow the usage of shared memory to be controlled by
2171 // the user, for now, default to global.
2172 llvm::Value *GlobalRecordSizeArg[] = {
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002173 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002174 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2175 createNVPTXRuntimeFunction(
2176 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2177 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002178 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002179 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002180 CGF.EmitBlock(ExitBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002181 auto *Phi = Bld.CreatePHI(GlobalRecPtrTy,
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002182 /*NumReservedValues=*/2, "_select_stack");
2183 Phi->addIncoming(RecPtr.getPointer(), SPMDBB);
2184 Phi->addIncoming(GlobalRecCastAddr, NonSPMDBB);
2185 GlobalRecCastAddr = Phi;
2186 I->getSecond().GlobalRecordAddr = Phi;
2187 I->getSecond().IsInSPMDModeFlag = IsSPMD;
Alexey Bataeve4090182018-11-02 14:54:07 +00002188 } else if (IsInTTDRegion) {
2189 assert(GlobalizedRecords.back().Records.size() < 2 &&
2190 "Expected less than 2 globalized records: one for target and one "
2191 "for teams.");
2192 unsigned Offset = 0;
2193 for (const RecordDecl *RD : GlobalizedRecords.back().Records) {
2194 QualType RDTy = CGM.getContext().getRecordType(RD);
2195 unsigned Alignment =
2196 CGM.getContext().getTypeAlignInChars(RDTy).getQuantity();
2197 unsigned Size = CGM.getContext().getTypeSizeInChars(RDTy).getQuantity();
2198 Offset =
2199 llvm::alignTo(llvm::alignTo(Offset, Alignment) + Size, Alignment);
2200 }
2201 unsigned Alignment =
2202 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
2203 Offset = llvm::alignTo(Offset, Alignment);
2204 GlobalizedRecords.back().Records.push_back(GlobalizedVarsRecord);
2205 ++GlobalizedRecords.back().RegionCounter;
2206 if (GlobalizedRecords.back().Records.size() == 1) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002207 assert(KernelStaticGlobalized &&
2208 "Kernel static pointer must be initialized already.");
2209 auto *UseSharedMemory = new llvm::GlobalVariable(
2210 CGM.getModule(), CGM.Int16Ty, /*isConstant=*/true,
2211 llvm::GlobalValue::InternalLinkage, nullptr,
2212 "_openmp_static_kernel$is_shared");
2213 UseSharedMemory->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2214 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2215 /*DestWidth=*/16, /*Signed=*/0);
2216 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2217 Address(UseSharedMemory,
2218 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2219 /*Volatile=*/false, Int16Ty, Loc);
2220 auto *StaticGlobalized = new llvm::GlobalVariable(
2221 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002222 llvm::GlobalValue::CommonLinkage, nullptr);
Alexey Bataeve4090182018-11-02 14:54:07 +00002223 auto *RecSize = new llvm::GlobalVariable(
2224 CGM.getModule(), CGM.SizeTy, /*isConstant=*/true,
2225 llvm::GlobalValue::InternalLinkage, nullptr,
2226 "_openmp_static_kernel$size");
2227 RecSize->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2228 llvm::Value *Ld = CGF.EmitLoadOfScalar(
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002229 Address(RecSize, CGM.getSizeAlign()), /*Volatile=*/false,
Alexey Bataeve4090182018-11-02 14:54:07 +00002230 CGM.getContext().getSizeType(), Loc);
2231 llvm::Value *ResAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2232 KernelStaticGlobalized, CGM.VoidPtrPtrTy);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002233 llvm::Value *GlobalRecordSizeArg[] = {StaticGlobalized, Ld,
2234 IsInSharedMemory, ResAddr};
Alexey Bataeve4090182018-11-02 14:54:07 +00002235 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2236 OMPRTL_NVPTX__kmpc_get_team_static_memory),
2237 GlobalRecordSizeArg);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002238 GlobalizedRecords.back().Buffer = StaticGlobalized;
Alexey Bataeve4090182018-11-02 14:54:07 +00002239 GlobalizedRecords.back().RecSize = RecSize;
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002240 GlobalizedRecords.back().UseSharedMemory = UseSharedMemory;
2241 GlobalizedRecords.back().Loc = Loc;
Alexey Bataeve4090182018-11-02 14:54:07 +00002242 }
2243 assert(KernelStaticGlobalized && "Global address must be set already.");
2244 Address FrameAddr = CGF.EmitLoadOfPointer(
2245 Address(KernelStaticGlobalized, CGM.getPointerAlign()),
2246 CGM.getContext()
2247 .getPointerType(CGM.getContext().VoidPtrTy)
2248 .castAs<PointerType>());
2249 llvm::Value *GlobalRecValue =
2250 Bld.CreateConstInBoundsGEP(FrameAddr, Offset, CharUnits::One())
2251 .getPointer();
2252 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2253 I->getSecond().IsInSPMDModeFlag = nullptr;
2254 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2255 GlobalRecValue, CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo());
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002256 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002257 // TODO: allow the usage of shared memory to be controlled by
2258 // the user, for now, default to global.
2259 llvm::Value *GlobalRecordSizeArg[] = {
2260 llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize),
2261 CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002262 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2263 createNVPTXRuntimeFunction(
2264 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2265 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002266 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002267 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002268 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2269 I->getSecond().IsInSPMDModeFlag = nullptr;
2270 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002271 LValue Base =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002272 CGF.MakeNaturalAlignPointeeAddrLValue(GlobalRecCastAddr, GlobalRecTy);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002273
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002274 // Emit the "global alloca" which is a GEP from the global declaration
2275 // record using the pointer returned by the runtime.
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002276 LValue SecBase;
2277 decltype(I->getSecond().LocalVarData)::const_iterator SecIt;
2278 if (IsTTD) {
2279 SecIt = I->getSecond().SecondaryLocalVarData->begin();
2280 llvm::PointerType *SecGlobalRecPtrTy =
2281 CGF.ConvertTypeForMem(SecGlobalRecTy)->getPointerTo();
2282 SecBase = CGF.MakeNaturalAlignPointeeAddrLValue(
2283 Bld.CreatePointerBitCastOrAddrSpaceCast(
2284 I->getSecond().GlobalRecordAddr, SecGlobalRecPtrTy),
2285 SecGlobalRecTy);
2286 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002287 for (auto &Rec : I->getSecond().LocalVarData) {
2288 bool EscapedParam = I->getSecond().EscapedParameters.count(Rec.first);
2289 llvm::Value *ParValue;
2290 if (EscapedParam) {
2291 const auto *VD = cast<VarDecl>(Rec.first);
2292 LValue ParLVal =
2293 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
2294 ParValue = CGF.EmitLoadOfScalar(ParLVal, Loc);
2295 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002296 LValue VarAddr = CGF.EmitLValueForField(Base, Rec.second.FD);
2297 // Emit VarAddr basing on lane-id if required.
2298 QualType VarTy;
2299 if (Rec.second.IsOnePerTeam) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002300 VarTy = Rec.second.FD->getType();
2301 } else {
2302 llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(
2303 VarAddr.getAddress().getPointer(),
2304 {Bld.getInt32(0), getNVPTXLaneID(CGF)});
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002305 VarTy =
2306 Rec.second.FD->getType()->castAsArrayTypeUnsafe()->getElementType();
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002307 VarAddr = CGF.MakeAddrLValue(
2308 Address(Ptr, CGM.getContext().getDeclAlign(Rec.first)), VarTy,
2309 AlignmentSource::Decl);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002310 }
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002311 Rec.second.PrivateAddr = VarAddr.getAddress();
Alexey Bataeve4090182018-11-02 14:54:07 +00002312 if (!IsInTTDRegion &&
2313 (WithSPMDCheck ||
2314 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002315 assert(I->getSecond().IsInSPMDModeFlag &&
2316 "Expected unknown execution mode or required SPMD check.");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002317 if (IsTTD) {
2318 assert(SecIt->second.IsOnePerTeam &&
2319 "Secondary glob data must be one per team.");
2320 LValue SecVarAddr = CGF.EmitLValueForField(SecBase, SecIt->second.FD);
2321 VarAddr.setAddress(
2322 Address(Bld.CreateSelect(IsTTD, SecVarAddr.getPointer(),
2323 VarAddr.getPointer()),
2324 VarAddr.getAlignment()));
2325 Rec.second.PrivateAddr = VarAddr.getAddress();
2326 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002327 Address GlobalPtr = Rec.second.PrivateAddr;
2328 Address LocalAddr = CGF.CreateMemTemp(VarTy, Rec.second.FD->getName());
2329 Rec.second.PrivateAddr = Address(
2330 Bld.CreateSelect(I->getSecond().IsInSPMDModeFlag,
2331 LocalAddr.getPointer(), GlobalPtr.getPointer()),
2332 LocalAddr.getAlignment());
2333 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002334 if (EscapedParam) {
2335 const auto *VD = cast<VarDecl>(Rec.first);
2336 CGF.EmitStoreOfScalar(ParValue, VarAddr);
2337 I->getSecond().MappedParams->setVarAddr(CGF, VD, VarAddr.getAddress());
2338 }
Alexey Bataev93a38d62018-10-16 00:09:06 +00002339 if (IsTTD)
2340 ++SecIt;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002341 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002342 }
2343 for (const ValueDecl *VD : I->getSecond().EscapedVariableLengthDecls) {
2344 // Recover pointer to this function's global record. The runtime will
2345 // handle the specifics of the allocation of the memory.
2346 // Use actual memory size of the record including the padding
2347 // for alignment purposes.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002348 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002349 llvm::Value *Size = CGF.getTypeSize(VD->getType());
2350 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2351 Size = Bld.CreateNUWAdd(
2352 Size, llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity() - 1));
2353 llvm::Value *AlignVal =
2354 llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity());
2355 Size = Bld.CreateUDiv(Size, AlignVal);
2356 Size = Bld.CreateNUWMul(Size, AlignVal);
2357 // TODO: allow the usage of shared memory to be controlled by
2358 // the user, for now, default to global.
2359 llvm::Value *GlobalRecordSizeArg[] = {
2360 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
2361 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002362 createNVPTXRuntimeFunction(
2363 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002364 GlobalRecordSizeArg);
2365 llvm::Value *GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2366 GlobalRecValue, CGF.ConvertTypeForMem(VD->getType())->getPointerTo());
2367 LValue Base = CGF.MakeAddrLValue(GlobalRecCastAddr, VD->getType(),
2368 CGM.getContext().getDeclAlign(VD),
2369 AlignmentSource::Decl);
2370 I->getSecond().MappedParams->setVarAddr(CGF, cast<VarDecl>(VD),
2371 Base.getAddress());
2372 I->getSecond().EscapedVariableLengthDeclsAddrs.emplace_back(GlobalRecValue);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002373 }
2374 I->getSecond().MappedParams->apply(CGF);
2375}
2376
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002377void CGOpenMPRuntimeNVPTX::emitGenericVarsEpilog(CodeGenFunction &CGF,
2378 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002379 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2380 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002381 return;
2382
Alexey Bataevc99042b2018-03-15 18:10:54 +00002383 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002384 if (I != FunctionGlobalizedDecls.end()) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00002385 I->getSecond().MappedParams->restore(CGF);
2386 if (!CGF.HaveInsertPoint())
2387 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002388 for (llvm::Value *Addr :
2389 llvm::reverse(I->getSecond().EscapedVariableLengthDeclsAddrs)) {
2390 CGF.EmitRuntimeCall(
2391 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2392 Addr);
2393 }
2394 if (I->getSecond().GlobalRecordAddr) {
Alexey Bataeve4090182018-11-02 14:54:07 +00002395 if (!IsInTTDRegion &&
2396 (WithSPMDCheck ||
2397 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002398 CGBuilderTy &Bld = CGF.Builder;
2399 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2400 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
2401 Bld.CreateCondBr(I->getSecond().IsInSPMDModeFlag, ExitBB, NonSPMDBB);
2402 // There is no need to emit line number for unconditional branch.
2403 (void)ApplyDebugLocation::CreateEmpty(CGF);
2404 CGF.EmitBlock(NonSPMDBB);
2405 CGF.EmitRuntimeCall(
2406 createNVPTXRuntimeFunction(
2407 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2408 CGF.EmitCastToVoidPtr(I->getSecond().GlobalRecordAddr));
2409 CGF.EmitBlock(ExitBB);
Alexey Bataeve4090182018-11-02 14:54:07 +00002410 } else if (IsInTTDRegion) {
2411 assert(GlobalizedRecords.back().RegionCounter > 0 &&
2412 "region counter must be > 0.");
2413 --GlobalizedRecords.back().RegionCounter;
2414 // Emit the restore function only in the target region.
2415 if (GlobalizedRecords.back().RegionCounter == 0) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002416 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2417 /*DestWidth=*/16, /*Signed=*/0);
2418 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2419 Address(GlobalizedRecords.back().UseSharedMemory,
2420 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2421 /*Volatile=*/false, Int16Ty, GlobalizedRecords.back().Loc);
Alexey Bataeve4090182018-11-02 14:54:07 +00002422 CGF.EmitRuntimeCall(
2423 createNVPTXRuntimeFunction(
2424 OMPRTL_NVPTX__kmpc_restore_team_static_memory),
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002425 IsInSharedMemory);
Alexey Bataeve4090182018-11-02 14:54:07 +00002426 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002427 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002428 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2429 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2430 I->getSecond().GlobalRecordAddr);
2431 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002432 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00002433 }
2434}
2435
Carlo Bertollic6872252016-04-04 15:55:02 +00002436void CGOpenMPRuntimeNVPTX::emitTeamsCall(CodeGenFunction &CGF,
2437 const OMPExecutableDirective &D,
2438 SourceLocation Loc,
2439 llvm::Value *OutlinedFn,
2440 ArrayRef<llvm::Value *> CapturedVars) {
2441 if (!CGF.HaveInsertPoint())
2442 return;
2443
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002444 Address ZeroAddr = CGF.CreateMemTemp(
2445 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2446 /*Name*/ ".zero.addr");
Carlo Bertollic6872252016-04-04 15:55:02 +00002447 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2448 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002449 OutlinedFnArgs.push_back(emitThreadIDAddress(CGF, Loc).getPointer());
Carlo Bertollic6872252016-04-04 15:55:02 +00002450 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2451 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002452 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Carlo Bertollic6872252016-04-04 15:55:02 +00002453}
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002454
2455void CGOpenMPRuntimeNVPTX::emitParallelCall(
2456 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2457 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2458 if (!CGF.HaveInsertPoint())
2459 return;
2460
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002461 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002462 emitSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002463 else
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002464 emitNonSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002465}
2466
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002467void CGOpenMPRuntimeNVPTX::emitNonSPMDParallelCall(
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002468 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2469 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2470 llvm::Function *Fn = cast<llvm::Function>(OutlinedFn);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002471
2472 // Force inline this outlined function at its call site.
2473 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
2474
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002475 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2476 /*DestWidth=*/32, /*Signed=*/1),
2477 ".zero.addr");
2478 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002479 // ThreadId for serialized parallels is 0.
2480 Address ThreadIDAddr = ZeroAddr;
2481 auto &&CodeGen = [this, Fn, CapturedVars, Loc, ZeroAddr, &ThreadIDAddr](
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002482 CodeGenFunction &CGF, PrePostActionTy &Action) {
2483 Action.Enter(CGF);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002484
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002485 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2486 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2487 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2488 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2489 emitOutlinedFunctionCall(CGF, Loc, Fn, OutlinedFnArgs);
2490 };
2491 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2492 PrePostActionTy &) {
2493
2494 RegionCodeGenTy RCG(CodeGen);
2495 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2496 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2497 llvm::Value *Args[] = {RTLoc, ThreadID};
2498
2499 NVPTXActionTy Action(
2500 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2501 Args,
2502 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2503 Args);
2504 RCG.setAction(Action);
2505 RCG(CGF);
2506 };
2507
2508 auto &&L0ParallelGen = [this, CapturedVars, Fn](CodeGenFunction &CGF,
2509 PrePostActionTy &Action) {
2510 CGBuilderTy &Bld = CGF.Builder;
2511 llvm::Function *WFn = WrapperFunctionsMap[Fn];
2512 assert(WFn && "Wrapper function does not exist!");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002513 llvm::Value *ID = Bld.CreateBitOrPointerCast(WFn, CGM.Int8PtrTy);
2514
2515 // Prepare for parallel region. Indicate the outlined function.
2516 llvm::Value *Args[] = {ID, /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002517 CGF.EmitRuntimeCall(
2518 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_prepare_parallel),
2519 Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002520
2521 // Create a private scope that will globalize the arguments
2522 // passed from the outside of the target region.
2523 CodeGenFunction::OMPPrivateScope PrivateArgScope(CGF);
2524
2525 // There's somehting to share.
2526 if (!CapturedVars.empty()) {
2527 // Prepare for parallel region. Indicate the outlined function.
2528 Address SharedArgs =
2529 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "shared_arg_refs");
2530 llvm::Value *SharedArgsPtr = SharedArgs.getPointer();
2531
2532 llvm::Value *DataSharingArgs[] = {
2533 SharedArgsPtr,
2534 llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size())};
2535 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2536 OMPRTL_NVPTX__kmpc_begin_sharing_variables),
2537 DataSharingArgs);
2538
2539 // Store variable address in a list of references to pass to workers.
2540 unsigned Idx = 0;
2541 ASTContext &Ctx = CGF.getContext();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002542 Address SharedArgListAddress = CGF.EmitLoadOfPointer(
2543 SharedArgs, Ctx.getPointerType(Ctx.getPointerType(Ctx.VoidPtrTy))
2544 .castAs<PointerType>());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002545 for (llvm::Value *V : CapturedVars) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002546 Address Dst = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
2547 CGF.getPointerSize());
2548 llvm::Value *PtrV;
Alexey Bataev17314212018-03-20 15:41:05 +00002549 if (V->getType()->isIntegerTy())
2550 PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
2551 else
2552 PtrV = Bld.CreatePointerBitCastOrAddrSpaceCast(V, CGF.VoidPtrTy);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002553 CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
2554 Ctx.getPointerType(Ctx.VoidPtrTy));
Alexey Bataevc99042b2018-03-15 18:10:54 +00002555 ++Idx;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002556 }
2557 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002558
2559 // Activate workers. This barrier is used by the master to signal
2560 // work for the workers.
2561 syncCTAThreads(CGF);
2562
2563 // OpenMP [2.5, Parallel Construct, p.49]
2564 // There is an implied barrier at the end of a parallel region. After the
2565 // end of a parallel region, only the master thread of the team resumes
2566 // execution of the enclosing task region.
2567 //
2568 // The master waits at this barrier until all workers are done.
2569 syncCTAThreads(CGF);
2570
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002571 if (!CapturedVars.empty())
2572 CGF.EmitRuntimeCall(
2573 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_sharing_variables));
2574
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002575 // Remember for post-processing in worker loop.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002576 Work.emplace_back(WFn);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002577 };
2578
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002579 auto &&LNParallelGen = [this, Loc, &SeqGen, &L0ParallelGen](
2580 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002581 if (IsInParallelRegion) {
2582 SeqGen(CGF, Action);
2583 } else if (IsInTargetMasterThreadRegion) {
2584 L0ParallelGen(CGF, Action);
2585 } else {
2586 // Check for master and then parallelism:
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002587 // if (__kmpc_is_spmd_exec_mode() || __kmpc_parallel_level(loc, gtid)) {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002588 // Serialized execution.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002589 // } else {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002590 // Worker call.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002591 // }
2592 CGBuilderTy &Bld = CGF.Builder;
2593 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002594 llvm::BasicBlock *SeqBB = CGF.createBasicBlock(".sequential");
2595 llvm::BasicBlock *ParallelCheckBB = CGF.createBasicBlock(".parcheck");
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002596 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
Alexey Bataev673110d2018-05-16 13:36:30 +00002597 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2598 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002599 Bld.CreateCondBr(IsSPMD, SeqBB, ParallelCheckBB);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002600 // There is no need to emit line number for unconditional branch.
2601 (void)ApplyDebugLocation::CreateEmpty(CGF);
2602 CGF.EmitBlock(ParallelCheckBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002603 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2604 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2605 llvm::Value *PL = CGF.EmitRuntimeCall(
2606 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2607 {RTLoc, ThreadID});
2608 llvm::Value *Res = Bld.CreateIsNotNull(PL);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002609 Bld.CreateCondBr(Res, SeqBB, MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002610 CGF.EmitBlock(SeqBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002611 SeqGen(CGF, Action);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002612 CGF.EmitBranch(ExitBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002613 // There is no need to emit line number for unconditional branch.
2614 (void)ApplyDebugLocation::CreateEmpty(CGF);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002615 CGF.EmitBlock(MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002616 L0ParallelGen(CGF, Action);
2617 CGF.EmitBranch(ExitBB);
2618 // There is no need to emit line number for unconditional branch.
2619 (void)ApplyDebugLocation::CreateEmpty(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002620 // Emit the continuation block for code after the if.
2621 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2622 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002623 };
2624
Alexey Bataev9ff80832018-04-16 20:16:21 +00002625 if (IfCond) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002626 emitOMPIfClause(CGF, IfCond, LNParallelGen, SeqGen);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002627 } else {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002628 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002629 RegionCodeGenTy ThenRCG(LNParallelGen);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002630 ThenRCG(CGF);
2631 }
2632}
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002633
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002634void CGOpenMPRuntimeNVPTX::emitSPMDParallelCall(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002635 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2636 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2637 // Just call the outlined function to execute the parallel region.
2638 // OutlinedFn(&GTid, &zero, CapturedStruct);
2639 //
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002640 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Carlo Bertolli79712092018-02-28 20:48:35 +00002641
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002642 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2643 /*DestWidth=*/32, /*Signed=*/1),
2644 ".zero.addr");
Carlo Bertolli79712092018-02-28 20:48:35 +00002645 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002646 // ThreadId for serialized parallels is 0.
2647 Address ThreadIDAddr = ZeroAddr;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002648 auto &&CodeGen = [this, OutlinedFn, CapturedVars, Loc, ZeroAddr,
Alexey Bataev8521ff62018-07-25 20:03:01 +00002649 &ThreadIDAddr](CodeGenFunction &CGF,
2650 PrePostActionTy &Action) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002651 Action.Enter(CGF);
2652
2653 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2654 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2655 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2656 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2657 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2658 };
2659 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2660 PrePostActionTy &) {
2661
2662 RegionCodeGenTy RCG(CodeGen);
2663 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2664 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2665 llvm::Value *Args[] = {RTLoc, ThreadID};
2666
2667 NVPTXActionTy Action(
2668 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2669 Args,
2670 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2671 Args);
2672 RCG.setAction(Action);
2673 RCG(CGF);
2674 };
2675
2676 if (IsInTargetMasterThreadRegion) {
Alexey Bataev8521ff62018-07-25 20:03:01 +00002677 // In the worker need to use the real thread id.
2678 ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002679 RegionCodeGenTy RCG(CodeGen);
2680 RCG(CGF);
2681 } else {
2682 // If we are not in the target region, it is definitely L2 parallelism or
2683 // more, because for SPMD mode we always has L1 parallel level, sowe don't
2684 // need to check for orphaned directives.
2685 RegionCodeGenTy RCG(SeqGen);
2686 RCG(CGF);
2687 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002688}
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002689
Alexey Bataevc3028ca2018-12-04 15:03:25 +00002690void CGOpenMPRuntimeNVPTX::emitBarrierCall(CodeGenFunction &CGF,
2691 SourceLocation Loc,
2692 OpenMPDirectiveKind Kind, bool,
2693 bool) {
2694 // Always emit simple barriers!
2695 if (!CGF.HaveInsertPoint())
2696 return;
2697 // Build call __kmpc_cancel_barrier(loc, thread_id);
2698 unsigned Flags = getDefaultFlagsForBarriers(Kind);
2699 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2700 getThreadID(CGF, Loc)};
2701 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier), Args);
2702}
2703
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002704void CGOpenMPRuntimeNVPTX::emitCriticalRegion(
2705 CodeGenFunction &CGF, StringRef CriticalName,
2706 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
2707 const Expr *Hint) {
2708 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
2709 llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
2710 llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
2711 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
2712 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
2713
2714 // Fetch team-local id of the thread.
2715 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
2716
2717 // Get the width of the team.
2718 llvm::Value *TeamWidth = getNVPTXNumThreads(CGF);
2719
2720 // Initialize the counter variable for the loop.
2721 QualType Int32Ty =
2722 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
2723 Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
2724 LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
2725 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
2726 /*isInit=*/true);
2727
2728 // Block checks if loop counter exceeds upper bound.
2729 CGF.EmitBlock(LoopBB);
2730 llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2731 llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
2732 CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
2733
2734 // Block tests which single thread should execute region, and which threads
2735 // should go straight to synchronisation point.
2736 CGF.EmitBlock(TestBB);
2737 CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2738 llvm::Value *CmpThreadToCounter =
2739 CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
2740 CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
2741
2742 // Block emits the body of the critical region.
2743 CGF.EmitBlock(BodyBB);
2744
2745 // Output the critical statement.
2746 CriticalOpGen(CGF);
2747
2748 // After the body surrounded by the critical region, the single executing
2749 // thread will jump to the synchronisation point.
2750 // Block waits for all threads in current team to finish then increments the
2751 // counter variable and returns to the loop.
2752 CGF.EmitBlock(SyncBB);
2753 getNVPTXCTABarrier(CGF);
2754
2755 llvm::Value *IncCounterVal =
2756 CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
2757 CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
2758 CGF.EmitBranch(LoopBB);
2759
2760 // Block that is reached when all threads in the team complete the region.
2761 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2762}
2763
Alexey Bataevb2575932018-01-04 20:18:55 +00002764/// Cast value to the specified type.
Alexey Bataeva453f362018-03-19 17:53:56 +00002765static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
2766 QualType ValTy, QualType CastTy,
2767 SourceLocation Loc) {
2768 assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
2769 "Cast type must sized.");
2770 assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
2771 "Val type must sized.");
2772 llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
2773 if (ValTy == CastTy)
Alexey Bataevb2575932018-01-04 20:18:55 +00002774 return Val;
Alexey Bataeva453f362018-03-19 17:53:56 +00002775 if (CGF.getContext().getTypeSizeInChars(ValTy) ==
2776 CGF.getContext().getTypeSizeInChars(CastTy))
2777 return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
2778 if (CastTy->isIntegerType() && ValTy->isIntegerType())
2779 return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
2780 CastTy->hasSignedIntegerRepresentation());
2781 Address CastItem = CGF.CreateMemTemp(CastTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002782 Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2783 CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
Alexey Bataeva453f362018-03-19 17:53:56 +00002784 CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy);
2785 return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc);
Alexey Bataevb2575932018-01-04 20:18:55 +00002786}
2787
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002788/// This function creates calls to one of two shuffle functions to copy
2789/// variables between lanes in a warp.
2790static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002791 llvm::Value *Elem,
Alexey Bataeva453f362018-03-19 17:53:56 +00002792 QualType ElemType,
2793 llvm::Value *Offset,
2794 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002795 CodeGenModule &CGM = CGF.CGM;
2796 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002797 CGOpenMPRuntimeNVPTX &RT =
2798 *(static_cast<CGOpenMPRuntimeNVPTX *>(&CGM.getOpenMPRuntime()));
2799
Alexey Bataeva453f362018-03-19 17:53:56 +00002800 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2801 assert(Size.getQuantity() <= 8 &&
2802 "Unsupported bitwidth in shuffle instruction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002803
Alexey Bataeva453f362018-03-19 17:53:56 +00002804 OpenMPRTLFunctionNVPTX ShuffleFn = Size.getQuantity() <= 4
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002805 ? OMPRTL_NVPTX__kmpc_shuffle_int32
2806 : OMPRTL_NVPTX__kmpc_shuffle_int64;
2807
2808 // Cast all types to 32- or 64-bit values before calling shuffle routines.
Alexey Bataeva453f362018-03-19 17:53:56 +00002809 QualType CastTy = CGF.getContext().getIntTypeForBitwidth(
2810 Size.getQuantity() <= 4 ? 32 : 64, /*Signed=*/1);
2811 llvm::Value *ElemCast = castValueToType(CGF, Elem, ElemType, CastTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002812 llvm::Value *WarpSize =
Alexey Bataevb2575932018-01-04 20:18:55 +00002813 Bld.CreateIntCast(getNVPTXWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002814
Alexey Bataev9ff80832018-04-16 20:16:21 +00002815 llvm::Value *ShuffledVal = CGF.EmitRuntimeCall(
2816 RT.createNVPTXRuntimeFunction(ShuffleFn), {ElemCast, Offset, WarpSize});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002817
Alexey Bataeva453f362018-03-19 17:53:56 +00002818 return castValueToType(CGF, ShuffledVal, CastTy, ElemType, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002819}
2820
Alexey Bataev12c62902018-06-22 19:10:38 +00002821static void shuffleAndStore(CodeGenFunction &CGF, Address SrcAddr,
2822 Address DestAddr, QualType ElemType,
2823 llvm::Value *Offset, SourceLocation Loc) {
2824 CGBuilderTy &Bld = CGF.Builder;
2825
2826 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2827 // Create the loop over the big sized data.
2828 // ptr = (void*)Elem;
2829 // ptrEnd = (void*) Elem + 1;
2830 // Step = 8;
2831 // while (ptr + Step < ptrEnd)
2832 // shuffle((int64_t)*ptr);
2833 // Step = 4;
2834 // while (ptr + Step < ptrEnd)
2835 // shuffle((int32_t)*ptr);
2836 // ...
2837 Address ElemPtr = DestAddr;
2838 Address Ptr = SrcAddr;
2839 Address PtrEnd = Bld.CreatePointerBitCastOrAddrSpaceCast(
2840 Bld.CreateConstGEP(SrcAddr, 1, Size), CGF.VoidPtrTy);
2841 for (int IntSize = 8; IntSize >= 1; IntSize /= 2) {
2842 if (Size < CharUnits::fromQuantity(IntSize))
2843 continue;
2844 QualType IntType = CGF.getContext().getIntTypeForBitwidth(
2845 CGF.getContext().toBits(CharUnits::fromQuantity(IntSize)),
2846 /*Signed=*/1);
2847 llvm::Type *IntTy = CGF.ConvertTypeForMem(IntType);
2848 Ptr = Bld.CreatePointerBitCastOrAddrSpaceCast(Ptr, IntTy->getPointerTo());
2849 ElemPtr =
2850 Bld.CreatePointerBitCastOrAddrSpaceCast(ElemPtr, IntTy->getPointerTo());
2851 if (Size.getQuantity() / IntSize > 1) {
2852 llvm::BasicBlock *PreCondBB = CGF.createBasicBlock(".shuffle.pre_cond");
2853 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".shuffle.then");
2854 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".shuffle.exit");
2855 llvm::BasicBlock *CurrentBB = Bld.GetInsertBlock();
2856 CGF.EmitBlock(PreCondBB);
2857 llvm::PHINode *PhiSrc =
2858 Bld.CreatePHI(Ptr.getType(), /*NumReservedValues=*/2);
2859 PhiSrc->addIncoming(Ptr.getPointer(), CurrentBB);
2860 llvm::PHINode *PhiDest =
2861 Bld.CreatePHI(ElemPtr.getType(), /*NumReservedValues=*/2);
2862 PhiDest->addIncoming(ElemPtr.getPointer(), CurrentBB);
2863 Ptr = Address(PhiSrc, Ptr.getAlignment());
2864 ElemPtr = Address(PhiDest, ElemPtr.getAlignment());
2865 llvm::Value *PtrDiff = Bld.CreatePtrDiff(
2866 PtrEnd.getPointer(), Bld.CreatePointerBitCastOrAddrSpaceCast(
2867 Ptr.getPointer(), CGF.VoidPtrTy));
2868 Bld.CreateCondBr(Bld.CreateICmpSGT(PtrDiff, Bld.getInt64(IntSize - 1)),
2869 ThenBB, ExitBB);
2870 CGF.EmitBlock(ThenBB);
2871 llvm::Value *Res = createRuntimeShuffleFunction(
2872 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2873 IntType, Offset, Loc);
2874 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002875 Address LocalPtr =
2876 Bld.CreateConstGEP(Ptr, 1, CharUnits::fromQuantity(IntSize));
2877 Address LocalElemPtr =
Alexey Bataev12c62902018-06-22 19:10:38 +00002878 Bld.CreateConstGEP(ElemPtr, 1, CharUnits::fromQuantity(IntSize));
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002879 PhiSrc->addIncoming(LocalPtr.getPointer(), ThenBB);
2880 PhiDest->addIncoming(LocalElemPtr.getPointer(), ThenBB);
Alexey Bataev12c62902018-06-22 19:10:38 +00002881 CGF.EmitBranch(PreCondBB);
2882 CGF.EmitBlock(ExitBB);
2883 } else {
2884 llvm::Value *Res = createRuntimeShuffleFunction(
2885 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2886 IntType, Offset, Loc);
2887 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
2888 Ptr = Bld.CreateConstGEP(Ptr, 1, CharUnits::fromQuantity(IntSize));
2889 ElemPtr =
2890 Bld.CreateConstGEP(ElemPtr, 1, CharUnits::fromQuantity(IntSize));
2891 }
2892 Size = Size % IntSize;
2893 }
2894}
2895
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002896namespace {
2897enum CopyAction : unsigned {
2898 // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
2899 // the warp using shuffle instructions.
2900 RemoteLaneToThread,
2901 // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
2902 ThreadCopy,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002903 // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
2904 ThreadToScratchpad,
2905 // ScratchpadToThread: Copy from a scratchpad array in global memory
2906 // containing team-reduced data to a thread's stack.
2907 ScratchpadToThread,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002908};
2909} // namespace
2910
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002911struct CopyOptionsTy {
2912 llvm::Value *RemoteLaneOffset;
2913 llvm::Value *ScratchpadIndex;
2914 llvm::Value *ScratchpadWidth;
2915};
2916
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002917/// Emit instructions to copy a Reduce list, which contains partially
2918/// aggregated values, in the specified direction.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002919static void emitReductionListCopy(
2920 CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
2921 ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
2922 CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002923
Alexey Bataev9ff80832018-04-16 20:16:21 +00002924 CodeGenModule &CGM = CGF.CGM;
2925 ASTContext &C = CGM.getContext();
2926 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002927
Alexey Bataev9ff80832018-04-16 20:16:21 +00002928 llvm::Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
2929 llvm::Value *ScratchpadIndex = CopyOptions.ScratchpadIndex;
2930 llvm::Value *ScratchpadWidth = CopyOptions.ScratchpadWidth;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002931
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002932 // Iterates, element-by-element, through the source Reduce list and
2933 // make a copy.
2934 unsigned Idx = 0;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002935 unsigned Size = Privates.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00002936 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002937 Address SrcElementAddr = Address::invalid();
2938 Address DestElementAddr = Address::invalid();
2939 Address DestElementPtrAddr = Address::invalid();
2940 // Should we shuffle in an element from a remote lane?
2941 bool ShuffleInElement = false;
2942 // Set to true to update the pointer in the dest Reduce list to a
2943 // newly created element.
2944 bool UpdateDestListPtr = false;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002945 // Increment the src or dest pointer to the scratchpad, for each
2946 // new element.
2947 bool IncrScratchpadSrc = false;
2948 bool IncrScratchpadDest = false;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002949
2950 switch (Action) {
2951 case RemoteLaneToThread: {
2952 // Step 1.1: Get the address for the src element in the Reduce list.
2953 Address SrcElementPtrAddr =
2954 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002955 SrcElementAddr = CGF.EmitLoadOfPointer(
2956 SrcElementPtrAddr,
2957 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002958
2959 // Step 1.2: Create a temporary to store the element in the destination
2960 // Reduce list.
2961 DestElementPtrAddr =
2962 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
2963 DestElementAddr =
2964 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2965 ShuffleInElement = true;
2966 UpdateDestListPtr = true;
2967 break;
2968 }
2969 case ThreadCopy: {
2970 // Step 1.1: Get the address for the src element in the Reduce list.
2971 Address SrcElementPtrAddr =
2972 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002973 SrcElementAddr = CGF.EmitLoadOfPointer(
2974 SrcElementPtrAddr,
2975 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002976
2977 // Step 1.2: Get the address for dest element. The destination
2978 // element has already been created on the thread's stack.
2979 DestElementPtrAddr =
2980 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002981 DestElementAddr = CGF.EmitLoadOfPointer(
2982 DestElementPtrAddr,
2983 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002984 break;
2985 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002986 case ThreadToScratchpad: {
2987 // Step 1.1: Get the address for the src element in the Reduce list.
2988 Address SrcElementPtrAddr =
2989 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002990 SrcElementAddr = CGF.EmitLoadOfPointer(
2991 SrcElementPtrAddr,
2992 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002993
2994 // Step 1.2: Get the address for dest element:
2995 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00002996 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00002997 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002998 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002999 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003000 Bld.CreateNUWAdd(DestBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003001 ScratchPadElemAbsolutePtrVal =
3002 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00003003 DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
3004 C.getTypeAlignInChars(Private->getType()));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003005 IncrScratchpadDest = true;
3006 break;
3007 }
3008 case ScratchpadToThread: {
3009 // Step 1.1: Get the address for the src element in the scratchpad.
3010 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00003011 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00003012 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003013 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003014 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003015 Bld.CreateNUWAdd(SrcBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003016 ScratchPadElemAbsolutePtrVal =
3017 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
3018 SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
3019 C.getTypeAlignInChars(Private->getType()));
3020 IncrScratchpadSrc = true;
3021
3022 // Step 1.2: Create a temporary to store the element in the destination
3023 // Reduce list.
3024 DestElementPtrAddr =
3025 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
3026 DestElementAddr =
3027 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
3028 UpdateDestListPtr = true;
3029 break;
3030 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003031 }
3032
3033 // Regardless of src and dest of copy, we emit the load of src
3034 // element as this is required in all directions
3035 SrcElementAddr = Bld.CreateElementBitCast(
3036 SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
Alexey Bataev12c62902018-06-22 19:10:38 +00003037 DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
3038 SrcElementAddr.getElementType());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003039
3040 // Now that all active lanes have read the element in the
3041 // Reduce list, shuffle over the value from the remote lane.
Alexey Bataeva453f362018-03-19 17:53:56 +00003042 if (ShuffleInElement) {
Alexey Bataev12c62902018-06-22 19:10:38 +00003043 shuffleAndStore(CGF, SrcElementAddr, DestElementAddr, Private->getType(),
3044 RemoteLaneOffset, Private->getExprLoc());
3045 } else {
3046 if (Private->getType()->isScalarType()) {
3047 llvm::Value *Elem =
3048 CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false,
3049 Private->getType(), Private->getExprLoc());
3050 // Store the source element value to the dest element address.
3051 CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false,
3052 Private->getType());
3053 } else {
3054 CGF.EmitAggregateCopy(
3055 CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3056 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3057 Private->getType(), AggValueSlot::DoesNotOverlap);
3058 }
Alexey Bataeva453f362018-03-19 17:53:56 +00003059 }
Alexey Bataevb2575932018-01-04 20:18:55 +00003060
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003061 // Step 3.1: Modify reference in dest Reduce list as needed.
3062 // Modifying the reference in Reduce list to point to the newly
3063 // created element. The element is live in the current function
3064 // scope and that of functions it invokes (i.e., reduce_function).
3065 // RemoteReduceData[i] = (void*)&RemoteElem
3066 if (UpdateDestListPtr) {
3067 CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
3068 DestElementAddr.getPointer(), CGF.VoidPtrTy),
3069 DestElementPtrAddr, /*Volatile=*/false,
3070 C.VoidPtrTy);
3071 }
3072
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003073 // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
3074 // address of the next element in scratchpad memory, unless we're currently
3075 // processing the last one. Memory alignment is also taken care of here.
3076 if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
3077 llvm::Value *ScratchpadBasePtr =
3078 IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
Alexey Bataeve290ec02018-04-06 16:03:36 +00003079 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
3080 ScratchpadBasePtr = Bld.CreateNUWAdd(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003081 ScratchpadBasePtr,
Alexey Bataeve290ec02018-04-06 16:03:36 +00003082 Bld.CreateNUWMul(ScratchpadWidth, ElementSizeInChars));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003083
3084 // Take care of global memory alignment for performance
Alexey Bataeve290ec02018-04-06 16:03:36 +00003085 ScratchpadBasePtr = Bld.CreateNUWSub(
3086 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3087 ScratchpadBasePtr = Bld.CreateUDiv(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003088 ScratchpadBasePtr,
3089 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
Alexey Bataeve290ec02018-04-06 16:03:36 +00003090 ScratchpadBasePtr = Bld.CreateNUWAdd(
3091 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3092 ScratchpadBasePtr = Bld.CreateNUWMul(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003093 ScratchpadBasePtr,
3094 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
3095
3096 if (IncrScratchpadDest)
3097 DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3098 else /* IncrScratchpadSrc = true */
3099 SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3100 }
3101
Alexey Bataev9ff80832018-04-16 20:16:21 +00003102 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003103 }
3104}
3105
3106/// This function emits a helper that gathers Reduce lists from the first
3107/// lane of every active warp to lanes in the first warp.
3108///
3109/// void inter_warp_copy_func(void* reduce_data, num_warps)
3110/// shared smem[warp_size];
3111/// For all data entries D in reduce_data:
3112/// If (I am the first lane in each warp)
3113/// Copy my local D to smem[warp_id]
3114/// sync
3115/// if (I am the first warp)
3116/// Copy smem[thread_id] to my local D
3117/// sync
3118static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
3119 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003120 QualType ReductionArrayTy,
3121 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003122 ASTContext &C = CGM.getContext();
3123 llvm::Module &M = CGM.getModule();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003124
3125 // ReduceList: thread local Reduce list.
3126 // At the stage of the computation when this function is called, partially
3127 // aggregated values reside in the first lane of every active warp.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003128 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3129 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003130 // NumWarps: number of warps active in the parallel region. This could
3131 // be smaller than 32 (max warps in a CTA) for partial block reduction.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003132 ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00003133 C.getIntTypeForBitwidth(32, /* Signed */ true),
3134 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003135 FunctionArgList Args;
3136 Args.push_back(&ReduceListArg);
3137 Args.push_back(&NumWarpsArg);
3138
Alexey Bataev9ff80832018-04-16 20:16:21 +00003139 const CGFunctionInfo &CGFI =
3140 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003141 auto *Fn = llvm::Function::Create(
3142 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3143 "_omp_reduction_inter_warp_copy_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003144 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003145 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003146 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003147 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003148
Alexey Bataev9ff80832018-04-16 20:16:21 +00003149 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003150
3151 // This array is used as a medium to transfer, one reduce element at a time,
3152 // the data from the first lane of every warp to lanes in the first warp
3153 // in order to perform the final step of a reduction in a parallel region
3154 // (reduction across warps). The array is placed in NVPTX __shared__ memory
3155 // for reduced latency, as well as to have a distinct copy for concurrently
3156 // executing target regions. The array is declared with common linkage so
3157 // as to be shared across compilation units.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003158 StringRef TransferMediumName =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003159 "__openmp_nvptx_data_transfer_temporary_storage";
3160 llvm::GlobalVariable *TransferMedium =
3161 M.getGlobalVariable(TransferMediumName);
3162 if (!TransferMedium) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003163 auto *Ty = llvm::ArrayType::get(CGM.Int32Ty, WarpSize);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003164 unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
3165 TransferMedium = new llvm::GlobalVariable(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003166 M, Ty, /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003167 llvm::Constant::getNullValue(Ty), TransferMediumName,
3168 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3169 SharedAddressSpace);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003170 CGM.addCompilerUsedGlobal(TransferMedium);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003171 }
3172
3173 // Get the CUDA thread id of the current OpenMP thread on the GPU.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003174 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003175 // nvptx_lane_id = nvptx_id % warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003176 llvm::Value *LaneID = getNVPTXLaneID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003177 // nvptx_warp_id = nvptx_id / warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003178 llvm::Value *WarpID = getNVPTXWarpID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003179
3180 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3181 Address LocalReduceList(
3182 Bld.CreatePointerBitCastOrAddrSpaceCast(
3183 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003184 C.VoidPtrTy, Loc),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003185 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3186 CGF.getPointerAlign());
3187
3188 unsigned Idx = 0;
Alexey Bataev9ff80832018-04-16 20:16:21 +00003189 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003190 //
3191 // Warp master copies reduce element to transfer medium in __shared__
3192 // memory.
3193 //
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003194 unsigned RealTySize =
3195 C.getTypeSizeInChars(Private->getType())
3196 .alignTo(C.getTypeAlignInChars(Private->getType()))
3197 .getQuantity();
3198 for (unsigned TySize = 4; TySize > 0 && RealTySize > 0; TySize /=2) {
3199 unsigned NumIters = RealTySize / TySize;
3200 if (NumIters == 0)
3201 continue;
3202 QualType CType = C.getIntTypeForBitwidth(
3203 C.toBits(CharUnits::fromQuantity(TySize)), /*Signed=*/1);
3204 llvm::Type *CopyType = CGF.ConvertTypeForMem(CType);
3205 CharUnits Align = CharUnits::fromQuantity(TySize);
3206 llvm::Value *Cnt = nullptr;
3207 Address CntAddr = Address::invalid();
3208 llvm::BasicBlock *PrecondBB = nullptr;
3209 llvm::BasicBlock *ExitBB = nullptr;
3210 if (NumIters > 1) {
3211 CntAddr = CGF.CreateMemTemp(C.IntTy, ".cnt.addr");
3212 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.IntTy), CntAddr,
3213 /*Volatile=*/false, C.IntTy);
3214 PrecondBB = CGF.createBasicBlock("precond");
3215 ExitBB = CGF.createBasicBlock("exit");
3216 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("body");
3217 // There is no need to emit line number for unconditional branch.
3218 (void)ApplyDebugLocation::CreateEmpty(CGF);
3219 CGF.EmitBlock(PrecondBB);
3220 Cnt = CGF.EmitLoadOfScalar(CntAddr, /*Volatile=*/false, C.IntTy, Loc);
3221 llvm::Value *Cmp =
3222 Bld.CreateICmpULT(Cnt, llvm::ConstantInt::get(CGM.IntTy, NumIters));
3223 Bld.CreateCondBr(Cmp, BodyBB, ExitBB);
3224 CGF.EmitBlock(BodyBB);
3225 }
3226 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3227 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3228 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003229
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003230 // if (lane_id == 0)
3231 llvm::Value *IsWarpMaster = Bld.CreateIsNull(LaneID, "warp_master");
3232 Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
3233 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003234
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003235 // Reduce element = LocalReduceList[i]
3236 Address ElemPtrPtrAddr =
3237 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
3238 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3239 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3240 // elemptr = ((CopyType*)(elemptrptr)) + I
3241 Address ElemPtr = Address(ElemPtrPtr, Align);
3242 ElemPtr = Bld.CreateElementBitCast(ElemPtr, CopyType);
3243 if (NumIters > 1) {
3244 ElemPtr = Address(Bld.CreateGEP(ElemPtr.getPointer(), Cnt),
3245 ElemPtr.getAlignment());
3246 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003247
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003248 // Get pointer to location in transfer medium.
3249 // MediumPtr = &medium[warp_id]
3250 llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
3251 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
3252 Address MediumPtr(MediumPtrVal, Align);
3253 // Casting to actual data type.
3254 // MediumPtr = (CopyType*)MediumPtrAddr;
3255 MediumPtr = Bld.CreateElementBitCast(MediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003256
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003257 // elem = *elemptr
3258 //*MediumPtr = elem
3259 llvm::Value *Elem =
3260 CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003261 // Store the source element value to the dest element address.
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003262 CGF.EmitStoreOfScalar(Elem, MediumPtr, /*Volatile=*/true, CType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003263
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003264 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003265
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003266 CGF.EmitBlock(ElseBB);
3267 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003268
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003269 CGF.EmitBlock(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003270
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003271 Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
3272 llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
3273 AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003274
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003275 llvm::Value *NumActiveThreads = Bld.CreateNSWMul(
3276 NumWarpsVal, getNVPTXWarpSize(CGF), "num_active_threads");
3277 // named_barrier_sync(ParallelBarrierID, num_active_threads)
3278 syncParallelThreads(CGF, NumActiveThreads);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003279
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003280 //
3281 // Warp 0 copies reduce element from transfer medium.
3282 //
3283 llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
3284 llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
3285 llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003286
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003287 // Up to 32 threads in warp 0 are active.
3288 llvm::Value *IsActiveThread =
3289 Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
3290 Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003291
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003292 CGF.EmitBlock(W0ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003293
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003294 // SrcMediumPtr = &medium[tid]
3295 llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
3296 TransferMedium,
3297 {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
3298 Address SrcMediumPtr(SrcMediumPtrVal, Align);
3299 // SrcMediumVal = *SrcMediumPtr;
3300 SrcMediumPtr = Bld.CreateElementBitCast(SrcMediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003301
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003302 // TargetElemPtr = (CopyType*)(SrcDataAddr[i]) + I
3303 Address TargetElemPtrPtr =
3304 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
3305 llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
3306 TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, Loc);
3307 Address TargetElemPtr = Address(TargetElemPtrVal, Align);
3308 TargetElemPtr = Bld.CreateElementBitCast(TargetElemPtr, CopyType);
3309 if (NumIters > 1) {
3310 TargetElemPtr = Address(Bld.CreateGEP(TargetElemPtr.getPointer(), Cnt),
3311 TargetElemPtr.getAlignment());
3312 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003313
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003314 // *TargetElemPtr = SrcMediumVal;
3315 llvm::Value *SrcMediumValue =
3316 CGF.EmitLoadOfScalar(SrcMediumPtr, /*Volatile=*/true, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003317 CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003318 CType);
3319 Bld.CreateBr(W0MergeBB);
3320
3321 CGF.EmitBlock(W0ElseBB);
3322 Bld.CreateBr(W0MergeBB);
3323
3324 CGF.EmitBlock(W0MergeBB);
3325
3326 // While warp 0 copies values from transfer medium, all other warps must
3327 // wait.
3328 syncParallelThreads(CGF, NumActiveThreads);
3329 if (NumIters > 1) {
3330 Cnt = Bld.CreateNSWAdd(Cnt, llvm::ConstantInt::get(CGM.IntTy, /*V=*/1));
3331 CGF.EmitStoreOfScalar(Cnt, CntAddr, /*Volatile=*/false, C.IntTy);
3332 CGF.EmitBranch(PrecondBB);
3333 (void)ApplyDebugLocation::CreateEmpty(CGF);
3334 CGF.EmitBlock(ExitBB);
3335 }
3336 RealTySize %= TySize;
Alexey Bataev12c62902018-06-22 19:10:38 +00003337 }
Alexey Bataev9ff80832018-04-16 20:16:21 +00003338 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003339 }
3340
3341 CGF.FinishFunction();
3342 return Fn;
3343}
3344
3345/// Emit a helper that reduces data across two OpenMP threads (lanes)
3346/// in the same warp. It uses shuffle instructions to copy over data from
3347/// a remote lane's stack. The reduction algorithm performed is specified
3348/// by the fourth parameter.
3349///
3350/// Algorithm Versions.
3351/// Full Warp Reduce (argument value 0):
3352/// This algorithm assumes that all 32 lanes are active and gathers
3353/// data from these 32 lanes, producing a single resultant value.
3354/// Contiguous Partial Warp Reduce (argument value 1):
3355/// This algorithm assumes that only a *contiguous* subset of lanes
3356/// are active. This happens for the last warp in a parallel region
3357/// when the user specified num_threads is not an integer multiple of
3358/// 32. This contiguous subset always starts with the zeroth lane.
3359/// Partial Warp Reduce (argument value 2):
3360/// This algorithm gathers data from any number of lanes at any position.
3361/// All reduced values are stored in the lowest possible lane. The set
3362/// of problems every algorithm addresses is a super set of those
3363/// addressable by algorithms with a lower version number. Overhead
3364/// increases as algorithm version increases.
3365///
3366/// Terminology
3367/// Reduce element:
3368/// Reduce element refers to the individual data field with primitive
3369/// data types to be combined and reduced across threads.
3370/// Reduce list:
3371/// Reduce list refers to a collection of local, thread-private
3372/// reduce elements.
3373/// Remote Reduce list:
3374/// Remote Reduce list refers to a collection of remote (relative to
3375/// the current thread) reduce elements.
3376///
3377/// We distinguish between three states of threads that are important to
3378/// the implementation of this function.
3379/// Alive threads:
3380/// Threads in a warp executing the SIMT instruction, as distinguished from
3381/// threads that are inactive due to divergent control flow.
3382/// Active threads:
3383/// The minimal set of threads that has to be alive upon entry to this
3384/// function. The computation is correct iff active threads are alive.
3385/// Some threads are alive but they are not active because they do not
3386/// contribute to the computation in any useful manner. Turning them off
3387/// may introduce control flow overheads without any tangible benefits.
3388/// Effective threads:
3389/// In order to comply with the argument requirements of the shuffle
3390/// function, we must keep all lanes holding data alive. But at most
3391/// half of them perform value aggregation; we refer to this half of
3392/// threads as effective. The other half is simply handing off their
3393/// data.
3394///
3395/// Procedure
3396/// Value shuffle:
3397/// In this step active threads transfer data from higher lane positions
3398/// in the warp to lower lane positions, creating Remote Reduce list.
3399/// Value aggregation:
3400/// In this step, effective threads combine their thread local Reduce list
3401/// with Remote Reduce list and store the result in the thread local
3402/// Reduce list.
3403/// Value copy:
3404/// In this step, we deal with the assumption made by algorithm 2
3405/// (i.e. contiguity assumption). When we have an odd number of lanes
3406/// active, say 2k+1, only k threads will be effective and therefore k
3407/// new values will be produced. However, the Reduce list owned by the
3408/// (2k+1)th thread is ignored in the value aggregation. Therefore
3409/// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
3410/// that the contiguity assumption still holds.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003411static llvm::Value *emitShuffleAndReduceFunction(
3412 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3413 QualType ReductionArrayTy, llvm::Value *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003414 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003415
3416 // Thread local Reduce list used to host the values of data to be reduced.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003417 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3418 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003419 // Current lane id; could be logical.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003420 ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
3421 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003422 // Offset of the remote source lane relative to the current lane.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003423 ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3424 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003425 // Algorithm version. This is expected to be known at compile time.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003426 ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3427 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003428 FunctionArgList Args;
3429 Args.push_back(&ReduceListArg);
3430 Args.push_back(&LaneIDArg);
3431 Args.push_back(&RemoteLaneOffsetArg);
3432 Args.push_back(&AlgoVerArg);
3433
Alexey Bataev9ff80832018-04-16 20:16:21 +00003434 const CGFunctionInfo &CGFI =
3435 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003436 auto *Fn = llvm::Function::Create(
3437 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3438 "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003439 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003440 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003441 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003442 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003443
Alexey Bataev9ff80832018-04-16 20:16:21 +00003444 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003445
3446 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3447 Address LocalReduceList(
3448 Bld.CreatePointerBitCastOrAddrSpaceCast(
3449 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3450 C.VoidPtrTy, SourceLocation()),
3451 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3452 CGF.getPointerAlign());
3453
3454 Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
3455 llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
3456 AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3457
3458 Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
3459 llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
3460 AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3461
3462 Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
3463 llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
3464 AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3465
3466 // Create a local thread-private variable to host the Reduce list
3467 // from a remote lane.
3468 Address RemoteReduceList =
3469 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
3470
3471 // This loop iterates through the list of reduce elements and copies,
3472 // element by element, from a remote lane in the warp to RemoteReduceList,
3473 // hosted on the thread's stack.
3474 emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
3475 LocalReduceList, RemoteReduceList,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003476 {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
3477 /*ScratchpadIndex=*/nullptr,
3478 /*ScratchpadWidth=*/nullptr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003479
3480 // The actions to be performed on the Remote Reduce list is dependent
3481 // on the algorithm version.
3482 //
3483 // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
3484 // LaneId % 2 == 0 && Offset > 0):
3485 // do the reduction value aggregation
3486 //
3487 // The thread local variable Reduce list is mutated in place to host the
3488 // reduced data, which is the aggregated value produced from local and
3489 // remote lanes.
3490 //
3491 // Note that AlgoVer is expected to be a constant integer known at compile
3492 // time.
3493 // When AlgoVer==0, the first conjunction evaluates to true, making
3494 // the entire predicate true during compile time.
3495 // When AlgoVer==1, the second conjunction has only the second part to be
3496 // evaluated during runtime. Other conjunctions evaluates to false
3497 // during compile time.
3498 // When AlgoVer==2, the third conjunction has only the second part to be
3499 // evaluated during runtime. Other conjunctions evaluates to false
3500 // during compile time.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003501 llvm::Value *CondAlgo0 = Bld.CreateIsNull(AlgoVerArgVal);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003502
Alexey Bataev9ff80832018-04-16 20:16:21 +00003503 llvm::Value *Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
3504 llvm::Value *CondAlgo1 = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003505 Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
3506
Alexey Bataev9ff80832018-04-16 20:16:21 +00003507 llvm::Value *Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
3508 llvm::Value *CondAlgo2 = Bld.CreateAnd(
3509 Algo2, Bld.CreateIsNull(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1))));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003510 CondAlgo2 = Bld.CreateAnd(
3511 CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
3512
Alexey Bataev9ff80832018-04-16 20:16:21 +00003513 llvm::Value *CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003514 CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
3515
3516 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3517 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3518 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
3519 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
3520
3521 CGF.EmitBlock(ThenBB);
3522 // reduce_function(LocalReduceList, RemoteReduceList)
3523 llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3524 LocalReduceList.getPointer(), CGF.VoidPtrTy);
3525 llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3526 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003527 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3528 CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003529 Bld.CreateBr(MergeBB);
3530
3531 CGF.EmitBlock(ElseBB);
3532 Bld.CreateBr(MergeBB);
3533
3534 CGF.EmitBlock(MergeBB);
3535
3536 // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
3537 // Reduce list.
3538 Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
Alexey Bataev9ff80832018-04-16 20:16:21 +00003539 llvm::Value *CondCopy = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003540 Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
3541
3542 llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
3543 llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
3544 llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
3545 Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
3546
3547 CGF.EmitBlock(CpyThenBB);
3548 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
3549 RemoteReduceList, LocalReduceList);
3550 Bld.CreateBr(CpyMergeBB);
3551
3552 CGF.EmitBlock(CpyElseBB);
3553 Bld.CreateBr(CpyMergeBB);
3554
3555 CGF.EmitBlock(CpyMergeBB);
3556
3557 CGF.FinishFunction();
3558 return Fn;
3559}
3560
3561///
3562/// Design of OpenMP reductions on the GPU
3563///
3564/// Consider a typical OpenMP program with one or more reduction
3565/// clauses:
3566///
3567/// float foo;
3568/// double bar;
3569/// #pragma omp target teams distribute parallel for \
3570/// reduction(+:foo) reduction(*:bar)
3571/// for (int i = 0; i < N; i++) {
3572/// foo += A[i]; bar *= B[i];
3573/// }
3574///
3575/// where 'foo' and 'bar' are reduced across all OpenMP threads in
3576/// all teams. In our OpenMP implementation on the NVPTX device an
3577/// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
3578/// within a team are mapped to CUDA threads within a threadblock.
3579/// Our goal is to efficiently aggregate values across all OpenMP
3580/// threads such that:
3581///
3582/// - the compiler and runtime are logically concise, and
3583/// - the reduction is performed efficiently in a hierarchical
3584/// manner as follows: within OpenMP threads in the same warp,
3585/// across warps in a threadblock, and finally across teams on
3586/// the NVPTX device.
3587///
3588/// Introduction to Decoupling
3589///
3590/// We would like to decouple the compiler and the runtime so that the
3591/// latter is ignorant of the reduction variables (number, data types)
3592/// and the reduction operators. This allows a simpler interface
3593/// and implementation while still attaining good performance.
3594///
3595/// Pseudocode for the aforementioned OpenMP program generated by the
3596/// compiler is as follows:
3597///
3598/// 1. Create private copies of reduction variables on each OpenMP
3599/// thread: 'foo_private', 'bar_private'
3600/// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
3601/// to it and writes the result in 'foo_private' and 'bar_private'
3602/// respectively.
3603/// 3. Call the OpenMP runtime on the GPU to reduce within a team
3604/// and store the result on the team master:
3605///
3606/// __kmpc_nvptx_parallel_reduce_nowait(...,
3607/// reduceData, shuffleReduceFn, interWarpCpyFn)
3608///
3609/// where:
3610/// struct ReduceData {
3611/// double *foo;
3612/// double *bar;
3613/// } reduceData
3614/// reduceData.foo = &foo_private
3615/// reduceData.bar = &bar_private
3616///
3617/// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
3618/// auxiliary functions generated by the compiler that operate on
3619/// variables of type 'ReduceData'. They aid the runtime perform
3620/// algorithmic steps in a data agnostic manner.
3621///
3622/// 'shuffleReduceFn' is a pointer to a function that reduces data
3623/// of type 'ReduceData' across two OpenMP threads (lanes) in the
3624/// same warp. It takes the following arguments as input:
3625///
3626/// a. variable of type 'ReduceData' on the calling lane,
3627/// b. its lane_id,
3628/// c. an offset relative to the current lane_id to generate a
3629/// remote_lane_id. The remote lane contains the second
3630/// variable of type 'ReduceData' that is to be reduced.
3631/// d. an algorithm version parameter determining which reduction
3632/// algorithm to use.
3633///
3634/// 'shuffleReduceFn' retrieves data from the remote lane using
3635/// efficient GPU shuffle intrinsics and reduces, using the
3636/// algorithm specified by the 4th parameter, the two operands
3637/// element-wise. The result is written to the first operand.
3638///
3639/// Different reduction algorithms are implemented in different
3640/// runtime functions, all calling 'shuffleReduceFn' to perform
3641/// the essential reduction step. Therefore, based on the 4th
3642/// parameter, this function behaves slightly differently to
3643/// cooperate with the runtime to ensure correctness under
3644/// different circumstances.
3645///
3646/// 'InterWarpCpyFn' is a pointer to a function that transfers
3647/// reduced variables across warps. It tunnels, through CUDA
3648/// shared memory, the thread-private data of type 'ReduceData'
3649/// from lane 0 of each warp to a lane in the first warp.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003650/// 4. Call the OpenMP runtime on the GPU to reduce across teams.
3651/// The last team writes the global reduced value to memory.
3652///
3653/// ret = __kmpc_nvptx_teams_reduce_nowait(...,
3654/// reduceData, shuffleReduceFn, interWarpCpyFn,
3655/// scratchpadCopyFn, loadAndReduceFn)
3656///
3657/// 'scratchpadCopyFn' is a helper that stores reduced
3658/// data from the team master to a scratchpad array in
3659/// global memory.
3660///
3661/// 'loadAndReduceFn' is a helper that loads data from
3662/// the scratchpad array and reduces it with the input
3663/// operand.
3664///
3665/// These compiler generated functions hide address
3666/// calculation and alignment information from the runtime.
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003667/// 5. if ret == 1:
3668/// The team master of the last team stores the reduced
3669/// result to the globals in memory.
3670/// foo += reduceData.foo; bar *= reduceData.bar
3671///
3672///
3673/// Warp Reduction Algorithms
3674///
3675/// On the warp level, we have three algorithms implemented in the
3676/// OpenMP runtime depending on the number of active lanes:
3677///
3678/// Full Warp Reduction
3679///
3680/// The reduce algorithm within a warp where all lanes are active
3681/// is implemented in the runtime as follows:
3682///
3683/// full_warp_reduce(void *reduce_data,
3684/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3685/// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
3686/// ShuffleReduceFn(reduce_data, 0, offset, 0);
3687/// }
3688///
3689/// The algorithm completes in log(2, WARPSIZE) steps.
3690///
3691/// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
3692/// not used therefore we save instructions by not retrieving lane_id
3693/// from the corresponding special registers. The 4th parameter, which
3694/// represents the version of the algorithm being used, is set to 0 to
3695/// signify full warp reduction.
3696///
3697/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3698///
3699/// #reduce_elem refers to an element in the local lane's data structure
3700/// #remote_elem is retrieved from a remote lane
3701/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3702/// reduce_elem = reduce_elem REDUCE_OP remote_elem;
3703///
3704/// Contiguous Partial Warp Reduction
3705///
3706/// This reduce algorithm is used within a warp where only the first
3707/// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
3708/// number of OpenMP threads in a parallel region is not a multiple of
3709/// WARPSIZE. The algorithm is implemented in the runtime as follows:
3710///
3711/// void
3712/// contiguous_partial_reduce(void *reduce_data,
3713/// kmp_ShuffleReductFctPtr ShuffleReduceFn,
3714/// int size, int lane_id) {
3715/// int curr_size;
3716/// int offset;
3717/// curr_size = size;
3718/// mask = curr_size/2;
3719/// while (offset>0) {
3720/// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
3721/// curr_size = (curr_size+1)/2;
3722/// offset = curr_size/2;
3723/// }
3724/// }
3725///
3726/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3727///
3728/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3729/// if (lane_id < offset)
3730/// reduce_elem = reduce_elem REDUCE_OP remote_elem
3731/// else
3732/// reduce_elem = remote_elem
3733///
3734/// This algorithm assumes that the data to be reduced are located in a
3735/// contiguous subset of lanes starting from the first. When there is
3736/// an odd number of active lanes, the data in the last lane is not
3737/// aggregated with any other lane's dat but is instead copied over.
3738///
3739/// Dispersed Partial Warp Reduction
3740///
3741/// This algorithm is used within a warp when any discontiguous subset of
3742/// lanes are active. It is used to implement the reduction operation
3743/// across lanes in an OpenMP simd region or in a nested parallel region.
3744///
3745/// void
3746/// dispersed_partial_reduce(void *reduce_data,
3747/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3748/// int size, remote_id;
3749/// int logical_lane_id = number_of_active_lanes_before_me() * 2;
3750/// do {
3751/// remote_id = next_active_lane_id_right_after_me();
3752/// # the above function returns 0 of no active lane
3753/// # is present right after the current lane.
3754/// size = number_of_active_lanes_in_this_warp();
3755/// logical_lane_id /= 2;
3756/// ShuffleReduceFn(reduce_data, logical_lane_id,
3757/// remote_id-1-threadIdx.x, 2);
3758/// } while (logical_lane_id % 2 == 0 && size > 1);
3759/// }
3760///
3761/// There is no assumption made about the initial state of the reduction.
3762/// Any number of lanes (>=1) could be active at any position. The reduction
3763/// result is returned in the first active lane.
3764///
3765/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3766///
3767/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3768/// if (lane_id % 2 == 0 && offset > 0)
3769/// reduce_elem = reduce_elem REDUCE_OP remote_elem
3770/// else
3771/// reduce_elem = remote_elem
3772///
3773///
3774/// Intra-Team Reduction
3775///
3776/// This function, as implemented in the runtime call
3777/// '__kmpc_nvptx_parallel_reduce_nowait', aggregates data across OpenMP
3778/// threads in a team. It first reduces within a warp using the
3779/// aforementioned algorithms. We then proceed to gather all such
3780/// reduced values at the first warp.
3781///
3782/// The runtime makes use of the function 'InterWarpCpyFn', which copies
3783/// data from each of the "warp master" (zeroth lane of each warp, where
3784/// warp-reduced data is held) to the zeroth warp. This step reduces (in
3785/// a mathematical sense) the problem of reduction across warp masters in
3786/// a block to the problem of warp reduction.
3787///
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003788///
3789/// Inter-Team Reduction
3790///
3791/// Once a team has reduced its data to a single value, it is stored in
3792/// a global scratchpad array. Since each team has a distinct slot, this
3793/// can be done without locking.
3794///
3795/// The last team to write to the scratchpad array proceeds to reduce the
3796/// scratchpad array. One or more workers in the last team use the helper
3797/// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
3798/// the k'th worker reduces every k'th element.
3799///
3800/// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait' to
3801/// reduce across workers and compute a globally reduced value.
3802///
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003803void CGOpenMPRuntimeNVPTX::emitReduction(
3804 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
3805 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
3806 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
3807 if (!CGF.HaveInsertPoint())
3808 return;
3809
3810 bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00003811#ifndef NDEBUG
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003812 bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00003813#endif
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003814
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00003815 if (Options.SimpleReduction) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003816 assert(!TeamsReduction && !ParallelReduction &&
3817 "Invalid reduction selection in emitReduction.");
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00003818 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
3819 ReductionOps, Options);
3820 return;
3821 }
3822
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003823 assert((TeamsReduction || ParallelReduction) &&
3824 "Invalid reduction selection in emitReduction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003825
Alexey Bataeva1166022018-11-27 21:24:54 +00003826 // Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003827 // RedList, shuffle_reduce_func, interwarp_copy_func);
Alexey Bataeva1166022018-11-27 21:24:54 +00003828 // or
3829 // Build res = __kmpc_reduce_teams_nowait_simple(<loc>, <gtid>, <lck>);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003830 llvm::Value *ThreadId = getThreadID(CGF, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003831
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003832 llvm::Value *Res;
3833 if (ParallelReduction) {
Alexey Bataeva1166022018-11-27 21:24:54 +00003834 ASTContext &C = CGM.getContext();
3835 // 1. Build a list of reduction variables.
3836 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3837 auto Size = RHSExprs.size();
3838 for (const Expr *E : Privates) {
3839 if (E->getType()->isVariablyModifiedType())
3840 // Reserve place for array size.
3841 ++Size;
3842 }
3843 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
3844 QualType ReductionArrayTy =
3845 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3846 /*IndexTypeQuals=*/0);
3847 Address ReductionList =
3848 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3849 auto IPriv = Privates.begin();
3850 unsigned Idx = 0;
3851 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
3852 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3853 CGF.getPointerSize());
3854 CGF.Builder.CreateStore(
3855 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3856 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
3857 Elem);
3858 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3859 // Store array size.
3860 ++Idx;
3861 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3862 CGF.getPointerSize());
3863 llvm::Value *Size = CGF.Builder.CreateIntCast(
3864 CGF.getVLASize(
3865 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3866 .NumElts,
3867 CGF.SizeTy, /*isSigned=*/false);
3868 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3869 Elem);
3870 }
3871 }
3872
3873 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
3874 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3875 ReductionList.getPointer(), CGF.VoidPtrTy);
3876 llvm::Value *ReductionFn = emitReductionFunction(
3877 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
3878 Privates, LHSExprs, RHSExprs, ReductionOps);
3879 llvm::Value *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
3880 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
3881 llvm::Value *InterWarpCopyFn =
3882 emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
3883
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003884 llvm::Value *Args[] = {ThreadId,
3885 CGF.Builder.getInt32(RHSExprs.size()),
3886 ReductionArrayTySize,
3887 RL,
3888 ShuffleAndReduceFn,
3889 InterWarpCopyFn};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003890
3891 Res = CGF.EmitRuntimeCall(
3892 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_reduce_nowait),
3893 Args);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003894 } else {
3895 assert(TeamsReduction && "expected teams reduction.");
Alexey Bataeva1166022018-11-27 21:24:54 +00003896 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
3897 std::string Name = getName({"reduction"});
3898 llvm::Value *Lock = getCriticalRegionLock(Name);
3899 llvm::Value *Args[] = {RTLoc, ThreadId, Lock};
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003900 Res = CGF.EmitRuntimeCall(
Alexey Bataeva1166022018-11-27 21:24:54 +00003901 createNVPTXRuntimeFunction(
3902 OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_simple),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003903 Args);
3904 }
3905
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003906 // 5. Build if (res == 1)
3907 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.reduction.done");
3908 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.then");
3909 llvm::Value *Cond = CGF.Builder.CreateICmpEQ(
3910 Res, llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1));
3911 CGF.Builder.CreateCondBr(Cond, ThenBB, ExitBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003912
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003913 // 6. Build then branch: where we have reduced values in the master
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003914 // thread in each team.
3915 // __kmpc_end_reduce{_nowait}(<gtid>);
3916 // break;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003917 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003918
3919 // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003920 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003921 this](CodeGenFunction &CGF, PrePostActionTy &Action) {
3922 auto IPriv = Privates.begin();
3923 auto ILHS = LHSExprs.begin();
3924 auto IRHS = RHSExprs.begin();
Alexey Bataev9ff80832018-04-16 20:16:21 +00003925 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003926 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
3927 cast<DeclRefExpr>(*IRHS));
3928 ++IPriv;
3929 ++ILHS;
3930 ++IRHS;
3931 }
3932 };
Alexey Bataeva1166022018-11-27 21:24:54 +00003933 if (ParallelReduction) {
3934 llvm::Value *EndArgs[] = {ThreadId};
3935 RegionCodeGenTy RCG(CodeGen);
3936 NVPTXActionTy Action(
3937 nullptr, llvm::None,
3938 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_reduce_nowait),
3939 EndArgs);
3940 RCG.setAction(Action);
3941 RCG(CGF);
3942 } else {
3943 assert(TeamsReduction && "expected teams reduction.");
3944 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
3945 std::string Name = getName({"reduction"});
3946 llvm::Value *Lock = getCriticalRegionLock(Name);
3947 llvm::Value *EndArgs[] = {RTLoc, ThreadId, Lock};
3948 RegionCodeGenTy RCG(CodeGen);
3949 NVPTXActionTy Action(
3950 nullptr, llvm::None,
3951 createNVPTXRuntimeFunction(
3952 OMPRTL_NVPTX__kmpc_nvptx_teams_end_reduce_nowait_simple),
3953 EndArgs);
3954 RCG.setAction(Action);
3955 RCG(CGF);
3956 }
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003957 // There is no need to emit line number for unconditional branch.
3958 (void)ApplyDebugLocation::CreateEmpty(CGF);
3959 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003960}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003961
3962const VarDecl *
3963CGOpenMPRuntimeNVPTX::translateParameter(const FieldDecl *FD,
3964 const VarDecl *NativeParam) const {
3965 if (!NativeParam->getType()->isReferenceType())
3966 return NativeParam;
3967 QualType ArgType = NativeParam->getType();
3968 QualifierCollector QC;
3969 const Type *NonQualTy = QC.strip(ArgType);
3970 QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
3971 if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
3972 if (Attr->getCaptureKind() == OMPC_map) {
3973 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
3974 LangAS::opencl_global);
3975 }
3976 }
3977 ArgType = CGM.getContext().getPointerType(PointeeTy);
3978 QC.addRestrict();
3979 enum { NVPTX_local_addr = 5 };
Alexander Richardson6d989432017-10-15 18:48:14 +00003980 QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003981 ArgType = QC.apply(CGM.getContext(), ArgType);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003982 if (isa<ImplicitParamDecl>(NativeParam))
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003983 return ImplicitParamDecl::Create(
3984 CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
3985 NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003986 return ParmVarDecl::Create(
3987 CGM.getContext(),
3988 const_cast<DeclContext *>(NativeParam->getDeclContext()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003989 NativeParam->getBeginLoc(), NativeParam->getLocation(),
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003990 NativeParam->getIdentifier(), ArgType,
3991 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003992}
3993
3994Address
3995CGOpenMPRuntimeNVPTX::getParameterAddress(CodeGenFunction &CGF,
3996 const VarDecl *NativeParam,
3997 const VarDecl *TargetParam) const {
3998 assert(NativeParam != TargetParam &&
3999 NativeParam->getType()->isReferenceType() &&
4000 "Native arg must not be the same as target arg.");
4001 Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
4002 QualType NativeParamType = NativeParam->getType();
4003 QualifierCollector QC;
4004 const Type *NonQualTy = QC.strip(NativeParamType);
4005 QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4006 unsigned NativePointeeAddrSpace =
Alexander Richardson6d989432017-10-15 18:48:14 +00004007 CGF.getContext().getTargetAddressSpace(NativePointeeTy);
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004008 QualType TargetTy = TargetParam->getType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004009 llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004010 LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004011 // First cast to generic.
4012 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4013 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4014 /*AddrSpace=*/0));
4015 // Cast from generic to native address space.
4016 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4017 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4018 NativePointeeAddrSpace));
4019 Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
4020 CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004021 NativeParamType);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004022 return NativeParamAddr;
4023}
4024
4025void CGOpenMPRuntimeNVPTX::emitOutlinedFunctionCall(
Alexey Bataev3c595a62017-08-14 15:01:03 +00004026 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004027 ArrayRef<llvm::Value *> Args) const {
4028 SmallVector<llvm::Value *, 4> TargetArgs;
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004029 TargetArgs.reserve(Args.size());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004030 auto *FnType =
4031 cast<llvm::FunctionType>(OutlinedFn->getType()->getPointerElementType());
4032 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004033 if (FnType->isVarArg() && FnType->getNumParams() <= I) {
4034 TargetArgs.append(std::next(Args.begin(), I), Args.end());
4035 break;
4036 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004037 llvm::Type *TargetType = FnType->getParamType(I);
4038 llvm::Value *NativeArg = Args[I];
4039 if (!TargetType->isPointerTy()) {
4040 TargetArgs.emplace_back(NativeArg);
4041 continue;
4042 }
4043 llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataevc99042b2018-03-15 18:10:54 +00004044 NativeArg,
4045 NativeArg->getType()->getPointerElementType()->getPointerTo());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004046 TargetArgs.emplace_back(
4047 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
4048 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00004049 CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004050}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004051
4052/// Emit function which wraps the outline parallel region
4053/// and controls the arguments which are passed to this function.
4054/// The wrapper ensures that the outlined function is called
4055/// with the correct arguments when data is shared.
4056llvm::Function *CGOpenMPRuntimeNVPTX::createParallelDataSharingWrapper(
4057 llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
4058 ASTContext &Ctx = CGM.getContext();
4059 const auto &CS = *D.getCapturedStmt(OMPD_parallel);
4060
4061 // Create a function that takes as argument the source thread.
4062 FunctionArgList WrapperArgs;
4063 QualType Int16QTy =
4064 Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
4065 QualType Int32QTy =
4066 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004067 ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004068 /*Id=*/nullptr, Int16QTy,
4069 ImplicitParamDecl::Other);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004070 ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004071 /*Id=*/nullptr, Int32QTy,
4072 ImplicitParamDecl::Other);
4073 WrapperArgs.emplace_back(&ParallelLevelArg);
4074 WrapperArgs.emplace_back(&WrapperArg);
4075
Alexey Bataev9ff80832018-04-16 20:16:21 +00004076 const CGFunctionInfo &CGFI =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004077 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
4078
4079 auto *Fn = llvm::Function::Create(
4080 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataev9ff80832018-04-16 20:16:21 +00004081 Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004082 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004083 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004084 Fn->setDoesNotRecurse();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004085
4086 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
4087 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004088 D.getBeginLoc(), D.getBeginLoc());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004089
4090 const auto *RD = CS.getCapturedRecordDecl();
4091 auto CurField = RD->field_begin();
4092
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004093 Address ZeroAddr = CGF.CreateMemTemp(
4094 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
4095 /*Name*/ ".zero.addr");
4096 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004097 // Get the array of arguments.
4098 SmallVector<llvm::Value *, 8> Args;
4099
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004100 Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).getPointer());
4101 Args.emplace_back(ZeroAddr.getPointer());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004102
4103 CGBuilderTy &Bld = CGF.Builder;
4104 auto CI = CS.capture_begin();
4105
4106 // Use global memory for data sharing.
4107 // Handle passing of global args to workers.
4108 Address GlobalArgs =
4109 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
4110 llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
4111 llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
4112 CGF.EmitRuntimeCall(
4113 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_get_shared_variables),
4114 DataSharingArgs);
4115
4116 // Retrieve the shared variables from the list of references returned
4117 // by the runtime. Pass the variables to the outlined function.
Alexey Bataev17314212018-03-20 15:41:05 +00004118 Address SharedArgListAddress = Address::invalid();
4119 if (CS.capture_size() > 0 ||
4120 isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4121 SharedArgListAddress = CGF.EmitLoadOfPointer(
4122 GlobalArgs, CGF.getContext()
4123 .getPointerType(CGF.getContext().getPointerType(
4124 CGF.getContext().VoidPtrTy))
4125 .castAs<PointerType>());
4126 }
4127 unsigned Idx = 0;
4128 if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4129 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
4130 CGF.getPointerSize());
4131 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4132 Src, CGF.SizeTy->getPointerTo());
4133 llvm::Value *LB = CGF.EmitLoadOfScalar(
4134 TypedAddress,
4135 /*Volatile=*/false,
4136 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4137 cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
4138 Args.emplace_back(LB);
4139 ++Idx;
4140 Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
4141 CGF.getPointerSize());
4142 TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4143 Src, CGF.SizeTy->getPointerTo());
4144 llvm::Value *UB = CGF.EmitLoadOfScalar(
4145 TypedAddress,
4146 /*Volatile=*/false,
4147 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4148 cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
4149 Args.emplace_back(UB);
4150 ++Idx;
4151 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004152 if (CS.capture_size() > 0) {
4153 ASTContext &CGFContext = CGF.getContext();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004154 for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
4155 QualType ElemTy = CurField->getType();
Alexey Bataev17314212018-03-20 15:41:05 +00004156 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx,
4157 CGF.getPointerSize());
4158 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004159 Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)));
4160 llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
4161 /*Volatile=*/false,
4162 CGFContext.getPointerType(ElemTy),
4163 CI->getLocation());
Alexey Bataev2091ca62018-04-23 17:33:41 +00004164 if (CI->capturesVariableByCopy() &&
4165 !CI->getCapturedVar()->getType()->isAnyPointerType()) {
Alexey Bataev17314212018-03-20 15:41:05 +00004166 Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
4167 CI->getLocation());
4168 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004169 Args.emplace_back(Arg);
4170 }
4171 }
4172
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004173 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedParallelFn, Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004174 CGF.FinishFunction();
4175 return Fn;
4176}
4177
4178void CGOpenMPRuntimeNVPTX::emitFunctionProlog(CodeGenFunction &CGF,
4179 const Decl *D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004180 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4181 return;
4182
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004183 assert(D && "Expected function or captured|block decl.");
4184 assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
4185 "Function is registered already.");
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004186 assert((!TeamAndReductions.first || TeamAndReductions.first == D) &&
4187 "Team is set but not processed.");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004188 const Stmt *Body = nullptr;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004189 bool NeedToDelayGlobalization = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004190 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4191 Body = FD->getBody();
4192 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
4193 Body = BD->getBody();
4194 } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
4195 Body = CD->getBody();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004196 NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
Alexey Bataev2adecff2018-09-21 14:22:53 +00004197 if (NeedToDelayGlobalization &&
4198 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
4199 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004200 }
4201 if (!Body)
4202 return;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004203 CheckVarsEscapingDeclContext VarChecker(CGF, TeamAndReductions.second);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004204 VarChecker.Visit(Body);
Alexey Bataevff23bb62018-10-11 18:30:31 +00004205 const RecordDecl *GlobalizedVarsRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004206 VarChecker.getGlobalizedRecord(IsInTTDRegion);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004207 TeamAndReductions.first = nullptr;
4208 TeamAndReductions.second.clear();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004209 ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
4210 VarChecker.getEscapedVariableLengthDecls();
4211 if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004212 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004213 auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
4214 I->getSecond().MappedParams =
4215 llvm::make_unique<CodeGenFunction::OMPMapVars>();
4216 I->getSecond().GlobalRecord = GlobalizedVarsRecord;
4217 I->getSecond().EscapedParameters.insert(
4218 VarChecker.getEscapedParameters().begin(),
4219 VarChecker.getEscapedParameters().end());
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004220 I->getSecond().EscapedVariableLengthDecls.append(
4221 EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004222 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004223 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004224 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004225 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004226 Data.insert(std::make_pair(VD, MappedVarData(FD, IsInTTDRegion)));
Alexey Bataevc99042b2018-03-15 18:10:54 +00004227 }
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004228 if (!IsInTTDRegion && !NeedToDelayGlobalization && !IsInParallelRegion) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004229 CheckVarsEscapingDeclContext VarChecker(CGF, llvm::None);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004230 VarChecker.Visit(Body);
4231 I->getSecond().SecondaryGlobalRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004232 VarChecker.getGlobalizedRecord(/*IsInTTDRegion=*/true);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004233 I->getSecond().SecondaryLocalVarData.emplace();
4234 DeclToAddrMapTy &Data = I->getSecond().SecondaryLocalVarData.getValue();
4235 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
4236 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
4237 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004238 Data.insert(
4239 std::make_pair(VD, MappedVarData(FD, /*IsInTTDRegion=*/true)));
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004240 }
4241 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00004242 if (!NeedToDelayGlobalization) {
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004243 emitGenericVarsProlog(CGF, D->getBeginLoc(), /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004244 struct GlobalizationScope final : EHScopeStack::Cleanup {
4245 GlobalizationScope() = default;
4246
4247 void Emit(CodeGenFunction &CGF, Flags flags) override {
4248 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004249 .emitGenericVarsEpilog(CGF, /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004250 }
4251 };
4252 CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004253 }
4254}
4255
4256Address CGOpenMPRuntimeNVPTX::getAddressOfLocalVariable(CodeGenFunction &CGF,
4257 const VarDecl *VD) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004258 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4259 return Address::invalid();
4260
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004261 VD = VD->getCanonicalDecl();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004262 auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
4263 if (I == FunctionGlobalizedDecls.end())
4264 return Address::invalid();
Alexey Bataevc99042b2018-03-15 18:10:54 +00004265 auto VDI = I->getSecond().LocalVarData.find(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004266 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004267 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004268 if (VD->hasAttrs()) {
4269 for (specific_attr_iterator<OMPReferencedVarAttr> IT(VD->attr_begin()),
4270 E(VD->attr_end());
4271 IT != E; ++IT) {
4272 auto VDI = I->getSecond().LocalVarData.find(
4273 cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
4274 ->getCanonicalDecl());
4275 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004276 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004277 }
4278 }
4279 return Address::invalid();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004280}
4281
4282void CGOpenMPRuntimeNVPTX::functionFinished(CodeGenFunction &CGF) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004283 FunctionGlobalizedDecls.erase(CGF.CurFn);
4284 CGOpenMPRuntime::functionFinished(CGF);
4285}
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004286
4287void CGOpenMPRuntimeNVPTX::getDefaultDistScheduleAndChunk(
4288 CodeGenFunction &CGF, const OMPLoopDirective &S,
4289 OpenMPDistScheduleClauseKind &ScheduleKind,
4290 llvm::Value *&Chunk) const {
4291 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
4292 ScheduleKind = OMPC_DIST_SCHEDULE_static;
4293 Chunk = CGF.EmitScalarConversion(getNVPTXNumThreads(CGF),
4294 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4295 S.getIterationVariable()->getType(), S.getBeginLoc());
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004296 return;
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004297 }
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004298 CGOpenMPRuntime::getDefaultDistScheduleAndChunk(
4299 CGF, S, ScheduleKind, Chunk);
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004300}
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004301
4302void CGOpenMPRuntimeNVPTX::getDefaultScheduleAndChunk(
4303 CodeGenFunction &CGF, const OMPLoopDirective &S,
4304 OpenMPScheduleClauseKind &ScheduleKind,
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004305 const Expr *&ChunkExpr) const {
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004306 ScheduleKind = OMPC_SCHEDULE_static;
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004307 // Chunk size is 1 in this case.
4308 llvm::APInt ChunkSize(32, 1);
4309 ChunkExpr = IntegerLiteral::Create(CGF.getContext(), ChunkSize,
4310 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4311 SourceLocation());
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004312}
Alexey Bataev60705422018-10-30 15:50:12 +00004313
4314void CGOpenMPRuntimeNVPTX::adjustTargetSpecificDataForLambdas(
4315 CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
4316 assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
4317 " Expected target-based directive.");
4318 const CapturedStmt *CS = D.getCapturedStmt(OMPD_target);
4319 for (const CapturedStmt::Capture &C : CS->captures()) {
4320 // Capture variables captured by reference in lambdas for target-based
4321 // directives.
4322 if (!C.capturesVariable())
4323 continue;
4324 const VarDecl *VD = C.getCapturedVar();
4325 const auto *RD = VD->getType()
4326 .getCanonicalType()
4327 .getNonReferenceType()
4328 ->getAsCXXRecordDecl();
4329 if (!RD || !RD->isLambda())
4330 continue;
4331 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4332 LValue VDLVal;
4333 if (VD->getType().getCanonicalType()->isReferenceType())
4334 VDLVal = CGF.EmitLoadOfReferenceLValue(VDAddr, VD->getType());
4335 else
4336 VDLVal = CGF.MakeAddrLValue(
4337 VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
4338 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4339 FieldDecl *ThisCapture = nullptr;
4340 RD->getCaptureFields(Captures, ThisCapture);
4341 if (ThisCapture && CGF.CapturedStmtInfo->isCXXThisExprCaptured()) {
4342 LValue ThisLVal =
4343 CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
4344 llvm::Value *CXXThis = CGF.LoadCXXThis();
4345 CGF.EmitStoreOfScalar(CXXThis, ThisLVal);
4346 }
4347 for (const LambdaCapture &LC : RD->captures()) {
4348 if (LC.getCaptureKind() != LCK_ByRef)
4349 continue;
4350 const VarDecl *VD = LC.getCapturedVar();
4351 if (!CS->capturesVariable(VD))
4352 continue;
4353 auto It = Captures.find(VD);
4354 assert(It != Captures.end() && "Found lambda capture without field.");
4355 LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
4356 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4357 if (VD->getType().getCanonicalType()->isReferenceType())
4358 VDAddr = CGF.EmitLoadOfReferenceLValue(VDAddr,
4359 VD->getType().getCanonicalType())
4360 .getAddress();
4361 CGF.EmitStoreOfScalar(VDAddr.getPointer(), VarLVal);
4362 }
4363 }
4364}
4365
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004366// Get current CudaArch and ignore any unknown values
4367static CudaArch getCudaArch(CodeGenModule &CGM) {
4368 if (!CGM.getTarget().hasFeature("ptx"))
4369 return CudaArch::UNKNOWN;
4370 llvm::StringMap<bool> Features;
4371 CGM.getTarget().initFeatureMap(Features, CGM.getDiags(),
4372 CGM.getTarget().getTargetOpts().CPU,
4373 CGM.getTarget().getTargetOpts().Features);
4374 for (const auto &Feature : Features) {
4375 if (Feature.getValue()) {
4376 CudaArch Arch = StringToCudaArch(Feature.getKey());
4377 if (Arch != CudaArch::UNKNOWN)
4378 return Arch;
4379 }
4380 }
4381 return CudaArch::UNKNOWN;
4382}
4383
4384/// Check to see if target architecture supports unified addressing which is
4385/// a restriction for OpenMP requires clause "unified_shared_memory".
4386void CGOpenMPRuntimeNVPTX::checkArchForUnifiedAddressing(
4387 CodeGenModule &CGM, const OMPRequiresDecl *D) const {
4388 for (const OMPClause *Clause : D->clauselists()) {
4389 if (Clause->getClauseKind() == OMPC_unified_shared_memory) {
4390 switch (getCudaArch(CGM)) {
4391 case CudaArch::SM_20:
4392 case CudaArch::SM_21:
4393 case CudaArch::SM_30:
4394 case CudaArch::SM_32:
4395 case CudaArch::SM_35:
4396 case CudaArch::SM_37:
4397 case CudaArch::SM_50:
4398 case CudaArch::SM_52:
4399 case CudaArch::SM_53:
4400 case CudaArch::SM_60:
4401 case CudaArch::SM_61:
4402 case CudaArch::SM_62:
4403 CGM.Error(Clause->getBeginLoc(),
4404 "Target architecture does not support unified addressing");
4405 return;
4406 case CudaArch::SM_70:
4407 case CudaArch::SM_72:
4408 case CudaArch::SM_75:
4409 case CudaArch::GFX600:
4410 case CudaArch::GFX601:
4411 case CudaArch::GFX700:
4412 case CudaArch::GFX701:
4413 case CudaArch::GFX702:
4414 case CudaArch::GFX703:
4415 case CudaArch::GFX704:
4416 case CudaArch::GFX801:
4417 case CudaArch::GFX802:
4418 case CudaArch::GFX803:
4419 case CudaArch::GFX810:
4420 case CudaArch::GFX900:
4421 case CudaArch::GFX902:
4422 case CudaArch::GFX904:
4423 case CudaArch::GFX906:
4424 case CudaArch::GFX909:
4425 case CudaArch::UNKNOWN:
4426 break;
4427 case CudaArch::LAST:
4428 llvm_unreachable("Unexpected Cuda arch.");
4429 }
4430 }
4431 }
4432}
4433
Alexey Bataeve4090182018-11-02 14:54:07 +00004434/// Get number of SMs and number of blocks per SM.
4435static std::pair<unsigned, unsigned> getSMsBlocksPerSM(CodeGenModule &CGM) {
4436 std::pair<unsigned, unsigned> Data;
4437 if (CGM.getLangOpts().OpenMPCUDANumSMs)
4438 Data.first = CGM.getLangOpts().OpenMPCUDANumSMs;
4439 if (CGM.getLangOpts().OpenMPCUDABlocksPerSM)
4440 Data.second = CGM.getLangOpts().OpenMPCUDABlocksPerSM;
4441 if (Data.first && Data.second)
4442 return Data;
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004443 switch (getCudaArch(CGM)) {
4444 case CudaArch::SM_20:
4445 case CudaArch::SM_21:
4446 case CudaArch::SM_30:
4447 case CudaArch::SM_32:
4448 case CudaArch::SM_35:
4449 case CudaArch::SM_37:
4450 case CudaArch::SM_50:
4451 case CudaArch::SM_52:
4452 case CudaArch::SM_53:
4453 return {16, 16};
4454 case CudaArch::SM_60:
4455 case CudaArch::SM_61:
4456 case CudaArch::SM_62:
4457 return {56, 32};
4458 case CudaArch::SM_70:
4459 case CudaArch::SM_72:
4460 case CudaArch::SM_75:
4461 return {84, 32};
4462 case CudaArch::GFX600:
4463 case CudaArch::GFX601:
4464 case CudaArch::GFX700:
4465 case CudaArch::GFX701:
4466 case CudaArch::GFX702:
4467 case CudaArch::GFX703:
4468 case CudaArch::GFX704:
4469 case CudaArch::GFX801:
4470 case CudaArch::GFX802:
4471 case CudaArch::GFX803:
4472 case CudaArch::GFX810:
4473 case CudaArch::GFX900:
4474 case CudaArch::GFX902:
4475 case CudaArch::GFX904:
4476 case CudaArch::GFX906:
4477 case CudaArch::GFX909:
4478 case CudaArch::UNKNOWN:
4479 break;
4480 case CudaArch::LAST:
4481 llvm_unreachable("Unexpected Cuda arch.");
Alexey Bataeve4090182018-11-02 14:54:07 +00004482 }
4483 llvm_unreachable("Unexpected NVPTX target without ptx feature.");
4484}
4485
4486void CGOpenMPRuntimeNVPTX::clear() {
4487 if (!GlobalizedRecords.empty()) {
4488 ASTContext &C = CGM.getContext();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004489 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> GlobalRecs;
4490 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> SharedRecs;
Alexey Bataeve4090182018-11-02 14:54:07 +00004491 RecordDecl *StaticRD = C.buildImplicitRecord(
4492 "_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
4493 StaticRD->startDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004494 RecordDecl *SharedStaticRD = C.buildImplicitRecord(
4495 "_shared_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
4496 SharedStaticRD->startDefinition();
Alexey Bataeve4090182018-11-02 14:54:07 +00004497 for (const GlobalPtrSizeRecsTy &Records : GlobalizedRecords) {
4498 if (Records.Records.empty())
4499 continue;
4500 unsigned Size = 0;
4501 unsigned RecAlignment = 0;
4502 for (const RecordDecl *RD : Records.Records) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004503 QualType RDTy = C.getRecordType(RD);
4504 unsigned Alignment = C.getTypeAlignInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00004505 RecAlignment = std::max(RecAlignment, Alignment);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004506 unsigned RecSize = C.getTypeSizeInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00004507 Size =
4508 llvm::alignTo(llvm::alignTo(Size, Alignment) + RecSize, Alignment);
4509 }
4510 Size = llvm::alignTo(Size, RecAlignment);
4511 llvm::APInt ArySize(/*numBits=*/64, Size);
4512 QualType SubTy = C.getConstantArrayType(
4513 C.CharTy, ArySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004514 const bool UseSharedMemory = Size <= SharedMemorySize;
4515 auto *Field =
4516 FieldDecl::Create(C, UseSharedMemory ? SharedStaticRD : StaticRD,
4517 SourceLocation(), SourceLocation(), nullptr, SubTy,
4518 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
4519 /*BW=*/nullptr, /*Mutable=*/false,
4520 /*InitStyle=*/ICIS_NoInit);
Alexey Bataeve4090182018-11-02 14:54:07 +00004521 Field->setAccess(AS_public);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004522 if (UseSharedMemory) {
4523 SharedStaticRD->addDecl(Field);
4524 SharedRecs.push_back(&Records);
4525 } else {
4526 StaticRD->addDecl(Field);
4527 GlobalRecs.push_back(&Records);
4528 }
Alexey Bataeve4090182018-11-02 14:54:07 +00004529 Records.RecSize->setInitializer(llvm::ConstantInt::get(CGM.SizeTy, Size));
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004530 Records.UseSharedMemory->setInitializer(
4531 llvm::ConstantInt::get(CGM.Int16Ty, UseSharedMemory ? 1 : 0));
4532 }
4533 SharedStaticRD->completeDefinition();
4534 if (!SharedStaticRD->field_empty()) {
4535 QualType StaticTy = C.getRecordType(SharedStaticRD);
4536 llvm::Type *LLVMStaticTy = CGM.getTypes().ConvertTypeForMem(StaticTy);
4537 auto *GV = new llvm::GlobalVariable(
4538 CGM.getModule(), LLVMStaticTy,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004539 /*isConstant=*/false, llvm::GlobalValue::CommonLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004540 llvm::Constant::getNullValue(LLVMStaticTy),
4541 "_openmp_shared_static_glob_rd_$_", /*InsertBefore=*/nullptr,
4542 llvm::GlobalValue::NotThreadLocal,
4543 C.getTargetAddressSpace(LangAS::cuda_shared));
4544 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
4545 GV, CGM.VoidPtrTy);
4546 for (const GlobalPtrSizeRecsTy *Rec : SharedRecs) {
4547 Rec->Buffer->replaceAllUsesWith(Replacement);
4548 Rec->Buffer->eraseFromParent();
4549 }
Alexey Bataeve4090182018-11-02 14:54:07 +00004550 }
4551 StaticRD->completeDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004552 if (!StaticRD->field_empty()) {
4553 QualType StaticTy = C.getRecordType(StaticRD);
4554 std::pair<unsigned, unsigned> SMsBlockPerSM = getSMsBlocksPerSM(CGM);
4555 llvm::APInt Size1(32, SMsBlockPerSM.second);
4556 QualType Arr1Ty =
4557 C.getConstantArrayType(StaticTy, Size1, ArrayType::Normal,
4558 /*IndexTypeQuals=*/0);
4559 llvm::APInt Size2(32, SMsBlockPerSM.first);
4560 QualType Arr2Ty = C.getConstantArrayType(Arr1Ty, Size2, ArrayType::Normal,
4561 /*IndexTypeQuals=*/0);
4562 llvm::Type *LLVMArr2Ty = CGM.getTypes().ConvertTypeForMem(Arr2Ty);
4563 auto *GV = new llvm::GlobalVariable(
4564 CGM.getModule(), LLVMArr2Ty,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004565 /*isConstant=*/false, llvm::GlobalValue::CommonLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004566 llvm::Constant::getNullValue(LLVMArr2Ty),
4567 "_openmp_static_glob_rd_$_");
4568 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
4569 GV, CGM.VoidPtrTy);
4570 for (const GlobalPtrSizeRecsTy *Rec : GlobalRecs) {
4571 Rec->Buffer->replaceAllUsesWith(Replacement);
4572 Rec->Buffer->eraseFromParent();
4573 }
4574 }
Alexey Bataeve4090182018-11-02 14:54:07 +00004575 }
4576 CGOpenMPRuntime::clear();
4577}