blob: 74b24eacce431f1f52ac02a6b525b9500e8f2c81 [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,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000036 /// Call to void __kmpc_spmd_kernel_deinit();
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +000037 OMPRTL_NVPTX__kmpc_spmd_kernel_deinit,
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,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000065 /// Call to __kmpc_nvptx_simd_reduce_nowait(kmp_int32
Alexey Bataevfac26cf2018-05-02 20:03:27 +000066 /// global_tid, kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
67 /// void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
68 /// lane_offset, int16_t shortCircuit),
69 /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num));
70 OMPRTL_NVPTX__kmpc_simd_reduce_nowait,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000071 /// Call to __kmpc_nvptx_teams_reduce_nowait(int32_t global_tid,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +000072 /// int32_t num_vars, size_t reduce_size, void *reduce_data,
73 /// void (*kmp_ShuffleReductFctPtr)(void *rhs, int16_t lane_id, int16_t
74 /// lane_offset, int16_t shortCircuit),
75 /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num),
76 /// void (*kmp_CopyToScratchpadFctPtr)(void *reduce_data, void * scratchpad,
77 /// int32_t index, int32_t width),
78 /// void (*kmp_LoadReduceFctPtr)(void *reduce_data, void * scratchpad, int32_t
79 /// index, int32_t width, int32_t reduce))
80 OMPRTL_NVPTX__kmpc_teams_reduce_nowait,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000081 /// Call to __kmpc_nvptx_end_reduce_nowait(int32_t global_tid);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000082 OMPRTL_NVPTX__kmpc_end_reduce_nowait,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000083 /// Call to void __kmpc_data_sharing_init_stack();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000084 OMPRTL_NVPTX__kmpc_data_sharing_init_stack,
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +000085 /// Call to void __kmpc_data_sharing_init_stack_spmd();
86 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd,
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +000087 /// Call to void* __kmpc_data_sharing_coalesced_push_stack(size_t size,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000088 /// int16_t UseSharedMemory);
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +000089 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000090 /// Call to void __kmpc_data_sharing_pop_stack(void *a);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000091 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000092 /// Call to void __kmpc_begin_sharing_variables(void ***args,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000093 /// size_t n_args);
94 OMPRTL_NVPTX__kmpc_begin_sharing_variables,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000095 /// Call to void __kmpc_end_sharing_variables();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000096 OMPRTL_NVPTX__kmpc_end_sharing_variables,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000097 /// Call to void __kmpc_get_shared_variables(void ***GlobalArgs)
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000098 OMPRTL_NVPTX__kmpc_get_shared_variables,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +000099 /// Call to uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32
100 /// global_tid);
101 OMPRTL_NVPTX__kmpc_parallel_level,
Alexey Bataev673110d2018-05-16 13:36:30 +0000102 /// Call to int8_t __kmpc_is_spmd_exec_mode();
103 OMPRTL_NVPTX__kmpc_is_spmd_exec_mode,
Alexey Bataeve4090182018-11-02 14:54:07 +0000104 /// Call to void __kmpc_get_team_static_memory(const void *buf, size_t size,
105 /// int16_t is_shared, const void **res);
106 OMPRTL_NVPTX__kmpc_get_team_static_memory,
107 /// Call to void __kmpc_restore_team_static_memory(int16_t is_shared);
108 OMPRTL_NVPTX__kmpc_restore_team_static_memory,
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000109};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000110
111/// Pre(post)-action for different OpenMP constructs specialized for NVPTX.
112class NVPTXActionTy final : public PrePostActionTy {
Alexey Bataev9ff80832018-04-16 20:16:21 +0000113 llvm::Value *EnterCallee = nullptr;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000114 ArrayRef<llvm::Value *> EnterArgs;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000115 llvm::Value *ExitCallee = nullptr;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000116 ArrayRef<llvm::Value *> ExitArgs;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000117 bool Conditional = false;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000118 llvm::BasicBlock *ContBlock = nullptr;
119
120public:
121 NVPTXActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
122 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
123 bool Conditional = false)
124 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
125 ExitArgs(ExitArgs), Conditional(Conditional) {}
126 void Enter(CodeGenFunction &CGF) override {
127 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
128 if (Conditional) {
129 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
130 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
131 ContBlock = CGF.createBasicBlock("omp_if.end");
132 // Generate the branch (If-stmt)
133 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
134 CGF.EmitBlock(ThenBlock);
135 }
136 }
137 void Done(CodeGenFunction &CGF) {
138 // Emit the rest of blocks/branches
139 CGF.EmitBranch(ContBlock);
140 CGF.EmitBlock(ContBlock, true);
141 }
142 void Exit(CodeGenFunction &CGF) override {
143 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
144 }
145};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000146
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000147/// A class to track the execution mode when codegening directives within
148/// a target region. The appropriate mode (SPMD|NON-SPMD) is set on entry
149/// to the target region and used by containing directives such as 'parallel'
150/// to emit optimized code.
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000151class ExecutionModeRAII {
152private:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000153 CGOpenMPRuntimeNVPTX::ExecutionMode SavedMode;
154 CGOpenMPRuntimeNVPTX::ExecutionMode &Mode;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000155
156public:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000157 ExecutionModeRAII(CGOpenMPRuntimeNVPTX::ExecutionMode &Mode, bool IsSPMD)
158 : Mode(Mode) {
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000159 SavedMode = Mode;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000160 Mode = IsSPMD ? CGOpenMPRuntimeNVPTX::EM_SPMD
161 : CGOpenMPRuntimeNVPTX::EM_NonSPMD;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000162 }
163 ~ExecutionModeRAII() { Mode = SavedMode; }
164};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000165
166/// GPU Configuration: This information can be derived from cuda registers,
167/// however, providing compile time constants helps generate more efficient
168/// code. For all practical purposes this is fine because the configuration
169/// is the same for all known NVPTX architectures.
170enum MachineConfiguration : unsigned {
171 WarpSize = 32,
172 /// Number of bits required to represent a lane identifier, which is
173 /// computed as log_2(WarpSize).
174 LaneIDBits = 5,
175 LaneIDMask = WarpSize - 1,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +0000176
177 /// Global memory alignment for performance.
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000178 GlobalMemoryAlignment = 128,
Alexey Bataev09c9eea2018-11-09 16:18:04 +0000179
180 /// Maximal size of the shared memory buffer.
181 SharedMemorySize = 128,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000182};
183
184enum NamedBarrier : unsigned {
185 /// Synchronize on this barrier #ID using a named barrier primitive.
186 /// Only the subset of active threads in a parallel region arrive at the
187 /// barrier.
188 NB_Parallel = 1,
189};
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000190
Alexey Bataevf2f39be2018-11-16 19:38:21 +0000191static const ValueDecl *getPrivateItem(const Expr *RefExpr) {
192 RefExpr = RefExpr->IgnoreParens();
193 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr)) {
194 const Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
195 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
196 Base = TempASE->getBase()->IgnoreParenImpCasts();
197 RefExpr = Base;
198 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr)) {
199 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
200 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
201 Base = TempOASE->getBase()->IgnoreParenImpCasts();
202 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
203 Base = TempASE->getBase()->IgnoreParenImpCasts();
204 RefExpr = Base;
205 }
206 RefExpr = RefExpr->IgnoreParenImpCasts();
207 if (const auto *DE = dyn_cast<DeclRefExpr>(RefExpr))
208 return cast<ValueDecl>(DE->getDecl()->getCanonicalDecl());
209 const auto *ME = cast<MemberExpr>(RefExpr);
210 return cast<ValueDecl>(ME->getMemberDecl()->getCanonicalDecl());
211}
212
Alexey Bataev2adecff2018-09-21 14:22:53 +0000213typedef std::pair<CharUnits /*Align*/, const ValueDecl *> VarsDataTy;
214static bool stable_sort_comparator(const VarsDataTy P1, const VarsDataTy P2) {
215 return P1.first > P2.first;
216}
217
218static RecordDecl *buildRecordForGlobalizedVars(
219 ASTContext &C, ArrayRef<const ValueDecl *> EscapedDecls,
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000220 ArrayRef<const ValueDecl *> EscapedDeclsForTeams,
Alexey Bataev2adecff2018-09-21 14:22:53 +0000221 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
222 &MappedDeclsFields) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000223 if (EscapedDecls.empty() && EscapedDeclsForTeams.empty())
Alexey Bataev2adecff2018-09-21 14:22:53 +0000224 return nullptr;
225 SmallVector<VarsDataTy, 4> GlobalizedVars;
226 for (const ValueDecl *D : EscapedDecls)
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000227 GlobalizedVars.emplace_back(
228 CharUnits::fromQuantity(std::max(
229 C.getDeclAlign(D).getQuantity(),
230 static_cast<CharUnits::QuantityType>(GlobalMemoryAlignment))),
231 D);
232 for (const ValueDecl *D : EscapedDeclsForTeams)
Alexey Bataev2adecff2018-09-21 14:22:53 +0000233 GlobalizedVars.emplace_back(C.getDeclAlign(D), D);
234 std::stable_sort(GlobalizedVars.begin(), GlobalizedVars.end(),
235 stable_sort_comparator);
236 // Build struct _globalized_locals_ty {
Alexey Bataevff23bb62018-10-11 18:30:31 +0000237 // /* globalized vars */[WarSize] align (max(decl_align,
238 // GlobalMemoryAlignment))
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000239 // /* globalized vars */ for EscapedDeclsForTeams
Alexey Bataev2adecff2018-09-21 14:22:53 +0000240 // };
241 RecordDecl *GlobalizedRD = C.buildImplicitRecord("_globalized_locals_ty");
242 GlobalizedRD->startDefinition();
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000243 llvm::SmallPtrSet<const ValueDecl *, 16> SingleEscaped(
244 EscapedDeclsForTeams.begin(), EscapedDeclsForTeams.end());
Alexey Bataev2adecff2018-09-21 14:22:53 +0000245 for (const auto &Pair : GlobalizedVars) {
246 const ValueDecl *VD = Pair.second;
247 QualType Type = VD->getType();
248 if (Type->isLValueReferenceType())
249 Type = C.getPointerType(Type.getNonReferenceType());
250 else
251 Type = Type.getNonReferenceType();
252 SourceLocation Loc = VD->getLocation();
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000253 FieldDecl *Field;
254 if (SingleEscaped.count(VD)) {
255 Field = FieldDecl::Create(
256 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
257 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
258 /*BW=*/nullptr, /*Mutable=*/false,
259 /*InitStyle=*/ICIS_NoInit);
260 Field->setAccess(AS_public);
261 if (VD->hasAttrs()) {
262 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
263 E(VD->getAttrs().end());
264 I != E; ++I)
265 Field->addAttr(*I);
266 }
267 } else {
268 llvm::APInt ArraySize(32, WarpSize);
269 Type = C.getConstantArrayType(Type, ArraySize, ArrayType::Normal, 0);
270 Field = FieldDecl::Create(
271 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
272 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
273 /*BW=*/nullptr, /*Mutable=*/false,
274 /*InitStyle=*/ICIS_NoInit);
275 Field->setAccess(AS_public);
276 llvm::APInt Align(32, std::max(C.getDeclAlign(VD).getQuantity(),
277 static_cast<CharUnits::QuantityType>(
278 GlobalMemoryAlignment)));
279 Field->addAttr(AlignedAttr::CreateImplicit(
280 C, AlignedAttr::GNU_aligned, /*IsAlignmentExpr=*/true,
281 IntegerLiteral::Create(C, Align,
282 C.getIntTypeForBitwidth(32, /*Signed=*/0),
283 SourceLocation())));
Alexey Bataev2adecff2018-09-21 14:22:53 +0000284 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000285 GlobalizedRD->addDecl(Field);
Alexey Bataev2adecff2018-09-21 14:22:53 +0000286 MappedDeclsFields.try_emplace(VD, Field);
287 }
288 GlobalizedRD->completeDefinition();
289 return GlobalizedRD;
290}
291
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000292/// Get the list of variables that can escape their declaration context.
293class CheckVarsEscapingDeclContext final
294 : public ConstStmtVisitor<CheckVarsEscapingDeclContext> {
295 CodeGenFunction &CGF;
296 llvm::SetVector<const ValueDecl *> EscapedDecls;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000297 llvm::SetVector<const ValueDecl *> EscapedVariableLengthDecls;
Alexey Bataevc99042b2018-03-15 18:10:54 +0000298 llvm::SmallPtrSet<const Decl *, 4> EscapedParameters;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000299 RecordDecl *GlobalizedRD = nullptr;
300 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000301 bool AllEscaped = false;
Alexey Bataev91433f62018-06-26 17:24:03 +0000302 bool IsForCombinedParallelRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000303
304 void markAsEscaped(const ValueDecl *VD) {
Alexey Bataev03f270c2018-03-30 18:31:07 +0000305 // Do not globalize declare target variables.
Alexey Bataev97b72212018-08-14 18:31:20 +0000306 if (!isa<VarDecl>(VD) ||
307 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataev03f270c2018-03-30 18:31:07 +0000308 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000309 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataevc99042b2018-03-15 18:10:54 +0000310 // Variables captured by value must be globalized.
311 if (auto *CSI = CGF.CapturedStmtInfo) {
Mikael Holmen9f373a32018-03-16 07:27:57 +0000312 if (const FieldDecl *FD = CSI->lookup(cast<VarDecl>(VD))) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000313 // Check if need to capture the variable that was already captured by
314 // value in the outer region.
Alexey Bataev91433f62018-06-26 17:24:03 +0000315 if (!IsForCombinedParallelRegion) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000316 if (!FD->hasAttrs())
317 return;
318 const auto *Attr = FD->getAttr<OMPCaptureKindAttr>();
319 if (!Attr)
320 return;
321 if (!isOpenMPPrivate(
322 static_cast<OpenMPClauseKind>(Attr->getCaptureKind())) ||
323 Attr->getCaptureKind() == OMPC_map)
324 return;
325 }
326 if (!FD->getType()->isReferenceType()) {
327 assert(!VD->getType()->isVariablyModifiedType() &&
328 "Parameter captured by value with variably modified type");
329 EscapedParameters.insert(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000330 } else if (!IsForCombinedParallelRegion) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000331 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000332 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000333 }
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000334 }
335 if ((!CGF.CapturedStmtInfo ||
Alexey Bataev91433f62018-06-26 17:24:03 +0000336 (IsForCombinedParallelRegion && CGF.CapturedStmtInfo)) &&
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000337 VD->getType()->isReferenceType())
338 // Do not globalize variables with reference type.
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000339 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000340 if (VD->getType()->isVariablyModifiedType())
341 EscapedVariableLengthDecls.insert(VD);
342 else
343 EscapedDecls.insert(VD);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000344 }
345
346 void VisitValueDecl(const ValueDecl *VD) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000347 if (VD->getType()->isLValueReferenceType())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000348 markAsEscaped(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000349 if (const auto *VarD = dyn_cast<VarDecl>(VD)) {
350 if (!isa<ParmVarDecl>(VarD) && VarD->hasInit()) {
351 const bool SavedAllEscaped = AllEscaped;
352 AllEscaped = VD->getType()->isLValueReferenceType();
353 Visit(VarD->getInit());
354 AllEscaped = SavedAllEscaped;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000355 }
356 }
357 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000358 void VisitOpenMPCapturedStmt(const CapturedStmt *S,
359 ArrayRef<OMPClause *> Clauses,
360 bool IsCombinedParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000361 if (!S)
362 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000363 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000364 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
365 const ValueDecl *VD = C.getCapturedVar();
Alexey Bataev91433f62018-06-26 17:24:03 +0000366 bool SavedIsForCombinedParallelRegion = IsForCombinedParallelRegion;
367 if (IsCombinedParallelRegion) {
368 // Check if the variable is privatized in the combined construct and
369 // those private copies must be shared in the inner parallel
370 // directive.
371 IsForCombinedParallelRegion = false;
372 for (const OMPClause *C : Clauses) {
373 if (!isOpenMPPrivate(C->getClauseKind()) ||
374 C->getClauseKind() == OMPC_reduction ||
375 C->getClauseKind() == OMPC_linear ||
376 C->getClauseKind() == OMPC_private)
377 continue;
378 ArrayRef<const Expr *> Vars;
379 if (const auto *PC = dyn_cast<OMPFirstprivateClause>(C))
380 Vars = PC->getVarRefs();
381 else if (const auto *PC = dyn_cast<OMPLastprivateClause>(C))
382 Vars = PC->getVarRefs();
383 else
384 llvm_unreachable("Unexpected clause.");
385 for (const auto *E : Vars) {
386 const Decl *D =
387 cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
388 if (D == VD->getCanonicalDecl()) {
389 IsForCombinedParallelRegion = true;
390 break;
391 }
392 }
393 if (IsForCombinedParallelRegion)
394 break;
395 }
396 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000397 markAsEscaped(VD);
398 if (isa<OMPCapturedExprDecl>(VD))
399 VisitValueDecl(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000400 IsForCombinedParallelRegion = SavedIsForCombinedParallelRegion;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000401 }
402 }
403 }
404
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000405 void buildRecordForGlobalizedVars(bool IsInTTDRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000406 assert(!GlobalizedRD &&
407 "Record for globalized variables is built already.");
Alexey Bataevff23bb62018-10-11 18:30:31 +0000408 ArrayRef<const ValueDecl *> EscapedDeclsForParallel, EscapedDeclsForTeams;
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000409 if (IsInTTDRegion)
Alexey Bataevff23bb62018-10-11 18:30:31 +0000410 EscapedDeclsForTeams = EscapedDecls.getArrayRef();
411 else
412 EscapedDeclsForParallel = EscapedDecls.getArrayRef();
Alexey Bataev2adecff2018-09-21 14:22:53 +0000413 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataevff23bb62018-10-11 18:30:31 +0000414 CGF.getContext(), EscapedDeclsForParallel, EscapedDeclsForTeams,
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000415 MappedDeclsFields);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000416 }
417
418public:
Alexey Bataevf2f39be2018-11-16 19:38:21 +0000419 CheckVarsEscapingDeclContext(CodeGenFunction &CGF,
420 ArrayRef<const ValueDecl *> TeamsReductions)
421 : CGF(CGF), EscapedDecls(TeamsReductions.begin(), TeamsReductions.end()) {
422 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000423 virtual ~CheckVarsEscapingDeclContext() = default;
424 void VisitDeclStmt(const DeclStmt *S) {
425 if (!S)
426 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000427 for (const Decl *D : S->decls())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000428 if (const auto *VD = dyn_cast_or_null<ValueDecl>(D))
429 VisitValueDecl(VD);
430 }
431 void VisitOMPExecutableDirective(const OMPExecutableDirective *D) {
432 if (!D)
433 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000434 if (!D->hasAssociatedStmt())
435 return;
436 if (const auto *S =
437 dyn_cast_or_null<CapturedStmt>(D->getAssociatedStmt())) {
438 // Do not analyze directives that do not actually require capturing,
439 // like `omp for` or `omp simd` directives.
440 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
441 getOpenMPCaptureRegions(CaptureRegions, D->getDirectiveKind());
442 if (CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown) {
443 VisitStmt(S->getCapturedStmt());
444 return;
Alexey Bataev673110d2018-05-16 13:36:30 +0000445 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000446 VisitOpenMPCapturedStmt(
447 S, D->clauses(),
448 CaptureRegions.back() == OMPD_parallel &&
449 isOpenMPDistributeDirective(D->getDirectiveKind()));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000450 }
451 }
452 void VisitCapturedStmt(const CapturedStmt *S) {
453 if (!S)
454 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000455 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000456 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
457 const ValueDecl *VD = C.getCapturedVar();
458 markAsEscaped(VD);
459 if (isa<OMPCapturedExprDecl>(VD))
460 VisitValueDecl(VD);
461 }
462 }
463 }
464 void VisitLambdaExpr(const LambdaExpr *E) {
465 if (!E)
466 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000467 for (const LambdaCapture &C : E->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000468 if (C.capturesVariable()) {
469 if (C.getCaptureKind() == LCK_ByRef) {
470 const ValueDecl *VD = C.getCapturedVar();
471 markAsEscaped(VD);
472 if (E->isInitCapture(&C) || isa<OMPCapturedExprDecl>(VD))
473 VisitValueDecl(VD);
474 }
475 }
476 }
477 }
478 void VisitBlockExpr(const BlockExpr *E) {
479 if (!E)
480 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000481 for (const BlockDecl::Capture &C : E->getBlockDecl()->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000482 if (C.isByRef()) {
483 const VarDecl *VD = C.getVariable();
484 markAsEscaped(VD);
485 if (isa<OMPCapturedExprDecl>(VD) || VD->isInitCapture())
486 VisitValueDecl(VD);
487 }
488 }
489 }
490 void VisitCallExpr(const CallExpr *E) {
491 if (!E)
492 return;
493 for (const Expr *Arg : E->arguments()) {
494 if (!Arg)
495 continue;
496 if (Arg->isLValue()) {
497 const bool SavedAllEscaped = AllEscaped;
498 AllEscaped = true;
499 Visit(Arg);
500 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000501 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000502 Visit(Arg);
Alexey Bataev9ff80832018-04-16 20:16:21 +0000503 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000504 }
505 Visit(E->getCallee());
506 }
507 void VisitDeclRefExpr(const DeclRefExpr *E) {
508 if (!E)
509 return;
510 const ValueDecl *VD = E->getDecl();
511 if (AllEscaped)
512 markAsEscaped(VD);
513 if (isa<OMPCapturedExprDecl>(VD))
514 VisitValueDecl(VD);
515 else if (const auto *VarD = dyn_cast<VarDecl>(VD))
516 if (VarD->isInitCapture())
517 VisitValueDecl(VD);
518 }
519 void VisitUnaryOperator(const UnaryOperator *E) {
520 if (!E)
521 return;
522 if (E->getOpcode() == UO_AddrOf) {
523 const bool SavedAllEscaped = AllEscaped;
524 AllEscaped = true;
525 Visit(E->getSubExpr());
526 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000527 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000528 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000529 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000530 }
531 void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
532 if (!E)
533 return;
534 if (E->getCastKind() == CK_ArrayToPointerDecay) {
535 const bool SavedAllEscaped = AllEscaped;
536 AllEscaped = true;
537 Visit(E->getSubExpr());
538 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000539 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000540 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000541 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000542 }
543 void VisitExpr(const Expr *E) {
544 if (!E)
545 return;
546 bool SavedAllEscaped = AllEscaped;
547 if (!E->isLValue())
548 AllEscaped = false;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000549 for (const Stmt *Child : E->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000550 if (Child)
551 Visit(Child);
552 AllEscaped = SavedAllEscaped;
553 }
554 void VisitStmt(const Stmt *S) {
555 if (!S)
556 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000557 for (const Stmt *Child : S->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000558 if (Child)
559 Visit(Child);
560 }
561
Alexey Bataevc99042b2018-03-15 18:10:54 +0000562 /// Returns the record that handles all the escaped local variables and used
563 /// instead of their original storage.
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000564 const RecordDecl *getGlobalizedRecord(bool IsInTTDRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000565 if (!GlobalizedRD)
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000566 buildRecordForGlobalizedVars(IsInTTDRegion);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000567 return GlobalizedRD;
568 }
569
Alexey Bataevc99042b2018-03-15 18:10:54 +0000570 /// Returns the field in the globalized record for the escaped variable.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000571 const FieldDecl *getFieldForGlobalizedVar(const ValueDecl *VD) const {
572 assert(GlobalizedRD &&
573 "Record for globalized variables must be generated already.");
574 auto I = MappedDeclsFields.find(VD);
575 if (I == MappedDeclsFields.end())
576 return nullptr;
577 return I->getSecond();
578 }
579
Alexey Bataevc99042b2018-03-15 18:10:54 +0000580 /// Returns the list of the escaped local variables/parameters.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000581 ArrayRef<const ValueDecl *> getEscapedDecls() const {
582 return EscapedDecls.getArrayRef();
583 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000584
585 /// Checks if the escaped local variable is actually a parameter passed by
586 /// value.
587 const llvm::SmallPtrSetImpl<const Decl *> &getEscapedParameters() const {
588 return EscapedParameters;
589 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000590
591 /// Returns the list of the escaped variables with the variably modified
592 /// types.
593 ArrayRef<const ValueDecl *> getEscapedVariableLengthDecls() const {
594 return EscapedVariableLengthDecls.getArrayRef();
595 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000596};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000597} // anonymous namespace
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000598
599/// Get the GPU warp size.
600static llvm::Value *getNVPTXWarpSize(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000601 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000602 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000603 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_warpsize),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000604 "nvptx_warp_size");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000605}
606
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000607/// Get the id of the current thread on the GPU.
608static llvm::Value *getNVPTXThreadID(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_tid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000612 "nvptx_tid");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000613}
614
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000615/// Get the id of the warp in the block.
616/// We assume that the warp size is 32, which is always the case
617/// on the NVPTX device, to generate more efficient code.
618static llvm::Value *getNVPTXWarpID(CodeGenFunction &CGF) {
619 CGBuilderTy &Bld = CGF.Builder;
620 return Bld.CreateAShr(getNVPTXThreadID(CGF), LaneIDBits, "nvptx_warp_id");
621}
622
623/// Get the id of the current lane in the Warp.
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 *getNVPTXLaneID(CodeGenFunction &CGF) {
627 CGBuilderTy &Bld = CGF.Builder;
628 return Bld.CreateAnd(getNVPTXThreadID(CGF), Bld.getInt32(LaneIDMask),
629 "nvptx_lane_id");
630}
631
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000632/// Get the maximum number of threads in a block of the GPU.
633static llvm::Value *getNVPTXNumThreads(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000634 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000635 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000636 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_ntid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000637 "nvptx_num_threads");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000638}
639
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000640/// Get barrier to synchronize all threads in a block.
641static void getNVPTXCTABarrier(CodeGenFunction &CGF) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +0000642 llvm::Function *F = llvm::Intrinsic::getDeclaration(
643 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_barrier0);
644 F->addFnAttr(llvm::Attribute::Convergent);
645 CGF.EmitRuntimeCall(F);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000646}
647
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000648/// Get barrier #ID to synchronize selected (multiple of warp size) threads in
649/// a CTA.
650static void getNVPTXBarrier(CodeGenFunction &CGF, int ID,
651 llvm::Value *NumThreads) {
652 CGBuilderTy &Bld = CGF.Builder;
653 llvm::Value *Args[] = {Bld.getInt32(ID), NumThreads};
Alexey Bataevf2f39be2018-11-16 19:38:21 +0000654 llvm::Function *F = llvm::Intrinsic::getDeclaration(
655 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_barrier);
656 F->addFnAttr(llvm::Attribute::Convergent);
657 CGF.EmitRuntimeCall(F, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000658}
659
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000660/// Synchronize all GPU threads in a block.
661static void syncCTAThreads(CodeGenFunction &CGF) { getNVPTXCTABarrier(CGF); }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000662
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000663/// Synchronize worker threads in a parallel region.
664static void syncParallelThreads(CodeGenFunction &CGF, llvm::Value *NumThreads) {
665 return getNVPTXBarrier(CGF, NB_Parallel, NumThreads);
666}
667
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000668/// Get the value of the thread_limit clause in the teams directive.
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000669/// For the 'generic' execution mode, the runtime encodes thread_limit in
670/// the launch parameters, always starting thread_limit+warpSize threads per
671/// CTA. The threads in the last warp are reserved for master execution.
672/// For the 'spmd' execution mode, all threads in a CTA are part of the team.
673static llvm::Value *getThreadLimit(CodeGenFunction &CGF,
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000674 bool IsInSPMDExecutionMode = false) {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000675 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000676 return IsInSPMDExecutionMode
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000677 ? getNVPTXNumThreads(CGF)
Alexey Bataeve290ec02018-04-06 16:03:36 +0000678 : Bld.CreateNUWSub(getNVPTXNumThreads(CGF), getNVPTXWarpSize(CGF),
679 "thread_limit");
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000680}
681
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000682/// Get the thread id of the OMP master thread.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000683/// The master thread id is the first thread (lane) of the last warp in the
684/// GPU block. Warp size is assumed to be some power of 2.
685/// Thread id is 0 indexed.
686/// E.g: If NumThreads is 33, master id is 32.
687/// If NumThreads is 64, master id is 32.
688/// If NumThreads is 1024, master id is 992.
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000689static llvm::Value *getMasterThreadID(CodeGenFunction &CGF) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000690 CGBuilderTy &Bld = CGF.Builder;
691 llvm::Value *NumThreads = getNVPTXNumThreads(CGF);
692
693 // We assume that the warp size is a power of 2.
Alexey Bataeve290ec02018-04-06 16:03:36 +0000694 llvm::Value *Mask = Bld.CreateNUWSub(getNVPTXWarpSize(CGF), Bld.getInt32(1));
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000695
Alexey Bataeve290ec02018-04-06 16:03:36 +0000696 return Bld.CreateAnd(Bld.CreateNUWSub(NumThreads, Bld.getInt32(1)),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000697 Bld.CreateNot(Mask), "master_tid");
698}
699
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000700CGOpenMPRuntimeNVPTX::WorkerFunctionState::WorkerFunctionState(
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000701 CodeGenModule &CGM, SourceLocation Loc)
Alexey Bataev9ff80832018-04-16 20:16:21 +0000702 : WorkerFn(nullptr), CGFI(CGM.getTypes().arrangeNullaryFunction()),
703 Loc(Loc) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000704 createWorkerFunction(CGM);
Vasileios Kalintirise5c09592016-03-22 10:41:20 +0000705}
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000706
707void CGOpenMPRuntimeNVPTX::WorkerFunctionState::createWorkerFunction(
708 CodeGenModule &CGM) {
709 // Create an worker function with no arguments.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000710
711 WorkerFn = llvm::Function::Create(
Alexey Bataev9ff80832018-04-16 20:16:21 +0000712 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataevaee93892018-01-08 20:09:47 +0000713 /*placeholder=*/"_worker", &CGM.getModule());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000714 CGM.SetInternalFunctionAttributes(GlobalDecl(), WorkerFn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +0000715 WorkerFn->setDoesNotRecurse();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000716}
717
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000718CGOpenMPRuntimeNVPTX::ExecutionMode
719CGOpenMPRuntimeNVPTX::getExecutionMode() const {
720 return CurrentExecutionMode;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000721}
722
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000723static CGOpenMPRuntimeNVPTX::DataSharingMode
724getDataSharingMode(CodeGenModule &CGM) {
725 return CGM.getLangOpts().OpenMPCUDAMode ? CGOpenMPRuntimeNVPTX::CUDA
726 : CGOpenMPRuntimeNVPTX::Generic;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000727}
728
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000729// Checks if the expression is constant or does not have non-trivial function
730// calls.
731static bool isTrivial(ASTContext &Ctx, const Expr * E) {
732 // We can skip constant expressions.
733 // We can skip expressions with trivial calls or simple expressions.
734 return (E->isEvaluatable(Ctx, Expr::SE_AllowUndefinedBehavior) ||
735 !E->hasNonTrivialCall(Ctx)) &&
736 !E->HasSideEffects(Ctx, /*IncludePossibleEffects=*/true);
737}
738
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000739/// Checks if the \p Body is the \a CompoundStmt and returns its child statement
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000740/// iff there is only one that is not evaluatable at the compile time.
741static const Stmt *getSingleCompoundChild(ASTContext &Ctx, const Stmt *Body) {
742 if (const auto *C = dyn_cast<CompoundStmt>(Body)) {
743 const Stmt *Child = nullptr;
744 for (const Stmt *S : C->body()) {
745 if (const auto *E = dyn_cast<Expr>(S)) {
746 if (isTrivial(Ctx, E))
747 continue;
748 }
749 // Some of the statements can be ignored.
750 if (isa<AsmStmt>(S) || isa<NullStmt>(S) || isa<OMPFlushDirective>(S) ||
751 isa<OMPBarrierDirective>(S) || isa<OMPTaskyieldDirective>(S))
752 continue;
753 // Analyze declarations.
754 if (const auto *DS = dyn_cast<DeclStmt>(S)) {
755 if (llvm::all_of(DS->decls(), [&Ctx](const Decl *D) {
756 if (isa<EmptyDecl>(D) || isa<DeclContext>(D) ||
757 isa<TypeDecl>(D) || isa<PragmaCommentDecl>(D) ||
758 isa<PragmaDetectMismatchDecl>(D) || isa<UsingDecl>(D) ||
759 isa<UsingDirectiveDecl>(D) ||
760 isa<OMPDeclareReductionDecl>(D) ||
761 isa<OMPThreadPrivateDecl>(D))
762 return true;
763 const auto *VD = dyn_cast<VarDecl>(D);
764 if (!VD)
765 return false;
766 return VD->isConstexpr() ||
767 ((VD->getType().isTrivialType(Ctx) ||
768 VD->getType()->isReferenceType()) &&
769 (!VD->hasInit() || isTrivial(Ctx, VD->getInit())));
770 }))
771 continue;
772 }
773 // Found multiple children - cannot get the one child only.
774 if (Child)
775 return Body;
776 Child = S;
777 }
778 if (Child)
779 return Child;
780 }
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000781 return Body;
782}
783
784/// Check if the parallel directive has an 'if' clause with non-constant or
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000785/// false condition. Also, check if the number of threads is strictly specified
786/// and run those directives in non-SPMD mode.
787static bool hasParallelIfNumThreadsClause(ASTContext &Ctx,
788 const OMPExecutableDirective &D) {
789 if (D.hasClausesOfKind<OMPNumThreadsClause>())
790 return true;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000791 for (const auto *C : D.getClausesOfKind<OMPIfClause>()) {
792 OpenMPDirectiveKind NameModifier = C->getNameModifier();
793 if (NameModifier != OMPD_parallel && NameModifier != OMPD_unknown)
794 continue;
795 const Expr *Cond = C->getCondition();
796 bool Result;
797 if (!Cond->EvaluateAsBooleanCondition(Result, Ctx) || !Result)
798 return true;
799 }
800 return false;
801}
802
803/// Check for inner (nested) SPMD construct, if any
804static bool hasNestedSPMDDirective(ASTContext &Ctx,
805 const OMPExecutableDirective &D) {
806 const auto *CS = D.getInnermostCapturedStmt();
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000807 const auto *Body =
808 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000809 const Stmt *ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000810
811 if (const auto *NestedDir = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
812 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000813 switch (D.getDirectiveKind()) {
814 case OMPD_target:
Alexey Bataevdf093e72018-05-11 19:45:14 +0000815 if (isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000816 !hasParallelIfNumThreadsClause(Ctx, *NestedDir))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000817 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000818 if (DKind == OMPD_teams) {
819 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
820 /*IgnoreCaptured=*/true);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000821 if (!Body)
822 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000823 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000824 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
825 DKind = NND->getDirectiveKind();
Alexey Bataevdf093e72018-05-11 19:45:14 +0000826 if (isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000827 !hasParallelIfNumThreadsClause(Ctx, *NND))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000828 return true;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000829 }
830 }
831 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000832 case OMPD_target_teams:
Alexey Bataevdf093e72018-05-11 19:45:14 +0000833 return isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000834 !hasParallelIfNumThreadsClause(Ctx, *NestedDir);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000835 case OMPD_target_simd:
836 case OMPD_target_parallel:
837 case OMPD_target_parallel_for:
838 case OMPD_target_parallel_for_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000839 case OMPD_target_teams_distribute:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000840 case OMPD_target_teams_distribute_simd:
841 case OMPD_target_teams_distribute_parallel_for:
842 case OMPD_target_teams_distribute_parallel_for_simd:
843 case OMPD_parallel:
844 case OMPD_for:
845 case OMPD_parallel_for:
846 case OMPD_parallel_sections:
847 case OMPD_for_simd:
848 case OMPD_parallel_for_simd:
849 case OMPD_cancel:
850 case OMPD_cancellation_point:
851 case OMPD_ordered:
852 case OMPD_threadprivate:
853 case OMPD_task:
854 case OMPD_simd:
855 case OMPD_sections:
856 case OMPD_section:
857 case OMPD_single:
858 case OMPD_master:
859 case OMPD_critical:
860 case OMPD_taskyield:
861 case OMPD_barrier:
862 case OMPD_taskwait:
863 case OMPD_taskgroup:
864 case OMPD_atomic:
865 case OMPD_flush:
866 case OMPD_teams:
867 case OMPD_target_data:
868 case OMPD_target_exit_data:
869 case OMPD_target_enter_data:
870 case OMPD_distribute:
871 case OMPD_distribute_simd:
872 case OMPD_distribute_parallel_for:
873 case OMPD_distribute_parallel_for_simd:
874 case OMPD_teams_distribute:
875 case OMPD_teams_distribute_simd:
876 case OMPD_teams_distribute_parallel_for:
877 case OMPD_teams_distribute_parallel_for_simd:
878 case OMPD_target_update:
879 case OMPD_declare_simd:
880 case OMPD_declare_target:
881 case OMPD_end_declare_target:
882 case OMPD_declare_reduction:
883 case OMPD_taskloop:
884 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000885 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000886 case OMPD_unknown:
887 llvm_unreachable("Unexpected directive.");
888 }
889 }
890
891 return false;
892}
893
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000894static bool supportsSPMDExecutionMode(ASTContext &Ctx,
895 const OMPExecutableDirective &D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000896 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
897 switch (DirectiveKind) {
898 case OMPD_target:
899 case OMPD_target_teams:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000900 return hasNestedSPMDDirective(Ctx, D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000901 case OMPD_target_parallel:
902 case OMPD_target_parallel_for:
903 case OMPD_target_parallel_for_simd:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000904 case OMPD_target_teams_distribute_parallel_for:
905 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev2adecff2018-09-21 14:22:53 +0000906 return !hasParallelIfNumThreadsClause(Ctx, D);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000907 case OMPD_target_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000908 case OMPD_target_teams_distribute:
909 case OMPD_target_teams_distribute_simd:
910 return false;
911 case OMPD_parallel:
912 case OMPD_for:
913 case OMPD_parallel_for:
914 case OMPD_parallel_sections:
915 case OMPD_for_simd:
916 case OMPD_parallel_for_simd:
917 case OMPD_cancel:
918 case OMPD_cancellation_point:
919 case OMPD_ordered:
920 case OMPD_threadprivate:
921 case OMPD_task:
922 case OMPD_simd:
923 case OMPD_sections:
924 case OMPD_section:
925 case OMPD_single:
926 case OMPD_master:
927 case OMPD_critical:
928 case OMPD_taskyield:
929 case OMPD_barrier:
930 case OMPD_taskwait:
931 case OMPD_taskgroup:
932 case OMPD_atomic:
933 case OMPD_flush:
934 case OMPD_teams:
935 case OMPD_target_data:
936 case OMPD_target_exit_data:
937 case OMPD_target_enter_data:
938 case OMPD_distribute:
939 case OMPD_distribute_simd:
940 case OMPD_distribute_parallel_for:
941 case OMPD_distribute_parallel_for_simd:
942 case OMPD_teams_distribute:
943 case OMPD_teams_distribute_simd:
944 case OMPD_teams_distribute_parallel_for:
945 case OMPD_teams_distribute_parallel_for_simd:
946 case OMPD_target_update:
947 case OMPD_declare_simd:
948 case OMPD_declare_target:
949 case OMPD_end_declare_target:
950 case OMPD_declare_reduction:
951 case OMPD_taskloop:
952 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000953 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000954 case OMPD_unknown:
955 break;
956 }
957 llvm_unreachable(
958 "Unknown programming model for OpenMP directive on NVPTX target.");
959}
960
961/// Check if the directive is loops based and has schedule clause at all or has
962/// static scheduling.
963static bool hasStaticScheduling(const OMPExecutableDirective &D) {
964 assert(isOpenMPWorksharingDirective(D.getDirectiveKind()) &&
965 isOpenMPLoopDirective(D.getDirectiveKind()) &&
966 "Expected loop-based directive.");
967 return !D.hasClausesOfKind<OMPOrderedClause>() &&
968 (!D.hasClausesOfKind<OMPScheduleClause>() ||
969 llvm::any_of(D.getClausesOfKind<OMPScheduleClause>(),
970 [](const OMPScheduleClause *C) {
971 return C->getScheduleKind() == OMPC_SCHEDULE_static;
972 }));
973}
974
975/// Check for inner (nested) lightweight runtime construct, if any
976static bool hasNestedLightweightDirective(ASTContext &Ctx,
977 const OMPExecutableDirective &D) {
978 assert(supportsSPMDExecutionMode(Ctx, D) && "Expected SPMD mode directive.");
979 const auto *CS = D.getInnermostCapturedStmt();
980 const auto *Body =
981 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000982 const Stmt *ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000983
984 if (const auto *NestedDir = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
985 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
986 switch (D.getDirectiveKind()) {
987 case OMPD_target:
988 if (isOpenMPParallelDirective(DKind) &&
989 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
990 hasStaticScheduling(*NestedDir))
991 return true;
992 if (DKind == OMPD_parallel) {
993 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
994 /*IgnoreCaptured=*/true);
995 if (!Body)
996 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000997 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000998 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
999 DKind = NND->getDirectiveKind();
1000 if (isOpenMPWorksharingDirective(DKind) &&
1001 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
1002 return true;
1003 }
1004 } else if (DKind == OMPD_teams) {
1005 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
1006 /*IgnoreCaptured=*/true);
1007 if (!Body)
1008 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001009 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001010 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
1011 DKind = NND->getDirectiveKind();
1012 if (isOpenMPParallelDirective(DKind) &&
1013 isOpenMPWorksharingDirective(DKind) &&
1014 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
1015 return true;
1016 if (DKind == OMPD_parallel) {
1017 Body = NND->getInnermostCapturedStmt()->IgnoreContainers(
1018 /*IgnoreCaptured=*/true);
1019 if (!Body)
1020 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001021 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001022 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
1023 DKind = NND->getDirectiveKind();
1024 if (isOpenMPWorksharingDirective(DKind) &&
1025 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
1026 return true;
1027 }
1028 }
1029 }
1030 }
1031 return false;
1032 case OMPD_target_teams:
1033 if (isOpenMPParallelDirective(DKind) &&
1034 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
1035 hasStaticScheduling(*NestedDir))
1036 return true;
1037 if (DKind == OMPD_parallel) {
1038 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
1039 /*IgnoreCaptured=*/true);
1040 if (!Body)
1041 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001042 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001043 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
1044 DKind = NND->getDirectiveKind();
1045 if (isOpenMPWorksharingDirective(DKind) &&
1046 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
1047 return true;
1048 }
1049 }
1050 return false;
1051 case OMPD_target_parallel:
1052 return isOpenMPWorksharingDirective(DKind) &&
1053 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NestedDir);
1054 case OMPD_target_teams_distribute:
1055 case OMPD_target_simd:
1056 case OMPD_target_parallel_for:
1057 case OMPD_target_parallel_for_simd:
1058 case OMPD_target_teams_distribute_simd:
1059 case OMPD_target_teams_distribute_parallel_for:
1060 case OMPD_target_teams_distribute_parallel_for_simd:
1061 case OMPD_parallel:
1062 case OMPD_for:
1063 case OMPD_parallel_for:
1064 case OMPD_parallel_sections:
1065 case OMPD_for_simd:
1066 case OMPD_parallel_for_simd:
1067 case OMPD_cancel:
1068 case OMPD_cancellation_point:
1069 case OMPD_ordered:
1070 case OMPD_threadprivate:
1071 case OMPD_task:
1072 case OMPD_simd:
1073 case OMPD_sections:
1074 case OMPD_section:
1075 case OMPD_single:
1076 case OMPD_master:
1077 case OMPD_critical:
1078 case OMPD_taskyield:
1079 case OMPD_barrier:
1080 case OMPD_taskwait:
1081 case OMPD_taskgroup:
1082 case OMPD_atomic:
1083 case OMPD_flush:
1084 case OMPD_teams:
1085 case OMPD_target_data:
1086 case OMPD_target_exit_data:
1087 case OMPD_target_enter_data:
1088 case OMPD_distribute:
1089 case OMPD_distribute_simd:
1090 case OMPD_distribute_parallel_for:
1091 case OMPD_distribute_parallel_for_simd:
1092 case OMPD_teams_distribute:
1093 case OMPD_teams_distribute_simd:
1094 case OMPD_teams_distribute_parallel_for:
1095 case OMPD_teams_distribute_parallel_for_simd:
1096 case OMPD_target_update:
1097 case OMPD_declare_simd:
1098 case OMPD_declare_target:
1099 case OMPD_end_declare_target:
1100 case OMPD_declare_reduction:
1101 case OMPD_taskloop:
1102 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001103 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001104 case OMPD_unknown:
1105 llvm_unreachable("Unexpected directive.");
1106 }
1107 }
1108
1109 return false;
1110}
1111
1112/// Checks if the construct supports lightweight runtime. It must be SPMD
1113/// construct + inner loop-based construct with static scheduling.
1114static bool supportsLightweightRuntime(ASTContext &Ctx,
1115 const OMPExecutableDirective &D) {
1116 if (!supportsSPMDExecutionMode(Ctx, D))
1117 return false;
1118 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
1119 switch (DirectiveKind) {
1120 case OMPD_target:
1121 case OMPD_target_teams:
1122 case OMPD_target_parallel:
1123 return hasNestedLightweightDirective(Ctx, D);
1124 case OMPD_target_parallel_for:
1125 case OMPD_target_parallel_for_simd:
1126 case OMPD_target_teams_distribute_parallel_for:
1127 case OMPD_target_teams_distribute_parallel_for_simd:
1128 // (Last|First)-privates must be shared in parallel region.
1129 return hasStaticScheduling(D);
1130 case OMPD_target_simd:
1131 case OMPD_target_teams_distribute:
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001132 case OMPD_target_teams_distribute_simd:
Alexey Bataevdf093e72018-05-11 19:45:14 +00001133 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001134 case OMPD_parallel:
1135 case OMPD_for:
1136 case OMPD_parallel_for:
1137 case OMPD_parallel_sections:
1138 case OMPD_for_simd:
1139 case OMPD_parallel_for_simd:
1140 case OMPD_cancel:
1141 case OMPD_cancellation_point:
1142 case OMPD_ordered:
1143 case OMPD_threadprivate:
1144 case OMPD_task:
1145 case OMPD_simd:
1146 case OMPD_sections:
1147 case OMPD_section:
1148 case OMPD_single:
1149 case OMPD_master:
1150 case OMPD_critical:
1151 case OMPD_taskyield:
1152 case OMPD_barrier:
1153 case OMPD_taskwait:
1154 case OMPD_taskgroup:
1155 case OMPD_atomic:
1156 case OMPD_flush:
1157 case OMPD_teams:
1158 case OMPD_target_data:
1159 case OMPD_target_exit_data:
1160 case OMPD_target_enter_data:
1161 case OMPD_distribute:
1162 case OMPD_distribute_simd:
1163 case OMPD_distribute_parallel_for:
1164 case OMPD_distribute_parallel_for_simd:
1165 case OMPD_teams_distribute:
1166 case OMPD_teams_distribute_simd:
1167 case OMPD_teams_distribute_parallel_for:
1168 case OMPD_teams_distribute_parallel_for_simd:
1169 case OMPD_target_update:
1170 case OMPD_declare_simd:
1171 case OMPD_declare_target:
1172 case OMPD_end_declare_target:
1173 case OMPD_declare_reduction:
1174 case OMPD_taskloop:
1175 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001176 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001177 case OMPD_unknown:
1178 break;
1179 }
1180 llvm_unreachable(
1181 "Unknown programming model for OpenMP directive on NVPTX target.");
1182}
1183
1184void CGOpenMPRuntimeNVPTX::emitNonSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001185 StringRef ParentName,
1186 llvm::Function *&OutlinedFn,
1187 llvm::Constant *&OutlinedFnID,
1188 bool IsOffloadEntry,
1189 const RegionCodeGenTy &CodeGen) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001190 ExecutionModeRAII ModeRAII(CurrentExecutionMode, /*IsSPMD=*/false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001191 EntryFunctionState EST;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001192 WorkerFunctionState WST(CGM, D.getBeginLoc());
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001193 Work.clear();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001194 WrapperFunctionsMap.clear();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001195
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001196 // Emit target region as a standalone region.
1197 class NVPTXPrePostActionTy : public PrePostActionTy {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001198 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1199 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001200
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001201 public:
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001202 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001203 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST)
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001204 : EST(EST), WST(WST) {}
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001205 void Enter(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001206 auto &RT =
1207 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001208 RT.emitNonSPMDEntryHeader(CGF, EST, WST);
1209 // Skip target region initialization.
1210 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001211 }
1212 void Exit(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001213 auto &RT =
1214 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001215 RT.clearLocThreadIdInsertPt(CGF);
1216 RT.emitNonSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001217 }
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001218 } Action(EST, WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001219 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001220 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001221 // Reserve place for the globalized memory.
1222 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001223 if (!KernelStaticGlobalized) {
1224 KernelStaticGlobalized = new llvm::GlobalVariable(
1225 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1226 llvm::GlobalValue::InternalLinkage,
1227 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1228 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1229 llvm::GlobalValue::NotThreadLocal,
1230 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1231 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001232 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1233 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001234 IsInTTDRegion = false;
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001235
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001236 // Now change the name of the worker function to correspond to this target
1237 // region's entry function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001238 WST.WorkerFn->setName(Twine(OutlinedFn->getName(), "_worker"));
Alexey Bataevaee93892018-01-08 20:09:47 +00001239
1240 // Create the worker function
1241 emitWorkerFunction(WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001242}
1243
1244// Setup NVPTX threads for master-worker OpenMP scheme.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001245void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryHeader(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001246 EntryFunctionState &EST,
1247 WorkerFunctionState &WST) {
1248 CGBuilderTy &Bld = CGF.Builder;
1249
1250 llvm::BasicBlock *WorkerBB = CGF.createBasicBlock(".worker");
1251 llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
1252 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
1253 EST.ExitBB = CGF.createBasicBlock(".exit");
1254
Alexey Bataev9ff80832018-04-16 20:16:21 +00001255 llvm::Value *IsWorker =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001256 Bld.CreateICmpULT(getNVPTXThreadID(CGF), getThreadLimit(CGF));
1257 Bld.CreateCondBr(IsWorker, WorkerBB, MasterCheckBB);
1258
1259 CGF.EmitBlock(WorkerBB);
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001260 emitCall(CGF, WST.Loc, WST.WorkerFn);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001261 CGF.EmitBranch(EST.ExitBB);
1262
1263 CGF.EmitBlock(MasterCheckBB);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001264 llvm::Value *IsMaster =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001265 Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
1266 Bld.CreateCondBr(IsMaster, MasterBB, EST.ExitBB);
1267
1268 CGF.EmitBlock(MasterBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001269 IsInTargetMasterThreadRegion = true;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001270 // SEQUENTIAL (MASTER) REGION START
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001271 // First action in sequential region:
1272 // Initialize the state of the OpenMP runtime library on the GPU.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001273 // TODO: Optimize runtime initialization and pass in correct value.
1274 llvm::Value *Args[] = {getThreadLimit(CGF),
1275 Bld.getInt16(/*RequiresOMPRuntime=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001276 CGF.EmitRuntimeCall(
1277 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_init), Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001278
1279 // For data sharing, we need to initialize the stack.
1280 CGF.EmitRuntimeCall(
1281 createNVPTXRuntimeFunction(
1282 OMPRTL_NVPTX__kmpc_data_sharing_init_stack));
1283
Alexey Bataevc99042b2018-03-15 18:10:54 +00001284 emitGenericVarsProlog(CGF, WST.Loc);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001285}
1286
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001287void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001288 EntryFunctionState &EST) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001289 IsInTargetMasterThreadRegion = false;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001290 if (!CGF.HaveInsertPoint())
1291 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001292
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001293 emitGenericVarsEpilog(CGF);
1294
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001295 if (!EST.ExitBB)
1296 EST.ExitBB = CGF.createBasicBlock(".exit");
1297
1298 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".termination.notifier");
1299 CGF.EmitBranch(TerminateBB);
1300
1301 CGF.EmitBlock(TerminateBB);
1302 // Signal termination condition.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001303 // TODO: Optimize runtime initialization and pass in correct value.
1304 llvm::Value *Args[] = {CGF.Builder.getInt16(/*IsOMPRuntimeInitialized=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001305 CGF.EmitRuntimeCall(
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001306 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_deinit), Args);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001307 // Barrier to terminate worker threads.
1308 syncCTAThreads(CGF);
1309 // Master thread jumps to exit point.
1310 CGF.EmitBranch(EST.ExitBB);
1311
1312 CGF.EmitBlock(EST.ExitBB);
1313 EST.ExitBB = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001314}
1315
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001316void CGOpenMPRuntimeNVPTX::emitSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001317 StringRef ParentName,
1318 llvm::Function *&OutlinedFn,
1319 llvm::Constant *&OutlinedFnID,
1320 bool IsOffloadEntry,
1321 const RegionCodeGenTy &CodeGen) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001322 ExecutionModeRAII ModeRAII(CurrentExecutionMode, /*IsSPMD=*/true);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001323 EntryFunctionState EST;
1324
1325 // Emit target region as a standalone region.
1326 class NVPTXPrePostActionTy : public PrePostActionTy {
1327 CGOpenMPRuntimeNVPTX &RT;
1328 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1329 const OMPExecutableDirective &D;
1330
1331 public:
1332 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT,
1333 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
1334 const OMPExecutableDirective &D)
1335 : RT(RT), EST(EST), D(D) {}
1336 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001337 RT.emitSPMDEntryHeader(CGF, EST, D);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001338 // Skip target region initialization.
1339 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001340 }
1341 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevfd006c42018-10-05 15:08:53 +00001342 RT.clearLocThreadIdInsertPt(CGF);
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001343 RT.emitSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001344 }
1345 } Action(*this, EST, D);
1346 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001347 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001348 // Reserve place for the globalized memory.
1349 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001350 if (!KernelStaticGlobalized) {
1351 KernelStaticGlobalized = new llvm::GlobalVariable(
1352 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1353 llvm::GlobalValue::InternalLinkage,
1354 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1355 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1356 llvm::GlobalValue::NotThreadLocal,
1357 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1358 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001359 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1360 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001361 IsInTTDRegion = false;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001362}
1363
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001364void CGOpenMPRuntimeNVPTX::emitSPMDEntryHeader(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001365 CodeGenFunction &CGF, EntryFunctionState &EST,
1366 const OMPExecutableDirective &D) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001367 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001368
1369 // Setup BBs in entry function.
1370 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute");
1371 EST.ExitBB = CGF.createBasicBlock(".exit");
1372
1373 // Initialize the OMP state in the runtime; called by all active threads.
Alexey Bataev80a9a612018-08-30 14:45:24 +00001374 bool RequiresFullRuntime = CGM.getLangOpts().OpenMPCUDAForceFullRuntime ||
1375 !supportsLightweightRuntime(CGF.getContext(), D);
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001376 llvm::Value *Args[] = {getThreadLimit(CGF, /*IsInSPMDExecutionMode=*/true),
1377 /*RequiresOMPRuntime=*/
1378 Bld.getInt16(RequiresFullRuntime ? 1 : 0),
1379 /*RequiresDataSharing=*/Bld.getInt16(0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001380 CGF.EmitRuntimeCall(
1381 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_init), Args);
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001382
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001383 if (RequiresFullRuntime) {
1384 // For data sharing, we need to initialize the stack.
1385 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1386 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd));
1387 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001388
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001389 CGF.EmitBranch(ExecuteBB);
1390
1391 CGF.EmitBlock(ExecuteBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001392
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001393 IsInTargetMasterThreadRegion = true;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001394}
1395
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001396void CGOpenMPRuntimeNVPTX::emitSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001397 EntryFunctionState &EST) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001398 IsInTargetMasterThreadRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001399 if (!CGF.HaveInsertPoint())
1400 return;
1401
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001402 if (!EST.ExitBB)
1403 EST.ExitBB = CGF.createBasicBlock(".exit");
1404
1405 llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit");
1406 CGF.EmitBranch(OMPDeInitBB);
1407
1408 CGF.EmitBlock(OMPDeInitBB);
1409 // DeInitialize the OMP state in the runtime; called by all active threads.
1410 CGF.EmitRuntimeCall(
1411 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_deinit), None);
1412 CGF.EmitBranch(EST.ExitBB);
1413
1414 CGF.EmitBlock(EST.ExitBB);
1415 EST.ExitBB = nullptr;
1416}
1417
1418// Create a unique global variable to indicate the execution mode of this target
1419// region. The execution mode is either 'generic', or 'spmd' depending on the
1420// target directive. This variable is picked up by the offload library to setup
1421// the device appropriately before kernel launch. If the execution mode is
1422// 'generic', the runtime reserves one warp for the master, otherwise, all
1423// warps participate in parallel work.
1424static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001425 bool Mode) {
1426 auto *GVMode =
1427 new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
1428 llvm::GlobalValue::WeakAnyLinkage,
1429 llvm::ConstantInt::get(CGM.Int8Ty, Mode ? 0 : 1),
1430 Twine(Name, "_exec_mode"));
Alexey Bataev9ff80832018-04-16 20:16:21 +00001431 CGM.addCompilerUsedGlobal(GVMode);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001432}
1433
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001434void CGOpenMPRuntimeNVPTX::emitWorkerFunction(WorkerFunctionState &WST) {
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +00001435 ASTContext &Ctx = CGM.getContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001436
1437 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001438 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, WST.CGFI, {},
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001439 WST.Loc, WST.Loc);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001440 emitWorkerLoop(CGF, WST);
1441 CGF.FinishFunction();
1442}
1443
1444void CGOpenMPRuntimeNVPTX::emitWorkerLoop(CodeGenFunction &CGF,
1445 WorkerFunctionState &WST) {
1446 //
1447 // The workers enter this loop and wait for parallel work from the master.
1448 // When the master encounters a parallel region it sets up the work + variable
1449 // arguments, and wakes up the workers. The workers first check to see if
1450 // they are required for the parallel region, i.e., within the # of requested
1451 // parallel threads. The activated workers load the variable arguments and
1452 // execute the parallel work.
1453 //
1454
1455 CGBuilderTy &Bld = CGF.Builder;
1456
1457 llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work");
1458 llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers");
1459 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel");
1460 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel");
1461 llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel");
1462 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1463
1464 CGF.EmitBranch(AwaitBB);
1465
1466 // Workers wait for work from master.
1467 CGF.EmitBlock(AwaitBB);
1468 // Wait for parallel work
1469 syncCTAThreads(CGF);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001470
1471 Address WorkFn =
1472 CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn");
1473 Address ExecStatus =
1474 CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status");
1475 CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0));
1476 CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy));
1477
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001478 // TODO: Optimize runtime initialization and pass in correct value.
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001479 llvm::Value *Args[] = {WorkFn.getPointer(),
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001480 /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001481 llvm::Value *Ret = CGF.EmitRuntimeCall(
1482 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args);
1483 Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001484
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001485 // On termination condition (workid == 0), exit loop.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001486 llvm::Value *WorkID = Bld.CreateLoad(WorkFn);
1487 llvm::Value *ShouldTerminate = Bld.CreateIsNull(WorkID, "should_terminate");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001488 Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB);
1489
1490 // Activate requested workers.
1491 CGF.EmitBlock(SelectWorkersBB);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001492 llvm::Value *IsActive =
1493 Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active");
1494 Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001495
1496 // Signal start of parallel region.
1497 CGF.EmitBlock(ExecuteBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001498
1499 // Process work items: outlined parallel functions.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001500 for (llvm::Function *W : Work) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001501 // Try to match this outlined function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001502 llvm::Value *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001503
1504 llvm::Value *WorkFnMatch =
1505 Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match");
1506
1507 llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn");
1508 llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next");
1509 Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB);
1510
1511 // Execute this outlined function.
1512 CGF.EmitBlock(ExecuteFNBB);
1513
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001514 // Insert call to work function via shared wrapper. The shared
1515 // wrapper takes two arguments:
1516 // - the parallelism level;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001517 // - the thread ID;
1518 emitCall(CGF, WST.Loc, W,
1519 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001520
1521 // Go to end of parallel region.
1522 CGF.EmitBranch(TerminateBB);
1523
1524 CGF.EmitBlock(CheckNextBB);
1525 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001526 // Default case: call to outlined function through pointer if the target
1527 // region makes a declare target call that may contain an orphaned parallel
1528 // directive.
1529 auto *ParallelFnTy =
1530 llvm::FunctionType::get(CGM.VoidTy, {CGM.Int16Ty, CGM.Int32Ty},
1531 /*isVarArg=*/false)
1532 ->getPointerTo();
1533 llvm::Value *WorkFnCast = Bld.CreateBitCast(WorkID, ParallelFnTy);
1534 // Insert call to work function via shared wrapper. The shared
1535 // wrapper takes two arguments:
1536 // - the parallelism level;
1537 // - the thread ID;
1538 emitCall(CGF, WST.Loc, WorkFnCast,
1539 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
1540 // Go to end of parallel region.
1541 CGF.EmitBranch(TerminateBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001542
1543 // Signal end of parallel region.
1544 CGF.EmitBlock(TerminateBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001545 CGF.EmitRuntimeCall(
1546 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_end_parallel),
1547 llvm::None);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001548 CGF.EmitBranch(BarrierBB);
1549
1550 // All active and inactive workers wait at a barrier after parallel region.
1551 CGF.EmitBlock(BarrierBB);
1552 // Barrier after parallel region.
1553 syncCTAThreads(CGF);
1554 CGF.EmitBranch(AwaitBB);
1555
1556 // Exit target region.
1557 CGF.EmitBlock(ExitBB);
1558}
1559
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001560/// Returns specified OpenMP runtime function for the current OpenMP
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001561/// implementation. Specialized for the NVPTX device.
1562/// \param Function OpenMP runtime function.
1563/// \return Specified function.
1564llvm::Constant *
1565CGOpenMPRuntimeNVPTX::createNVPTXRuntimeFunction(unsigned Function) {
1566 llvm::Constant *RTLFn = nullptr;
1567 switch (static_cast<OpenMPRTLFunctionNVPTX>(Function)) {
1568 case OMPRTL_NVPTX__kmpc_kernel_init: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001569 // Build void __kmpc_kernel_init(kmp_int32 thread_limit, int16_t
1570 // RequiresOMPRuntime);
1571 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001572 auto *FnTy =
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001573 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1574 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_init");
1575 break;
1576 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001577 case OMPRTL_NVPTX__kmpc_kernel_deinit: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001578 // Build void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
1579 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001580 auto *FnTy =
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001581 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001582 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_deinit");
1583 break;
1584 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001585 case OMPRTL_NVPTX__kmpc_spmd_kernel_init: {
1586 // Build void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001587 // int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001588 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001589 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001590 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1591 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_init");
1592 break;
1593 }
1594 case OMPRTL_NVPTX__kmpc_spmd_kernel_deinit: {
1595 // Build void __kmpc_spmd_kernel_deinit();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001596 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001597 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1598 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_deinit");
1599 break;
1600 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001601 case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: {
1602 /// Build void __kmpc_kernel_prepare_parallel(
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001603 /// void *outlined_function, int16_t IsOMPRuntimeInitialized);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001604 llvm::Type *TypeParams[] = {CGM.Int8PtrTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001605 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001606 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1607 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_prepare_parallel");
1608 break;
1609 }
1610 case OMPRTL_NVPTX__kmpc_kernel_parallel: {
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001611 /// Build bool __kmpc_kernel_parallel(void **outlined_function,
1612 /// int16_t IsOMPRuntimeInitialized);
1613 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy, CGM.Int16Ty};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001614 llvm::Type *RetTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001615 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001616 llvm::FunctionType::get(RetTy, TypeParams, /*isVarArg*/ false);
1617 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_parallel");
1618 break;
1619 }
1620 case OMPRTL_NVPTX__kmpc_kernel_end_parallel: {
1621 /// Build void __kmpc_kernel_end_parallel();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001622 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001623 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1624 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_end_parallel");
1625 break;
1626 }
1627 case OMPRTL_NVPTX__kmpc_serialized_parallel: {
1628 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1629 // global_tid);
1630 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001631 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001632 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1633 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1634 break;
1635 }
1636 case OMPRTL_NVPTX__kmpc_end_serialized_parallel: {
1637 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1638 // global_tid);
1639 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001640 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001641 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1642 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1643 break;
1644 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001645 case OMPRTL_NVPTX__kmpc_shuffle_int32: {
1646 // Build int32_t __kmpc_shuffle_int32(int32_t element,
1647 // int16_t lane_offset, int16_t warp_size);
1648 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001649 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001650 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1651 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int32");
1652 break;
1653 }
1654 case OMPRTL_NVPTX__kmpc_shuffle_int64: {
1655 // Build int64_t __kmpc_shuffle_int64(int64_t element,
1656 // int16_t lane_offset, int16_t warp_size);
1657 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001658 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001659 llvm::FunctionType::get(CGM.Int64Ty, TypeParams, /*isVarArg*/ false);
1660 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int64");
1661 break;
1662 }
1663 case OMPRTL_NVPTX__kmpc_parallel_reduce_nowait: {
1664 // Build int32_t kmpc_nvptx_parallel_reduce_nowait(kmp_int32 global_tid,
1665 // kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
1666 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1667 // lane_offset, int16_t Algorithm Version),
1668 // void (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
1669 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1670 CGM.Int16Ty, CGM.Int16Ty};
1671 auto *ShuffleReduceFnTy =
1672 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1673 /*isVarArg=*/false);
1674 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1675 auto *InterWarpCopyFnTy =
1676 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1677 /*isVarArg=*/false);
1678 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1679 CGM.Int32Ty,
1680 CGM.SizeTy,
1681 CGM.VoidPtrTy,
1682 ShuffleReduceFnTy->getPointerTo(),
1683 InterWarpCopyFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001684 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001685 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1686 RTLFn = CGM.CreateRuntimeFunction(
1687 FnTy, /*Name=*/"__kmpc_nvptx_parallel_reduce_nowait");
1688 break;
1689 }
Alexey Bataevfac26cf2018-05-02 20:03:27 +00001690 case OMPRTL_NVPTX__kmpc_simd_reduce_nowait: {
1691 // Build int32_t kmpc_nvptx_simd_reduce_nowait(kmp_int32 global_tid,
1692 // kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
1693 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1694 // lane_offset, int16_t Algorithm Version),
1695 // void (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
1696 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1697 CGM.Int16Ty, CGM.Int16Ty};
1698 auto *ShuffleReduceFnTy =
1699 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1700 /*isVarArg=*/false);
1701 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1702 auto *InterWarpCopyFnTy =
1703 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1704 /*isVarArg=*/false);
1705 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1706 CGM.Int32Ty,
1707 CGM.SizeTy,
1708 CGM.VoidPtrTy,
1709 ShuffleReduceFnTy->getPointerTo(),
1710 InterWarpCopyFnTy->getPointerTo()};
1711 auto *FnTy =
1712 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1713 RTLFn = CGM.CreateRuntimeFunction(
1714 FnTy, /*Name=*/"__kmpc_nvptx_simd_reduce_nowait");
1715 break;
1716 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001717 case OMPRTL_NVPTX__kmpc_teams_reduce_nowait: {
1718 // Build int32_t __kmpc_nvptx_teams_reduce_nowait(int32_t global_tid,
1719 // int32_t num_vars, size_t reduce_size, void *reduce_data,
1720 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1721 // lane_offset, int16_t shortCircuit),
1722 // void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num),
1723 // void (*kmp_CopyToScratchpadFctPtr)(void *reduce_data, void * scratchpad,
1724 // int32_t index, int32_t width),
1725 // void (*kmp_LoadReduceFctPtr)(void *reduce_data, void * scratchpad,
1726 // int32_t index, int32_t width, int32_t reduce))
1727 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1728 CGM.Int16Ty, CGM.Int16Ty};
1729 auto *ShuffleReduceFnTy =
1730 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1731 /*isVarArg=*/false);
1732 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1733 auto *InterWarpCopyFnTy =
1734 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1735 /*isVarArg=*/false);
1736 llvm::Type *CopyToScratchpadTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy,
1737 CGM.Int32Ty, CGM.Int32Ty};
1738 auto *CopyToScratchpadFnTy =
1739 llvm::FunctionType::get(CGM.VoidTy, CopyToScratchpadTypeParams,
1740 /*isVarArg=*/false);
1741 llvm::Type *LoadReduceTypeParams[] = {
1742 CGM.VoidPtrTy, CGM.VoidPtrTy, CGM.Int32Ty, CGM.Int32Ty, CGM.Int32Ty};
1743 auto *LoadReduceFnTy =
1744 llvm::FunctionType::get(CGM.VoidTy, LoadReduceTypeParams,
1745 /*isVarArg=*/false);
1746 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1747 CGM.Int32Ty,
1748 CGM.SizeTy,
1749 CGM.VoidPtrTy,
1750 ShuffleReduceFnTy->getPointerTo(),
1751 InterWarpCopyFnTy->getPointerTo(),
1752 CopyToScratchpadFnTy->getPointerTo(),
1753 LoadReduceFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001754 auto *FnTy =
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001755 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1756 RTLFn = CGM.CreateRuntimeFunction(
1757 FnTy, /*Name=*/"__kmpc_nvptx_teams_reduce_nowait");
1758 break;
1759 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001760 case OMPRTL_NVPTX__kmpc_end_reduce_nowait: {
1761 // Build __kmpc_end_reduce_nowait(kmp_int32 global_tid);
1762 llvm::Type *TypeParams[] = {CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001763 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001764 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1765 RTLFn = CGM.CreateRuntimeFunction(
1766 FnTy, /*Name=*/"__kmpc_nvptx_end_reduce_nowait");
1767 break;
1768 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001769 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack: {
1770 /// Build void __kmpc_data_sharing_init_stack();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001771 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001772 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1773 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack");
1774 break;
1775 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001776 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd: {
1777 /// Build void __kmpc_data_sharing_init_stack_spmd();
1778 auto *FnTy =
1779 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001780 RTLFn =
1781 CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack_spmd");
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001782 break;
1783 }
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001784 case OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack: {
1785 // Build void *__kmpc_data_sharing_coalesced_push_stack(size_t size,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001786 // int16_t UseSharedMemory);
1787 llvm::Type *TypeParams[] = {CGM.SizeTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001788 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001789 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1790 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001791 FnTy, /*Name=*/"__kmpc_data_sharing_coalesced_push_stack");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001792 break;
1793 }
1794 case OMPRTL_NVPTX__kmpc_data_sharing_pop_stack: {
1795 // Build void __kmpc_data_sharing_pop_stack(void *a);
1796 llvm::Type *TypeParams[] = {CGM.VoidPtrTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001797 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001798 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1799 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1800 /*Name=*/"__kmpc_data_sharing_pop_stack");
1801 break;
1802 }
1803 case OMPRTL_NVPTX__kmpc_begin_sharing_variables: {
1804 /// Build void __kmpc_begin_sharing_variables(void ***args,
1805 /// size_t n_args);
1806 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo(), CGM.SizeTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001807 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001808 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1809 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_begin_sharing_variables");
1810 break;
1811 }
1812 case OMPRTL_NVPTX__kmpc_end_sharing_variables: {
1813 /// Build void __kmpc_end_sharing_variables();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001814 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001815 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1816 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_sharing_variables");
1817 break;
1818 }
1819 case OMPRTL_NVPTX__kmpc_get_shared_variables: {
1820 /// Build void __kmpc_get_shared_variables(void ***GlobalArgs);
1821 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001822 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001823 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1824 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_shared_variables");
1825 break;
1826 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001827 case OMPRTL_NVPTX__kmpc_parallel_level: {
1828 // Build uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32 global_tid);
1829 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1830 auto *FnTy =
1831 llvm::FunctionType::get(CGM.Int16Ty, TypeParams, /*isVarArg*/ false);
1832 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_parallel_level");
1833 break;
1834 }
Alexey Bataev673110d2018-05-16 13:36:30 +00001835 case OMPRTL_NVPTX__kmpc_is_spmd_exec_mode: {
1836 // Build int8_t __kmpc_is_spmd_exec_mode();
1837 auto *FnTy = llvm::FunctionType::get(CGM.Int8Ty, /*isVarArg=*/false);
1838 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_is_spmd_exec_mode");
1839 break;
1840 }
Alexey Bataeve4090182018-11-02 14:54:07 +00001841 case OMPRTL_NVPTX__kmpc_get_team_static_memory: {
1842 // Build void __kmpc_get_team_static_memory(const void *buf, size_t size,
1843 // int16_t is_shared, const void **res);
1844 llvm::Type *TypeParams[] = {CGM.VoidPtrTy, CGM.SizeTy, CGM.Int16Ty,
1845 CGM.VoidPtrPtrTy};
1846 auto *FnTy =
1847 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1848 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_team_static_memory");
1849 break;
1850 }
1851 case OMPRTL_NVPTX__kmpc_restore_team_static_memory: {
1852 // Build void __kmpc_restore_team_static_memory(int16_t is_shared);
1853 auto *FnTy =
1854 llvm::FunctionType::get(CGM.VoidTy, CGM.Int16Ty, /*isVarArg=*/false);
1855 RTLFn =
1856 CGM.CreateRuntimeFunction(FnTy, "__kmpc_restore_team_static_memory");
1857 break;
1858 }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001859 }
1860 return RTLFn;
1861}
1862
1863void CGOpenMPRuntimeNVPTX::createOffloadEntry(llvm::Constant *ID,
1864 llvm::Constant *Addr,
Alexey Bataev03f270c2018-03-30 18:31:07 +00001865 uint64_t Size, int32_t,
1866 llvm::GlobalValue::LinkageTypes) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001867 // TODO: Add support for global variables on the device after declare target
1868 // support.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001869 if (!isa<llvm::Function>(Addr))
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001870 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +00001871 llvm::Module &M = CGM.getModule();
1872 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001873
1874 // Get "nvvm.annotations" metadata node
Alexey Bataev9ff80832018-04-16 20:16:21 +00001875 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001876
1877 llvm::Metadata *MDVals[] = {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001878 llvm::ConstantAsMetadata::get(Addr), llvm::MDString::get(Ctx, "kernel"),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001879 llvm::ConstantAsMetadata::get(
1880 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))};
1881 // Append metadata to nvvm.annotations
1882 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
1883}
1884
1885void CGOpenMPRuntimeNVPTX::emitTargetOutlinedFunction(
1886 const OMPExecutableDirective &D, StringRef ParentName,
1887 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001888 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001889 if (!IsOffloadEntry) // Nothing to do.
1890 return;
1891
1892 assert(!ParentName.empty() && "Invalid target region parent name!");
1893
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001894 bool Mode = supportsSPMDExecutionMode(CGM.getContext(), D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001895 if (Mode)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001896 emitSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001897 CodeGen);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001898 else
1899 emitNonSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1900 CodeGen);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001901
1902 setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001903}
1904
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001905CGOpenMPRuntimeNVPTX::CGOpenMPRuntimeNVPTX(CodeGenModule &CGM)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001906 : CGOpenMPRuntime(CGM, "_", "$") {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001907 if (!CGM.getLangOpts().OpenMPIsDevice)
1908 llvm_unreachable("OpenMP NVPTX can only handle device code.");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001909}
Carlo Bertollic6872252016-04-04 15:55:02 +00001910
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001911void CGOpenMPRuntimeNVPTX::emitProcBindClause(CodeGenFunction &CGF,
1912 OpenMPProcBindClauseKind ProcBind,
1913 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001914 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001915 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001916 return;
1917
1918 CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc);
1919}
1920
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001921void CGOpenMPRuntimeNVPTX::emitNumThreadsClause(CodeGenFunction &CGF,
1922 llvm::Value *NumThreads,
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 Jacobe04da5d2017-01-25 01:18:34 +00001926 return;
1927
1928 CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc);
1929}
1930
Carlo Bertollic6872252016-04-04 15:55:02 +00001931void CGOpenMPRuntimeNVPTX::emitNumTeamsClause(CodeGenFunction &CGF,
1932 const Expr *NumTeams,
1933 const Expr *ThreadLimit,
1934 SourceLocation Loc) {}
1935
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001936llvm::Value *CGOpenMPRuntimeNVPTX::emitParallelOutlinedFunction(
1937 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1938 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00001939 // Emit target region as a standalone region.
1940 class NVPTXPrePostActionTy : public PrePostActionTy {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001941 bool &IsInParallelRegion;
1942 bool PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001943
1944 public:
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001945 NVPTXPrePostActionTy(bool &IsInParallelRegion)
1946 : IsInParallelRegion(IsInParallelRegion) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00001947 void Enter(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001948 PrevIsInParallelRegion = IsInParallelRegion;
1949 IsInParallelRegion = true;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001950 }
1951 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001952 IsInParallelRegion = PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001953 }
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001954 } Action(IsInParallelRegion);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001955 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001956 bool PrevIsInTTDRegion = IsInTTDRegion;
1957 IsInTTDRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001958 bool PrevIsInTargetMasterThreadRegion = IsInTargetMasterThreadRegion;
1959 IsInTargetMasterThreadRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001960 auto *OutlinedFun =
1961 cast<llvm::Function>(CGOpenMPRuntime::emitParallelOutlinedFunction(
1962 D, ThreadIDVar, InnermostKind, CodeGen));
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001963 IsInTargetMasterThreadRegion = PrevIsInTargetMasterThreadRegion;
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001964 IsInTTDRegion = PrevIsInTTDRegion;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001965 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD &&
1966 !IsInParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001967 llvm::Function *WrapperFun =
1968 createParallelDataSharingWrapper(OutlinedFun, D);
1969 WrapperFunctionsMap[OutlinedFun] = WrapperFun;
1970 }
1971
1972 return OutlinedFun;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001973}
1974
Alexey Bataev2adecff2018-09-21 14:22:53 +00001975/// Get list of lastprivate variables from the teams distribute ... or
1976/// teams {distribute ...} directives.
1977static void
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001978getDistributeLastprivateVars(ASTContext &Ctx, const OMPExecutableDirective &D,
Alexey Bataev2adecff2018-09-21 14:22:53 +00001979 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
1980 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
1981 "expected teams directive.");
1982 const OMPExecutableDirective *Dir = &D;
1983 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
1984 if (const Stmt *S = getSingleCompoundChild(
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001985 Ctx,
Alexey Bataev2adecff2018-09-21 14:22:53 +00001986 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
1987 /*IgnoreCaptured=*/true))) {
1988 Dir = dyn_cast<OMPExecutableDirective>(S);
1989 if (Dir && !isOpenMPDistributeDirective(Dir->getDirectiveKind()))
1990 Dir = nullptr;
1991 }
1992 }
1993 if (!Dir)
1994 return;
Alexey Bataev9ea3c382018-10-09 14:49:00 +00001995 for (const auto *C : Dir->getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00001996 for (const Expr *E : C->getVarRefs())
1997 Vars.push_back(getPrivateItem(E));
1998 }
1999}
2000
2001/// Get list of reduction variables from the teams ... directives.
2002static void
2003getTeamsReductionVars(ASTContext &Ctx, const OMPExecutableDirective &D,
2004 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
2005 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
2006 "expected teams directive.");
2007 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
2008 for (const Expr *E : C->privates())
2009 Vars.push_back(getPrivateItem(E));
Alexey Bataev2adecff2018-09-21 14:22:53 +00002010 }
2011}
2012
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002013llvm::Value *CGOpenMPRuntimeNVPTX::emitTeamsOutlinedFunction(
Carlo Bertollic6872252016-04-04 15:55:02 +00002014 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
2015 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002016 SourceLocation Loc = D.getBeginLoc();
Carlo Bertollic6872252016-04-04 15:55:02 +00002017
Alexey Bataev2adecff2018-09-21 14:22:53 +00002018 const RecordDecl *GlobalizedRD = nullptr;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002019 llvm::SmallVector<const ValueDecl *, 4> LastPrivatesReductions;
Alexey Bataev2adecff2018-09-21 14:22:53 +00002020 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002021 // Globalize team reductions variable unconditionally in all modes.
2022 getTeamsReductionVars(CGM.getContext(), D, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002023 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002024 getDistributeLastprivateVars(CGM.getContext(), D, LastPrivatesReductions);
2025 if (!LastPrivatesReductions.empty()) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002026 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002027 CGM.getContext(), llvm::None, LastPrivatesReductions,
2028 MappedDeclsFields);
2029 }
2030 } else if (!LastPrivatesReductions.empty()) {
2031 assert(!TeamAndReductions.first &&
2032 "Previous team declaration is not expected.");
2033 TeamAndReductions.first = D.getCapturedStmt(OMPD_teams)->getCapturedDecl();
2034 std::swap(TeamAndReductions.second, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002035 }
2036
Alexey Bataevc99042b2018-03-15 18:10:54 +00002037 // Emit target region as a standalone region.
2038 class NVPTXPrePostActionTy : public PrePostActionTy {
2039 SourceLocation &Loc;
Alexey Bataev2adecff2018-09-21 14:22:53 +00002040 const RecordDecl *GlobalizedRD;
2041 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2042 &MappedDeclsFields;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002043
2044 public:
Alexey Bataev2adecff2018-09-21 14:22:53 +00002045 NVPTXPrePostActionTy(
2046 SourceLocation &Loc, const RecordDecl *GlobalizedRD,
2047 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2048 &MappedDeclsFields)
2049 : Loc(Loc), GlobalizedRD(GlobalizedRD),
2050 MappedDeclsFields(MappedDeclsFields) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00002051 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002052 auto &Rt =
2053 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
2054 if (GlobalizedRD) {
2055 auto I = Rt.FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
2056 I->getSecond().GlobalRecord = GlobalizedRD;
2057 I->getSecond().MappedParams =
2058 llvm::make_unique<CodeGenFunction::OMPMapVars>();
2059 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
2060 for (const auto &Pair : MappedDeclsFields) {
2061 assert(Pair.getFirst()->isCanonicalDecl() &&
2062 "Expected canonical declaration");
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002063 Data.insert(std::make_pair(Pair.getFirst(),
2064 MappedVarData(Pair.getSecond(),
2065 /*IsOnePerTeam=*/true)));
Alexey Bataev2adecff2018-09-21 14:22:53 +00002066 }
2067 }
2068 Rt.emitGenericVarsProlog(CGF, Loc);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002069 }
2070 void Exit(CodeGenFunction &CGF) override {
2071 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
2072 .emitGenericVarsEpilog(CGF);
2073 }
Alexey Bataev2adecff2018-09-21 14:22:53 +00002074 } Action(Loc, GlobalizedRD, MappedDeclsFields);
2075 CodeGen.setAction(Action);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002076 llvm::Value *OutlinedFunVal = CGOpenMPRuntime::emitTeamsOutlinedFunction(
2077 D, ThreadIDVar, InnermostKind, CodeGen);
2078 llvm::Function *OutlinedFun = cast<llvm::Function>(OutlinedFunVal);
2079 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00002080 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002081 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
Carlo Bertollic6872252016-04-04 15:55:02 +00002082
2083 return OutlinedFun;
2084}
2085
Alexey Bataevc99042b2018-03-15 18:10:54 +00002086void CGOpenMPRuntimeNVPTX::emitGenericVarsProlog(CodeGenFunction &CGF,
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002087 SourceLocation Loc,
2088 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002089 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2090 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002091 return;
2092
Alexey Bataevc99042b2018-03-15 18:10:54 +00002093 CGBuilderTy &Bld = CGF.Builder;
2094
2095 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
2096 if (I == FunctionGlobalizedDecls.end())
2097 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002098 if (const RecordDecl *GlobalizedVarsRecord = I->getSecond().GlobalRecord) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002099 QualType GlobalRecTy = CGM.getContext().getRecordType(GlobalizedVarsRecord);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002100 QualType SecGlobalRecTy;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002101
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002102 // Recover pointer to this function's global record. The runtime will
2103 // handle the specifics of the allocation of the memory.
2104 // Use actual memory size of the record including the padding
2105 // for alignment purposes.
2106 unsigned Alignment =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002107 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002108 unsigned GlobalRecordSize =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002109 CGM.getContext().getTypeSizeInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002110 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002111
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002112 llvm::PointerType *GlobalRecPtrTy =
2113 CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo();
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002114 llvm::Value *GlobalRecCastAddr;
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002115 llvm::Value *IsTTD = nullptr;
Alexey Bataeve4090182018-11-02 14:54:07 +00002116 if (!IsInTTDRegion &&
2117 (WithSPMDCheck ||
2118 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002119 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2120 llvm::BasicBlock *SPMDBB = CGF.createBasicBlock(".spmd");
2121 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002122 if (I->getSecond().SecondaryGlobalRecord.hasValue()) {
2123 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2124 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2125 llvm::Value *PL = CGF.EmitRuntimeCall(
2126 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2127 {RTLoc, ThreadID});
2128 IsTTD = Bld.CreateIsNull(PL);
2129 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002130 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2131 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
2132 Bld.CreateCondBr(IsSPMD, SPMDBB, NonSPMDBB);
2133 // There is no need to emit line number for unconditional branch.
2134 (void)ApplyDebugLocation::CreateEmpty(CGF);
2135 CGF.EmitBlock(SPMDBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002136 Address RecPtr = Address(llvm::ConstantPointerNull::get(GlobalRecPtrTy),
2137 CharUnits::fromQuantity(Alignment));
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002138 CGF.EmitBranch(ExitBB);
2139 // There is no need to emit line number for unconditional branch.
2140 (void)ApplyDebugLocation::CreateEmpty(CGF);
2141 CGF.EmitBlock(NonSPMDBB);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002142 llvm::Value *Size = llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize);
2143 if (const RecordDecl *SecGlobalizedVarsRecord =
2144 I->getSecond().SecondaryGlobalRecord.getValueOr(nullptr)) {
2145 SecGlobalRecTy =
2146 CGM.getContext().getRecordType(SecGlobalizedVarsRecord);
2147
2148 // Recover pointer to this function's global record. The runtime will
2149 // handle the specifics of the allocation of the memory.
2150 // Use actual memory size of the record including the padding
2151 // for alignment purposes.
2152 unsigned Alignment =
2153 CGM.getContext().getTypeAlignInChars(SecGlobalRecTy).getQuantity();
2154 unsigned GlobalRecordSize =
2155 CGM.getContext().getTypeSizeInChars(SecGlobalRecTy).getQuantity();
2156 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
2157 Size = Bld.CreateSelect(
2158 IsTTD, llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize), Size);
2159 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002160 // TODO: allow the usage of shared memory to be controlled by
2161 // the user, for now, default to global.
2162 llvm::Value *GlobalRecordSizeArg[] = {
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002163 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002164 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2165 createNVPTXRuntimeFunction(
2166 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2167 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002168 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002169 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002170 CGF.EmitBlock(ExitBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002171 auto *Phi = Bld.CreatePHI(GlobalRecPtrTy,
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002172 /*NumReservedValues=*/2, "_select_stack");
2173 Phi->addIncoming(RecPtr.getPointer(), SPMDBB);
2174 Phi->addIncoming(GlobalRecCastAddr, NonSPMDBB);
2175 GlobalRecCastAddr = Phi;
2176 I->getSecond().GlobalRecordAddr = Phi;
2177 I->getSecond().IsInSPMDModeFlag = IsSPMD;
Alexey Bataeve4090182018-11-02 14:54:07 +00002178 } else if (IsInTTDRegion) {
2179 assert(GlobalizedRecords.back().Records.size() < 2 &&
2180 "Expected less than 2 globalized records: one for target and one "
2181 "for teams.");
2182 unsigned Offset = 0;
2183 for (const RecordDecl *RD : GlobalizedRecords.back().Records) {
2184 QualType RDTy = CGM.getContext().getRecordType(RD);
2185 unsigned Alignment =
2186 CGM.getContext().getTypeAlignInChars(RDTy).getQuantity();
2187 unsigned Size = CGM.getContext().getTypeSizeInChars(RDTy).getQuantity();
2188 Offset =
2189 llvm::alignTo(llvm::alignTo(Offset, Alignment) + Size, Alignment);
2190 }
2191 unsigned Alignment =
2192 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
2193 Offset = llvm::alignTo(Offset, Alignment);
2194 GlobalizedRecords.back().Records.push_back(GlobalizedVarsRecord);
2195 ++GlobalizedRecords.back().RegionCounter;
2196 if (GlobalizedRecords.back().Records.size() == 1) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002197 assert(KernelStaticGlobalized &&
2198 "Kernel static pointer must be initialized already.");
2199 auto *UseSharedMemory = new llvm::GlobalVariable(
2200 CGM.getModule(), CGM.Int16Ty, /*isConstant=*/true,
2201 llvm::GlobalValue::InternalLinkage, nullptr,
2202 "_openmp_static_kernel$is_shared");
2203 UseSharedMemory->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2204 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2205 /*DestWidth=*/16, /*Signed=*/0);
2206 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2207 Address(UseSharedMemory,
2208 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2209 /*Volatile=*/false, Int16Ty, Loc);
2210 auto *StaticGlobalized = new llvm::GlobalVariable(
2211 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002212 llvm::GlobalValue::CommonLinkage, nullptr);
Alexey Bataeve4090182018-11-02 14:54:07 +00002213 auto *RecSize = new llvm::GlobalVariable(
2214 CGM.getModule(), CGM.SizeTy, /*isConstant=*/true,
2215 llvm::GlobalValue::InternalLinkage, nullptr,
2216 "_openmp_static_kernel$size");
2217 RecSize->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2218 llvm::Value *Ld = CGF.EmitLoadOfScalar(
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002219 Address(RecSize, CGM.getSizeAlign()), /*Volatile=*/false,
Alexey Bataeve4090182018-11-02 14:54:07 +00002220 CGM.getContext().getSizeType(), Loc);
2221 llvm::Value *ResAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2222 KernelStaticGlobalized, CGM.VoidPtrPtrTy);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002223 llvm::Value *GlobalRecordSizeArg[] = {StaticGlobalized, Ld,
2224 IsInSharedMemory, ResAddr};
Alexey Bataeve4090182018-11-02 14:54:07 +00002225 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2226 OMPRTL_NVPTX__kmpc_get_team_static_memory),
2227 GlobalRecordSizeArg);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002228 GlobalizedRecords.back().Buffer = StaticGlobalized;
Alexey Bataeve4090182018-11-02 14:54:07 +00002229 GlobalizedRecords.back().RecSize = RecSize;
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002230 GlobalizedRecords.back().UseSharedMemory = UseSharedMemory;
2231 GlobalizedRecords.back().Loc = Loc;
Alexey Bataeve4090182018-11-02 14:54:07 +00002232 }
2233 assert(KernelStaticGlobalized && "Global address must be set already.");
2234 Address FrameAddr = CGF.EmitLoadOfPointer(
2235 Address(KernelStaticGlobalized, CGM.getPointerAlign()),
2236 CGM.getContext()
2237 .getPointerType(CGM.getContext().VoidPtrTy)
2238 .castAs<PointerType>());
2239 llvm::Value *GlobalRecValue =
2240 Bld.CreateConstInBoundsGEP(FrameAddr, Offset, CharUnits::One())
2241 .getPointer();
2242 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2243 I->getSecond().IsInSPMDModeFlag = nullptr;
2244 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2245 GlobalRecValue, CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo());
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002246 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002247 // TODO: allow the usage of shared memory to be controlled by
2248 // the user, for now, default to global.
2249 llvm::Value *GlobalRecordSizeArg[] = {
2250 llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize),
2251 CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002252 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2253 createNVPTXRuntimeFunction(
2254 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2255 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002256 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002257 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002258 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2259 I->getSecond().IsInSPMDModeFlag = nullptr;
2260 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002261 LValue Base =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002262 CGF.MakeNaturalAlignPointeeAddrLValue(GlobalRecCastAddr, GlobalRecTy);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002263
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002264 // Emit the "global alloca" which is a GEP from the global declaration
2265 // record using the pointer returned by the runtime.
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002266 LValue SecBase;
2267 decltype(I->getSecond().LocalVarData)::const_iterator SecIt;
2268 if (IsTTD) {
2269 SecIt = I->getSecond().SecondaryLocalVarData->begin();
2270 llvm::PointerType *SecGlobalRecPtrTy =
2271 CGF.ConvertTypeForMem(SecGlobalRecTy)->getPointerTo();
2272 SecBase = CGF.MakeNaturalAlignPointeeAddrLValue(
2273 Bld.CreatePointerBitCastOrAddrSpaceCast(
2274 I->getSecond().GlobalRecordAddr, SecGlobalRecPtrTy),
2275 SecGlobalRecTy);
2276 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002277 for (auto &Rec : I->getSecond().LocalVarData) {
2278 bool EscapedParam = I->getSecond().EscapedParameters.count(Rec.first);
2279 llvm::Value *ParValue;
2280 if (EscapedParam) {
2281 const auto *VD = cast<VarDecl>(Rec.first);
2282 LValue ParLVal =
2283 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
2284 ParValue = CGF.EmitLoadOfScalar(ParLVal, Loc);
2285 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002286 LValue VarAddr = CGF.EmitLValueForField(Base, Rec.second.FD);
2287 // Emit VarAddr basing on lane-id if required.
2288 QualType VarTy;
2289 if (Rec.second.IsOnePerTeam) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002290 VarTy = Rec.second.FD->getType();
2291 } else {
2292 llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(
2293 VarAddr.getAddress().getPointer(),
2294 {Bld.getInt32(0), getNVPTXLaneID(CGF)});
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002295 VarTy =
2296 Rec.second.FD->getType()->castAsArrayTypeUnsafe()->getElementType();
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002297 VarAddr = CGF.MakeAddrLValue(
2298 Address(Ptr, CGM.getContext().getDeclAlign(Rec.first)), VarTy,
2299 AlignmentSource::Decl);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002300 }
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002301 Rec.second.PrivateAddr = VarAddr.getAddress();
Alexey Bataeve4090182018-11-02 14:54:07 +00002302 if (!IsInTTDRegion &&
2303 (WithSPMDCheck ||
2304 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002305 assert(I->getSecond().IsInSPMDModeFlag &&
2306 "Expected unknown execution mode or required SPMD check.");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002307 if (IsTTD) {
2308 assert(SecIt->second.IsOnePerTeam &&
2309 "Secondary glob data must be one per team.");
2310 LValue SecVarAddr = CGF.EmitLValueForField(SecBase, SecIt->second.FD);
2311 VarAddr.setAddress(
2312 Address(Bld.CreateSelect(IsTTD, SecVarAddr.getPointer(),
2313 VarAddr.getPointer()),
2314 VarAddr.getAlignment()));
2315 Rec.second.PrivateAddr = VarAddr.getAddress();
2316 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002317 Address GlobalPtr = Rec.second.PrivateAddr;
2318 Address LocalAddr = CGF.CreateMemTemp(VarTy, Rec.second.FD->getName());
2319 Rec.second.PrivateAddr = Address(
2320 Bld.CreateSelect(I->getSecond().IsInSPMDModeFlag,
2321 LocalAddr.getPointer(), GlobalPtr.getPointer()),
2322 LocalAddr.getAlignment());
2323 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002324 if (EscapedParam) {
2325 const auto *VD = cast<VarDecl>(Rec.first);
2326 CGF.EmitStoreOfScalar(ParValue, VarAddr);
2327 I->getSecond().MappedParams->setVarAddr(CGF, VD, VarAddr.getAddress());
2328 }
Alexey Bataev93a38d62018-10-16 00:09:06 +00002329 if (IsTTD)
2330 ++SecIt;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002331 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002332 }
2333 for (const ValueDecl *VD : I->getSecond().EscapedVariableLengthDecls) {
2334 // Recover pointer to this function's global record. The runtime will
2335 // handle the specifics of the allocation of the memory.
2336 // Use actual memory size of the record including the padding
2337 // for alignment purposes.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002338 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002339 llvm::Value *Size = CGF.getTypeSize(VD->getType());
2340 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2341 Size = Bld.CreateNUWAdd(
2342 Size, llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity() - 1));
2343 llvm::Value *AlignVal =
2344 llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity());
2345 Size = Bld.CreateUDiv(Size, AlignVal);
2346 Size = Bld.CreateNUWMul(Size, AlignVal);
2347 // TODO: allow the usage of shared memory to be controlled by
2348 // the user, for now, default to global.
2349 llvm::Value *GlobalRecordSizeArg[] = {
2350 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
2351 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002352 createNVPTXRuntimeFunction(
2353 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002354 GlobalRecordSizeArg);
2355 llvm::Value *GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2356 GlobalRecValue, CGF.ConvertTypeForMem(VD->getType())->getPointerTo());
2357 LValue Base = CGF.MakeAddrLValue(GlobalRecCastAddr, VD->getType(),
2358 CGM.getContext().getDeclAlign(VD),
2359 AlignmentSource::Decl);
2360 I->getSecond().MappedParams->setVarAddr(CGF, cast<VarDecl>(VD),
2361 Base.getAddress());
2362 I->getSecond().EscapedVariableLengthDeclsAddrs.emplace_back(GlobalRecValue);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002363 }
2364 I->getSecond().MappedParams->apply(CGF);
2365}
2366
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002367void CGOpenMPRuntimeNVPTX::emitGenericVarsEpilog(CodeGenFunction &CGF,
2368 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002369 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2370 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002371 return;
2372
Alexey Bataevc99042b2018-03-15 18:10:54 +00002373 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002374 if (I != FunctionGlobalizedDecls.end()) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00002375 I->getSecond().MappedParams->restore(CGF);
2376 if (!CGF.HaveInsertPoint())
2377 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002378 for (llvm::Value *Addr :
2379 llvm::reverse(I->getSecond().EscapedVariableLengthDeclsAddrs)) {
2380 CGF.EmitRuntimeCall(
2381 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2382 Addr);
2383 }
2384 if (I->getSecond().GlobalRecordAddr) {
Alexey Bataeve4090182018-11-02 14:54:07 +00002385 if (!IsInTTDRegion &&
2386 (WithSPMDCheck ||
2387 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002388 CGBuilderTy &Bld = CGF.Builder;
2389 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2390 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
2391 Bld.CreateCondBr(I->getSecond().IsInSPMDModeFlag, ExitBB, NonSPMDBB);
2392 // There is no need to emit line number for unconditional branch.
2393 (void)ApplyDebugLocation::CreateEmpty(CGF);
2394 CGF.EmitBlock(NonSPMDBB);
2395 CGF.EmitRuntimeCall(
2396 createNVPTXRuntimeFunction(
2397 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2398 CGF.EmitCastToVoidPtr(I->getSecond().GlobalRecordAddr));
2399 CGF.EmitBlock(ExitBB);
Alexey Bataeve4090182018-11-02 14:54:07 +00002400 } else if (IsInTTDRegion) {
2401 assert(GlobalizedRecords.back().RegionCounter > 0 &&
2402 "region counter must be > 0.");
2403 --GlobalizedRecords.back().RegionCounter;
2404 // Emit the restore function only in the target region.
2405 if (GlobalizedRecords.back().RegionCounter == 0) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002406 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2407 /*DestWidth=*/16, /*Signed=*/0);
2408 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2409 Address(GlobalizedRecords.back().UseSharedMemory,
2410 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2411 /*Volatile=*/false, Int16Ty, GlobalizedRecords.back().Loc);
Alexey Bataeve4090182018-11-02 14:54:07 +00002412 CGF.EmitRuntimeCall(
2413 createNVPTXRuntimeFunction(
2414 OMPRTL_NVPTX__kmpc_restore_team_static_memory),
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002415 IsInSharedMemory);
Alexey Bataeve4090182018-11-02 14:54:07 +00002416 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002417 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002418 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2419 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2420 I->getSecond().GlobalRecordAddr);
2421 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002422 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00002423 }
2424}
2425
Carlo Bertollic6872252016-04-04 15:55:02 +00002426void CGOpenMPRuntimeNVPTX::emitTeamsCall(CodeGenFunction &CGF,
2427 const OMPExecutableDirective &D,
2428 SourceLocation Loc,
2429 llvm::Value *OutlinedFn,
2430 ArrayRef<llvm::Value *> CapturedVars) {
2431 if (!CGF.HaveInsertPoint())
2432 return;
2433
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002434 Address ZeroAddr = CGF.CreateMemTemp(
2435 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2436 /*Name*/ ".zero.addr");
Carlo Bertollic6872252016-04-04 15:55:02 +00002437 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2438 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002439 OutlinedFnArgs.push_back(emitThreadIDAddress(CGF, Loc).getPointer());
Carlo Bertollic6872252016-04-04 15:55:02 +00002440 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2441 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002442 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Carlo Bertollic6872252016-04-04 15:55:02 +00002443}
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002444
2445void CGOpenMPRuntimeNVPTX::emitParallelCall(
2446 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2447 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2448 if (!CGF.HaveInsertPoint())
2449 return;
2450
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002451 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002452 emitSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002453 else
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002454 emitNonSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002455}
2456
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002457void CGOpenMPRuntimeNVPTX::emitNonSPMDParallelCall(
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002458 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2459 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2460 llvm::Function *Fn = cast<llvm::Function>(OutlinedFn);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002461
2462 // Force inline this outlined function at its call site.
2463 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
2464
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002465 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2466 /*DestWidth=*/32, /*Signed=*/1),
2467 ".zero.addr");
2468 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002469 // ThreadId for serialized parallels is 0.
2470 Address ThreadIDAddr = ZeroAddr;
2471 auto &&CodeGen = [this, Fn, CapturedVars, Loc, ZeroAddr, &ThreadIDAddr](
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002472 CodeGenFunction &CGF, PrePostActionTy &Action) {
2473 Action.Enter(CGF);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002474
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002475 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2476 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2477 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2478 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2479 emitOutlinedFunctionCall(CGF, Loc, Fn, OutlinedFnArgs);
2480 };
2481 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2482 PrePostActionTy &) {
2483
2484 RegionCodeGenTy RCG(CodeGen);
2485 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2486 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2487 llvm::Value *Args[] = {RTLoc, ThreadID};
2488
2489 NVPTXActionTy Action(
2490 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2491 Args,
2492 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2493 Args);
2494 RCG.setAction(Action);
2495 RCG(CGF);
2496 };
2497
2498 auto &&L0ParallelGen = [this, CapturedVars, Fn](CodeGenFunction &CGF,
2499 PrePostActionTy &Action) {
2500 CGBuilderTy &Bld = CGF.Builder;
2501 llvm::Function *WFn = WrapperFunctionsMap[Fn];
2502 assert(WFn && "Wrapper function does not exist!");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002503 llvm::Value *ID = Bld.CreateBitOrPointerCast(WFn, CGM.Int8PtrTy);
2504
2505 // Prepare for parallel region. Indicate the outlined function.
2506 llvm::Value *Args[] = {ID, /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002507 CGF.EmitRuntimeCall(
2508 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_prepare_parallel),
2509 Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002510
2511 // Create a private scope that will globalize the arguments
2512 // passed from the outside of the target region.
2513 CodeGenFunction::OMPPrivateScope PrivateArgScope(CGF);
2514
2515 // There's somehting to share.
2516 if (!CapturedVars.empty()) {
2517 // Prepare for parallel region. Indicate the outlined function.
2518 Address SharedArgs =
2519 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "shared_arg_refs");
2520 llvm::Value *SharedArgsPtr = SharedArgs.getPointer();
2521
2522 llvm::Value *DataSharingArgs[] = {
2523 SharedArgsPtr,
2524 llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size())};
2525 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2526 OMPRTL_NVPTX__kmpc_begin_sharing_variables),
2527 DataSharingArgs);
2528
2529 // Store variable address in a list of references to pass to workers.
2530 unsigned Idx = 0;
2531 ASTContext &Ctx = CGF.getContext();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002532 Address SharedArgListAddress = CGF.EmitLoadOfPointer(
2533 SharedArgs, Ctx.getPointerType(Ctx.getPointerType(Ctx.VoidPtrTy))
2534 .castAs<PointerType>());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002535 for (llvm::Value *V : CapturedVars) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002536 Address Dst = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
2537 CGF.getPointerSize());
2538 llvm::Value *PtrV;
Alexey Bataev17314212018-03-20 15:41:05 +00002539 if (V->getType()->isIntegerTy())
2540 PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
2541 else
2542 PtrV = Bld.CreatePointerBitCastOrAddrSpaceCast(V, CGF.VoidPtrTy);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002543 CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
2544 Ctx.getPointerType(Ctx.VoidPtrTy));
Alexey Bataevc99042b2018-03-15 18:10:54 +00002545 ++Idx;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002546 }
2547 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002548
2549 // Activate workers. This barrier is used by the master to signal
2550 // work for the workers.
2551 syncCTAThreads(CGF);
2552
2553 // OpenMP [2.5, Parallel Construct, p.49]
2554 // There is an implied barrier at the end of a parallel region. After the
2555 // end of a parallel region, only the master thread of the team resumes
2556 // execution of the enclosing task region.
2557 //
2558 // The master waits at this barrier until all workers are done.
2559 syncCTAThreads(CGF);
2560
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002561 if (!CapturedVars.empty())
2562 CGF.EmitRuntimeCall(
2563 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_sharing_variables));
2564
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002565 // Remember for post-processing in worker loop.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002566 Work.emplace_back(WFn);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002567 };
2568
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002569 auto &&LNParallelGen = [this, Loc, &SeqGen, &L0ParallelGen](
2570 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002571 if (IsInParallelRegion) {
2572 SeqGen(CGF, Action);
2573 } else if (IsInTargetMasterThreadRegion) {
2574 L0ParallelGen(CGF, Action);
2575 } else {
2576 // Check for master and then parallelism:
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002577 // if (__kmpc_is_spmd_exec_mode() || __kmpc_parallel_level(loc, gtid)) {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002578 // Serialized execution.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002579 // } else {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002580 // Worker call.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002581 // }
2582 CGBuilderTy &Bld = CGF.Builder;
2583 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002584 llvm::BasicBlock *SeqBB = CGF.createBasicBlock(".sequential");
2585 llvm::BasicBlock *ParallelCheckBB = CGF.createBasicBlock(".parcheck");
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002586 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
Alexey Bataev673110d2018-05-16 13:36:30 +00002587 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2588 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002589 Bld.CreateCondBr(IsSPMD, SeqBB, ParallelCheckBB);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002590 // There is no need to emit line number for unconditional branch.
2591 (void)ApplyDebugLocation::CreateEmpty(CGF);
2592 CGF.EmitBlock(ParallelCheckBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002593 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2594 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2595 llvm::Value *PL = CGF.EmitRuntimeCall(
2596 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2597 {RTLoc, ThreadID});
2598 llvm::Value *Res = Bld.CreateIsNotNull(PL);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002599 Bld.CreateCondBr(Res, SeqBB, MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002600 CGF.EmitBlock(SeqBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002601 SeqGen(CGF, Action);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002602 CGF.EmitBranch(ExitBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002603 // There is no need to emit line number for unconditional branch.
2604 (void)ApplyDebugLocation::CreateEmpty(CGF);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002605 CGF.EmitBlock(MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002606 L0ParallelGen(CGF, Action);
2607 CGF.EmitBranch(ExitBB);
2608 // There is no need to emit line number for unconditional branch.
2609 (void)ApplyDebugLocation::CreateEmpty(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002610 // Emit the continuation block for code after the if.
2611 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2612 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002613 };
2614
Alexey Bataev9ff80832018-04-16 20:16:21 +00002615 if (IfCond) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002616 emitOMPIfClause(CGF, IfCond, LNParallelGen, SeqGen);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002617 } else {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002618 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002619 RegionCodeGenTy ThenRCG(LNParallelGen);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002620 ThenRCG(CGF);
2621 }
2622}
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002623
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002624void CGOpenMPRuntimeNVPTX::emitSPMDParallelCall(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002625 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2626 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2627 // Just call the outlined function to execute the parallel region.
2628 // OutlinedFn(&GTid, &zero, CapturedStruct);
2629 //
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002630 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Carlo Bertolli79712092018-02-28 20:48:35 +00002631
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002632 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2633 /*DestWidth=*/32, /*Signed=*/1),
2634 ".zero.addr");
Carlo Bertolli79712092018-02-28 20:48:35 +00002635 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002636 // ThreadId for serialized parallels is 0.
2637 Address ThreadIDAddr = ZeroAddr;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002638 auto &&CodeGen = [this, OutlinedFn, CapturedVars, Loc, ZeroAddr,
Alexey Bataev8521ff62018-07-25 20:03:01 +00002639 &ThreadIDAddr](CodeGenFunction &CGF,
2640 PrePostActionTy &Action) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002641 Action.Enter(CGF);
2642
2643 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2644 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2645 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2646 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2647 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2648 };
2649 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2650 PrePostActionTy &) {
2651
2652 RegionCodeGenTy RCG(CodeGen);
2653 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2654 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2655 llvm::Value *Args[] = {RTLoc, ThreadID};
2656
2657 NVPTXActionTy Action(
2658 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2659 Args,
2660 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2661 Args);
2662 RCG.setAction(Action);
2663 RCG(CGF);
2664 };
2665
2666 if (IsInTargetMasterThreadRegion) {
Alexey Bataev8521ff62018-07-25 20:03:01 +00002667 // In the worker need to use the real thread id.
2668 ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002669 RegionCodeGenTy RCG(CodeGen);
2670 RCG(CGF);
2671 } else {
2672 // If we are not in the target region, it is definitely L2 parallelism or
2673 // more, because for SPMD mode we always has L1 parallel level, sowe don't
2674 // need to check for orphaned directives.
2675 RegionCodeGenTy RCG(SeqGen);
2676 RCG(CGF);
2677 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002678}
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002679
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002680void CGOpenMPRuntimeNVPTX::emitCriticalRegion(
2681 CodeGenFunction &CGF, StringRef CriticalName,
2682 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
2683 const Expr *Hint) {
2684 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
2685 llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
2686 llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
2687 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
2688 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
2689
2690 // Fetch team-local id of the thread.
2691 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
2692
2693 // Get the width of the team.
2694 llvm::Value *TeamWidth = getNVPTXNumThreads(CGF);
2695
2696 // Initialize the counter variable for the loop.
2697 QualType Int32Ty =
2698 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
2699 Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
2700 LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
2701 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
2702 /*isInit=*/true);
2703
2704 // Block checks if loop counter exceeds upper bound.
2705 CGF.EmitBlock(LoopBB);
2706 llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2707 llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
2708 CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
2709
2710 // Block tests which single thread should execute region, and which threads
2711 // should go straight to synchronisation point.
2712 CGF.EmitBlock(TestBB);
2713 CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2714 llvm::Value *CmpThreadToCounter =
2715 CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
2716 CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
2717
2718 // Block emits the body of the critical region.
2719 CGF.EmitBlock(BodyBB);
2720
2721 // Output the critical statement.
2722 CriticalOpGen(CGF);
2723
2724 // After the body surrounded by the critical region, the single executing
2725 // thread will jump to the synchronisation point.
2726 // Block waits for all threads in current team to finish then increments the
2727 // counter variable and returns to the loop.
2728 CGF.EmitBlock(SyncBB);
2729 getNVPTXCTABarrier(CGF);
2730
2731 llvm::Value *IncCounterVal =
2732 CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
2733 CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
2734 CGF.EmitBranch(LoopBB);
2735
2736 // Block that is reached when all threads in the team complete the region.
2737 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2738}
2739
Alexey Bataevb2575932018-01-04 20:18:55 +00002740/// Cast value to the specified type.
Alexey Bataeva453f362018-03-19 17:53:56 +00002741static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
2742 QualType ValTy, QualType CastTy,
2743 SourceLocation Loc) {
2744 assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
2745 "Cast type must sized.");
2746 assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
2747 "Val type must sized.");
2748 llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
2749 if (ValTy == CastTy)
Alexey Bataevb2575932018-01-04 20:18:55 +00002750 return Val;
Alexey Bataeva453f362018-03-19 17:53:56 +00002751 if (CGF.getContext().getTypeSizeInChars(ValTy) ==
2752 CGF.getContext().getTypeSizeInChars(CastTy))
2753 return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
2754 if (CastTy->isIntegerType() && ValTy->isIntegerType())
2755 return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
2756 CastTy->hasSignedIntegerRepresentation());
2757 Address CastItem = CGF.CreateMemTemp(CastTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002758 Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2759 CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
Alexey Bataeva453f362018-03-19 17:53:56 +00002760 CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy);
2761 return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc);
Alexey Bataevb2575932018-01-04 20:18:55 +00002762}
2763
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002764/// This function creates calls to one of two shuffle functions to copy
2765/// variables between lanes in a warp.
2766static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002767 llvm::Value *Elem,
Alexey Bataeva453f362018-03-19 17:53:56 +00002768 QualType ElemType,
2769 llvm::Value *Offset,
2770 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002771 CodeGenModule &CGM = CGF.CGM;
2772 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002773 CGOpenMPRuntimeNVPTX &RT =
2774 *(static_cast<CGOpenMPRuntimeNVPTX *>(&CGM.getOpenMPRuntime()));
2775
Alexey Bataeva453f362018-03-19 17:53:56 +00002776 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2777 assert(Size.getQuantity() <= 8 &&
2778 "Unsupported bitwidth in shuffle instruction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002779
Alexey Bataeva453f362018-03-19 17:53:56 +00002780 OpenMPRTLFunctionNVPTX ShuffleFn = Size.getQuantity() <= 4
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002781 ? OMPRTL_NVPTX__kmpc_shuffle_int32
2782 : OMPRTL_NVPTX__kmpc_shuffle_int64;
2783
2784 // Cast all types to 32- or 64-bit values before calling shuffle routines.
Alexey Bataeva453f362018-03-19 17:53:56 +00002785 QualType CastTy = CGF.getContext().getIntTypeForBitwidth(
2786 Size.getQuantity() <= 4 ? 32 : 64, /*Signed=*/1);
2787 llvm::Value *ElemCast = castValueToType(CGF, Elem, ElemType, CastTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002788 llvm::Value *WarpSize =
Alexey Bataevb2575932018-01-04 20:18:55 +00002789 Bld.CreateIntCast(getNVPTXWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002790
Alexey Bataev9ff80832018-04-16 20:16:21 +00002791 llvm::Value *ShuffledVal = CGF.EmitRuntimeCall(
2792 RT.createNVPTXRuntimeFunction(ShuffleFn), {ElemCast, Offset, WarpSize});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002793
Alexey Bataeva453f362018-03-19 17:53:56 +00002794 return castValueToType(CGF, ShuffledVal, CastTy, ElemType, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002795}
2796
Alexey Bataev12c62902018-06-22 19:10:38 +00002797static void shuffleAndStore(CodeGenFunction &CGF, Address SrcAddr,
2798 Address DestAddr, QualType ElemType,
2799 llvm::Value *Offset, SourceLocation Loc) {
2800 CGBuilderTy &Bld = CGF.Builder;
2801
2802 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2803 // Create the loop over the big sized data.
2804 // ptr = (void*)Elem;
2805 // ptrEnd = (void*) Elem + 1;
2806 // Step = 8;
2807 // while (ptr + Step < ptrEnd)
2808 // shuffle((int64_t)*ptr);
2809 // Step = 4;
2810 // while (ptr + Step < ptrEnd)
2811 // shuffle((int32_t)*ptr);
2812 // ...
2813 Address ElemPtr = DestAddr;
2814 Address Ptr = SrcAddr;
2815 Address PtrEnd = Bld.CreatePointerBitCastOrAddrSpaceCast(
2816 Bld.CreateConstGEP(SrcAddr, 1, Size), CGF.VoidPtrTy);
2817 for (int IntSize = 8; IntSize >= 1; IntSize /= 2) {
2818 if (Size < CharUnits::fromQuantity(IntSize))
2819 continue;
2820 QualType IntType = CGF.getContext().getIntTypeForBitwidth(
2821 CGF.getContext().toBits(CharUnits::fromQuantity(IntSize)),
2822 /*Signed=*/1);
2823 llvm::Type *IntTy = CGF.ConvertTypeForMem(IntType);
2824 Ptr = Bld.CreatePointerBitCastOrAddrSpaceCast(Ptr, IntTy->getPointerTo());
2825 ElemPtr =
2826 Bld.CreatePointerBitCastOrAddrSpaceCast(ElemPtr, IntTy->getPointerTo());
2827 if (Size.getQuantity() / IntSize > 1) {
2828 llvm::BasicBlock *PreCondBB = CGF.createBasicBlock(".shuffle.pre_cond");
2829 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".shuffle.then");
2830 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".shuffle.exit");
2831 llvm::BasicBlock *CurrentBB = Bld.GetInsertBlock();
2832 CGF.EmitBlock(PreCondBB);
2833 llvm::PHINode *PhiSrc =
2834 Bld.CreatePHI(Ptr.getType(), /*NumReservedValues=*/2);
2835 PhiSrc->addIncoming(Ptr.getPointer(), CurrentBB);
2836 llvm::PHINode *PhiDest =
2837 Bld.CreatePHI(ElemPtr.getType(), /*NumReservedValues=*/2);
2838 PhiDest->addIncoming(ElemPtr.getPointer(), CurrentBB);
2839 Ptr = Address(PhiSrc, Ptr.getAlignment());
2840 ElemPtr = Address(PhiDest, ElemPtr.getAlignment());
2841 llvm::Value *PtrDiff = Bld.CreatePtrDiff(
2842 PtrEnd.getPointer(), Bld.CreatePointerBitCastOrAddrSpaceCast(
2843 Ptr.getPointer(), CGF.VoidPtrTy));
2844 Bld.CreateCondBr(Bld.CreateICmpSGT(PtrDiff, Bld.getInt64(IntSize - 1)),
2845 ThenBB, ExitBB);
2846 CGF.EmitBlock(ThenBB);
2847 llvm::Value *Res = createRuntimeShuffleFunction(
2848 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2849 IntType, Offset, Loc);
2850 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002851 Address LocalPtr =
2852 Bld.CreateConstGEP(Ptr, 1, CharUnits::fromQuantity(IntSize));
2853 Address LocalElemPtr =
Alexey Bataev12c62902018-06-22 19:10:38 +00002854 Bld.CreateConstGEP(ElemPtr, 1, CharUnits::fromQuantity(IntSize));
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002855 PhiSrc->addIncoming(LocalPtr.getPointer(), ThenBB);
2856 PhiDest->addIncoming(LocalElemPtr.getPointer(), ThenBB);
Alexey Bataev12c62902018-06-22 19:10:38 +00002857 CGF.EmitBranch(PreCondBB);
2858 CGF.EmitBlock(ExitBB);
2859 } else {
2860 llvm::Value *Res = createRuntimeShuffleFunction(
2861 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2862 IntType, Offset, Loc);
2863 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
2864 Ptr = Bld.CreateConstGEP(Ptr, 1, CharUnits::fromQuantity(IntSize));
2865 ElemPtr =
2866 Bld.CreateConstGEP(ElemPtr, 1, CharUnits::fromQuantity(IntSize));
2867 }
2868 Size = Size % IntSize;
2869 }
2870}
2871
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002872namespace {
2873enum CopyAction : unsigned {
2874 // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
2875 // the warp using shuffle instructions.
2876 RemoteLaneToThread,
2877 // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
2878 ThreadCopy,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002879 // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
2880 ThreadToScratchpad,
2881 // ScratchpadToThread: Copy from a scratchpad array in global memory
2882 // containing team-reduced data to a thread's stack.
2883 ScratchpadToThread,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002884};
2885} // namespace
2886
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002887struct CopyOptionsTy {
2888 llvm::Value *RemoteLaneOffset;
2889 llvm::Value *ScratchpadIndex;
2890 llvm::Value *ScratchpadWidth;
2891};
2892
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002893/// Emit instructions to copy a Reduce list, which contains partially
2894/// aggregated values, in the specified direction.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002895static void emitReductionListCopy(
2896 CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
2897 ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
2898 CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002899
Alexey Bataev9ff80832018-04-16 20:16:21 +00002900 CodeGenModule &CGM = CGF.CGM;
2901 ASTContext &C = CGM.getContext();
2902 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002903
Alexey Bataev9ff80832018-04-16 20:16:21 +00002904 llvm::Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
2905 llvm::Value *ScratchpadIndex = CopyOptions.ScratchpadIndex;
2906 llvm::Value *ScratchpadWidth = CopyOptions.ScratchpadWidth;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002907
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002908 // Iterates, element-by-element, through the source Reduce list and
2909 // make a copy.
2910 unsigned Idx = 0;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002911 unsigned Size = Privates.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00002912 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002913 Address SrcElementAddr = Address::invalid();
2914 Address DestElementAddr = Address::invalid();
2915 Address DestElementPtrAddr = Address::invalid();
2916 // Should we shuffle in an element from a remote lane?
2917 bool ShuffleInElement = false;
2918 // Set to true to update the pointer in the dest Reduce list to a
2919 // newly created element.
2920 bool UpdateDestListPtr = false;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002921 // Increment the src or dest pointer to the scratchpad, for each
2922 // new element.
2923 bool IncrScratchpadSrc = false;
2924 bool IncrScratchpadDest = false;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002925
2926 switch (Action) {
2927 case RemoteLaneToThread: {
2928 // Step 1.1: Get the address for the src element in the Reduce list.
2929 Address SrcElementPtrAddr =
2930 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002931 SrcElementAddr = CGF.EmitLoadOfPointer(
2932 SrcElementPtrAddr,
2933 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002934
2935 // Step 1.2: Create a temporary to store the element in the destination
2936 // Reduce list.
2937 DestElementPtrAddr =
2938 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
2939 DestElementAddr =
2940 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2941 ShuffleInElement = true;
2942 UpdateDestListPtr = true;
2943 break;
2944 }
2945 case ThreadCopy: {
2946 // Step 1.1: Get the address for the src element in the Reduce list.
2947 Address SrcElementPtrAddr =
2948 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002949 SrcElementAddr = CGF.EmitLoadOfPointer(
2950 SrcElementPtrAddr,
2951 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002952
2953 // Step 1.2: Get the address for dest element. The destination
2954 // element has already been created on the thread's stack.
2955 DestElementPtrAddr =
2956 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002957 DestElementAddr = CGF.EmitLoadOfPointer(
2958 DestElementPtrAddr,
2959 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002960 break;
2961 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002962 case ThreadToScratchpad: {
2963 // Step 1.1: Get the address for the src element in the Reduce list.
2964 Address SrcElementPtrAddr =
2965 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002966 SrcElementAddr = CGF.EmitLoadOfPointer(
2967 SrcElementPtrAddr,
2968 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002969
2970 // Step 1.2: Get the address for dest element:
2971 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00002972 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00002973 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002974 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002975 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002976 Bld.CreateNUWAdd(DestBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002977 ScratchPadElemAbsolutePtrVal =
2978 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002979 DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
2980 C.getTypeAlignInChars(Private->getType()));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002981 IncrScratchpadDest = true;
2982 break;
2983 }
2984 case ScratchpadToThread: {
2985 // Step 1.1: Get the address for the src element in the scratchpad.
2986 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00002987 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00002988 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002989 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002990 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002991 Bld.CreateNUWAdd(SrcBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002992 ScratchPadElemAbsolutePtrVal =
2993 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
2994 SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
2995 C.getTypeAlignInChars(Private->getType()));
2996 IncrScratchpadSrc = true;
2997
2998 // Step 1.2: Create a temporary to store the element in the destination
2999 // Reduce list.
3000 DestElementPtrAddr =
3001 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
3002 DestElementAddr =
3003 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
3004 UpdateDestListPtr = true;
3005 break;
3006 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003007 }
3008
3009 // Regardless of src and dest of copy, we emit the load of src
3010 // element as this is required in all directions
3011 SrcElementAddr = Bld.CreateElementBitCast(
3012 SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
Alexey Bataev12c62902018-06-22 19:10:38 +00003013 DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
3014 SrcElementAddr.getElementType());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003015
3016 // Now that all active lanes have read the element in the
3017 // Reduce list, shuffle over the value from the remote lane.
Alexey Bataeva453f362018-03-19 17:53:56 +00003018 if (ShuffleInElement) {
Alexey Bataev12c62902018-06-22 19:10:38 +00003019 shuffleAndStore(CGF, SrcElementAddr, DestElementAddr, Private->getType(),
3020 RemoteLaneOffset, Private->getExprLoc());
3021 } else {
3022 if (Private->getType()->isScalarType()) {
3023 llvm::Value *Elem =
3024 CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false,
3025 Private->getType(), Private->getExprLoc());
3026 // Store the source element value to the dest element address.
3027 CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false,
3028 Private->getType());
3029 } else {
3030 CGF.EmitAggregateCopy(
3031 CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3032 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3033 Private->getType(), AggValueSlot::DoesNotOverlap);
3034 }
Alexey Bataeva453f362018-03-19 17:53:56 +00003035 }
Alexey Bataevb2575932018-01-04 20:18:55 +00003036
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003037 // Step 3.1: Modify reference in dest Reduce list as needed.
3038 // Modifying the reference in Reduce list to point to the newly
3039 // created element. The element is live in the current function
3040 // scope and that of functions it invokes (i.e., reduce_function).
3041 // RemoteReduceData[i] = (void*)&RemoteElem
3042 if (UpdateDestListPtr) {
3043 CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
3044 DestElementAddr.getPointer(), CGF.VoidPtrTy),
3045 DestElementPtrAddr, /*Volatile=*/false,
3046 C.VoidPtrTy);
3047 }
3048
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003049 // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
3050 // address of the next element in scratchpad memory, unless we're currently
3051 // processing the last one. Memory alignment is also taken care of here.
3052 if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
3053 llvm::Value *ScratchpadBasePtr =
3054 IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
Alexey Bataeve290ec02018-04-06 16:03:36 +00003055 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
3056 ScratchpadBasePtr = Bld.CreateNUWAdd(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003057 ScratchpadBasePtr,
Alexey Bataeve290ec02018-04-06 16:03:36 +00003058 Bld.CreateNUWMul(ScratchpadWidth, ElementSizeInChars));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003059
3060 // Take care of global memory alignment for performance
Alexey Bataeve290ec02018-04-06 16:03:36 +00003061 ScratchpadBasePtr = Bld.CreateNUWSub(
3062 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3063 ScratchpadBasePtr = Bld.CreateUDiv(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003064 ScratchpadBasePtr,
3065 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
Alexey Bataeve290ec02018-04-06 16:03:36 +00003066 ScratchpadBasePtr = Bld.CreateNUWAdd(
3067 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3068 ScratchpadBasePtr = Bld.CreateNUWMul(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003069 ScratchpadBasePtr,
3070 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
3071
3072 if (IncrScratchpadDest)
3073 DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3074 else /* IncrScratchpadSrc = true */
3075 SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3076 }
3077
Alexey Bataev9ff80832018-04-16 20:16:21 +00003078 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003079 }
3080}
3081
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003082/// This function emits a helper that loads data from the scratchpad array
3083/// and (optionally) reduces it with the input operand.
3084///
3085/// load_and_reduce(local, scratchpad, index, width, should_reduce)
3086/// reduce_data remote;
3087/// for elem in remote:
3088/// remote.elem = Scratchpad[elem_id][index]
3089/// if (should_reduce)
3090/// local = local @ remote
3091/// else
3092/// local = remote
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003093static llvm::Value *emitReduceScratchpadFunction(
3094 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3095 QualType ReductionArrayTy, llvm::Value *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003096 ASTContext &C = CGM.getContext();
3097 QualType Int32Ty = C.getIntTypeForBitwidth(32, /*Signed=*/1);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003098
3099 // Destination of the copy.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003100 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3101 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003102 // Base address of the scratchpad array, with each element storing a
3103 // Reduce list per team.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003104 ImplicitParamDecl ScratchPadArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3105 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003106 // A source index into the scratchpad array.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003107 ImplicitParamDecl IndexArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
3108 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003109 // Row width of an element in the scratchpad array, typically
3110 // the number of teams.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003111 ImplicitParamDecl WidthArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
3112 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003113 // If should_reduce == 1, then it's load AND reduce,
3114 // If should_reduce == 0 (or otherwise), then it only loads (+ copy).
3115 // The latter case is used for initialization.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003116 ImplicitParamDecl ShouldReduceArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3117 Int32Ty, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003118
3119 FunctionArgList Args;
3120 Args.push_back(&ReduceListArg);
3121 Args.push_back(&ScratchPadArg);
3122 Args.push_back(&IndexArg);
3123 Args.push_back(&WidthArg);
3124 Args.push_back(&ShouldReduceArg);
3125
Alexey Bataev9ff80832018-04-16 20:16:21 +00003126 const CGFunctionInfo &CGFI =
3127 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003128 auto *Fn = llvm::Function::Create(
3129 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3130 "_omp_reduction_load_and_reduce", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003131 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003132 Fn->setDoesNotRecurse();
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003133 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003134 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003135
Alexey Bataev9ff80832018-04-16 20:16:21 +00003136 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003137
3138 // Get local Reduce list pointer.
3139 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3140 Address ReduceListAddr(
3141 Bld.CreatePointerBitCastOrAddrSpaceCast(
3142 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003143 C.VoidPtrTy, Loc),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003144 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3145 CGF.getPointerAlign());
3146
3147 Address AddrScratchPadArg = CGF.GetAddrOfLocalVar(&ScratchPadArg);
3148 llvm::Value *ScratchPadBase = CGF.EmitLoadOfScalar(
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003149 AddrScratchPadArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003150
3151 Address AddrIndexArg = CGF.GetAddrOfLocalVar(&IndexArg);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003152 llvm::Value *IndexVal = Bld.CreateIntCast(
3153 CGF.EmitLoadOfScalar(AddrIndexArg, /*Volatile=*/false, Int32Ty, Loc),
3154 CGM.SizeTy, /*isSigned=*/true);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003155
3156 Address AddrWidthArg = CGF.GetAddrOfLocalVar(&WidthArg);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003157 llvm::Value *WidthVal = Bld.CreateIntCast(
3158 CGF.EmitLoadOfScalar(AddrWidthArg, /*Volatile=*/false, Int32Ty, Loc),
3159 CGM.SizeTy, /*isSigned=*/true);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003160
3161 Address AddrShouldReduceArg = CGF.GetAddrOfLocalVar(&ShouldReduceArg);
3162 llvm::Value *ShouldReduceVal = CGF.EmitLoadOfScalar(
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003163 AddrShouldReduceArg, /*Volatile=*/false, Int32Ty, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003164
3165 // The absolute ptr address to the base addr of the next element to copy.
3166 llvm::Value *CumulativeElemBasePtr =
3167 Bld.CreatePtrToInt(ScratchPadBase, CGM.SizeTy);
3168 Address SrcDataAddr(CumulativeElemBasePtr, CGF.getPointerAlign());
3169
3170 // Create a Remote Reduce list to store the elements read from the
3171 // scratchpad array.
3172 Address RemoteReduceList =
3173 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_red_list");
3174
3175 // Assemble remote Reduce list from scratchpad array.
3176 emitReductionListCopy(ScratchpadToThread, CGF, ReductionArrayTy, Privates,
3177 SrcDataAddr, RemoteReduceList,
3178 {/*RemoteLaneOffset=*/nullptr,
3179 /*ScratchpadIndex=*/IndexVal,
3180 /*ScratchpadWidth=*/WidthVal});
3181
3182 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3183 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3184 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
3185
Alexey Bataev9ff80832018-04-16 20:16:21 +00003186 llvm::Value *CondReduce = Bld.CreateIsNotNull(ShouldReduceVal);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003187 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
3188
3189 CGF.EmitBlock(ThenBB);
3190 // We should reduce with the local Reduce list.
3191 // reduce_function(LocalReduceList, RemoteReduceList)
3192 llvm::Value *LocalDataPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3193 ReduceListAddr.getPointer(), CGF.VoidPtrTy);
3194 llvm::Value *RemoteDataPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3195 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003196 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3197 CGF, Loc, ReduceFn, {LocalDataPtr, RemoteDataPtr});
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003198 Bld.CreateBr(MergeBB);
3199
3200 CGF.EmitBlock(ElseBB);
3201 // No reduction; just copy:
3202 // Local Reduce list = Remote Reduce list.
3203 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
3204 RemoteReduceList, ReduceListAddr);
3205 Bld.CreateBr(MergeBB);
3206
3207 CGF.EmitBlock(MergeBB);
3208
3209 CGF.FinishFunction();
3210 return Fn;
3211}
3212
3213/// This function emits a helper that stores reduced data from the team
3214/// master to a scratchpad array in global memory.
3215///
3216/// for elem in Reduce List:
3217/// scratchpad[elem_id][index] = elem
3218///
Benjamin Kramer674d5792017-05-26 20:08:24 +00003219static llvm::Value *emitCopyToScratchpad(CodeGenModule &CGM,
3220 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003221 QualType ReductionArrayTy,
3222 SourceLocation Loc) {
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003223
Alexey Bataev9ff80832018-04-16 20:16:21 +00003224 ASTContext &C = CGM.getContext();
3225 QualType Int32Ty = C.getIntTypeForBitwidth(32, /*Signed=*/1);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003226
3227 // Source of the copy.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003228 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3229 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003230 // Base address of the scratchpad array, with each element storing a
3231 // Reduce list per team.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003232 ImplicitParamDecl ScratchPadArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3233 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003234 // A destination index into the scratchpad array, typically the team
3235 // identifier.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003236 ImplicitParamDecl IndexArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
3237 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003238 // Row width of an element in the scratchpad array, typically
3239 // the number of teams.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003240 ImplicitParamDecl WidthArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
3241 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003242
3243 FunctionArgList Args;
3244 Args.push_back(&ReduceListArg);
3245 Args.push_back(&ScratchPadArg);
3246 Args.push_back(&IndexArg);
3247 Args.push_back(&WidthArg);
3248
Alexey Bataev9ff80832018-04-16 20:16:21 +00003249 const CGFunctionInfo &CGFI =
3250 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003251 auto *Fn = llvm::Function::Create(
3252 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3253 "_omp_reduction_copy_to_scratchpad", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003254 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003255 Fn->setDoesNotRecurse();
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003256 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003257 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003258
Alexey Bataev9ff80832018-04-16 20:16:21 +00003259 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003260
3261 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3262 Address SrcDataAddr(
3263 Bld.CreatePointerBitCastOrAddrSpaceCast(
3264 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003265 C.VoidPtrTy, Loc),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003266 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3267 CGF.getPointerAlign());
3268
3269 Address AddrScratchPadArg = CGF.GetAddrOfLocalVar(&ScratchPadArg);
3270 llvm::Value *ScratchPadBase = CGF.EmitLoadOfScalar(
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003271 AddrScratchPadArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003272
3273 Address AddrIndexArg = CGF.GetAddrOfLocalVar(&IndexArg);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003274 llvm::Value *IndexVal = Bld.CreateIntCast(
3275 CGF.EmitLoadOfScalar(AddrIndexArg, /*Volatile=*/false, Int32Ty, Loc),
3276 CGF.SizeTy, /*isSigned=*/true);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003277
3278 Address AddrWidthArg = CGF.GetAddrOfLocalVar(&WidthArg);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003279 llvm::Value *WidthVal = Bld.CreateIntCast(
3280 CGF.EmitLoadOfScalar(AddrWidthArg, /*Volatile=*/false, Int32Ty, Loc),
3281 CGF.SizeTy, /*isSigned=*/true);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003282
3283 // The absolute ptr address to the base addr of the next element to copy.
3284 llvm::Value *CumulativeElemBasePtr =
3285 Bld.CreatePtrToInt(ScratchPadBase, CGM.SizeTy);
3286 Address DestDataAddr(CumulativeElemBasePtr, CGF.getPointerAlign());
3287
3288 emitReductionListCopy(ThreadToScratchpad, CGF, ReductionArrayTy, Privates,
3289 SrcDataAddr, DestDataAddr,
3290 {/*RemoteLaneOffset=*/nullptr,
3291 /*ScratchpadIndex=*/IndexVal,
3292 /*ScratchpadWidth=*/WidthVal});
3293
3294 CGF.FinishFunction();
3295 return Fn;
3296}
3297
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003298/// This function emits a helper that gathers Reduce lists from the first
3299/// lane of every active warp to lanes in the first warp.
3300///
3301/// void inter_warp_copy_func(void* reduce_data, num_warps)
3302/// shared smem[warp_size];
3303/// For all data entries D in reduce_data:
3304/// If (I am the first lane in each warp)
3305/// Copy my local D to smem[warp_id]
3306/// sync
3307/// if (I am the first warp)
3308/// Copy smem[thread_id] to my local D
3309/// sync
3310static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
3311 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003312 QualType ReductionArrayTy,
3313 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003314 ASTContext &C = CGM.getContext();
3315 llvm::Module &M = CGM.getModule();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003316
3317 // ReduceList: thread local Reduce list.
3318 // At the stage of the computation when this function is called, partially
3319 // aggregated values reside in the first lane of every active warp.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003320 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3321 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003322 // NumWarps: number of warps active in the parallel region. This could
3323 // be smaller than 32 (max warps in a CTA) for partial block reduction.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003324 ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00003325 C.getIntTypeForBitwidth(32, /* Signed */ true),
3326 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003327 FunctionArgList Args;
3328 Args.push_back(&ReduceListArg);
3329 Args.push_back(&NumWarpsArg);
3330
Alexey Bataev9ff80832018-04-16 20:16:21 +00003331 const CGFunctionInfo &CGFI =
3332 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003333 auto *Fn = llvm::Function::Create(
3334 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3335 "_omp_reduction_inter_warp_copy_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003336 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003337 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003338 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003339 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003340
Alexey Bataev9ff80832018-04-16 20:16:21 +00003341 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003342
3343 // This array is used as a medium to transfer, one reduce element at a time,
3344 // the data from the first lane of every warp to lanes in the first warp
3345 // in order to perform the final step of a reduction in a parallel region
3346 // (reduction across warps). The array is placed in NVPTX __shared__ memory
3347 // for reduced latency, as well as to have a distinct copy for concurrently
3348 // executing target regions. The array is declared with common linkage so
3349 // as to be shared across compilation units.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003350 StringRef TransferMediumName =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003351 "__openmp_nvptx_data_transfer_temporary_storage";
3352 llvm::GlobalVariable *TransferMedium =
3353 M.getGlobalVariable(TransferMediumName);
3354 if (!TransferMedium) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003355 auto *Ty = llvm::ArrayType::get(CGM.Int32Ty, WarpSize);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003356 unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
3357 TransferMedium = new llvm::GlobalVariable(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003358 M, Ty, /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003359 llvm::Constant::getNullValue(Ty), TransferMediumName,
3360 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3361 SharedAddressSpace);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003362 CGM.addCompilerUsedGlobal(TransferMedium);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003363 }
3364
3365 // Get the CUDA thread id of the current OpenMP thread on the GPU.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003366 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003367 // nvptx_lane_id = nvptx_id % warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003368 llvm::Value *LaneID = getNVPTXLaneID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003369 // nvptx_warp_id = nvptx_id / warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003370 llvm::Value *WarpID = getNVPTXWarpID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003371
3372 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3373 Address LocalReduceList(
3374 Bld.CreatePointerBitCastOrAddrSpaceCast(
3375 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003376 C.VoidPtrTy, Loc),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003377 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3378 CGF.getPointerAlign());
3379
3380 unsigned Idx = 0;
Alexey Bataev9ff80832018-04-16 20:16:21 +00003381 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003382 //
3383 // Warp master copies reduce element to transfer medium in __shared__
3384 // memory.
3385 //
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003386 unsigned RealTySize =
3387 C.getTypeSizeInChars(Private->getType())
3388 .alignTo(C.getTypeAlignInChars(Private->getType()))
3389 .getQuantity();
3390 for (unsigned TySize = 4; TySize > 0 && RealTySize > 0; TySize /=2) {
3391 unsigned NumIters = RealTySize / TySize;
3392 if (NumIters == 0)
3393 continue;
3394 QualType CType = C.getIntTypeForBitwidth(
3395 C.toBits(CharUnits::fromQuantity(TySize)), /*Signed=*/1);
3396 llvm::Type *CopyType = CGF.ConvertTypeForMem(CType);
3397 CharUnits Align = CharUnits::fromQuantity(TySize);
3398 llvm::Value *Cnt = nullptr;
3399 Address CntAddr = Address::invalid();
3400 llvm::BasicBlock *PrecondBB = nullptr;
3401 llvm::BasicBlock *ExitBB = nullptr;
3402 if (NumIters > 1) {
3403 CntAddr = CGF.CreateMemTemp(C.IntTy, ".cnt.addr");
3404 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.IntTy), CntAddr,
3405 /*Volatile=*/false, C.IntTy);
3406 PrecondBB = CGF.createBasicBlock("precond");
3407 ExitBB = CGF.createBasicBlock("exit");
3408 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("body");
3409 // There is no need to emit line number for unconditional branch.
3410 (void)ApplyDebugLocation::CreateEmpty(CGF);
3411 CGF.EmitBlock(PrecondBB);
3412 Cnt = CGF.EmitLoadOfScalar(CntAddr, /*Volatile=*/false, C.IntTy, Loc);
3413 llvm::Value *Cmp =
3414 Bld.CreateICmpULT(Cnt, llvm::ConstantInt::get(CGM.IntTy, NumIters));
3415 Bld.CreateCondBr(Cmp, BodyBB, ExitBB);
3416 CGF.EmitBlock(BodyBB);
3417 }
3418 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3419 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3420 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003421
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003422 // if (lane_id == 0)
3423 llvm::Value *IsWarpMaster = Bld.CreateIsNull(LaneID, "warp_master");
3424 Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
3425 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003426
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003427 // Reduce element = LocalReduceList[i]
3428 Address ElemPtrPtrAddr =
3429 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
3430 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3431 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3432 // elemptr = ((CopyType*)(elemptrptr)) + I
3433 Address ElemPtr = Address(ElemPtrPtr, Align);
3434 ElemPtr = Bld.CreateElementBitCast(ElemPtr, CopyType);
3435 if (NumIters > 1) {
3436 ElemPtr = Address(Bld.CreateGEP(ElemPtr.getPointer(), Cnt),
3437 ElemPtr.getAlignment());
3438 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003439
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003440 // Get pointer to location in transfer medium.
3441 // MediumPtr = &medium[warp_id]
3442 llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
3443 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
3444 Address MediumPtr(MediumPtrVal, Align);
3445 // Casting to actual data type.
3446 // MediumPtr = (CopyType*)MediumPtrAddr;
3447 MediumPtr = Bld.CreateElementBitCast(MediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003448
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003449 // elem = *elemptr
3450 //*MediumPtr = elem
3451 llvm::Value *Elem =
3452 CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003453 // Store the source element value to the dest element address.
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003454 CGF.EmitStoreOfScalar(Elem, MediumPtr, /*Volatile=*/true, CType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003455
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003456 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003457
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003458 CGF.EmitBlock(ElseBB);
3459 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003460
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003461 CGF.EmitBlock(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003462
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003463 Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
3464 llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
3465 AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003466
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003467 llvm::Value *NumActiveThreads = Bld.CreateNSWMul(
3468 NumWarpsVal, getNVPTXWarpSize(CGF), "num_active_threads");
3469 // named_barrier_sync(ParallelBarrierID, num_active_threads)
3470 syncParallelThreads(CGF, NumActiveThreads);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003471
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003472 //
3473 // Warp 0 copies reduce element from transfer medium.
3474 //
3475 llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
3476 llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
3477 llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003478
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003479 // Up to 32 threads in warp 0 are active.
3480 llvm::Value *IsActiveThread =
3481 Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
3482 Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003483
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003484 CGF.EmitBlock(W0ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003485
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003486 // SrcMediumPtr = &medium[tid]
3487 llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
3488 TransferMedium,
3489 {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
3490 Address SrcMediumPtr(SrcMediumPtrVal, Align);
3491 // SrcMediumVal = *SrcMediumPtr;
3492 SrcMediumPtr = Bld.CreateElementBitCast(SrcMediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003493
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003494 // TargetElemPtr = (CopyType*)(SrcDataAddr[i]) + I
3495 Address TargetElemPtrPtr =
3496 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
3497 llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
3498 TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, Loc);
3499 Address TargetElemPtr = Address(TargetElemPtrVal, Align);
3500 TargetElemPtr = Bld.CreateElementBitCast(TargetElemPtr, CopyType);
3501 if (NumIters > 1) {
3502 TargetElemPtr = Address(Bld.CreateGEP(TargetElemPtr.getPointer(), Cnt),
3503 TargetElemPtr.getAlignment());
3504 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003505
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003506 // *TargetElemPtr = SrcMediumVal;
3507 llvm::Value *SrcMediumValue =
3508 CGF.EmitLoadOfScalar(SrcMediumPtr, /*Volatile=*/true, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003509 CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003510 CType);
3511 Bld.CreateBr(W0MergeBB);
3512
3513 CGF.EmitBlock(W0ElseBB);
3514 Bld.CreateBr(W0MergeBB);
3515
3516 CGF.EmitBlock(W0MergeBB);
3517
3518 // While warp 0 copies values from transfer medium, all other warps must
3519 // wait.
3520 syncParallelThreads(CGF, NumActiveThreads);
3521 if (NumIters > 1) {
3522 Cnt = Bld.CreateNSWAdd(Cnt, llvm::ConstantInt::get(CGM.IntTy, /*V=*/1));
3523 CGF.EmitStoreOfScalar(Cnt, CntAddr, /*Volatile=*/false, C.IntTy);
3524 CGF.EmitBranch(PrecondBB);
3525 (void)ApplyDebugLocation::CreateEmpty(CGF);
3526 CGF.EmitBlock(ExitBB);
3527 }
3528 RealTySize %= TySize;
Alexey Bataev12c62902018-06-22 19:10:38 +00003529 }
Alexey Bataev9ff80832018-04-16 20:16:21 +00003530 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003531 }
3532
3533 CGF.FinishFunction();
3534 return Fn;
3535}
3536
3537/// Emit a helper that reduces data across two OpenMP threads (lanes)
3538/// in the same warp. It uses shuffle instructions to copy over data from
3539/// a remote lane's stack. The reduction algorithm performed is specified
3540/// by the fourth parameter.
3541///
3542/// Algorithm Versions.
3543/// Full Warp Reduce (argument value 0):
3544/// This algorithm assumes that all 32 lanes are active and gathers
3545/// data from these 32 lanes, producing a single resultant value.
3546/// Contiguous Partial Warp Reduce (argument value 1):
3547/// This algorithm assumes that only a *contiguous* subset of lanes
3548/// are active. This happens for the last warp in a parallel region
3549/// when the user specified num_threads is not an integer multiple of
3550/// 32. This contiguous subset always starts with the zeroth lane.
3551/// Partial Warp Reduce (argument value 2):
3552/// This algorithm gathers data from any number of lanes at any position.
3553/// All reduced values are stored in the lowest possible lane. The set
3554/// of problems every algorithm addresses is a super set of those
3555/// addressable by algorithms with a lower version number. Overhead
3556/// increases as algorithm version increases.
3557///
3558/// Terminology
3559/// Reduce element:
3560/// Reduce element refers to the individual data field with primitive
3561/// data types to be combined and reduced across threads.
3562/// Reduce list:
3563/// Reduce list refers to a collection of local, thread-private
3564/// reduce elements.
3565/// Remote Reduce list:
3566/// Remote Reduce list refers to a collection of remote (relative to
3567/// the current thread) reduce elements.
3568///
3569/// We distinguish between three states of threads that are important to
3570/// the implementation of this function.
3571/// Alive threads:
3572/// Threads in a warp executing the SIMT instruction, as distinguished from
3573/// threads that are inactive due to divergent control flow.
3574/// Active threads:
3575/// The minimal set of threads that has to be alive upon entry to this
3576/// function. The computation is correct iff active threads are alive.
3577/// Some threads are alive but they are not active because they do not
3578/// contribute to the computation in any useful manner. Turning them off
3579/// may introduce control flow overheads without any tangible benefits.
3580/// Effective threads:
3581/// In order to comply with the argument requirements of the shuffle
3582/// function, we must keep all lanes holding data alive. But at most
3583/// half of them perform value aggregation; we refer to this half of
3584/// threads as effective. The other half is simply handing off their
3585/// data.
3586///
3587/// Procedure
3588/// Value shuffle:
3589/// In this step active threads transfer data from higher lane positions
3590/// in the warp to lower lane positions, creating Remote Reduce list.
3591/// Value aggregation:
3592/// In this step, effective threads combine their thread local Reduce list
3593/// with Remote Reduce list and store the result in the thread local
3594/// Reduce list.
3595/// Value copy:
3596/// In this step, we deal with the assumption made by algorithm 2
3597/// (i.e. contiguity assumption). When we have an odd number of lanes
3598/// active, say 2k+1, only k threads will be effective and therefore k
3599/// new values will be produced. However, the Reduce list owned by the
3600/// (2k+1)th thread is ignored in the value aggregation. Therefore
3601/// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
3602/// that the contiguity assumption still holds.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003603static llvm::Value *emitShuffleAndReduceFunction(
3604 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3605 QualType ReductionArrayTy, llvm::Value *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003606 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003607
3608 // Thread local Reduce list used to host the values of data to be reduced.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003609 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3610 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003611 // Current lane id; could be logical.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003612 ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
3613 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003614 // Offset of the remote source lane relative to the current lane.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003615 ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3616 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003617 // Algorithm version. This is expected to be known at compile time.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003618 ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3619 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003620 FunctionArgList Args;
3621 Args.push_back(&ReduceListArg);
3622 Args.push_back(&LaneIDArg);
3623 Args.push_back(&RemoteLaneOffsetArg);
3624 Args.push_back(&AlgoVerArg);
3625
Alexey Bataev9ff80832018-04-16 20:16:21 +00003626 const CGFunctionInfo &CGFI =
3627 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003628 auto *Fn = llvm::Function::Create(
3629 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3630 "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003631 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003632 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003633 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003634 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003635
Alexey Bataev9ff80832018-04-16 20:16:21 +00003636 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003637
3638 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3639 Address LocalReduceList(
3640 Bld.CreatePointerBitCastOrAddrSpaceCast(
3641 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3642 C.VoidPtrTy, SourceLocation()),
3643 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3644 CGF.getPointerAlign());
3645
3646 Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
3647 llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
3648 AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3649
3650 Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
3651 llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
3652 AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3653
3654 Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
3655 llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
3656 AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3657
3658 // Create a local thread-private variable to host the Reduce list
3659 // from a remote lane.
3660 Address RemoteReduceList =
3661 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
3662
3663 // This loop iterates through the list of reduce elements and copies,
3664 // element by element, from a remote lane in the warp to RemoteReduceList,
3665 // hosted on the thread's stack.
3666 emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
3667 LocalReduceList, RemoteReduceList,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003668 {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
3669 /*ScratchpadIndex=*/nullptr,
3670 /*ScratchpadWidth=*/nullptr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003671
3672 // The actions to be performed on the Remote Reduce list is dependent
3673 // on the algorithm version.
3674 //
3675 // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
3676 // LaneId % 2 == 0 && Offset > 0):
3677 // do the reduction value aggregation
3678 //
3679 // The thread local variable Reduce list is mutated in place to host the
3680 // reduced data, which is the aggregated value produced from local and
3681 // remote lanes.
3682 //
3683 // Note that AlgoVer is expected to be a constant integer known at compile
3684 // time.
3685 // When AlgoVer==0, the first conjunction evaluates to true, making
3686 // the entire predicate true during compile time.
3687 // When AlgoVer==1, the second conjunction has only the second part to be
3688 // evaluated during runtime. Other conjunctions evaluates to false
3689 // during compile time.
3690 // When AlgoVer==2, the third conjunction has only the second part to be
3691 // evaluated during runtime. Other conjunctions evaluates to false
3692 // during compile time.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003693 llvm::Value *CondAlgo0 = Bld.CreateIsNull(AlgoVerArgVal);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003694
Alexey Bataev9ff80832018-04-16 20:16:21 +00003695 llvm::Value *Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
3696 llvm::Value *CondAlgo1 = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003697 Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
3698
Alexey Bataev9ff80832018-04-16 20:16:21 +00003699 llvm::Value *Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
3700 llvm::Value *CondAlgo2 = Bld.CreateAnd(
3701 Algo2, Bld.CreateIsNull(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1))));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003702 CondAlgo2 = Bld.CreateAnd(
3703 CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
3704
Alexey Bataev9ff80832018-04-16 20:16:21 +00003705 llvm::Value *CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003706 CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
3707
3708 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3709 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3710 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
3711 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
3712
3713 CGF.EmitBlock(ThenBB);
3714 // reduce_function(LocalReduceList, RemoteReduceList)
3715 llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3716 LocalReduceList.getPointer(), CGF.VoidPtrTy);
3717 llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3718 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003719 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3720 CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003721 Bld.CreateBr(MergeBB);
3722
3723 CGF.EmitBlock(ElseBB);
3724 Bld.CreateBr(MergeBB);
3725
3726 CGF.EmitBlock(MergeBB);
3727
3728 // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
3729 // Reduce list.
3730 Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
Alexey Bataev9ff80832018-04-16 20:16:21 +00003731 llvm::Value *CondCopy = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003732 Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
3733
3734 llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
3735 llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
3736 llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
3737 Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
3738
3739 CGF.EmitBlock(CpyThenBB);
3740 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
3741 RemoteReduceList, LocalReduceList);
3742 Bld.CreateBr(CpyMergeBB);
3743
3744 CGF.EmitBlock(CpyElseBB);
3745 Bld.CreateBr(CpyMergeBB);
3746
3747 CGF.EmitBlock(CpyMergeBB);
3748
3749 CGF.FinishFunction();
3750 return Fn;
3751}
3752
3753///
3754/// Design of OpenMP reductions on the GPU
3755///
3756/// Consider a typical OpenMP program with one or more reduction
3757/// clauses:
3758///
3759/// float foo;
3760/// double bar;
3761/// #pragma omp target teams distribute parallel for \
3762/// reduction(+:foo) reduction(*:bar)
3763/// for (int i = 0; i < N; i++) {
3764/// foo += A[i]; bar *= B[i];
3765/// }
3766///
3767/// where 'foo' and 'bar' are reduced across all OpenMP threads in
3768/// all teams. In our OpenMP implementation on the NVPTX device an
3769/// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
3770/// within a team are mapped to CUDA threads within a threadblock.
3771/// Our goal is to efficiently aggregate values across all OpenMP
3772/// threads such that:
3773///
3774/// - the compiler and runtime are logically concise, and
3775/// - the reduction is performed efficiently in a hierarchical
3776/// manner as follows: within OpenMP threads in the same warp,
3777/// across warps in a threadblock, and finally across teams on
3778/// the NVPTX device.
3779///
3780/// Introduction to Decoupling
3781///
3782/// We would like to decouple the compiler and the runtime so that the
3783/// latter is ignorant of the reduction variables (number, data types)
3784/// and the reduction operators. This allows a simpler interface
3785/// and implementation while still attaining good performance.
3786///
3787/// Pseudocode for the aforementioned OpenMP program generated by the
3788/// compiler is as follows:
3789///
3790/// 1. Create private copies of reduction variables on each OpenMP
3791/// thread: 'foo_private', 'bar_private'
3792/// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
3793/// to it and writes the result in 'foo_private' and 'bar_private'
3794/// respectively.
3795/// 3. Call the OpenMP runtime on the GPU to reduce within a team
3796/// and store the result on the team master:
3797///
3798/// __kmpc_nvptx_parallel_reduce_nowait(...,
3799/// reduceData, shuffleReduceFn, interWarpCpyFn)
3800///
3801/// where:
3802/// struct ReduceData {
3803/// double *foo;
3804/// double *bar;
3805/// } reduceData
3806/// reduceData.foo = &foo_private
3807/// reduceData.bar = &bar_private
3808///
3809/// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
3810/// auxiliary functions generated by the compiler that operate on
3811/// variables of type 'ReduceData'. They aid the runtime perform
3812/// algorithmic steps in a data agnostic manner.
3813///
3814/// 'shuffleReduceFn' is a pointer to a function that reduces data
3815/// of type 'ReduceData' across two OpenMP threads (lanes) in the
3816/// same warp. It takes the following arguments as input:
3817///
3818/// a. variable of type 'ReduceData' on the calling lane,
3819/// b. its lane_id,
3820/// c. an offset relative to the current lane_id to generate a
3821/// remote_lane_id. The remote lane contains the second
3822/// variable of type 'ReduceData' that is to be reduced.
3823/// d. an algorithm version parameter determining which reduction
3824/// algorithm to use.
3825///
3826/// 'shuffleReduceFn' retrieves data from the remote lane using
3827/// efficient GPU shuffle intrinsics and reduces, using the
3828/// algorithm specified by the 4th parameter, the two operands
3829/// element-wise. The result is written to the first operand.
3830///
3831/// Different reduction algorithms are implemented in different
3832/// runtime functions, all calling 'shuffleReduceFn' to perform
3833/// the essential reduction step. Therefore, based on the 4th
3834/// parameter, this function behaves slightly differently to
3835/// cooperate with the runtime to ensure correctness under
3836/// different circumstances.
3837///
3838/// 'InterWarpCpyFn' is a pointer to a function that transfers
3839/// reduced variables across warps. It tunnels, through CUDA
3840/// shared memory, the thread-private data of type 'ReduceData'
3841/// from lane 0 of each warp to a lane in the first warp.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003842/// 4. Call the OpenMP runtime on the GPU to reduce across teams.
3843/// The last team writes the global reduced value to memory.
3844///
3845/// ret = __kmpc_nvptx_teams_reduce_nowait(...,
3846/// reduceData, shuffleReduceFn, interWarpCpyFn,
3847/// scratchpadCopyFn, loadAndReduceFn)
3848///
3849/// 'scratchpadCopyFn' is a helper that stores reduced
3850/// data from the team master to a scratchpad array in
3851/// global memory.
3852///
3853/// 'loadAndReduceFn' is a helper that loads data from
3854/// the scratchpad array and reduces it with the input
3855/// operand.
3856///
3857/// These compiler generated functions hide address
3858/// calculation and alignment information from the runtime.
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003859/// 5. if ret == 1:
3860/// The team master of the last team stores the reduced
3861/// result to the globals in memory.
3862/// foo += reduceData.foo; bar *= reduceData.bar
3863///
3864///
3865/// Warp Reduction Algorithms
3866///
3867/// On the warp level, we have three algorithms implemented in the
3868/// OpenMP runtime depending on the number of active lanes:
3869///
3870/// Full Warp Reduction
3871///
3872/// The reduce algorithm within a warp where all lanes are active
3873/// is implemented in the runtime as follows:
3874///
3875/// full_warp_reduce(void *reduce_data,
3876/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3877/// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
3878/// ShuffleReduceFn(reduce_data, 0, offset, 0);
3879/// }
3880///
3881/// The algorithm completes in log(2, WARPSIZE) steps.
3882///
3883/// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
3884/// not used therefore we save instructions by not retrieving lane_id
3885/// from the corresponding special registers. The 4th parameter, which
3886/// represents the version of the algorithm being used, is set to 0 to
3887/// signify full warp reduction.
3888///
3889/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3890///
3891/// #reduce_elem refers to an element in the local lane's data structure
3892/// #remote_elem is retrieved from a remote lane
3893/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3894/// reduce_elem = reduce_elem REDUCE_OP remote_elem;
3895///
3896/// Contiguous Partial Warp Reduction
3897///
3898/// This reduce algorithm is used within a warp where only the first
3899/// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
3900/// number of OpenMP threads in a parallel region is not a multiple of
3901/// WARPSIZE. The algorithm is implemented in the runtime as follows:
3902///
3903/// void
3904/// contiguous_partial_reduce(void *reduce_data,
3905/// kmp_ShuffleReductFctPtr ShuffleReduceFn,
3906/// int size, int lane_id) {
3907/// int curr_size;
3908/// int offset;
3909/// curr_size = size;
3910/// mask = curr_size/2;
3911/// while (offset>0) {
3912/// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
3913/// curr_size = (curr_size+1)/2;
3914/// offset = curr_size/2;
3915/// }
3916/// }
3917///
3918/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3919///
3920/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3921/// if (lane_id < offset)
3922/// reduce_elem = reduce_elem REDUCE_OP remote_elem
3923/// else
3924/// reduce_elem = remote_elem
3925///
3926/// This algorithm assumes that the data to be reduced are located in a
3927/// contiguous subset of lanes starting from the first. When there is
3928/// an odd number of active lanes, the data in the last lane is not
3929/// aggregated with any other lane's dat but is instead copied over.
3930///
3931/// Dispersed Partial Warp Reduction
3932///
3933/// This algorithm is used within a warp when any discontiguous subset of
3934/// lanes are active. It is used to implement the reduction operation
3935/// across lanes in an OpenMP simd region or in a nested parallel region.
3936///
3937/// void
3938/// dispersed_partial_reduce(void *reduce_data,
3939/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3940/// int size, remote_id;
3941/// int logical_lane_id = number_of_active_lanes_before_me() * 2;
3942/// do {
3943/// remote_id = next_active_lane_id_right_after_me();
3944/// # the above function returns 0 of no active lane
3945/// # is present right after the current lane.
3946/// size = number_of_active_lanes_in_this_warp();
3947/// logical_lane_id /= 2;
3948/// ShuffleReduceFn(reduce_data, logical_lane_id,
3949/// remote_id-1-threadIdx.x, 2);
3950/// } while (logical_lane_id % 2 == 0 && size > 1);
3951/// }
3952///
3953/// There is no assumption made about the initial state of the reduction.
3954/// Any number of lanes (>=1) could be active at any position. The reduction
3955/// result is returned in the first active lane.
3956///
3957/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3958///
3959/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3960/// if (lane_id % 2 == 0 && offset > 0)
3961/// reduce_elem = reduce_elem REDUCE_OP remote_elem
3962/// else
3963/// reduce_elem = remote_elem
3964///
3965///
3966/// Intra-Team Reduction
3967///
3968/// This function, as implemented in the runtime call
3969/// '__kmpc_nvptx_parallel_reduce_nowait', aggregates data across OpenMP
3970/// threads in a team. It first reduces within a warp using the
3971/// aforementioned algorithms. We then proceed to gather all such
3972/// reduced values at the first warp.
3973///
3974/// The runtime makes use of the function 'InterWarpCpyFn', which copies
3975/// data from each of the "warp master" (zeroth lane of each warp, where
3976/// warp-reduced data is held) to the zeroth warp. This step reduces (in
3977/// a mathematical sense) the problem of reduction across warp masters in
3978/// a block to the problem of warp reduction.
3979///
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003980///
3981/// Inter-Team Reduction
3982///
3983/// Once a team has reduced its data to a single value, it is stored in
3984/// a global scratchpad array. Since each team has a distinct slot, this
3985/// can be done without locking.
3986///
3987/// The last team to write to the scratchpad array proceeds to reduce the
3988/// scratchpad array. One or more workers in the last team use the helper
3989/// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
3990/// the k'th worker reduces every k'th element.
3991///
3992/// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait' to
3993/// reduce across workers and compute a globally reduced value.
3994///
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003995void CGOpenMPRuntimeNVPTX::emitReduction(
3996 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
3997 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
3998 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
3999 if (!CGF.HaveInsertPoint())
4000 return;
4001
4002 bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00004003#ifndef NDEBUG
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004004 bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00004005#endif
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004006
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00004007 if (Options.SimpleReduction) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004008 assert(!TeamsReduction && !ParallelReduction &&
4009 "Invalid reduction selection in emitReduction.");
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00004010 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
4011 ReductionOps, Options);
4012 return;
4013 }
4014
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004015 assert((TeamsReduction || ParallelReduction) &&
4016 "Invalid reduction selection in emitReduction.");
Alexey Bataev9ff80832018-04-16 20:16:21 +00004017 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004018
4019 // 1. Build a list of reduction variables.
4020 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
4021 auto Size = RHSExprs.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00004022 for (const Expr *E : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004023 if (E->getType()->isVariablyModifiedType())
4024 // Reserve place for array size.
4025 ++Size;
4026 }
4027 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
4028 QualType ReductionArrayTy =
4029 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
4030 /*IndexTypeQuals=*/0);
4031 Address ReductionList =
4032 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
4033 auto IPriv = Privates.begin();
4034 unsigned Idx = 0;
4035 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
4036 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
4037 CGF.getPointerSize());
4038 CGF.Builder.CreateStore(
4039 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4040 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
4041 Elem);
4042 if ((*IPriv)->getType()->isVariablyModifiedType()) {
4043 // Store array size.
4044 ++Idx;
4045 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
4046 CGF.getPointerSize());
4047 llvm::Value *Size = CGF.Builder.CreateIntCast(
4048 CGF.getVLASize(
4049 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
Sander de Smalen891af03a2018-02-03 13:55:59 +00004050 .NumElts,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004051 CGF.SizeTy, /*isSigned=*/false);
4052 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
4053 Elem);
4054 }
4055 }
4056
4057 // 2. Emit reduce_func().
Alexey Bataev9ff80832018-04-16 20:16:21 +00004058 llvm::Value *ReductionFn = emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004059 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
4060 Privates, LHSExprs, RHSExprs, ReductionOps);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004061
4062 // 4. Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
4063 // RedList, shuffle_reduce_func, interwarp_copy_func);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004064 llvm::Value *ThreadId = getThreadID(CGF, Loc);
4065 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
4066 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004067 ReductionList.getPointer(), CGF.VoidPtrTy);
4068
Alexey Bataev9ff80832018-04-16 20:16:21 +00004069 llvm::Value *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004070 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004071 llvm::Value *InterWarpCopyFn =
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004072 emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004073
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004074 llvm::Value *Res;
4075 if (ParallelReduction) {
4076 llvm::Value *Args[] = {ThreadId,
4077 CGF.Builder.getInt32(RHSExprs.size()),
4078 ReductionArrayTySize,
4079 RL,
4080 ShuffleAndReduceFn,
4081 InterWarpCopyFn};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004082
4083 Res = CGF.EmitRuntimeCall(
4084 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_reduce_nowait),
4085 Args);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004086 } else {
4087 assert(TeamsReduction && "expected teams reduction.");
Alexey Bataev9ff80832018-04-16 20:16:21 +00004088 llvm::Value *ScratchPadCopyFn =
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004089 emitCopyToScratchpad(CGM, Privates, ReductionArrayTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004090 llvm::Value *LoadAndReduceFn = emitReduceScratchpadFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004091 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004092
4093 llvm::Value *Args[] = {ThreadId,
4094 CGF.Builder.getInt32(RHSExprs.size()),
4095 ReductionArrayTySize,
4096 RL,
4097 ShuffleAndReduceFn,
4098 InterWarpCopyFn,
4099 ScratchPadCopyFn,
4100 LoadAndReduceFn};
4101 Res = CGF.EmitRuntimeCall(
4102 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_teams_reduce_nowait),
4103 Args);
4104 }
4105
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004106 // 5. Build if (res == 1)
4107 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.reduction.done");
4108 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.then");
4109 llvm::Value *Cond = CGF.Builder.CreateICmpEQ(
4110 Res, llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1));
4111 CGF.Builder.CreateCondBr(Cond, ThenBB, ExitBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004112
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004113 // 6. Build then branch: where we have reduced values in the master
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004114 // thread in each team.
4115 // __kmpc_end_reduce{_nowait}(<gtid>);
4116 // break;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004117 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004118
4119 // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
4120 llvm::Value *EndArgs[] = {ThreadId};
Alexey Bataev9ff80832018-04-16 20:16:21 +00004121 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004122 this](CodeGenFunction &CGF, PrePostActionTy &Action) {
4123 auto IPriv = Privates.begin();
4124 auto ILHS = LHSExprs.begin();
4125 auto IRHS = RHSExprs.begin();
Alexey Bataev9ff80832018-04-16 20:16:21 +00004126 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004127 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4128 cast<DeclRefExpr>(*IRHS));
4129 ++IPriv;
4130 ++ILHS;
4131 ++IRHS;
4132 }
4133 };
4134 RegionCodeGenTy RCG(CodeGen);
4135 NVPTXActionTy Action(
4136 nullptr, llvm::None,
4137 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_reduce_nowait),
4138 EndArgs);
4139 RCG.setAction(Action);
4140 RCG(CGF);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004141 // There is no need to emit line number for unconditional branch.
4142 (void)ApplyDebugLocation::CreateEmpty(CGF);
4143 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004144}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004145
4146const VarDecl *
4147CGOpenMPRuntimeNVPTX::translateParameter(const FieldDecl *FD,
4148 const VarDecl *NativeParam) const {
4149 if (!NativeParam->getType()->isReferenceType())
4150 return NativeParam;
4151 QualType ArgType = NativeParam->getType();
4152 QualifierCollector QC;
4153 const Type *NonQualTy = QC.strip(ArgType);
4154 QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4155 if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
4156 if (Attr->getCaptureKind() == OMPC_map) {
4157 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
4158 LangAS::opencl_global);
4159 }
4160 }
4161 ArgType = CGM.getContext().getPointerType(PointeeTy);
4162 QC.addRestrict();
4163 enum { NVPTX_local_addr = 5 };
Alexander Richardson6d989432017-10-15 18:48:14 +00004164 QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004165 ArgType = QC.apply(CGM.getContext(), ArgType);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004166 if (isa<ImplicitParamDecl>(NativeParam))
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004167 return ImplicitParamDecl::Create(
4168 CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
4169 NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004170 return ParmVarDecl::Create(
4171 CGM.getContext(),
4172 const_cast<DeclContext *>(NativeParam->getDeclContext()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004173 NativeParam->getBeginLoc(), NativeParam->getLocation(),
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004174 NativeParam->getIdentifier(), ArgType,
4175 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004176}
4177
4178Address
4179CGOpenMPRuntimeNVPTX::getParameterAddress(CodeGenFunction &CGF,
4180 const VarDecl *NativeParam,
4181 const VarDecl *TargetParam) const {
4182 assert(NativeParam != TargetParam &&
4183 NativeParam->getType()->isReferenceType() &&
4184 "Native arg must not be the same as target arg.");
4185 Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
4186 QualType NativeParamType = NativeParam->getType();
4187 QualifierCollector QC;
4188 const Type *NonQualTy = QC.strip(NativeParamType);
4189 QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4190 unsigned NativePointeeAddrSpace =
Alexander Richardson6d989432017-10-15 18:48:14 +00004191 CGF.getContext().getTargetAddressSpace(NativePointeeTy);
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004192 QualType TargetTy = TargetParam->getType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004193 llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004194 LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004195 // First cast to generic.
4196 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4197 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4198 /*AddrSpace=*/0));
4199 // Cast from generic to native address space.
4200 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4201 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4202 NativePointeeAddrSpace));
4203 Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
4204 CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004205 NativeParamType);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004206 return NativeParamAddr;
4207}
4208
4209void CGOpenMPRuntimeNVPTX::emitOutlinedFunctionCall(
Alexey Bataev3c595a62017-08-14 15:01:03 +00004210 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004211 ArrayRef<llvm::Value *> Args) const {
4212 SmallVector<llvm::Value *, 4> TargetArgs;
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004213 TargetArgs.reserve(Args.size());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004214 auto *FnType =
4215 cast<llvm::FunctionType>(OutlinedFn->getType()->getPointerElementType());
4216 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004217 if (FnType->isVarArg() && FnType->getNumParams() <= I) {
4218 TargetArgs.append(std::next(Args.begin(), I), Args.end());
4219 break;
4220 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004221 llvm::Type *TargetType = FnType->getParamType(I);
4222 llvm::Value *NativeArg = Args[I];
4223 if (!TargetType->isPointerTy()) {
4224 TargetArgs.emplace_back(NativeArg);
4225 continue;
4226 }
4227 llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataevc99042b2018-03-15 18:10:54 +00004228 NativeArg,
4229 NativeArg->getType()->getPointerElementType()->getPointerTo());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004230 TargetArgs.emplace_back(
4231 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
4232 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00004233 CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004234}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004235
4236/// Emit function which wraps the outline parallel region
4237/// and controls the arguments which are passed to this function.
4238/// The wrapper ensures that the outlined function is called
4239/// with the correct arguments when data is shared.
4240llvm::Function *CGOpenMPRuntimeNVPTX::createParallelDataSharingWrapper(
4241 llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
4242 ASTContext &Ctx = CGM.getContext();
4243 const auto &CS = *D.getCapturedStmt(OMPD_parallel);
4244
4245 // Create a function that takes as argument the source thread.
4246 FunctionArgList WrapperArgs;
4247 QualType Int16QTy =
4248 Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
4249 QualType Int32QTy =
4250 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004251 ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004252 /*Id=*/nullptr, Int16QTy,
4253 ImplicitParamDecl::Other);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004254 ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004255 /*Id=*/nullptr, Int32QTy,
4256 ImplicitParamDecl::Other);
4257 WrapperArgs.emplace_back(&ParallelLevelArg);
4258 WrapperArgs.emplace_back(&WrapperArg);
4259
Alexey Bataev9ff80832018-04-16 20:16:21 +00004260 const CGFunctionInfo &CGFI =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004261 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
4262
4263 auto *Fn = llvm::Function::Create(
4264 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataev9ff80832018-04-16 20:16:21 +00004265 Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004266 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004267 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004268 Fn->setDoesNotRecurse();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004269
4270 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
4271 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004272 D.getBeginLoc(), D.getBeginLoc());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004273
4274 const auto *RD = CS.getCapturedRecordDecl();
4275 auto CurField = RD->field_begin();
4276
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004277 Address ZeroAddr = CGF.CreateMemTemp(
4278 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
4279 /*Name*/ ".zero.addr");
4280 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004281 // Get the array of arguments.
4282 SmallVector<llvm::Value *, 8> Args;
4283
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004284 Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).getPointer());
4285 Args.emplace_back(ZeroAddr.getPointer());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004286
4287 CGBuilderTy &Bld = CGF.Builder;
4288 auto CI = CS.capture_begin();
4289
4290 // Use global memory for data sharing.
4291 // Handle passing of global args to workers.
4292 Address GlobalArgs =
4293 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
4294 llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
4295 llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
4296 CGF.EmitRuntimeCall(
4297 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_get_shared_variables),
4298 DataSharingArgs);
4299
4300 // Retrieve the shared variables from the list of references returned
4301 // by the runtime. Pass the variables to the outlined function.
Alexey Bataev17314212018-03-20 15:41:05 +00004302 Address SharedArgListAddress = Address::invalid();
4303 if (CS.capture_size() > 0 ||
4304 isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4305 SharedArgListAddress = CGF.EmitLoadOfPointer(
4306 GlobalArgs, CGF.getContext()
4307 .getPointerType(CGF.getContext().getPointerType(
4308 CGF.getContext().VoidPtrTy))
4309 .castAs<PointerType>());
4310 }
4311 unsigned Idx = 0;
4312 if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4313 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
4314 CGF.getPointerSize());
4315 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4316 Src, CGF.SizeTy->getPointerTo());
4317 llvm::Value *LB = CGF.EmitLoadOfScalar(
4318 TypedAddress,
4319 /*Volatile=*/false,
4320 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4321 cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
4322 Args.emplace_back(LB);
4323 ++Idx;
4324 Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
4325 CGF.getPointerSize());
4326 TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4327 Src, CGF.SizeTy->getPointerTo());
4328 llvm::Value *UB = CGF.EmitLoadOfScalar(
4329 TypedAddress,
4330 /*Volatile=*/false,
4331 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4332 cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
4333 Args.emplace_back(UB);
4334 ++Idx;
4335 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004336 if (CS.capture_size() > 0) {
4337 ASTContext &CGFContext = CGF.getContext();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004338 for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
4339 QualType ElemTy = CurField->getType();
Alexey Bataev17314212018-03-20 15:41:05 +00004340 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx,
4341 CGF.getPointerSize());
4342 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004343 Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)));
4344 llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
4345 /*Volatile=*/false,
4346 CGFContext.getPointerType(ElemTy),
4347 CI->getLocation());
Alexey Bataev2091ca62018-04-23 17:33:41 +00004348 if (CI->capturesVariableByCopy() &&
4349 !CI->getCapturedVar()->getType()->isAnyPointerType()) {
Alexey Bataev17314212018-03-20 15:41:05 +00004350 Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
4351 CI->getLocation());
4352 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004353 Args.emplace_back(Arg);
4354 }
4355 }
4356
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004357 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedParallelFn, Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004358 CGF.FinishFunction();
4359 return Fn;
4360}
4361
4362void CGOpenMPRuntimeNVPTX::emitFunctionProlog(CodeGenFunction &CGF,
4363 const Decl *D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004364 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4365 return;
4366
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004367 assert(D && "Expected function or captured|block decl.");
4368 assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
4369 "Function is registered already.");
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004370 assert((!TeamAndReductions.first || TeamAndReductions.first == D) &&
4371 "Team is set but not processed.");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004372 const Stmt *Body = nullptr;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004373 bool NeedToDelayGlobalization = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004374 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4375 Body = FD->getBody();
4376 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
4377 Body = BD->getBody();
4378 } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
4379 Body = CD->getBody();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004380 NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
Alexey Bataev2adecff2018-09-21 14:22:53 +00004381 if (NeedToDelayGlobalization &&
4382 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
4383 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004384 }
4385 if (!Body)
4386 return;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004387 CheckVarsEscapingDeclContext VarChecker(CGF, TeamAndReductions.second);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004388 VarChecker.Visit(Body);
Alexey Bataevff23bb62018-10-11 18:30:31 +00004389 const RecordDecl *GlobalizedVarsRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004390 VarChecker.getGlobalizedRecord(IsInTTDRegion);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004391 TeamAndReductions.first = nullptr;
4392 TeamAndReductions.second.clear();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004393 ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
4394 VarChecker.getEscapedVariableLengthDecls();
4395 if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004396 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004397 auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
4398 I->getSecond().MappedParams =
4399 llvm::make_unique<CodeGenFunction::OMPMapVars>();
4400 I->getSecond().GlobalRecord = GlobalizedVarsRecord;
4401 I->getSecond().EscapedParameters.insert(
4402 VarChecker.getEscapedParameters().begin(),
4403 VarChecker.getEscapedParameters().end());
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004404 I->getSecond().EscapedVariableLengthDecls.append(
4405 EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004406 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004407 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004408 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004409 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004410 Data.insert(std::make_pair(VD, MappedVarData(FD, IsInTTDRegion)));
Alexey Bataevc99042b2018-03-15 18:10:54 +00004411 }
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004412 if (!IsInTTDRegion && !NeedToDelayGlobalization && !IsInParallelRegion) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004413 CheckVarsEscapingDeclContext VarChecker(CGF, llvm::None);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004414 VarChecker.Visit(Body);
4415 I->getSecond().SecondaryGlobalRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004416 VarChecker.getGlobalizedRecord(/*IsInTTDRegion=*/true);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004417 I->getSecond().SecondaryLocalVarData.emplace();
4418 DeclToAddrMapTy &Data = I->getSecond().SecondaryLocalVarData.getValue();
4419 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
4420 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
4421 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004422 Data.insert(
4423 std::make_pair(VD, MappedVarData(FD, /*IsInTTDRegion=*/true)));
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004424 }
4425 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00004426 if (!NeedToDelayGlobalization) {
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004427 emitGenericVarsProlog(CGF, D->getBeginLoc(), /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004428 struct GlobalizationScope final : EHScopeStack::Cleanup {
4429 GlobalizationScope() = default;
4430
4431 void Emit(CodeGenFunction &CGF, Flags flags) override {
4432 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004433 .emitGenericVarsEpilog(CGF, /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004434 }
4435 };
4436 CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004437 }
4438}
4439
4440Address CGOpenMPRuntimeNVPTX::getAddressOfLocalVariable(CodeGenFunction &CGF,
4441 const VarDecl *VD) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004442 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4443 return Address::invalid();
4444
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004445 VD = VD->getCanonicalDecl();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004446 auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
4447 if (I == FunctionGlobalizedDecls.end())
4448 return Address::invalid();
Alexey Bataevc99042b2018-03-15 18:10:54 +00004449 auto VDI = I->getSecond().LocalVarData.find(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004450 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004451 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004452 if (VD->hasAttrs()) {
4453 for (specific_attr_iterator<OMPReferencedVarAttr> IT(VD->attr_begin()),
4454 E(VD->attr_end());
4455 IT != E; ++IT) {
4456 auto VDI = I->getSecond().LocalVarData.find(
4457 cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
4458 ->getCanonicalDecl());
4459 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004460 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004461 }
4462 }
4463 return Address::invalid();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004464}
4465
4466void CGOpenMPRuntimeNVPTX::functionFinished(CodeGenFunction &CGF) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004467 FunctionGlobalizedDecls.erase(CGF.CurFn);
4468 CGOpenMPRuntime::functionFinished(CGF);
4469}
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004470
4471void CGOpenMPRuntimeNVPTX::getDefaultDistScheduleAndChunk(
4472 CodeGenFunction &CGF, const OMPLoopDirective &S,
4473 OpenMPDistScheduleClauseKind &ScheduleKind,
4474 llvm::Value *&Chunk) const {
4475 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
4476 ScheduleKind = OMPC_DIST_SCHEDULE_static;
4477 Chunk = CGF.EmitScalarConversion(getNVPTXNumThreads(CGF),
4478 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4479 S.getIterationVariable()->getType(), S.getBeginLoc());
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004480 return;
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004481 }
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004482 CGOpenMPRuntime::getDefaultDistScheduleAndChunk(
4483 CGF, S, ScheduleKind, Chunk);
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004484}
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004485
4486void CGOpenMPRuntimeNVPTX::getDefaultScheduleAndChunk(
4487 CodeGenFunction &CGF, const OMPLoopDirective &S,
4488 OpenMPScheduleClauseKind &ScheduleKind,
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004489 const Expr *&ChunkExpr) const {
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004490 ScheduleKind = OMPC_SCHEDULE_static;
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004491 // Chunk size is 1 in this case.
4492 llvm::APInt ChunkSize(32, 1);
4493 ChunkExpr = IntegerLiteral::Create(CGF.getContext(), ChunkSize,
4494 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4495 SourceLocation());
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004496}
Alexey Bataev60705422018-10-30 15:50:12 +00004497
4498void CGOpenMPRuntimeNVPTX::adjustTargetSpecificDataForLambdas(
4499 CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
4500 assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
4501 " Expected target-based directive.");
4502 const CapturedStmt *CS = D.getCapturedStmt(OMPD_target);
4503 for (const CapturedStmt::Capture &C : CS->captures()) {
4504 // Capture variables captured by reference in lambdas for target-based
4505 // directives.
4506 if (!C.capturesVariable())
4507 continue;
4508 const VarDecl *VD = C.getCapturedVar();
4509 const auto *RD = VD->getType()
4510 .getCanonicalType()
4511 .getNonReferenceType()
4512 ->getAsCXXRecordDecl();
4513 if (!RD || !RD->isLambda())
4514 continue;
4515 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4516 LValue VDLVal;
4517 if (VD->getType().getCanonicalType()->isReferenceType())
4518 VDLVal = CGF.EmitLoadOfReferenceLValue(VDAddr, VD->getType());
4519 else
4520 VDLVal = CGF.MakeAddrLValue(
4521 VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
4522 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4523 FieldDecl *ThisCapture = nullptr;
4524 RD->getCaptureFields(Captures, ThisCapture);
4525 if (ThisCapture && CGF.CapturedStmtInfo->isCXXThisExprCaptured()) {
4526 LValue ThisLVal =
4527 CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
4528 llvm::Value *CXXThis = CGF.LoadCXXThis();
4529 CGF.EmitStoreOfScalar(CXXThis, ThisLVal);
4530 }
4531 for (const LambdaCapture &LC : RD->captures()) {
4532 if (LC.getCaptureKind() != LCK_ByRef)
4533 continue;
4534 const VarDecl *VD = LC.getCapturedVar();
4535 if (!CS->capturesVariable(VD))
4536 continue;
4537 auto It = Captures.find(VD);
4538 assert(It != Captures.end() && "Found lambda capture without field.");
4539 LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
4540 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4541 if (VD->getType().getCanonicalType()->isReferenceType())
4542 VDAddr = CGF.EmitLoadOfReferenceLValue(VDAddr,
4543 VD->getType().getCanonicalType())
4544 .getAddress();
4545 CGF.EmitStoreOfScalar(VDAddr.getPointer(), VarLVal);
4546 }
4547 }
4548}
4549
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004550// Get current CudaArch and ignore any unknown values
4551static CudaArch getCudaArch(CodeGenModule &CGM) {
4552 if (!CGM.getTarget().hasFeature("ptx"))
4553 return CudaArch::UNKNOWN;
4554 llvm::StringMap<bool> Features;
4555 CGM.getTarget().initFeatureMap(Features, CGM.getDiags(),
4556 CGM.getTarget().getTargetOpts().CPU,
4557 CGM.getTarget().getTargetOpts().Features);
4558 for (const auto &Feature : Features) {
4559 if (Feature.getValue()) {
4560 CudaArch Arch = StringToCudaArch(Feature.getKey());
4561 if (Arch != CudaArch::UNKNOWN)
4562 return Arch;
4563 }
4564 }
4565 return CudaArch::UNKNOWN;
4566}
4567
4568/// Check to see if target architecture supports unified addressing which is
4569/// a restriction for OpenMP requires clause "unified_shared_memory".
4570void CGOpenMPRuntimeNVPTX::checkArchForUnifiedAddressing(
4571 CodeGenModule &CGM, const OMPRequiresDecl *D) const {
4572 for (const OMPClause *Clause : D->clauselists()) {
4573 if (Clause->getClauseKind() == OMPC_unified_shared_memory) {
4574 switch (getCudaArch(CGM)) {
4575 case CudaArch::SM_20:
4576 case CudaArch::SM_21:
4577 case CudaArch::SM_30:
4578 case CudaArch::SM_32:
4579 case CudaArch::SM_35:
4580 case CudaArch::SM_37:
4581 case CudaArch::SM_50:
4582 case CudaArch::SM_52:
4583 case CudaArch::SM_53:
4584 case CudaArch::SM_60:
4585 case CudaArch::SM_61:
4586 case CudaArch::SM_62:
4587 CGM.Error(Clause->getBeginLoc(),
4588 "Target architecture does not support unified addressing");
4589 return;
4590 case CudaArch::SM_70:
4591 case CudaArch::SM_72:
4592 case CudaArch::SM_75:
4593 case CudaArch::GFX600:
4594 case CudaArch::GFX601:
4595 case CudaArch::GFX700:
4596 case CudaArch::GFX701:
4597 case CudaArch::GFX702:
4598 case CudaArch::GFX703:
4599 case CudaArch::GFX704:
4600 case CudaArch::GFX801:
4601 case CudaArch::GFX802:
4602 case CudaArch::GFX803:
4603 case CudaArch::GFX810:
4604 case CudaArch::GFX900:
4605 case CudaArch::GFX902:
4606 case CudaArch::GFX904:
4607 case CudaArch::GFX906:
4608 case CudaArch::GFX909:
4609 case CudaArch::UNKNOWN:
4610 break;
4611 case CudaArch::LAST:
4612 llvm_unreachable("Unexpected Cuda arch.");
4613 }
4614 }
4615 }
4616}
4617
Alexey Bataeve4090182018-11-02 14:54:07 +00004618/// Get number of SMs and number of blocks per SM.
4619static std::pair<unsigned, unsigned> getSMsBlocksPerSM(CodeGenModule &CGM) {
4620 std::pair<unsigned, unsigned> Data;
4621 if (CGM.getLangOpts().OpenMPCUDANumSMs)
4622 Data.first = CGM.getLangOpts().OpenMPCUDANumSMs;
4623 if (CGM.getLangOpts().OpenMPCUDABlocksPerSM)
4624 Data.second = CGM.getLangOpts().OpenMPCUDABlocksPerSM;
4625 if (Data.first && Data.second)
4626 return Data;
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004627 switch (getCudaArch(CGM)) {
4628 case CudaArch::SM_20:
4629 case CudaArch::SM_21:
4630 case CudaArch::SM_30:
4631 case CudaArch::SM_32:
4632 case CudaArch::SM_35:
4633 case CudaArch::SM_37:
4634 case CudaArch::SM_50:
4635 case CudaArch::SM_52:
4636 case CudaArch::SM_53:
4637 return {16, 16};
4638 case CudaArch::SM_60:
4639 case CudaArch::SM_61:
4640 case CudaArch::SM_62:
4641 return {56, 32};
4642 case CudaArch::SM_70:
4643 case CudaArch::SM_72:
4644 case CudaArch::SM_75:
4645 return {84, 32};
4646 case CudaArch::GFX600:
4647 case CudaArch::GFX601:
4648 case CudaArch::GFX700:
4649 case CudaArch::GFX701:
4650 case CudaArch::GFX702:
4651 case CudaArch::GFX703:
4652 case CudaArch::GFX704:
4653 case CudaArch::GFX801:
4654 case CudaArch::GFX802:
4655 case CudaArch::GFX803:
4656 case CudaArch::GFX810:
4657 case CudaArch::GFX900:
4658 case CudaArch::GFX902:
4659 case CudaArch::GFX904:
4660 case CudaArch::GFX906:
4661 case CudaArch::GFX909:
4662 case CudaArch::UNKNOWN:
4663 break;
4664 case CudaArch::LAST:
4665 llvm_unreachable("Unexpected Cuda arch.");
Alexey Bataeve4090182018-11-02 14:54:07 +00004666 }
4667 llvm_unreachable("Unexpected NVPTX target without ptx feature.");
4668}
4669
4670void CGOpenMPRuntimeNVPTX::clear() {
4671 if (!GlobalizedRecords.empty()) {
4672 ASTContext &C = CGM.getContext();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004673 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> GlobalRecs;
4674 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> SharedRecs;
Alexey Bataeve4090182018-11-02 14:54:07 +00004675 RecordDecl *StaticRD = C.buildImplicitRecord(
4676 "_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
4677 StaticRD->startDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004678 RecordDecl *SharedStaticRD = C.buildImplicitRecord(
4679 "_shared_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
4680 SharedStaticRD->startDefinition();
Alexey Bataeve4090182018-11-02 14:54:07 +00004681 for (const GlobalPtrSizeRecsTy &Records : GlobalizedRecords) {
4682 if (Records.Records.empty())
4683 continue;
4684 unsigned Size = 0;
4685 unsigned RecAlignment = 0;
4686 for (const RecordDecl *RD : Records.Records) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004687 QualType RDTy = C.getRecordType(RD);
4688 unsigned Alignment = C.getTypeAlignInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00004689 RecAlignment = std::max(RecAlignment, Alignment);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004690 unsigned RecSize = C.getTypeSizeInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00004691 Size =
4692 llvm::alignTo(llvm::alignTo(Size, Alignment) + RecSize, Alignment);
4693 }
4694 Size = llvm::alignTo(Size, RecAlignment);
4695 llvm::APInt ArySize(/*numBits=*/64, Size);
4696 QualType SubTy = C.getConstantArrayType(
4697 C.CharTy, ArySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004698 const bool UseSharedMemory = Size <= SharedMemorySize;
4699 auto *Field =
4700 FieldDecl::Create(C, UseSharedMemory ? SharedStaticRD : StaticRD,
4701 SourceLocation(), SourceLocation(), nullptr, SubTy,
4702 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
4703 /*BW=*/nullptr, /*Mutable=*/false,
4704 /*InitStyle=*/ICIS_NoInit);
Alexey Bataeve4090182018-11-02 14:54:07 +00004705 Field->setAccess(AS_public);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004706 if (UseSharedMemory) {
4707 SharedStaticRD->addDecl(Field);
4708 SharedRecs.push_back(&Records);
4709 } else {
4710 StaticRD->addDecl(Field);
4711 GlobalRecs.push_back(&Records);
4712 }
Alexey Bataeve4090182018-11-02 14:54:07 +00004713 Records.RecSize->setInitializer(llvm::ConstantInt::get(CGM.SizeTy, Size));
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004714 Records.UseSharedMemory->setInitializer(
4715 llvm::ConstantInt::get(CGM.Int16Ty, UseSharedMemory ? 1 : 0));
4716 }
4717 SharedStaticRD->completeDefinition();
4718 if (!SharedStaticRD->field_empty()) {
4719 QualType StaticTy = C.getRecordType(SharedStaticRD);
4720 llvm::Type *LLVMStaticTy = CGM.getTypes().ConvertTypeForMem(StaticTy);
4721 auto *GV = new llvm::GlobalVariable(
4722 CGM.getModule(), LLVMStaticTy,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004723 /*isConstant=*/false, llvm::GlobalValue::CommonLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004724 llvm::Constant::getNullValue(LLVMStaticTy),
4725 "_openmp_shared_static_glob_rd_$_", /*InsertBefore=*/nullptr,
4726 llvm::GlobalValue::NotThreadLocal,
4727 C.getTargetAddressSpace(LangAS::cuda_shared));
4728 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
4729 GV, CGM.VoidPtrTy);
4730 for (const GlobalPtrSizeRecsTy *Rec : SharedRecs) {
4731 Rec->Buffer->replaceAllUsesWith(Replacement);
4732 Rec->Buffer->eraseFromParent();
4733 }
Alexey Bataeve4090182018-11-02 14:54:07 +00004734 }
4735 StaticRD->completeDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004736 if (!StaticRD->field_empty()) {
4737 QualType StaticTy = C.getRecordType(StaticRD);
4738 std::pair<unsigned, unsigned> SMsBlockPerSM = getSMsBlocksPerSM(CGM);
4739 llvm::APInt Size1(32, SMsBlockPerSM.second);
4740 QualType Arr1Ty =
4741 C.getConstantArrayType(StaticTy, Size1, ArrayType::Normal,
4742 /*IndexTypeQuals=*/0);
4743 llvm::APInt Size2(32, SMsBlockPerSM.first);
4744 QualType Arr2Ty = C.getConstantArrayType(Arr1Ty, Size2, ArrayType::Normal,
4745 /*IndexTypeQuals=*/0);
4746 llvm::Type *LLVMArr2Ty = CGM.getTypes().ConvertTypeForMem(Arr2Ty);
4747 auto *GV = new llvm::GlobalVariable(
4748 CGM.getModule(), LLVMArr2Ty,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004749 /*isConstant=*/false, llvm::GlobalValue::CommonLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004750 llvm::Constant::getNullValue(LLVMArr2Ty),
4751 "_openmp_static_glob_rd_$_");
4752 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
4753 GV, CGM.VoidPtrTy);
4754 for (const GlobalPtrSizeRecsTy *Rec : GlobalRecs) {
4755 Rec->Buffer->replaceAllUsesWith(Replacement);
4756 Rec->Buffer->eraseFromParent();
4757 }
4758 }
Alexey Bataeve4090182018-11-02 14:54:07 +00004759 }
4760 CGOpenMPRuntime::clear();
4761}