blob: 559a26f6f357101dbb9602d660d7f2468fc3ae74 [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"
20#include "llvm/ADT/SmallPtrSet.h"
Samuel Antao45bfe4c2016-02-08 15:59:20 +000021
22using namespace clang;
23using namespace CodeGen;
24
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +000025namespace {
26enum OpenMPRTLFunctionNVPTX {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000027 /// Call to void __kmpc_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +000028 /// int16_t RequiresOMPRuntime);
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +000029 OMPRTL_NVPTX__kmpc_kernel_init,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000030 /// Call to void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +000031 OMPRTL_NVPTX__kmpc_kernel_deinit,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000032 /// Call to void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +000033 /// int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +000034 OMPRTL_NVPTX__kmpc_spmd_kernel_init,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000035 /// Call to void __kmpc_spmd_kernel_deinit();
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +000036 OMPRTL_NVPTX__kmpc_spmd_kernel_deinit,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000037 /// Call to void __kmpc_kernel_prepare_parallel(void
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +000038 /// *outlined_function, int16_t
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +000039 /// IsOMPRuntimeInitialized);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000040 OMPRTL_NVPTX__kmpc_kernel_prepare_parallel,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000041 /// Call to bool __kmpc_kernel_parallel(void **outlined_function,
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +000042 /// int16_t IsOMPRuntimeInitialized);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000043 OMPRTL_NVPTX__kmpc_kernel_parallel,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000044 /// Call to void __kmpc_kernel_end_parallel();
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000045 OMPRTL_NVPTX__kmpc_kernel_end_parallel,
46 /// Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
47 /// global_tid);
48 OMPRTL_NVPTX__kmpc_serialized_parallel,
49 /// Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
50 /// global_tid);
51 OMPRTL_NVPTX__kmpc_end_serialized_parallel,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000052 /// Call to int32_t __kmpc_shuffle_int32(int32_t element,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000053 /// int16_t lane_offset, int16_t warp_size);
54 OMPRTL_NVPTX__kmpc_shuffle_int32,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000055 /// Call to int64_t __kmpc_shuffle_int64(int64_t element,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000056 /// int16_t lane_offset, int16_t warp_size);
57 OMPRTL_NVPTX__kmpc_shuffle_int64,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000058 /// Call to __kmpc_nvptx_parallel_reduce_nowait(kmp_int32
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000059 /// global_tid, kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
60 /// void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
61 /// lane_offset, int16_t shortCircuit),
62 /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num));
63 OMPRTL_NVPTX__kmpc_parallel_reduce_nowait,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000064 /// Call to __kmpc_nvptx_simd_reduce_nowait(kmp_int32
Alexey Bataevfac26cf2018-05-02 20:03:27 +000065 /// global_tid, kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
66 /// void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
67 /// lane_offset, int16_t shortCircuit),
68 /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num));
69 OMPRTL_NVPTX__kmpc_simd_reduce_nowait,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000070 /// Call to __kmpc_nvptx_teams_reduce_nowait(int32_t global_tid,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +000071 /// int32_t num_vars, size_t reduce_size, void *reduce_data,
72 /// void (*kmp_ShuffleReductFctPtr)(void *rhs, int16_t lane_id, int16_t
73 /// lane_offset, int16_t shortCircuit),
74 /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num),
75 /// void (*kmp_CopyToScratchpadFctPtr)(void *reduce_data, void * scratchpad,
76 /// int32_t index, int32_t width),
77 /// void (*kmp_LoadReduceFctPtr)(void *reduce_data, void * scratchpad, int32_t
78 /// index, int32_t width, int32_t reduce))
79 OMPRTL_NVPTX__kmpc_teams_reduce_nowait,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000080 /// Call to __kmpc_nvptx_end_reduce_nowait(int32_t global_tid);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000081 OMPRTL_NVPTX__kmpc_end_reduce_nowait,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000082 /// Call to void __kmpc_data_sharing_init_stack();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000083 OMPRTL_NVPTX__kmpc_data_sharing_init_stack,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000084 /// Call to void* __kmpc_data_sharing_push_stack(size_t size,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000085 /// int16_t UseSharedMemory);
86 OMPRTL_NVPTX__kmpc_data_sharing_push_stack,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000087 /// Call to void __kmpc_data_sharing_pop_stack(void *a);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000088 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000089 /// Call to void __kmpc_begin_sharing_variables(void ***args,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000090 /// size_t n_args);
91 OMPRTL_NVPTX__kmpc_begin_sharing_variables,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000092 /// Call to void __kmpc_end_sharing_variables();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000093 OMPRTL_NVPTX__kmpc_end_sharing_variables,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000094 /// Call to void __kmpc_get_shared_variables(void ***GlobalArgs)
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000095 OMPRTL_NVPTX__kmpc_get_shared_variables,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +000096 /// Call to uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32
97 /// global_tid);
98 OMPRTL_NVPTX__kmpc_parallel_level,
Alexey Bataev673110d2018-05-16 13:36:30 +000099 /// Call to int8_t __kmpc_is_spmd_exec_mode();
100 OMPRTL_NVPTX__kmpc_is_spmd_exec_mode,
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000101};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000102
103/// Pre(post)-action for different OpenMP constructs specialized for NVPTX.
104class NVPTXActionTy final : public PrePostActionTy {
Alexey Bataev9ff80832018-04-16 20:16:21 +0000105 llvm::Value *EnterCallee = nullptr;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000106 ArrayRef<llvm::Value *> EnterArgs;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000107 llvm::Value *ExitCallee = nullptr;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000108 ArrayRef<llvm::Value *> ExitArgs;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000109 bool Conditional = false;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000110 llvm::BasicBlock *ContBlock = nullptr;
111
112public:
113 NVPTXActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
114 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
115 bool Conditional = false)
116 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
117 ExitArgs(ExitArgs), Conditional(Conditional) {}
118 void Enter(CodeGenFunction &CGF) override {
119 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
120 if (Conditional) {
121 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
122 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
123 ContBlock = CGF.createBasicBlock("omp_if.end");
124 // Generate the branch (If-stmt)
125 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
126 CGF.EmitBlock(ThenBlock);
127 }
128 }
129 void Done(CodeGenFunction &CGF) {
130 // Emit the rest of blocks/branches
131 CGF.EmitBranch(ContBlock);
132 CGF.EmitBlock(ContBlock, true);
133 }
134 void Exit(CodeGenFunction &CGF) override {
135 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
136 }
137};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000138
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000139/// A class to track the execution mode when codegening directives within
140/// a target region. The appropriate mode (SPMD|NON-SPMD) is set on entry
141/// to the target region and used by containing directives such as 'parallel'
142/// to emit optimized code.
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000143class ExecutionModeRAII {
144private:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000145 CGOpenMPRuntimeNVPTX::ExecutionMode SavedMode;
146 CGOpenMPRuntimeNVPTX::ExecutionMode &Mode;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000147
148public:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000149 ExecutionModeRAII(CGOpenMPRuntimeNVPTX::ExecutionMode &Mode, bool IsSPMD)
150 : Mode(Mode) {
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000151 SavedMode = Mode;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000152 Mode = IsSPMD ? CGOpenMPRuntimeNVPTX::EM_SPMD
153 : CGOpenMPRuntimeNVPTX::EM_NonSPMD;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000154 }
155 ~ExecutionModeRAII() { Mode = SavedMode; }
156};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000157
158/// GPU Configuration: This information can be derived from cuda registers,
159/// however, providing compile time constants helps generate more efficient
160/// code. For all practical purposes this is fine because the configuration
161/// is the same for all known NVPTX architectures.
162enum MachineConfiguration : unsigned {
163 WarpSize = 32,
164 /// Number of bits required to represent a lane identifier, which is
165 /// computed as log_2(WarpSize).
166 LaneIDBits = 5,
167 LaneIDMask = WarpSize - 1,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +0000168
169 /// Global memory alignment for performance.
170 GlobalMemoryAlignment = 256,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000171};
172
173enum NamedBarrier : unsigned {
174 /// Synchronize on this barrier #ID using a named barrier primitive.
175 /// Only the subset of active threads in a parallel region arrive at the
176 /// barrier.
177 NB_Parallel = 1,
178};
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000179
180/// Get the list of variables that can escape their declaration context.
181class CheckVarsEscapingDeclContext final
182 : public ConstStmtVisitor<CheckVarsEscapingDeclContext> {
183 CodeGenFunction &CGF;
184 llvm::SetVector<const ValueDecl *> EscapedDecls;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000185 llvm::SetVector<const ValueDecl *> EscapedVariableLengthDecls;
Alexey Bataevc99042b2018-03-15 18:10:54 +0000186 llvm::SmallPtrSet<const Decl *, 4> EscapedParameters;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000187 bool AllEscaped = false;
188 RecordDecl *GlobalizedRD = nullptr;
189 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
190
Alexey Bataev03f270c2018-03-30 18:31:07 +0000191 static llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy>
192 isDeclareTargetDeclaration(const ValueDecl *VD) {
Alexey Bataev9ff80832018-04-16 20:16:21 +0000193 for (const Decl *D : VD->redecls()) {
Alexey Bataev03f270c2018-03-30 18:31:07 +0000194 if (!D->hasAttrs())
195 continue;
196 if (const auto *Attr = D->getAttr<OMPDeclareTargetDeclAttr>())
197 return Attr->getMapType();
198 }
199 return llvm::None;
200 }
201
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000202 void markAsEscaped(const ValueDecl *VD) {
Alexey Bataev03f270c2018-03-30 18:31:07 +0000203 // Do not globalize declare target variables.
204 if (isDeclareTargetDeclaration(VD))
205 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000206 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataevc99042b2018-03-15 18:10:54 +0000207 // Variables captured by value must be globalized.
208 if (auto *CSI = CGF.CapturedStmtInfo) {
Mikael Holmen9f373a32018-03-16 07:27:57 +0000209 if (const FieldDecl *FD = CSI->lookup(cast<VarDecl>(VD))) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000210 if (!FD->hasAttrs())
211 return;
212 const auto *Attr = FD->getAttr<OMPCaptureKindAttr>();
213 if (!Attr)
214 return;
215 if (!isOpenMPPrivate(
216 static_cast<OpenMPClauseKind>(Attr->getCaptureKind())) ||
217 Attr->getCaptureKind() == OMPC_map)
218 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +0000219 if (FD->getType()->isReferenceType())
220 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000221 assert(!VD->getType()->isVariablyModifiedType() &&
222 "Parameter captured by value with variably modified type");
Alexey Bataevc99042b2018-03-15 18:10:54 +0000223 EscapedParameters.insert(VD);
224 }
Alexey Bataev673110d2018-05-16 13:36:30 +0000225 } else if (VD->getType()->isReferenceType())
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000226 // Do not globalize variables with reference or pointer type.
227 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000228 if (VD->getType()->isVariablyModifiedType())
229 EscapedVariableLengthDecls.insert(VD);
230 else
231 EscapedDecls.insert(VD);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000232 }
233
234 void VisitValueDecl(const ValueDecl *VD) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000235 if (VD->getType()->isLValueReferenceType())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000236 markAsEscaped(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000237 if (const auto *VarD = dyn_cast<VarDecl>(VD)) {
238 if (!isa<ParmVarDecl>(VarD) && VarD->hasInit()) {
239 const bool SavedAllEscaped = AllEscaped;
240 AllEscaped = VD->getType()->isLValueReferenceType();
241 Visit(VarD->getInit());
242 AllEscaped = SavedAllEscaped;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000243 }
244 }
245 }
246 void VisitOpenMPCapturedStmt(const CapturedStmt *S) {
247 if (!S)
248 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000249 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000250 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
251 const ValueDecl *VD = C.getCapturedVar();
252 markAsEscaped(VD);
253 if (isa<OMPCapturedExprDecl>(VD))
254 VisitValueDecl(VD);
255 }
256 }
257 }
258
259 typedef std::pair<CharUnits /*Align*/, const ValueDecl *> VarsDataTy;
260 static bool stable_sort_comparator(const VarsDataTy P1, const VarsDataTy P2) {
261 return P1.first > P2.first;
262 }
263
264 void buildRecordForGlobalizedVars() {
265 assert(!GlobalizedRD &&
266 "Record for globalized variables is built already.");
267 if (EscapedDecls.empty())
268 return;
269 ASTContext &C = CGF.getContext();
270 SmallVector<VarsDataTy, 4> GlobalizedVars;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000271 for (const ValueDecl *D : EscapedDecls)
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000272 GlobalizedVars.emplace_back(C.getDeclAlign(D), D);
273 std::stable_sort(GlobalizedVars.begin(), GlobalizedVars.end(),
274 stable_sort_comparator);
275 // Build struct _globalized_locals_ty {
276 // /* globalized vars */
277 // };
278 GlobalizedRD = C.buildImplicitRecord("_globalized_locals_ty");
279 GlobalizedRD->startDefinition();
280 for (const auto &Pair : GlobalizedVars) {
281 const ValueDecl *VD = Pair.second;
282 QualType Type = VD->getType();
283 if (Type->isLValueReferenceType())
284 Type = C.getPointerType(Type.getNonReferenceType());
285 else
286 Type = Type.getNonReferenceType();
287 SourceLocation Loc = VD->getLocation();
288 auto *Field = FieldDecl::Create(
289 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
290 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
291 /*BW=*/nullptr, /*Mutable=*/false,
292 /*InitStyle=*/ICIS_NoInit);
293 Field->setAccess(AS_public);
294 GlobalizedRD->addDecl(Field);
295 if (VD->hasAttrs()) {
296 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
297 E(VD->getAttrs().end());
298 I != E; ++I)
299 Field->addAttr(*I);
300 }
301 MappedDeclsFields.try_emplace(VD, Field);
302 }
303 GlobalizedRD->completeDefinition();
304 }
305
306public:
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000307 CheckVarsEscapingDeclContext(CodeGenFunction &CGF) : CGF(CGF) {}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000308 virtual ~CheckVarsEscapingDeclContext() = default;
309 void VisitDeclStmt(const DeclStmt *S) {
310 if (!S)
311 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000312 for (const Decl *D : S->decls())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000313 if (const auto *VD = dyn_cast_or_null<ValueDecl>(D))
314 VisitValueDecl(VD);
315 }
316 void VisitOMPExecutableDirective(const OMPExecutableDirective *D) {
317 if (!D)
318 return;
319 if (D->hasAssociatedStmt()) {
320 if (const auto *S =
Alexey Bataev673110d2018-05-16 13:36:30 +0000321 dyn_cast_or_null<CapturedStmt>(D->getAssociatedStmt())) {
322 // Do not analyze directives that do not actually require capturing,
323 // like `omp for` or `omp simd` directives.
324 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
325 getOpenMPCaptureRegions(CaptureRegions, D->getDirectiveKind());
326 if (CaptureRegions.size() == 1 &&
327 CaptureRegions.back() == OMPD_unknown) {
328 VisitStmt(S->getCapturedStmt());
329 return;
330 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000331 VisitOpenMPCapturedStmt(S);
Alexey Bataev673110d2018-05-16 13:36:30 +0000332 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000333 }
334 }
335 void VisitCapturedStmt(const CapturedStmt *S) {
336 if (!S)
337 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000338 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000339 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
340 const ValueDecl *VD = C.getCapturedVar();
341 markAsEscaped(VD);
342 if (isa<OMPCapturedExprDecl>(VD))
343 VisitValueDecl(VD);
344 }
345 }
346 }
347 void VisitLambdaExpr(const LambdaExpr *E) {
348 if (!E)
349 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000350 for (const LambdaCapture &C : E->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000351 if (C.capturesVariable()) {
352 if (C.getCaptureKind() == LCK_ByRef) {
353 const ValueDecl *VD = C.getCapturedVar();
354 markAsEscaped(VD);
355 if (E->isInitCapture(&C) || isa<OMPCapturedExprDecl>(VD))
356 VisitValueDecl(VD);
357 }
358 }
359 }
360 }
361 void VisitBlockExpr(const BlockExpr *E) {
362 if (!E)
363 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000364 for (const BlockDecl::Capture &C : E->getBlockDecl()->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000365 if (C.isByRef()) {
366 const VarDecl *VD = C.getVariable();
367 markAsEscaped(VD);
368 if (isa<OMPCapturedExprDecl>(VD) || VD->isInitCapture())
369 VisitValueDecl(VD);
370 }
371 }
372 }
373 void VisitCallExpr(const CallExpr *E) {
374 if (!E)
375 return;
376 for (const Expr *Arg : E->arguments()) {
377 if (!Arg)
378 continue;
379 if (Arg->isLValue()) {
380 const bool SavedAllEscaped = AllEscaped;
381 AllEscaped = true;
382 Visit(Arg);
383 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000384 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000385 Visit(Arg);
Alexey Bataev9ff80832018-04-16 20:16:21 +0000386 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000387 }
388 Visit(E->getCallee());
389 }
390 void VisitDeclRefExpr(const DeclRefExpr *E) {
391 if (!E)
392 return;
393 const ValueDecl *VD = E->getDecl();
394 if (AllEscaped)
395 markAsEscaped(VD);
396 if (isa<OMPCapturedExprDecl>(VD))
397 VisitValueDecl(VD);
398 else if (const auto *VarD = dyn_cast<VarDecl>(VD))
399 if (VarD->isInitCapture())
400 VisitValueDecl(VD);
401 }
402 void VisitUnaryOperator(const UnaryOperator *E) {
403 if (!E)
404 return;
405 if (E->getOpcode() == UO_AddrOf) {
406 const bool SavedAllEscaped = AllEscaped;
407 AllEscaped = true;
408 Visit(E->getSubExpr());
409 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000410 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000411 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000412 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000413 }
414 void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
415 if (!E)
416 return;
417 if (E->getCastKind() == CK_ArrayToPointerDecay) {
418 const bool SavedAllEscaped = AllEscaped;
419 AllEscaped = true;
420 Visit(E->getSubExpr());
421 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000422 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000423 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000424 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000425 }
426 void VisitExpr(const Expr *E) {
427 if (!E)
428 return;
429 bool SavedAllEscaped = AllEscaped;
430 if (!E->isLValue())
431 AllEscaped = false;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000432 for (const Stmt *Child : E->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000433 if (Child)
434 Visit(Child);
435 AllEscaped = SavedAllEscaped;
436 }
437 void VisitStmt(const Stmt *S) {
438 if (!S)
439 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000440 for (const Stmt *Child : S->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000441 if (Child)
442 Visit(Child);
443 }
444
Alexey Bataevc99042b2018-03-15 18:10:54 +0000445 /// Returns the record that handles all the escaped local variables and used
446 /// instead of their original storage.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000447 const RecordDecl *getGlobalizedRecord() {
448 if (!GlobalizedRD)
449 buildRecordForGlobalizedVars();
450 return GlobalizedRD;
451 }
452
Alexey Bataevc99042b2018-03-15 18:10:54 +0000453 /// Returns the field in the globalized record for the escaped variable.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000454 const FieldDecl *getFieldForGlobalizedVar(const ValueDecl *VD) const {
455 assert(GlobalizedRD &&
456 "Record for globalized variables must be generated already.");
457 auto I = MappedDeclsFields.find(VD);
458 if (I == MappedDeclsFields.end())
459 return nullptr;
460 return I->getSecond();
461 }
462
Alexey Bataevc99042b2018-03-15 18:10:54 +0000463 /// Returns the list of the escaped local variables/parameters.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000464 ArrayRef<const ValueDecl *> getEscapedDecls() const {
465 return EscapedDecls.getArrayRef();
466 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000467
468 /// Checks if the escaped local variable is actually a parameter passed by
469 /// value.
470 const llvm::SmallPtrSetImpl<const Decl *> &getEscapedParameters() const {
471 return EscapedParameters;
472 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000473
474 /// Returns the list of the escaped variables with the variably modified
475 /// types.
476 ArrayRef<const ValueDecl *> getEscapedVariableLengthDecls() const {
477 return EscapedVariableLengthDecls.getArrayRef();
478 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000479};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000480} // anonymous namespace
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000481
482/// Get the GPU warp size.
483static llvm::Value *getNVPTXWarpSize(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000484 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000485 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000486 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_warpsize),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000487 "nvptx_warp_size");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000488}
489
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000490/// Get the id of the current thread on the GPU.
491static llvm::Value *getNVPTXThreadID(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000492 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000493 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000494 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_tid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000495 "nvptx_tid");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000496}
497
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000498/// Get the id of the warp in the block.
499/// We assume that the warp size is 32, which is always the case
500/// on the NVPTX device, to generate more efficient code.
501static llvm::Value *getNVPTXWarpID(CodeGenFunction &CGF) {
502 CGBuilderTy &Bld = CGF.Builder;
503 return Bld.CreateAShr(getNVPTXThreadID(CGF), LaneIDBits, "nvptx_warp_id");
504}
505
506/// Get the id of the current lane in the Warp.
507/// We assume that the warp size is 32, which is always the case
508/// on the NVPTX device, to generate more efficient code.
509static llvm::Value *getNVPTXLaneID(CodeGenFunction &CGF) {
510 CGBuilderTy &Bld = CGF.Builder;
511 return Bld.CreateAnd(getNVPTXThreadID(CGF), Bld.getInt32(LaneIDMask),
512 "nvptx_lane_id");
513}
514
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000515/// Get the maximum number of threads in a block of the GPU.
516static llvm::Value *getNVPTXNumThreads(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000517 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000518 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000519 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_ntid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000520 "nvptx_num_threads");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000521}
522
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000523/// Get barrier to synchronize all threads in a block.
524static void getNVPTXCTABarrier(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000525 CGF.EmitRuntimeCall(llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000526 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_barrier0));
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000527}
528
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000529/// Get barrier #ID to synchronize selected (multiple of warp size) threads in
530/// a CTA.
531static void getNVPTXBarrier(CodeGenFunction &CGF, int ID,
532 llvm::Value *NumThreads) {
533 CGBuilderTy &Bld = CGF.Builder;
534 llvm::Value *Args[] = {Bld.getInt32(ID), NumThreads};
Alexey Bataev3c595a62017-08-14 15:01:03 +0000535 CGF.EmitRuntimeCall(llvm::Intrinsic::getDeclaration(
536 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_barrier),
537 Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000538}
539
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000540/// Synchronize all GPU threads in a block.
541static void syncCTAThreads(CodeGenFunction &CGF) { getNVPTXCTABarrier(CGF); }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000542
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000543/// Synchronize worker threads in a parallel region.
544static void syncParallelThreads(CodeGenFunction &CGF, llvm::Value *NumThreads) {
545 return getNVPTXBarrier(CGF, NB_Parallel, NumThreads);
546}
547
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000548/// Get the value of the thread_limit clause in the teams directive.
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000549/// For the 'generic' execution mode, the runtime encodes thread_limit in
550/// the launch parameters, always starting thread_limit+warpSize threads per
551/// CTA. The threads in the last warp are reserved for master execution.
552/// For the 'spmd' execution mode, all threads in a CTA are part of the team.
553static llvm::Value *getThreadLimit(CodeGenFunction &CGF,
554 bool IsInSpmdExecutionMode = false) {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000555 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000556 return IsInSpmdExecutionMode
557 ? getNVPTXNumThreads(CGF)
Alexey Bataeve290ec02018-04-06 16:03:36 +0000558 : Bld.CreateNUWSub(getNVPTXNumThreads(CGF), getNVPTXWarpSize(CGF),
559 "thread_limit");
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000560}
561
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000562/// Get the thread id of the OMP master thread.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000563/// The master thread id is the first thread (lane) of the last warp in the
564/// GPU block. Warp size is assumed to be some power of 2.
565/// Thread id is 0 indexed.
566/// E.g: If NumThreads is 33, master id is 32.
567/// If NumThreads is 64, master id is 32.
568/// If NumThreads is 1024, master id is 992.
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000569static llvm::Value *getMasterThreadID(CodeGenFunction &CGF) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000570 CGBuilderTy &Bld = CGF.Builder;
571 llvm::Value *NumThreads = getNVPTXNumThreads(CGF);
572
573 // We assume that the warp size is a power of 2.
Alexey Bataeve290ec02018-04-06 16:03:36 +0000574 llvm::Value *Mask = Bld.CreateNUWSub(getNVPTXWarpSize(CGF), Bld.getInt32(1));
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000575
Alexey Bataeve290ec02018-04-06 16:03:36 +0000576 return Bld.CreateAnd(Bld.CreateNUWSub(NumThreads, Bld.getInt32(1)),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000577 Bld.CreateNot(Mask), "master_tid");
578}
579
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000580CGOpenMPRuntimeNVPTX::WorkerFunctionState::WorkerFunctionState(
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000581 CodeGenModule &CGM, SourceLocation Loc)
Alexey Bataev9ff80832018-04-16 20:16:21 +0000582 : WorkerFn(nullptr), CGFI(CGM.getTypes().arrangeNullaryFunction()),
583 Loc(Loc) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000584 createWorkerFunction(CGM);
Vasileios Kalintirise5c09592016-03-22 10:41:20 +0000585}
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000586
587void CGOpenMPRuntimeNVPTX::WorkerFunctionState::createWorkerFunction(
588 CodeGenModule &CGM) {
589 // Create an worker function with no arguments.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000590
591 WorkerFn = llvm::Function::Create(
Alexey Bataev9ff80832018-04-16 20:16:21 +0000592 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataevaee93892018-01-08 20:09:47 +0000593 /*placeholder=*/"_worker", &CGM.getModule());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000594 CGM.SetInternalFunctionAttributes(GlobalDecl(), WorkerFn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +0000595 WorkerFn->setDoesNotRecurse();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000596}
597
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000598CGOpenMPRuntimeNVPTX::ExecutionMode
599CGOpenMPRuntimeNVPTX::getExecutionMode() const {
600 return CurrentExecutionMode;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000601}
602
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000603static CGOpenMPRuntimeNVPTX::DataSharingMode
604getDataSharingMode(CodeGenModule &CGM) {
605 return CGM.getLangOpts().OpenMPCUDAMode ? CGOpenMPRuntimeNVPTX::CUDA
606 : CGOpenMPRuntimeNVPTX::Generic;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000607}
608
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000609/// Checks if the \p Body is the \a CompoundStmt and returns its child statement
610/// iff there is only one.
611static const Stmt *getSingleCompoundChild(const Stmt *Body) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000612 if (const auto *C = dyn_cast<CompoundStmt>(Body))
613 if (C->size() == 1)
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000614 return C->body_front();
615 return Body;
616}
617
618/// Check if the parallel directive has an 'if' clause with non-constant or
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000619/// false condition. Also, check if the number of threads is strictly specified
620/// and run those directives in non-SPMD mode.
621static bool hasParallelIfNumThreadsClause(ASTContext &Ctx,
622 const OMPExecutableDirective &D) {
623 if (D.hasClausesOfKind<OMPNumThreadsClause>())
624 return true;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000625 for (const auto *C : D.getClausesOfKind<OMPIfClause>()) {
626 OpenMPDirectiveKind NameModifier = C->getNameModifier();
627 if (NameModifier != OMPD_parallel && NameModifier != OMPD_unknown)
628 continue;
629 const Expr *Cond = C->getCondition();
630 bool Result;
631 if (!Cond->EvaluateAsBooleanCondition(Result, Ctx) || !Result)
632 return true;
633 }
634 return false;
635}
636
637/// Check for inner (nested) SPMD construct, if any
638static bool hasNestedSPMDDirective(ASTContext &Ctx,
639 const OMPExecutableDirective &D) {
640 const auto *CS = D.getInnermostCapturedStmt();
641 const auto *Body = CS->getCapturedStmt()->IgnoreContainers();
642 const Stmt *ChildStmt = getSingleCompoundChild(Body);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000643
644 if (const auto *NestedDir = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
645 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000646 switch (D.getDirectiveKind()) {
647 case OMPD_target:
Alexey Bataevdf093e72018-05-11 19:45:14 +0000648 if (isOpenMPParallelDirective(DKind) &&
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000649 !hasParallelIfNumThreadsClause(Ctx, *NestedDir))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000650 return true;
651 if (DKind == OMPD_teams || DKind == OMPD_teams_distribute) {
652 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers();
653 if (!Body)
654 return false;
655 ChildStmt = getSingleCompoundChild(Body);
656 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
657 DKind = NND->getDirectiveKind();
Alexey Bataevdf093e72018-05-11 19:45:14 +0000658 if (isOpenMPParallelDirective(DKind) &&
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000659 !hasParallelIfNumThreadsClause(Ctx, *NND))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000660 return true;
661 if (DKind == OMPD_distribute) {
662 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers();
663 if (!Body)
664 return false;
665 ChildStmt = getSingleCompoundChild(Body);
666 if (!ChildStmt)
667 return false;
668 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
669 DKind = NND->getDirectiveKind();
Alexey Bataevdf093e72018-05-11 19:45:14 +0000670 return isOpenMPParallelDirective(DKind) &&
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000671 !hasParallelIfNumThreadsClause(Ctx, *NND);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000672 }
673 }
674 }
675 }
676 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000677 case OMPD_target_teams:
Alexey Bataevdf093e72018-05-11 19:45:14 +0000678 if (isOpenMPParallelDirective(DKind) &&
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000679 !hasParallelIfNumThreadsClause(Ctx, *NestedDir))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000680 return true;
681 if (DKind == OMPD_distribute) {
682 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers();
683 if (!Body)
684 return false;
685 ChildStmt = getSingleCompoundChild(Body);
686 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
687 DKind = NND->getDirectiveKind();
Alexey Bataevdf093e72018-05-11 19:45:14 +0000688 return isOpenMPParallelDirective(DKind) &&
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000689 !hasParallelIfNumThreadsClause(Ctx, *NND);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000690 }
691 }
692 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000693 case OMPD_target_teams_distribute:
Alexey Bataevdf093e72018-05-11 19:45:14 +0000694 return isOpenMPParallelDirective(DKind) &&
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000695 !hasParallelIfNumThreadsClause(Ctx, *NestedDir);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000696 case OMPD_target_simd:
697 case OMPD_target_parallel:
698 case OMPD_target_parallel_for:
699 case OMPD_target_parallel_for_simd:
700 case OMPD_target_teams_distribute_simd:
701 case OMPD_target_teams_distribute_parallel_for:
702 case OMPD_target_teams_distribute_parallel_for_simd:
703 case OMPD_parallel:
704 case OMPD_for:
705 case OMPD_parallel_for:
706 case OMPD_parallel_sections:
707 case OMPD_for_simd:
708 case OMPD_parallel_for_simd:
709 case OMPD_cancel:
710 case OMPD_cancellation_point:
711 case OMPD_ordered:
712 case OMPD_threadprivate:
713 case OMPD_task:
714 case OMPD_simd:
715 case OMPD_sections:
716 case OMPD_section:
717 case OMPD_single:
718 case OMPD_master:
719 case OMPD_critical:
720 case OMPD_taskyield:
721 case OMPD_barrier:
722 case OMPD_taskwait:
723 case OMPD_taskgroup:
724 case OMPD_atomic:
725 case OMPD_flush:
726 case OMPD_teams:
727 case OMPD_target_data:
728 case OMPD_target_exit_data:
729 case OMPD_target_enter_data:
730 case OMPD_distribute:
731 case OMPD_distribute_simd:
732 case OMPD_distribute_parallel_for:
733 case OMPD_distribute_parallel_for_simd:
734 case OMPD_teams_distribute:
735 case OMPD_teams_distribute_simd:
736 case OMPD_teams_distribute_parallel_for:
737 case OMPD_teams_distribute_parallel_for_simd:
738 case OMPD_target_update:
739 case OMPD_declare_simd:
740 case OMPD_declare_target:
741 case OMPD_end_declare_target:
742 case OMPD_declare_reduction:
743 case OMPD_taskloop:
744 case OMPD_taskloop_simd:
745 case OMPD_unknown:
746 llvm_unreachable("Unexpected directive.");
747 }
748 }
749
750 return false;
751}
752
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000753static bool supportsSPMDExecutionMode(ASTContext &Ctx,
754 const OMPExecutableDirective &D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000755 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
756 switch (DirectiveKind) {
757 case OMPD_target:
758 case OMPD_target_teams:
759 case OMPD_target_teams_distribute:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000760 return hasNestedSPMDDirective(Ctx, D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000761 case OMPD_target_parallel:
762 case OMPD_target_parallel_for:
763 case OMPD_target_parallel_for_simd:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000764 case OMPD_target_teams_distribute_parallel_for:
765 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000766 return !hasParallelIfNumThreadsClause(Ctx, D);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000767 case OMPD_target_simd:
768 case OMPD_target_teams_distribute_simd:
Alexey Bataevdf093e72018-05-11 19:45:14 +0000769 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000770 case OMPD_parallel:
771 case OMPD_for:
772 case OMPD_parallel_for:
773 case OMPD_parallel_sections:
774 case OMPD_for_simd:
775 case OMPD_parallel_for_simd:
776 case OMPD_cancel:
777 case OMPD_cancellation_point:
778 case OMPD_ordered:
779 case OMPD_threadprivate:
780 case OMPD_task:
781 case OMPD_simd:
782 case OMPD_sections:
783 case OMPD_section:
784 case OMPD_single:
785 case OMPD_master:
786 case OMPD_critical:
787 case OMPD_taskyield:
788 case OMPD_barrier:
789 case OMPD_taskwait:
790 case OMPD_taskgroup:
791 case OMPD_atomic:
792 case OMPD_flush:
793 case OMPD_teams:
794 case OMPD_target_data:
795 case OMPD_target_exit_data:
796 case OMPD_target_enter_data:
797 case OMPD_distribute:
798 case OMPD_distribute_simd:
799 case OMPD_distribute_parallel_for:
800 case OMPD_distribute_parallel_for_simd:
801 case OMPD_teams_distribute:
802 case OMPD_teams_distribute_simd:
803 case OMPD_teams_distribute_parallel_for:
804 case OMPD_teams_distribute_parallel_for_simd:
805 case OMPD_target_update:
806 case OMPD_declare_simd:
807 case OMPD_declare_target:
808 case OMPD_end_declare_target:
809 case OMPD_declare_reduction:
810 case OMPD_taskloop:
811 case OMPD_taskloop_simd:
812 case OMPD_unknown:
813 break;
814 }
815 llvm_unreachable(
816 "Unknown programming model for OpenMP directive on NVPTX target.");
817}
818
819void CGOpenMPRuntimeNVPTX::emitNonSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000820 StringRef ParentName,
821 llvm::Function *&OutlinedFn,
822 llvm::Constant *&OutlinedFnID,
823 bool IsOffloadEntry,
824 const RegionCodeGenTy &CodeGen) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000825 ExecutionModeRAII ModeRAII(CurrentExecutionMode, /*IsSPMD=*/false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000826 EntryFunctionState EST;
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000827 WorkerFunctionState WST(CGM, D.getLocStart());
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000828 Work.clear();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000829 WrapperFunctionsMap.clear();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000830
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000831 // Emit target region as a standalone region.
832 class NVPTXPrePostActionTy : public PrePostActionTy {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000833 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
834 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000835
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000836 public:
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000837 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000838 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST)
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000839 : EST(EST), WST(WST) {}
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000840 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000841 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000842 .emitNonSPMDEntryHeader(CGF, EST, WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000843 }
844 void Exit(CodeGenFunction &CGF) override {
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000845 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000846 .emitNonSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000847 }
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000848 } Action(EST, WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000849 CodeGen.setAction(Action);
850 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
851 IsOffloadEntry, CodeGen);
852
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000853 // Now change the name of the worker function to correspond to this target
854 // region's entry function.
Alexey Bataev9ff80832018-04-16 20:16:21 +0000855 WST.WorkerFn->setName(Twine(OutlinedFn->getName(), "_worker"));
Alexey Bataevaee93892018-01-08 20:09:47 +0000856
857 // Create the worker function
858 emitWorkerFunction(WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000859}
860
861// Setup NVPTX threads for master-worker OpenMP scheme.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000862void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryHeader(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000863 EntryFunctionState &EST,
864 WorkerFunctionState &WST) {
865 CGBuilderTy &Bld = CGF.Builder;
866
867 llvm::BasicBlock *WorkerBB = CGF.createBasicBlock(".worker");
868 llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
869 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
870 EST.ExitBB = CGF.createBasicBlock(".exit");
871
Alexey Bataev9ff80832018-04-16 20:16:21 +0000872 llvm::Value *IsWorker =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000873 Bld.CreateICmpULT(getNVPTXThreadID(CGF), getThreadLimit(CGF));
874 Bld.CreateCondBr(IsWorker, WorkerBB, MasterCheckBB);
875
876 CGF.EmitBlock(WorkerBB);
Alexey Bataevb7f3cba2018-03-19 17:04:07 +0000877 emitCall(CGF, WST.Loc, WST.WorkerFn);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000878 CGF.EmitBranch(EST.ExitBB);
879
880 CGF.EmitBlock(MasterCheckBB);
Alexey Bataev9ff80832018-04-16 20:16:21 +0000881 llvm::Value *IsMaster =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000882 Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
883 Bld.CreateCondBr(IsMaster, MasterBB, EST.ExitBB);
884
885 CGF.EmitBlock(MasterBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000886 IsInTargetMasterThreadRegion = true;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000887 // SEQUENTIAL (MASTER) REGION START
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000888 // First action in sequential region:
889 // Initialize the state of the OpenMP runtime library on the GPU.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +0000890 // TODO: Optimize runtime initialization and pass in correct value.
891 llvm::Value *Args[] = {getThreadLimit(CGF),
892 Bld.getInt16(/*RequiresOMPRuntime=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000893 CGF.EmitRuntimeCall(
894 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_init), Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000895
896 // For data sharing, we need to initialize the stack.
897 CGF.EmitRuntimeCall(
898 createNVPTXRuntimeFunction(
899 OMPRTL_NVPTX__kmpc_data_sharing_init_stack));
900
Alexey Bataevc99042b2018-03-15 18:10:54 +0000901 emitGenericVarsProlog(CGF, WST.Loc);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000902}
903
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000904void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000905 EntryFunctionState &EST) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000906 IsInTargetMasterThreadRegion = false;
Alexey Bataevc99042b2018-03-15 18:10:54 +0000907 if (!CGF.HaveInsertPoint())
908 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000909
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000910 emitGenericVarsEpilog(CGF);
911
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000912 if (!EST.ExitBB)
913 EST.ExitBB = CGF.createBasicBlock(".exit");
914
915 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".termination.notifier");
916 CGF.EmitBranch(TerminateBB);
917
918 CGF.EmitBlock(TerminateBB);
919 // Signal termination condition.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +0000920 // TODO: Optimize runtime initialization and pass in correct value.
921 llvm::Value *Args[] = {CGF.Builder.getInt16(/*IsOMPRuntimeInitialized=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000922 CGF.EmitRuntimeCall(
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +0000923 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_deinit), Args);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000924 // Barrier to terminate worker threads.
925 syncCTAThreads(CGF);
926 // Master thread jumps to exit point.
927 CGF.EmitBranch(EST.ExitBB);
928
929 CGF.EmitBlock(EST.ExitBB);
930 EST.ExitBB = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000931}
932
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000933void CGOpenMPRuntimeNVPTX::emitSpmdKernel(const OMPExecutableDirective &D,
934 StringRef ParentName,
935 llvm::Function *&OutlinedFn,
936 llvm::Constant *&OutlinedFnID,
937 bool IsOffloadEntry,
938 const RegionCodeGenTy &CodeGen) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000939 ExecutionModeRAII ModeRAII(CurrentExecutionMode, /*IsSPMD=*/true);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000940 EntryFunctionState EST;
941
942 // Emit target region as a standalone region.
943 class NVPTXPrePostActionTy : public PrePostActionTy {
944 CGOpenMPRuntimeNVPTX &RT;
945 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
946 const OMPExecutableDirective &D;
947
948 public:
949 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT,
950 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
951 const OMPExecutableDirective &D)
952 : RT(RT), EST(EST), D(D) {}
953 void Enter(CodeGenFunction &CGF) override {
954 RT.emitSpmdEntryHeader(CGF, EST, D);
955 }
956 void Exit(CodeGenFunction &CGF) override {
957 RT.emitSpmdEntryFooter(CGF, EST);
958 }
959 } Action(*this, EST, D);
960 CodeGen.setAction(Action);
961 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
962 IsOffloadEntry, CodeGen);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000963}
964
965void CGOpenMPRuntimeNVPTX::emitSpmdEntryHeader(
966 CodeGenFunction &CGF, EntryFunctionState &EST,
967 const OMPExecutableDirective &D) {
Alexey Bataev9ff80832018-04-16 20:16:21 +0000968 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000969
970 // Setup BBs in entry function.
971 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute");
972 EST.ExitBB = CGF.createBasicBlock(".exit");
973
974 // Initialize the OMP state in the runtime; called by all active threads.
975 // TODO: Set RequiresOMPRuntime and RequiresDataSharing parameters
976 // based on code analysis of the target region.
977 llvm::Value *Args[] = {getThreadLimit(CGF, /*IsInSpmdExecutionMode=*/true),
978 /*RequiresOMPRuntime=*/Bld.getInt16(1),
979 /*RequiresDataSharing=*/Bld.getInt16(1)};
980 CGF.EmitRuntimeCall(
981 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_init), Args);
982 CGF.EmitBranch(ExecuteBB);
983
984 CGF.EmitBlock(ExecuteBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000985
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000986 IsInTargetMasterThreadRegion = true;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000987}
988
989void CGOpenMPRuntimeNVPTX::emitSpmdEntryFooter(CodeGenFunction &CGF,
990 EntryFunctionState &EST) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000991 IsInTargetMasterThreadRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000992 if (!CGF.HaveInsertPoint())
993 return;
994
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000995 if (!EST.ExitBB)
996 EST.ExitBB = CGF.createBasicBlock(".exit");
997
998 llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit");
999 CGF.EmitBranch(OMPDeInitBB);
1000
1001 CGF.EmitBlock(OMPDeInitBB);
1002 // DeInitialize the OMP state in the runtime; called by all active threads.
1003 CGF.EmitRuntimeCall(
1004 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_deinit), None);
1005 CGF.EmitBranch(EST.ExitBB);
1006
1007 CGF.EmitBlock(EST.ExitBB);
1008 EST.ExitBB = nullptr;
1009}
1010
1011// Create a unique global variable to indicate the execution mode of this target
1012// region. The execution mode is either 'generic', or 'spmd' depending on the
1013// target directive. This variable is picked up by the offload library to setup
1014// the device appropriately before kernel launch. If the execution mode is
1015// 'generic', the runtime reserves one warp for the master, otherwise, all
1016// warps participate in parallel work.
1017static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001018 bool Mode) {
1019 auto *GVMode =
1020 new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
1021 llvm::GlobalValue::WeakAnyLinkage,
1022 llvm::ConstantInt::get(CGM.Int8Ty, Mode ? 0 : 1),
1023 Twine(Name, "_exec_mode"));
Alexey Bataev9ff80832018-04-16 20:16:21 +00001024 CGM.addCompilerUsedGlobal(GVMode);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001025}
1026
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001027void CGOpenMPRuntimeNVPTX::emitWorkerFunction(WorkerFunctionState &WST) {
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +00001028 ASTContext &Ctx = CGM.getContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001029
1030 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001031 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, WST.CGFI, {},
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001032 WST.Loc, WST.Loc);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001033 emitWorkerLoop(CGF, WST);
1034 CGF.FinishFunction();
1035}
1036
1037void CGOpenMPRuntimeNVPTX::emitWorkerLoop(CodeGenFunction &CGF,
1038 WorkerFunctionState &WST) {
1039 //
1040 // The workers enter this loop and wait for parallel work from the master.
1041 // When the master encounters a parallel region it sets up the work + variable
1042 // arguments, and wakes up the workers. The workers first check to see if
1043 // they are required for the parallel region, i.e., within the # of requested
1044 // parallel threads. The activated workers load the variable arguments and
1045 // execute the parallel work.
1046 //
1047
1048 CGBuilderTy &Bld = CGF.Builder;
1049
1050 llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work");
1051 llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers");
1052 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel");
1053 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel");
1054 llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel");
1055 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1056
1057 CGF.EmitBranch(AwaitBB);
1058
1059 // Workers wait for work from master.
1060 CGF.EmitBlock(AwaitBB);
1061 // Wait for parallel work
1062 syncCTAThreads(CGF);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001063
Gheorghe-Teodor Bercea36cdfad2018-03-22 17:33:27 +00001064 // For data sharing, we need to initialize the stack for workers.
1065 CGF.EmitRuntimeCall(
1066 createNVPTXRuntimeFunction(
1067 OMPRTL_NVPTX__kmpc_data_sharing_init_stack));
1068
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001069 Address WorkFn =
1070 CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn");
1071 Address ExecStatus =
1072 CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status");
1073 CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0));
1074 CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy));
1075
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001076 // TODO: Optimize runtime initialization and pass in correct value.
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001077 llvm::Value *Args[] = {WorkFn.getPointer(),
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001078 /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001079 llvm::Value *Ret = CGF.EmitRuntimeCall(
1080 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args);
1081 Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001082
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001083 // On termination condition (workid == 0), exit loop.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001084 llvm::Value *WorkID = Bld.CreateLoad(WorkFn);
1085 llvm::Value *ShouldTerminate = Bld.CreateIsNull(WorkID, "should_terminate");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001086 Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB);
1087
1088 // Activate requested workers.
1089 CGF.EmitBlock(SelectWorkersBB);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001090 llvm::Value *IsActive =
1091 Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active");
1092 Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001093
1094 // Signal start of parallel region.
1095 CGF.EmitBlock(ExecuteBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001096
1097 // Process work items: outlined parallel functions.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001098 for (llvm::Function *W : Work) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001099 // Try to match this outlined function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001100 llvm::Value *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001101
1102 llvm::Value *WorkFnMatch =
1103 Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match");
1104
1105 llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn");
1106 llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next");
1107 Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB);
1108
1109 // Execute this outlined function.
1110 CGF.EmitBlock(ExecuteFNBB);
1111
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001112 // Insert call to work function via shared wrapper. The shared
1113 // wrapper takes two arguments:
1114 // - the parallelism level;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001115 // - the thread ID;
1116 emitCall(CGF, WST.Loc, W,
1117 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001118
1119 // Go to end of parallel region.
1120 CGF.EmitBranch(TerminateBB);
1121
1122 CGF.EmitBlock(CheckNextBB);
1123 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001124 // Default case: call to outlined function through pointer if the target
1125 // region makes a declare target call that may contain an orphaned parallel
1126 // directive.
1127 auto *ParallelFnTy =
1128 llvm::FunctionType::get(CGM.VoidTy, {CGM.Int16Ty, CGM.Int32Ty},
1129 /*isVarArg=*/false)
1130 ->getPointerTo();
1131 llvm::Value *WorkFnCast = Bld.CreateBitCast(WorkID, ParallelFnTy);
1132 // Insert call to work function via shared wrapper. The shared
1133 // wrapper takes two arguments:
1134 // - the parallelism level;
1135 // - the thread ID;
1136 emitCall(CGF, WST.Loc, WorkFnCast,
1137 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
1138 // Go to end of parallel region.
1139 CGF.EmitBranch(TerminateBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001140
1141 // Signal end of parallel region.
1142 CGF.EmitBlock(TerminateBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001143 CGF.EmitRuntimeCall(
1144 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_end_parallel),
1145 llvm::None);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001146 CGF.EmitBranch(BarrierBB);
1147
1148 // All active and inactive workers wait at a barrier after parallel region.
1149 CGF.EmitBlock(BarrierBB);
1150 // Barrier after parallel region.
1151 syncCTAThreads(CGF);
1152 CGF.EmitBranch(AwaitBB);
1153
1154 // Exit target region.
1155 CGF.EmitBlock(ExitBB);
1156}
1157
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001158/// Returns specified OpenMP runtime function for the current OpenMP
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001159/// implementation. Specialized for the NVPTX device.
1160/// \param Function OpenMP runtime function.
1161/// \return Specified function.
1162llvm::Constant *
1163CGOpenMPRuntimeNVPTX::createNVPTXRuntimeFunction(unsigned Function) {
1164 llvm::Constant *RTLFn = nullptr;
1165 switch (static_cast<OpenMPRTLFunctionNVPTX>(Function)) {
1166 case OMPRTL_NVPTX__kmpc_kernel_init: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001167 // Build void __kmpc_kernel_init(kmp_int32 thread_limit, int16_t
1168 // RequiresOMPRuntime);
1169 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001170 auto *FnTy =
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001171 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1172 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_init");
1173 break;
1174 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001175 case OMPRTL_NVPTX__kmpc_kernel_deinit: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001176 // Build void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
1177 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001178 auto *FnTy =
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001179 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001180 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_deinit");
1181 break;
1182 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001183 case OMPRTL_NVPTX__kmpc_spmd_kernel_init: {
1184 // Build void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001185 // int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001186 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001187 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001188 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1189 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_init");
1190 break;
1191 }
1192 case OMPRTL_NVPTX__kmpc_spmd_kernel_deinit: {
1193 // Build void __kmpc_spmd_kernel_deinit();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001194 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001195 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1196 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_deinit");
1197 break;
1198 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001199 case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: {
1200 /// Build void __kmpc_kernel_prepare_parallel(
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001201 /// void *outlined_function, int16_t IsOMPRuntimeInitialized);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001202 llvm::Type *TypeParams[] = {CGM.Int8PtrTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001203 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001204 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1205 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_prepare_parallel");
1206 break;
1207 }
1208 case OMPRTL_NVPTX__kmpc_kernel_parallel: {
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001209 /// Build bool __kmpc_kernel_parallel(void **outlined_function,
1210 /// int16_t IsOMPRuntimeInitialized);
1211 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy, CGM.Int16Ty};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001212 llvm::Type *RetTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001213 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001214 llvm::FunctionType::get(RetTy, TypeParams, /*isVarArg*/ false);
1215 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_parallel");
1216 break;
1217 }
1218 case OMPRTL_NVPTX__kmpc_kernel_end_parallel: {
1219 /// Build void __kmpc_kernel_end_parallel();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001220 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001221 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1222 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_end_parallel");
1223 break;
1224 }
1225 case OMPRTL_NVPTX__kmpc_serialized_parallel: {
1226 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1227 // global_tid);
1228 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001229 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001230 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1231 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1232 break;
1233 }
1234 case OMPRTL_NVPTX__kmpc_end_serialized_parallel: {
1235 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1236 // global_tid);
1237 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001238 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001239 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1240 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1241 break;
1242 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001243 case OMPRTL_NVPTX__kmpc_shuffle_int32: {
1244 // Build int32_t __kmpc_shuffle_int32(int32_t element,
1245 // int16_t lane_offset, int16_t warp_size);
1246 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001247 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001248 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1249 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int32");
1250 break;
1251 }
1252 case OMPRTL_NVPTX__kmpc_shuffle_int64: {
1253 // Build int64_t __kmpc_shuffle_int64(int64_t element,
1254 // int16_t lane_offset, int16_t warp_size);
1255 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001256 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001257 llvm::FunctionType::get(CGM.Int64Ty, TypeParams, /*isVarArg*/ false);
1258 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int64");
1259 break;
1260 }
1261 case OMPRTL_NVPTX__kmpc_parallel_reduce_nowait: {
1262 // Build int32_t kmpc_nvptx_parallel_reduce_nowait(kmp_int32 global_tid,
1263 // kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
1264 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1265 // lane_offset, int16_t Algorithm Version),
1266 // void (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
1267 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1268 CGM.Int16Ty, CGM.Int16Ty};
1269 auto *ShuffleReduceFnTy =
1270 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1271 /*isVarArg=*/false);
1272 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1273 auto *InterWarpCopyFnTy =
1274 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1275 /*isVarArg=*/false);
1276 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1277 CGM.Int32Ty,
1278 CGM.SizeTy,
1279 CGM.VoidPtrTy,
1280 ShuffleReduceFnTy->getPointerTo(),
1281 InterWarpCopyFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001282 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001283 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1284 RTLFn = CGM.CreateRuntimeFunction(
1285 FnTy, /*Name=*/"__kmpc_nvptx_parallel_reduce_nowait");
1286 break;
1287 }
Alexey Bataevfac26cf2018-05-02 20:03:27 +00001288 case OMPRTL_NVPTX__kmpc_simd_reduce_nowait: {
1289 // Build int32_t kmpc_nvptx_simd_reduce_nowait(kmp_int32 global_tid,
1290 // kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
1291 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1292 // lane_offset, int16_t Algorithm Version),
1293 // void (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
1294 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1295 CGM.Int16Ty, CGM.Int16Ty};
1296 auto *ShuffleReduceFnTy =
1297 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1298 /*isVarArg=*/false);
1299 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1300 auto *InterWarpCopyFnTy =
1301 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1302 /*isVarArg=*/false);
1303 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1304 CGM.Int32Ty,
1305 CGM.SizeTy,
1306 CGM.VoidPtrTy,
1307 ShuffleReduceFnTy->getPointerTo(),
1308 InterWarpCopyFnTy->getPointerTo()};
1309 auto *FnTy =
1310 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1311 RTLFn = CGM.CreateRuntimeFunction(
1312 FnTy, /*Name=*/"__kmpc_nvptx_simd_reduce_nowait");
1313 break;
1314 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001315 case OMPRTL_NVPTX__kmpc_teams_reduce_nowait: {
1316 // Build int32_t __kmpc_nvptx_teams_reduce_nowait(int32_t global_tid,
1317 // int32_t num_vars, size_t reduce_size, void *reduce_data,
1318 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1319 // lane_offset, int16_t shortCircuit),
1320 // void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num),
1321 // void (*kmp_CopyToScratchpadFctPtr)(void *reduce_data, void * scratchpad,
1322 // int32_t index, int32_t width),
1323 // void (*kmp_LoadReduceFctPtr)(void *reduce_data, void * scratchpad,
1324 // int32_t index, int32_t width, int32_t reduce))
1325 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1326 CGM.Int16Ty, CGM.Int16Ty};
1327 auto *ShuffleReduceFnTy =
1328 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1329 /*isVarArg=*/false);
1330 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1331 auto *InterWarpCopyFnTy =
1332 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1333 /*isVarArg=*/false);
1334 llvm::Type *CopyToScratchpadTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy,
1335 CGM.Int32Ty, CGM.Int32Ty};
1336 auto *CopyToScratchpadFnTy =
1337 llvm::FunctionType::get(CGM.VoidTy, CopyToScratchpadTypeParams,
1338 /*isVarArg=*/false);
1339 llvm::Type *LoadReduceTypeParams[] = {
1340 CGM.VoidPtrTy, CGM.VoidPtrTy, CGM.Int32Ty, CGM.Int32Ty, CGM.Int32Ty};
1341 auto *LoadReduceFnTy =
1342 llvm::FunctionType::get(CGM.VoidTy, LoadReduceTypeParams,
1343 /*isVarArg=*/false);
1344 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1345 CGM.Int32Ty,
1346 CGM.SizeTy,
1347 CGM.VoidPtrTy,
1348 ShuffleReduceFnTy->getPointerTo(),
1349 InterWarpCopyFnTy->getPointerTo(),
1350 CopyToScratchpadFnTy->getPointerTo(),
1351 LoadReduceFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001352 auto *FnTy =
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001353 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1354 RTLFn = CGM.CreateRuntimeFunction(
1355 FnTy, /*Name=*/"__kmpc_nvptx_teams_reduce_nowait");
1356 break;
1357 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001358 case OMPRTL_NVPTX__kmpc_end_reduce_nowait: {
1359 // Build __kmpc_end_reduce_nowait(kmp_int32 global_tid);
1360 llvm::Type *TypeParams[] = {CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001361 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001362 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1363 RTLFn = CGM.CreateRuntimeFunction(
1364 FnTy, /*Name=*/"__kmpc_nvptx_end_reduce_nowait");
1365 break;
1366 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001367 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack: {
1368 /// Build void __kmpc_data_sharing_init_stack();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001369 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001370 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1371 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack");
1372 break;
1373 }
1374 case OMPRTL_NVPTX__kmpc_data_sharing_push_stack: {
1375 // Build void *__kmpc_data_sharing_push_stack(size_t size,
1376 // int16_t UseSharedMemory);
1377 llvm::Type *TypeParams[] = {CGM.SizeTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001378 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001379 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1380 RTLFn = CGM.CreateRuntimeFunction(
1381 FnTy, /*Name=*/"__kmpc_data_sharing_push_stack");
1382 break;
1383 }
1384 case OMPRTL_NVPTX__kmpc_data_sharing_pop_stack: {
1385 // Build void __kmpc_data_sharing_pop_stack(void *a);
1386 llvm::Type *TypeParams[] = {CGM.VoidPtrTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001387 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001388 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1389 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1390 /*Name=*/"__kmpc_data_sharing_pop_stack");
1391 break;
1392 }
1393 case OMPRTL_NVPTX__kmpc_begin_sharing_variables: {
1394 /// Build void __kmpc_begin_sharing_variables(void ***args,
1395 /// size_t n_args);
1396 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo(), CGM.SizeTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001397 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001398 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1399 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_begin_sharing_variables");
1400 break;
1401 }
1402 case OMPRTL_NVPTX__kmpc_end_sharing_variables: {
1403 /// Build void __kmpc_end_sharing_variables();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001404 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001405 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1406 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_sharing_variables");
1407 break;
1408 }
1409 case OMPRTL_NVPTX__kmpc_get_shared_variables: {
1410 /// Build void __kmpc_get_shared_variables(void ***GlobalArgs);
1411 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001412 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001413 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1414 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_shared_variables");
1415 break;
1416 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001417 case OMPRTL_NVPTX__kmpc_parallel_level: {
1418 // Build uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32 global_tid);
1419 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1420 auto *FnTy =
1421 llvm::FunctionType::get(CGM.Int16Ty, TypeParams, /*isVarArg*/ false);
1422 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_parallel_level");
1423 break;
1424 }
Alexey Bataev673110d2018-05-16 13:36:30 +00001425 case OMPRTL_NVPTX__kmpc_is_spmd_exec_mode: {
1426 // Build int8_t __kmpc_is_spmd_exec_mode();
1427 auto *FnTy = llvm::FunctionType::get(CGM.Int8Ty, /*isVarArg=*/false);
1428 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_is_spmd_exec_mode");
1429 break;
1430 }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001431 }
1432 return RTLFn;
1433}
1434
1435void CGOpenMPRuntimeNVPTX::createOffloadEntry(llvm::Constant *ID,
1436 llvm::Constant *Addr,
Alexey Bataev03f270c2018-03-30 18:31:07 +00001437 uint64_t Size, int32_t,
1438 llvm::GlobalValue::LinkageTypes) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001439 // TODO: Add support for global variables on the device after declare target
1440 // support.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001441 if (!isa<llvm::Function>(Addr))
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001442 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +00001443 llvm::Module &M = CGM.getModule();
1444 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001445
1446 // Get "nvvm.annotations" metadata node
Alexey Bataev9ff80832018-04-16 20:16:21 +00001447 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001448
1449 llvm::Metadata *MDVals[] = {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001450 llvm::ConstantAsMetadata::get(Addr), llvm::MDString::get(Ctx, "kernel"),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001451 llvm::ConstantAsMetadata::get(
1452 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))};
1453 // Append metadata to nvvm.annotations
1454 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
1455}
1456
1457void CGOpenMPRuntimeNVPTX::emitTargetOutlinedFunction(
1458 const OMPExecutableDirective &D, StringRef ParentName,
1459 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001460 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001461 if (!IsOffloadEntry) // Nothing to do.
1462 return;
1463
1464 assert(!ParentName.empty() && "Invalid target region parent name!");
1465
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001466 bool Mode = supportsSPMDExecutionMode(CGM.getContext(), D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001467 if (Mode)
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001468 emitSpmdKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1469 CodeGen);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001470 else
1471 emitNonSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1472 CodeGen);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001473
1474 setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001475}
1476
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001477CGOpenMPRuntimeNVPTX::CGOpenMPRuntimeNVPTX(CodeGenModule &CGM)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001478 : CGOpenMPRuntime(CGM, "_", "$") {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001479 if (!CGM.getLangOpts().OpenMPIsDevice)
1480 llvm_unreachable("OpenMP NVPTX can only handle device code.");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001481}
Carlo Bertollic6872252016-04-04 15:55:02 +00001482
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001483void CGOpenMPRuntimeNVPTX::emitProcBindClause(CodeGenFunction &CGF,
1484 OpenMPProcBindClauseKind ProcBind,
1485 SourceLocation Loc) {
1486 // Do nothing in case of Spmd mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001487 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001488 return;
1489
1490 CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc);
1491}
1492
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001493void CGOpenMPRuntimeNVPTX::emitNumThreadsClause(CodeGenFunction &CGF,
1494 llvm::Value *NumThreads,
1495 SourceLocation Loc) {
1496 // Do nothing in case of Spmd mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001497 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001498 return;
1499
1500 CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc);
1501}
1502
Carlo Bertollic6872252016-04-04 15:55:02 +00001503void CGOpenMPRuntimeNVPTX::emitNumTeamsClause(CodeGenFunction &CGF,
1504 const Expr *NumTeams,
1505 const Expr *ThreadLimit,
1506 SourceLocation Loc) {}
1507
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001508llvm::Value *CGOpenMPRuntimeNVPTX::emitParallelOutlinedFunction(
1509 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1510 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00001511 SourceLocation Loc = D.getLocStart();
1512
1513 // Emit target region as a standalone region.
1514 class NVPTXPrePostActionTy : public PrePostActionTy {
1515 SourceLocation &Loc;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001516 bool &IsInParallelRegion;
1517 bool PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001518
1519 public:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001520 NVPTXPrePostActionTy(SourceLocation &Loc, bool &IsInParallelRegion)
1521 : Loc(Loc), IsInParallelRegion(IsInParallelRegion) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00001522 void Enter(CodeGenFunction &CGF) override {
1523 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
1524 .emitGenericVarsProlog(CGF, Loc);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001525 PrevIsInParallelRegion = IsInParallelRegion;
1526 IsInParallelRegion = true;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001527 }
1528 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001529 IsInParallelRegion = PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001530 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
1531 .emitGenericVarsEpilog(CGF);
1532 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001533 } Action(Loc, IsInParallelRegion);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001534 CodeGen.setAction(Action);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001535 bool PrevIsInTargetMasterThreadRegion = IsInTargetMasterThreadRegion;
1536 IsInTargetMasterThreadRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001537 auto *OutlinedFun =
1538 cast<llvm::Function>(CGOpenMPRuntime::emitParallelOutlinedFunction(
1539 D, ThreadIDVar, InnermostKind, CodeGen));
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001540 IsInTargetMasterThreadRegion = PrevIsInTargetMasterThreadRegion;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001541 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD &&
1542 !IsInParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001543 llvm::Function *WrapperFun =
1544 createParallelDataSharingWrapper(OutlinedFun, D);
1545 WrapperFunctionsMap[OutlinedFun] = WrapperFun;
1546 }
1547
1548 return OutlinedFun;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001549}
1550
1551llvm::Value *CGOpenMPRuntimeNVPTX::emitTeamsOutlinedFunction(
Carlo Bertollic6872252016-04-04 15:55:02 +00001552 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1553 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00001554 SourceLocation Loc = D.getLocStart();
Carlo Bertollic6872252016-04-04 15:55:02 +00001555
Alexey Bataevc99042b2018-03-15 18:10:54 +00001556 // Emit target region as a standalone region.
1557 class NVPTXPrePostActionTy : public PrePostActionTy {
1558 SourceLocation &Loc;
1559
1560 public:
1561 NVPTXPrePostActionTy(SourceLocation &Loc) : Loc(Loc) {}
1562 void Enter(CodeGenFunction &CGF) override {
1563 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
1564 .emitGenericVarsProlog(CGF, Loc);
1565 }
1566 void Exit(CodeGenFunction &CGF) override {
1567 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
1568 .emitGenericVarsEpilog(CGF);
1569 }
1570 } Action(Loc);
1571 CodeGen.setAction(Action);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001572 llvm::Value *OutlinedFunVal = CGOpenMPRuntime::emitTeamsOutlinedFunction(
1573 D, ThreadIDVar, InnermostKind, CodeGen);
1574 llvm::Function *OutlinedFun = cast<llvm::Function>(OutlinedFunVal);
1575 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001576 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001577 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
Carlo Bertollic6872252016-04-04 15:55:02 +00001578
1579 return OutlinedFun;
1580}
1581
Alexey Bataevc99042b2018-03-15 18:10:54 +00001582void CGOpenMPRuntimeNVPTX::emitGenericVarsProlog(CodeGenFunction &CGF,
1583 SourceLocation Loc) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001584 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
1585 return;
1586
Alexey Bataevc99042b2018-03-15 18:10:54 +00001587 CGBuilderTy &Bld = CGF.Builder;
1588
1589 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
1590 if (I == FunctionGlobalizedDecls.end())
1591 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001592 if (const RecordDecl *GlobalizedVarsRecord = I->getSecond().GlobalRecord) {
1593 QualType RecTy = CGM.getContext().getRecordType(GlobalizedVarsRecord);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001594
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001595 // Recover pointer to this function's global record. The runtime will
1596 // handle the specifics of the allocation of the memory.
1597 // Use actual memory size of the record including the padding
1598 // for alignment purposes.
1599 unsigned Alignment =
1600 CGM.getContext().getTypeAlignInChars(RecTy).getQuantity();
1601 unsigned GlobalRecordSize =
1602 CGM.getContext().getTypeSizeInChars(RecTy).getQuantity();
1603 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
1604 // TODO: allow the usage of shared memory to be controlled by
1605 // the user, for now, default to global.
1606 llvm::Value *GlobalRecordSizeArg[] = {
1607 llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize),
1608 CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
1609 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
1610 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_push_stack),
1611 GlobalRecordSizeArg);
1612 llvm::Value *GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
1613 GlobalRecValue, CGF.ConvertTypeForMem(RecTy)->getPointerTo());
1614 LValue Base =
1615 CGF.MakeNaturalAlignPointeeAddrLValue(GlobalRecCastAddr, RecTy);
1616 I->getSecond().GlobalRecordAddr = GlobalRecValue;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001617
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001618 // Emit the "global alloca" which is a GEP from the global declaration
1619 // record using the pointer returned by the runtime.
1620 for (auto &Rec : I->getSecond().LocalVarData) {
1621 bool EscapedParam = I->getSecond().EscapedParameters.count(Rec.first);
1622 llvm::Value *ParValue;
1623 if (EscapedParam) {
1624 const auto *VD = cast<VarDecl>(Rec.first);
1625 LValue ParLVal =
1626 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
1627 ParValue = CGF.EmitLoadOfScalar(ParLVal, Loc);
1628 }
1629 const FieldDecl *FD = Rec.second.first;
1630 LValue VarAddr = CGF.EmitLValueForField(Base, FD);
1631 Rec.second.second = VarAddr.getAddress();
1632 if (EscapedParam) {
1633 const auto *VD = cast<VarDecl>(Rec.first);
1634 CGF.EmitStoreOfScalar(ParValue, VarAddr);
1635 I->getSecond().MappedParams->setVarAddr(CGF, VD, VarAddr.getAddress());
1636 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00001637 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001638 }
1639 for (const ValueDecl *VD : I->getSecond().EscapedVariableLengthDecls) {
1640 // Recover pointer to this function's global record. The runtime will
1641 // handle the specifics of the allocation of the memory.
1642 // Use actual memory size of the record including the padding
1643 // for alignment purposes.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001644 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001645 llvm::Value *Size = CGF.getTypeSize(VD->getType());
1646 CharUnits Align = CGM.getContext().getDeclAlign(VD);
1647 Size = Bld.CreateNUWAdd(
1648 Size, llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity() - 1));
1649 llvm::Value *AlignVal =
1650 llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity());
1651 Size = Bld.CreateUDiv(Size, AlignVal);
1652 Size = Bld.CreateNUWMul(Size, AlignVal);
1653 // TODO: allow the usage of shared memory to be controlled by
1654 // the user, for now, default to global.
1655 llvm::Value *GlobalRecordSizeArg[] = {
1656 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
1657 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
1658 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_push_stack),
1659 GlobalRecordSizeArg);
1660 llvm::Value *GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
1661 GlobalRecValue, CGF.ConvertTypeForMem(VD->getType())->getPointerTo());
1662 LValue Base = CGF.MakeAddrLValue(GlobalRecCastAddr, VD->getType(),
1663 CGM.getContext().getDeclAlign(VD),
1664 AlignmentSource::Decl);
1665 I->getSecond().MappedParams->setVarAddr(CGF, cast<VarDecl>(VD),
1666 Base.getAddress());
1667 I->getSecond().EscapedVariableLengthDeclsAddrs.emplace_back(GlobalRecValue);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001668 }
1669 I->getSecond().MappedParams->apply(CGF);
1670}
1671
1672void CGOpenMPRuntimeNVPTX::emitGenericVarsEpilog(CodeGenFunction &CGF) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001673 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
1674 return;
1675
Alexey Bataevc99042b2018-03-15 18:10:54 +00001676 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001677 if (I != FunctionGlobalizedDecls.end()) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00001678 I->getSecond().MappedParams->restore(CGF);
1679 if (!CGF.HaveInsertPoint())
1680 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001681 for (llvm::Value *Addr :
1682 llvm::reverse(I->getSecond().EscapedVariableLengthDeclsAddrs)) {
1683 CGF.EmitRuntimeCall(
1684 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
1685 Addr);
1686 }
1687 if (I->getSecond().GlobalRecordAddr) {
1688 CGF.EmitRuntimeCall(
1689 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
1690 I->getSecond().GlobalRecordAddr);
1691 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00001692 }
1693}
1694
Carlo Bertollic6872252016-04-04 15:55:02 +00001695void CGOpenMPRuntimeNVPTX::emitTeamsCall(CodeGenFunction &CGF,
1696 const OMPExecutableDirective &D,
1697 SourceLocation Loc,
1698 llvm::Value *OutlinedFn,
1699 ArrayRef<llvm::Value *> CapturedVars) {
1700 if (!CGF.HaveInsertPoint())
1701 return;
1702
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001703 Address ZeroAddr = CGF.CreateMemTemp(
1704 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
1705 /*Name*/ ".zero.addr");
Carlo Bertollic6872252016-04-04 15:55:02 +00001706 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
1707 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001708 OutlinedFnArgs.push_back(emitThreadIDAddress(CGF, Loc).getPointer());
Carlo Bertollic6872252016-04-04 15:55:02 +00001709 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
1710 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00001711 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Carlo Bertollic6872252016-04-04 15:55:02 +00001712}
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001713
1714void CGOpenMPRuntimeNVPTX::emitParallelCall(
1715 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
1716 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
1717 if (!CGF.HaveInsertPoint())
1718 return;
1719
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001720 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001721 emitSpmdParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
1722 else
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001723 emitNonSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001724}
1725
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001726void CGOpenMPRuntimeNVPTX::emitNonSPMDParallelCall(
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001727 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
1728 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
1729 llvm::Function *Fn = cast<llvm::Function>(OutlinedFn);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001730
1731 // Force inline this outlined function at its call site.
1732 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
1733
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001734 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
1735 /*DestWidth=*/32, /*Signed=*/1),
1736 ".zero.addr");
1737 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
1738 Address ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
1739 auto &&CodeGen = [this, Fn, CapturedVars, Loc, ZeroAddr, ThreadIDAddr](
1740 CodeGenFunction &CGF, PrePostActionTy &Action) {
1741 Action.Enter(CGF);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001742
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001743 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
1744 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
1745 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
1746 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
1747 emitOutlinedFunctionCall(CGF, Loc, Fn, OutlinedFnArgs);
1748 };
1749 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
1750 PrePostActionTy &) {
1751
1752 RegionCodeGenTy RCG(CodeGen);
1753 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
1754 llvm::Value *ThreadID = getThreadID(CGF, Loc);
1755 llvm::Value *Args[] = {RTLoc, ThreadID};
1756
1757 NVPTXActionTy Action(
1758 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
1759 Args,
1760 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
1761 Args);
1762 RCG.setAction(Action);
1763 RCG(CGF);
1764 };
1765
1766 auto &&L0ParallelGen = [this, CapturedVars, Fn](CodeGenFunction &CGF,
1767 PrePostActionTy &Action) {
1768 CGBuilderTy &Bld = CGF.Builder;
1769 llvm::Function *WFn = WrapperFunctionsMap[Fn];
1770 assert(WFn && "Wrapper function does not exist!");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001771 llvm::Value *ID = Bld.CreateBitOrPointerCast(WFn, CGM.Int8PtrTy);
1772
1773 // Prepare for parallel region. Indicate the outlined function.
1774 llvm::Value *Args[] = {ID, /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001775 CGF.EmitRuntimeCall(
1776 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_prepare_parallel),
1777 Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001778
1779 // Create a private scope that will globalize the arguments
1780 // passed from the outside of the target region.
1781 CodeGenFunction::OMPPrivateScope PrivateArgScope(CGF);
1782
1783 // There's somehting to share.
1784 if (!CapturedVars.empty()) {
1785 // Prepare for parallel region. Indicate the outlined function.
1786 Address SharedArgs =
1787 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "shared_arg_refs");
1788 llvm::Value *SharedArgsPtr = SharedArgs.getPointer();
1789
1790 llvm::Value *DataSharingArgs[] = {
1791 SharedArgsPtr,
1792 llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size())};
1793 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1794 OMPRTL_NVPTX__kmpc_begin_sharing_variables),
1795 DataSharingArgs);
1796
1797 // Store variable address in a list of references to pass to workers.
1798 unsigned Idx = 0;
1799 ASTContext &Ctx = CGF.getContext();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001800 Address SharedArgListAddress = CGF.EmitLoadOfPointer(
1801 SharedArgs, Ctx.getPointerType(Ctx.getPointerType(Ctx.VoidPtrTy))
1802 .castAs<PointerType>());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001803 for (llvm::Value *V : CapturedVars) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001804 Address Dst = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
1805 CGF.getPointerSize());
1806 llvm::Value *PtrV;
Alexey Bataev17314212018-03-20 15:41:05 +00001807 if (V->getType()->isIntegerTy())
1808 PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
1809 else
1810 PtrV = Bld.CreatePointerBitCastOrAddrSpaceCast(V, CGF.VoidPtrTy);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001811 CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
1812 Ctx.getPointerType(Ctx.VoidPtrTy));
Alexey Bataevc99042b2018-03-15 18:10:54 +00001813 ++Idx;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001814 }
1815 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001816
1817 // Activate workers. This barrier is used by the master to signal
1818 // work for the workers.
1819 syncCTAThreads(CGF);
1820
1821 // OpenMP [2.5, Parallel Construct, p.49]
1822 // There is an implied barrier at the end of a parallel region. After the
1823 // end of a parallel region, only the master thread of the team resumes
1824 // execution of the enclosing task region.
1825 //
1826 // The master waits at this barrier until all workers are done.
1827 syncCTAThreads(CGF);
1828
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001829 if (!CapturedVars.empty())
1830 CGF.EmitRuntimeCall(
1831 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_sharing_variables));
1832
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001833 // Remember for post-processing in worker loop.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001834 Work.emplace_back(WFn);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001835 };
1836
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001837 auto &&LNParallelGen = [this, Loc, &SeqGen, &L0ParallelGen, &CodeGen](
1838 CodeGenFunction &CGF, PrePostActionTy &Action) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001839 RegionCodeGenTy RCG(CodeGen);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001840 if (IsInParallelRegion) {
1841 SeqGen(CGF, Action);
1842 } else if (IsInTargetMasterThreadRegion) {
1843 L0ParallelGen(CGF, Action);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001844 } else if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_NonSPMD) {
1845 RCG(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001846 } else {
1847 // Check for master and then parallelism:
Alexey Bataev673110d2018-05-16 13:36:30 +00001848 // if (__kmpc_is_spmd_exec_mode()) {
1849 // Serialized execution.
1850 // } else if (is_master) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001851 // Worker call.
1852 // } else if (__kmpc_parallel_level(loc, gtid)) {
1853 // Serialized execution.
1854 // } else {
1855 // Outlined function call.
1856 // }
1857 CGBuilderTy &Bld = CGF.Builder;
1858 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
Alexey Bataev673110d2018-05-16 13:36:30 +00001859 llvm::BasicBlock *SPMDCheckBB = CGF.createBasicBlock(".spmdcheck");
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001860 llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
1861 llvm::BasicBlock *ParallelCheckBB =
1862 CGF.createBasicBlock(".parallelcheck");
Alexey Bataev673110d2018-05-16 13:36:30 +00001863 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
1864 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
1865 Bld.CreateCondBr(IsSPMD, SPMDCheckBB, MasterCheckBB);
1866 CGF.EmitBlock(SPMDCheckBB);
1867 SeqGen(CGF, Action);
1868 CGF.EmitBranch(ExitBB);
1869 CGF.EmitBlock(MasterCheckBB);
1870 llvm::BasicBlock *MasterThenBB = CGF.createBasicBlock("master.then");
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001871 llvm::Value *IsMaster =
1872 Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
Alexey Bataev673110d2018-05-16 13:36:30 +00001873 Bld.CreateCondBr(IsMaster, MasterThenBB, ParallelCheckBB);
1874 CGF.EmitBlock(MasterThenBB);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001875 L0ParallelGen(CGF, Action);
1876 CGF.EmitBranch(ExitBB);
1877 // There is no need to emit line number for unconditional branch.
1878 (void)ApplyDebugLocation::CreateEmpty(CGF);
1879 CGF.EmitBlock(ParallelCheckBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001880 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
1881 llvm::Value *ThreadID = getThreadID(CGF, Loc);
1882 llvm::Value *PL = CGF.EmitRuntimeCall(
1883 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
1884 {RTLoc, ThreadID});
1885 llvm::Value *Res = Bld.CreateIsNotNull(PL);
1886 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("omp_if.then");
1887 llvm::BasicBlock *ElseBlock = CGF.createBasicBlock("omp_if.else");
1888 Bld.CreateCondBr(Res, ThenBlock, ElseBlock);
1889 // Emit the 'then' code.
1890 CGF.EmitBlock(ThenBlock);
1891 SeqGen(CGF, Action);
1892 // There is no need to emit line number for unconditional branch.
1893 (void)ApplyDebugLocation::CreateEmpty(CGF);
1894 // Emit the 'else' code.
1895 CGF.EmitBlock(ElseBlock);
1896 RCG(CGF);
1897 // There is no need to emit line number for unconditional branch.
1898 (void)ApplyDebugLocation::CreateEmpty(CGF);
1899 // Emit the continuation block for code after the if.
1900 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1901 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001902 };
1903
Alexey Bataev9ff80832018-04-16 20:16:21 +00001904 if (IfCond) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001905 emitOMPIfClause(CGF, IfCond, LNParallelGen, SeqGen);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001906 } else {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001907 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001908 RegionCodeGenTy ThenRCG(LNParallelGen);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001909 ThenRCG(CGF);
1910 }
1911}
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001912
1913void CGOpenMPRuntimeNVPTX::emitSpmdParallelCall(
1914 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
1915 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
1916 // Just call the outlined function to execute the parallel region.
1917 // OutlinedFn(&GTid, &zero, CapturedStruct);
1918 //
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001919 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Carlo Bertolli79712092018-02-28 20:48:35 +00001920
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001921 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
1922 /*DestWidth=*/32, /*Signed=*/1),
1923 ".zero.addr");
Carlo Bertolli79712092018-02-28 20:48:35 +00001924 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001925 Address ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
1926 auto &&CodeGen = [this, OutlinedFn, CapturedVars, Loc, ZeroAddr,
1927 ThreadIDAddr](CodeGenFunction &CGF,
1928 PrePostActionTy &Action) {
1929 Action.Enter(CGF);
1930
1931 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
1932 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
1933 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
1934 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
1935 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
1936 };
1937 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
1938 PrePostActionTy &) {
1939
1940 RegionCodeGenTy RCG(CodeGen);
1941 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
1942 llvm::Value *ThreadID = getThreadID(CGF, Loc);
1943 llvm::Value *Args[] = {RTLoc, ThreadID};
1944
1945 NVPTXActionTy Action(
1946 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
1947 Args,
1948 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
1949 Args);
1950 RCG.setAction(Action);
1951 RCG(CGF);
1952 };
1953
1954 if (IsInTargetMasterThreadRegion) {
1955 RegionCodeGenTy RCG(CodeGen);
1956 RCG(CGF);
1957 } else {
1958 // If we are not in the target region, it is definitely L2 parallelism or
1959 // more, because for SPMD mode we always has L1 parallel level, sowe don't
1960 // need to check for orphaned directives.
1961 RegionCodeGenTy RCG(SeqGen);
1962 RCG(CGF);
1963 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001964}
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001965
Alexey Bataev504fc2d2018-05-07 17:23:05 +00001966void CGOpenMPRuntimeNVPTX::emitCriticalRegion(
1967 CodeGenFunction &CGF, StringRef CriticalName,
1968 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
1969 const Expr *Hint) {
1970 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
1971 llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
1972 llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
1973 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
1974 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
1975
1976 // Fetch team-local id of the thread.
1977 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
1978
1979 // Get the width of the team.
1980 llvm::Value *TeamWidth = getNVPTXNumThreads(CGF);
1981
1982 // Initialize the counter variable for the loop.
1983 QualType Int32Ty =
1984 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
1985 Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
1986 LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
1987 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
1988 /*isInit=*/true);
1989
1990 // Block checks if loop counter exceeds upper bound.
1991 CGF.EmitBlock(LoopBB);
1992 llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
1993 llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
1994 CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
1995
1996 // Block tests which single thread should execute region, and which threads
1997 // should go straight to synchronisation point.
1998 CGF.EmitBlock(TestBB);
1999 CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2000 llvm::Value *CmpThreadToCounter =
2001 CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
2002 CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
2003
2004 // Block emits the body of the critical region.
2005 CGF.EmitBlock(BodyBB);
2006
2007 // Output the critical statement.
2008 CriticalOpGen(CGF);
2009
2010 // After the body surrounded by the critical region, the single executing
2011 // thread will jump to the synchronisation point.
2012 // Block waits for all threads in current team to finish then increments the
2013 // counter variable and returns to the loop.
2014 CGF.EmitBlock(SyncBB);
2015 getNVPTXCTABarrier(CGF);
2016
2017 llvm::Value *IncCounterVal =
2018 CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
2019 CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
2020 CGF.EmitBranch(LoopBB);
2021
2022 // Block that is reached when all threads in the team complete the region.
2023 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2024}
2025
Alexey Bataevb2575932018-01-04 20:18:55 +00002026/// Cast value to the specified type.
Alexey Bataeva453f362018-03-19 17:53:56 +00002027static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
2028 QualType ValTy, QualType CastTy,
2029 SourceLocation Loc) {
2030 assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
2031 "Cast type must sized.");
2032 assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
2033 "Val type must sized.");
2034 llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
2035 if (ValTy == CastTy)
Alexey Bataevb2575932018-01-04 20:18:55 +00002036 return Val;
Alexey Bataeva453f362018-03-19 17:53:56 +00002037 if (CGF.getContext().getTypeSizeInChars(ValTy) ==
2038 CGF.getContext().getTypeSizeInChars(CastTy))
2039 return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
2040 if (CastTy->isIntegerType() && ValTy->isIntegerType())
2041 return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
2042 CastTy->hasSignedIntegerRepresentation());
2043 Address CastItem = CGF.CreateMemTemp(CastTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002044 Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2045 CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
Alexey Bataeva453f362018-03-19 17:53:56 +00002046 CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy);
2047 return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc);
Alexey Bataevb2575932018-01-04 20:18:55 +00002048}
2049
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002050/// This function creates calls to one of two shuffle functions to copy
2051/// variables between lanes in a warp.
2052static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002053 llvm::Value *Elem,
Alexey Bataeva453f362018-03-19 17:53:56 +00002054 QualType ElemType,
2055 llvm::Value *Offset,
2056 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002057 CodeGenModule &CGM = CGF.CGM;
2058 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002059 CGOpenMPRuntimeNVPTX &RT =
2060 *(static_cast<CGOpenMPRuntimeNVPTX *>(&CGM.getOpenMPRuntime()));
2061
Alexey Bataeva453f362018-03-19 17:53:56 +00002062 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2063 assert(Size.getQuantity() <= 8 &&
2064 "Unsupported bitwidth in shuffle instruction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002065
Alexey Bataeva453f362018-03-19 17:53:56 +00002066 OpenMPRTLFunctionNVPTX ShuffleFn = Size.getQuantity() <= 4
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002067 ? OMPRTL_NVPTX__kmpc_shuffle_int32
2068 : OMPRTL_NVPTX__kmpc_shuffle_int64;
2069
2070 // Cast all types to 32- or 64-bit values before calling shuffle routines.
Alexey Bataeva453f362018-03-19 17:53:56 +00002071 QualType CastTy = CGF.getContext().getIntTypeForBitwidth(
2072 Size.getQuantity() <= 4 ? 32 : 64, /*Signed=*/1);
2073 llvm::Value *ElemCast = castValueToType(CGF, Elem, ElemType, CastTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002074 llvm::Value *WarpSize =
Alexey Bataevb2575932018-01-04 20:18:55 +00002075 Bld.CreateIntCast(getNVPTXWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002076
Alexey Bataev9ff80832018-04-16 20:16:21 +00002077 llvm::Value *ShuffledVal = CGF.EmitRuntimeCall(
2078 RT.createNVPTXRuntimeFunction(ShuffleFn), {ElemCast, Offset, WarpSize});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002079
Alexey Bataeva453f362018-03-19 17:53:56 +00002080 return castValueToType(CGF, ShuffledVal, CastTy, ElemType, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002081}
2082
2083namespace {
2084enum CopyAction : unsigned {
2085 // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
2086 // the warp using shuffle instructions.
2087 RemoteLaneToThread,
2088 // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
2089 ThreadCopy,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002090 // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
2091 ThreadToScratchpad,
2092 // ScratchpadToThread: Copy from a scratchpad array in global memory
2093 // containing team-reduced data to a thread's stack.
2094 ScratchpadToThread,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002095};
2096} // namespace
2097
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002098struct CopyOptionsTy {
2099 llvm::Value *RemoteLaneOffset;
2100 llvm::Value *ScratchpadIndex;
2101 llvm::Value *ScratchpadWidth;
2102};
2103
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002104/// Emit instructions to copy a Reduce list, which contains partially
2105/// aggregated values, in the specified direction.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002106static void emitReductionListCopy(
2107 CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
2108 ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
2109 CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002110
Alexey Bataev9ff80832018-04-16 20:16:21 +00002111 CodeGenModule &CGM = CGF.CGM;
2112 ASTContext &C = CGM.getContext();
2113 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002114
Alexey Bataev9ff80832018-04-16 20:16:21 +00002115 llvm::Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
2116 llvm::Value *ScratchpadIndex = CopyOptions.ScratchpadIndex;
2117 llvm::Value *ScratchpadWidth = CopyOptions.ScratchpadWidth;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002118
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002119 // Iterates, element-by-element, through the source Reduce list and
2120 // make a copy.
2121 unsigned Idx = 0;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002122 unsigned Size = Privates.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00002123 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002124 Address SrcElementAddr = Address::invalid();
2125 Address DestElementAddr = Address::invalid();
2126 Address DestElementPtrAddr = Address::invalid();
2127 // Should we shuffle in an element from a remote lane?
2128 bool ShuffleInElement = false;
2129 // Set to true to update the pointer in the dest Reduce list to a
2130 // newly created element.
2131 bool UpdateDestListPtr = false;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002132 // Increment the src or dest pointer to the scratchpad, for each
2133 // new element.
2134 bool IncrScratchpadSrc = false;
2135 bool IncrScratchpadDest = false;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002136
2137 switch (Action) {
2138 case RemoteLaneToThread: {
2139 // Step 1.1: Get the address for the src element in the Reduce list.
2140 Address SrcElementPtrAddr =
2141 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002142 SrcElementAddr = CGF.EmitLoadOfPointer(
2143 SrcElementPtrAddr,
2144 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002145
2146 // Step 1.2: Create a temporary to store the element in the destination
2147 // Reduce list.
2148 DestElementPtrAddr =
2149 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
2150 DestElementAddr =
2151 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2152 ShuffleInElement = true;
2153 UpdateDestListPtr = true;
2154 break;
2155 }
2156 case ThreadCopy: {
2157 // Step 1.1: Get the address for the src element in the Reduce list.
2158 Address SrcElementPtrAddr =
2159 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002160 SrcElementAddr = CGF.EmitLoadOfPointer(
2161 SrcElementPtrAddr,
2162 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002163
2164 // Step 1.2: Get the address for dest element. The destination
2165 // element has already been created on the thread's stack.
2166 DestElementPtrAddr =
2167 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002168 DestElementAddr = CGF.EmitLoadOfPointer(
2169 DestElementPtrAddr,
2170 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002171 break;
2172 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002173 case ThreadToScratchpad: {
2174 // Step 1.1: Get the address for the src element in the Reduce list.
2175 Address SrcElementPtrAddr =
2176 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002177 SrcElementAddr = CGF.EmitLoadOfPointer(
2178 SrcElementPtrAddr,
2179 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002180
2181 // Step 1.2: Get the address for dest element:
2182 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00002183 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00002184 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002185 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002186 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002187 Bld.CreateNUWAdd(DestBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002188 ScratchPadElemAbsolutePtrVal =
2189 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002190 DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
2191 C.getTypeAlignInChars(Private->getType()));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002192 IncrScratchpadDest = true;
2193 break;
2194 }
2195 case ScratchpadToThread: {
2196 // Step 1.1: Get the address for the src element in the scratchpad.
2197 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00002198 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00002199 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002200 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002201 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002202 Bld.CreateNUWAdd(SrcBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002203 ScratchPadElemAbsolutePtrVal =
2204 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
2205 SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
2206 C.getTypeAlignInChars(Private->getType()));
2207 IncrScratchpadSrc = true;
2208
2209 // Step 1.2: Create a temporary to store the element in the destination
2210 // Reduce list.
2211 DestElementPtrAddr =
2212 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
2213 DestElementAddr =
2214 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2215 UpdateDestListPtr = true;
2216 break;
2217 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002218 }
2219
2220 // Regardless of src and dest of copy, we emit the load of src
2221 // element as this is required in all directions
2222 SrcElementAddr = Bld.CreateElementBitCast(
2223 SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
2224 llvm::Value *Elem =
2225 CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002226 Private->getType(), Private->getExprLoc());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002227
2228 // Now that all active lanes have read the element in the
2229 // Reduce list, shuffle over the value from the remote lane.
Alexey Bataeva453f362018-03-19 17:53:56 +00002230 if (ShuffleInElement) {
2231 Elem =
2232 createRuntimeShuffleFunction(CGF, Elem, Private->getType(),
2233 RemoteLaneOffset, Private->getExprLoc());
2234 }
Alexey Bataevb2575932018-01-04 20:18:55 +00002235
2236 DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
2237 SrcElementAddr.getElementType());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002238
2239 // Store the source element value to the dest element address.
2240 CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false,
2241 Private->getType());
2242
2243 // Step 3.1: Modify reference in dest Reduce list as needed.
2244 // Modifying the reference in Reduce list to point to the newly
2245 // created element. The element is live in the current function
2246 // scope and that of functions it invokes (i.e., reduce_function).
2247 // RemoteReduceData[i] = (void*)&RemoteElem
2248 if (UpdateDestListPtr) {
2249 CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
2250 DestElementAddr.getPointer(), CGF.VoidPtrTy),
2251 DestElementPtrAddr, /*Volatile=*/false,
2252 C.VoidPtrTy);
2253 }
2254
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002255 // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
2256 // address of the next element in scratchpad memory, unless we're currently
2257 // processing the last one. Memory alignment is also taken care of here.
2258 if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
2259 llvm::Value *ScratchpadBasePtr =
2260 IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
Alexey Bataeve290ec02018-04-06 16:03:36 +00002261 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
2262 ScratchpadBasePtr = Bld.CreateNUWAdd(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002263 ScratchpadBasePtr,
Alexey Bataeve290ec02018-04-06 16:03:36 +00002264 Bld.CreateNUWMul(ScratchpadWidth, ElementSizeInChars));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002265
2266 // Take care of global memory alignment for performance
Alexey Bataeve290ec02018-04-06 16:03:36 +00002267 ScratchpadBasePtr = Bld.CreateNUWSub(
2268 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
2269 ScratchpadBasePtr = Bld.CreateUDiv(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002270 ScratchpadBasePtr,
2271 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
Alexey Bataeve290ec02018-04-06 16:03:36 +00002272 ScratchpadBasePtr = Bld.CreateNUWAdd(
2273 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
2274 ScratchpadBasePtr = Bld.CreateNUWMul(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002275 ScratchpadBasePtr,
2276 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
2277
2278 if (IncrScratchpadDest)
2279 DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
2280 else /* IncrScratchpadSrc = true */
2281 SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
2282 }
2283
Alexey Bataev9ff80832018-04-16 20:16:21 +00002284 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002285 }
2286}
2287
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002288/// This function emits a helper that loads data from the scratchpad array
2289/// and (optionally) reduces it with the input operand.
2290///
2291/// load_and_reduce(local, scratchpad, index, width, should_reduce)
2292/// reduce_data remote;
2293/// for elem in remote:
2294/// remote.elem = Scratchpad[elem_id][index]
2295/// if (should_reduce)
2296/// local = local @ remote
2297/// else
2298/// local = remote
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002299static llvm::Value *emitReduceScratchpadFunction(
2300 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
2301 QualType ReductionArrayTy, llvm::Value *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002302 ASTContext &C = CGM.getContext();
2303 QualType Int32Ty = C.getIntTypeForBitwidth(32, /*Signed=*/1);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002304
2305 // Destination of the copy.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002306 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2307 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002308 // Base address of the scratchpad array, with each element storing a
2309 // Reduce list per team.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002310 ImplicitParamDecl ScratchPadArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2311 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002312 // A source index into the scratchpad array.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002313 ImplicitParamDecl IndexArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
2314 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002315 // Row width of an element in the scratchpad array, typically
2316 // the number of teams.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002317 ImplicitParamDecl WidthArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
2318 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002319 // If should_reduce == 1, then it's load AND reduce,
2320 // If should_reduce == 0 (or otherwise), then it only loads (+ copy).
2321 // The latter case is used for initialization.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002322 ImplicitParamDecl ShouldReduceArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2323 Int32Ty, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002324
2325 FunctionArgList Args;
2326 Args.push_back(&ReduceListArg);
2327 Args.push_back(&ScratchPadArg);
2328 Args.push_back(&IndexArg);
2329 Args.push_back(&WidthArg);
2330 Args.push_back(&ShouldReduceArg);
2331
Alexey Bataev9ff80832018-04-16 20:16:21 +00002332 const CGFunctionInfo &CGFI =
2333 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002334 auto *Fn = llvm::Function::Create(
2335 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2336 "_omp_reduction_load_and_reduce", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002337 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002338 Fn->setDoesNotRecurse();
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002339 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002340 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002341
Alexey Bataev9ff80832018-04-16 20:16:21 +00002342 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002343
2344 // Get local Reduce list pointer.
2345 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2346 Address ReduceListAddr(
2347 Bld.CreatePointerBitCastOrAddrSpaceCast(
2348 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002349 C.VoidPtrTy, Loc),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002350 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
2351 CGF.getPointerAlign());
2352
2353 Address AddrScratchPadArg = CGF.GetAddrOfLocalVar(&ScratchPadArg);
2354 llvm::Value *ScratchPadBase = CGF.EmitLoadOfScalar(
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002355 AddrScratchPadArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002356
2357 Address AddrIndexArg = CGF.GetAddrOfLocalVar(&IndexArg);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002358 llvm::Value *IndexVal = Bld.CreateIntCast(
2359 CGF.EmitLoadOfScalar(AddrIndexArg, /*Volatile=*/false, Int32Ty, Loc),
2360 CGM.SizeTy, /*isSigned=*/true);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002361
2362 Address AddrWidthArg = CGF.GetAddrOfLocalVar(&WidthArg);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002363 llvm::Value *WidthVal = Bld.CreateIntCast(
2364 CGF.EmitLoadOfScalar(AddrWidthArg, /*Volatile=*/false, Int32Ty, Loc),
2365 CGM.SizeTy, /*isSigned=*/true);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002366
2367 Address AddrShouldReduceArg = CGF.GetAddrOfLocalVar(&ShouldReduceArg);
2368 llvm::Value *ShouldReduceVal = CGF.EmitLoadOfScalar(
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002369 AddrShouldReduceArg, /*Volatile=*/false, Int32Ty, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002370
2371 // The absolute ptr address to the base addr of the next element to copy.
2372 llvm::Value *CumulativeElemBasePtr =
2373 Bld.CreatePtrToInt(ScratchPadBase, CGM.SizeTy);
2374 Address SrcDataAddr(CumulativeElemBasePtr, CGF.getPointerAlign());
2375
2376 // Create a Remote Reduce list to store the elements read from the
2377 // scratchpad array.
2378 Address RemoteReduceList =
2379 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_red_list");
2380
2381 // Assemble remote Reduce list from scratchpad array.
2382 emitReductionListCopy(ScratchpadToThread, CGF, ReductionArrayTy, Privates,
2383 SrcDataAddr, RemoteReduceList,
2384 {/*RemoteLaneOffset=*/nullptr,
2385 /*ScratchpadIndex=*/IndexVal,
2386 /*ScratchpadWidth=*/WidthVal});
2387
2388 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
2389 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
2390 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
2391
Alexey Bataev9ff80832018-04-16 20:16:21 +00002392 llvm::Value *CondReduce = Bld.CreateIsNotNull(ShouldReduceVal);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002393 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
2394
2395 CGF.EmitBlock(ThenBB);
2396 // We should reduce with the local Reduce list.
2397 // reduce_function(LocalReduceList, RemoteReduceList)
2398 llvm::Value *LocalDataPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2399 ReduceListAddr.getPointer(), CGF.VoidPtrTy);
2400 llvm::Value *RemoteDataPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2401 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002402 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
2403 CGF, Loc, ReduceFn, {LocalDataPtr, RemoteDataPtr});
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002404 Bld.CreateBr(MergeBB);
2405
2406 CGF.EmitBlock(ElseBB);
2407 // No reduction; just copy:
2408 // Local Reduce list = Remote Reduce list.
2409 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
2410 RemoteReduceList, ReduceListAddr);
2411 Bld.CreateBr(MergeBB);
2412
2413 CGF.EmitBlock(MergeBB);
2414
2415 CGF.FinishFunction();
2416 return Fn;
2417}
2418
2419/// This function emits a helper that stores reduced data from the team
2420/// master to a scratchpad array in global memory.
2421///
2422/// for elem in Reduce List:
2423/// scratchpad[elem_id][index] = elem
2424///
Benjamin Kramer674d5792017-05-26 20:08:24 +00002425static llvm::Value *emitCopyToScratchpad(CodeGenModule &CGM,
2426 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002427 QualType ReductionArrayTy,
2428 SourceLocation Loc) {
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002429
Alexey Bataev9ff80832018-04-16 20:16:21 +00002430 ASTContext &C = CGM.getContext();
2431 QualType Int32Ty = C.getIntTypeForBitwidth(32, /*Signed=*/1);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002432
2433 // Source of the copy.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002434 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2435 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002436 // Base address of the scratchpad array, with each element storing a
2437 // Reduce list per team.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002438 ImplicitParamDecl ScratchPadArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2439 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002440 // A destination index into the scratchpad array, typically the team
2441 // identifier.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002442 ImplicitParamDecl IndexArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
2443 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002444 // Row width of an element in the scratchpad array, typically
2445 // the number of teams.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002446 ImplicitParamDecl WidthArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
2447 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002448
2449 FunctionArgList Args;
2450 Args.push_back(&ReduceListArg);
2451 Args.push_back(&ScratchPadArg);
2452 Args.push_back(&IndexArg);
2453 Args.push_back(&WidthArg);
2454
Alexey Bataev9ff80832018-04-16 20:16:21 +00002455 const CGFunctionInfo &CGFI =
2456 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002457 auto *Fn = llvm::Function::Create(
2458 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2459 "_omp_reduction_copy_to_scratchpad", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002460 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002461 Fn->setDoesNotRecurse();
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002462 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002463 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002464
Alexey Bataev9ff80832018-04-16 20:16:21 +00002465 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002466
2467 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2468 Address SrcDataAddr(
2469 Bld.CreatePointerBitCastOrAddrSpaceCast(
2470 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002471 C.VoidPtrTy, Loc),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002472 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
2473 CGF.getPointerAlign());
2474
2475 Address AddrScratchPadArg = CGF.GetAddrOfLocalVar(&ScratchPadArg);
2476 llvm::Value *ScratchPadBase = CGF.EmitLoadOfScalar(
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002477 AddrScratchPadArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002478
2479 Address AddrIndexArg = CGF.GetAddrOfLocalVar(&IndexArg);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002480 llvm::Value *IndexVal = Bld.CreateIntCast(
2481 CGF.EmitLoadOfScalar(AddrIndexArg, /*Volatile=*/false, Int32Ty, Loc),
2482 CGF.SizeTy, /*isSigned=*/true);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002483
2484 Address AddrWidthArg = CGF.GetAddrOfLocalVar(&WidthArg);
2485 llvm::Value *WidthVal =
2486 Bld.CreateIntCast(CGF.EmitLoadOfScalar(AddrWidthArg, /*Volatile=*/false,
2487 Int32Ty, SourceLocation()),
2488 CGF.SizeTy, /*isSigned=*/true);
2489
2490 // The absolute ptr address to the base addr of the next element to copy.
2491 llvm::Value *CumulativeElemBasePtr =
2492 Bld.CreatePtrToInt(ScratchPadBase, CGM.SizeTy);
2493 Address DestDataAddr(CumulativeElemBasePtr, CGF.getPointerAlign());
2494
2495 emitReductionListCopy(ThreadToScratchpad, CGF, ReductionArrayTy, Privates,
2496 SrcDataAddr, DestDataAddr,
2497 {/*RemoteLaneOffset=*/nullptr,
2498 /*ScratchpadIndex=*/IndexVal,
2499 /*ScratchpadWidth=*/WidthVal});
2500
2501 CGF.FinishFunction();
2502 return Fn;
2503}
2504
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002505/// This function emits a helper that gathers Reduce lists from the first
2506/// lane of every active warp to lanes in the first warp.
2507///
2508/// void inter_warp_copy_func(void* reduce_data, num_warps)
2509/// shared smem[warp_size];
2510/// For all data entries D in reduce_data:
2511/// If (I am the first lane in each warp)
2512/// Copy my local D to smem[warp_id]
2513/// sync
2514/// if (I am the first warp)
2515/// Copy smem[thread_id] to my local D
2516/// sync
2517static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
2518 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002519 QualType ReductionArrayTy,
2520 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002521 ASTContext &C = CGM.getContext();
2522 llvm::Module &M = CGM.getModule();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002523
2524 // ReduceList: thread local Reduce list.
2525 // At the stage of the computation when this function is called, partially
2526 // aggregated values reside in the first lane of every active warp.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002527 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2528 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002529 // NumWarps: number of warps active in the parallel region. This could
2530 // be smaller than 32 (max warps in a CTA) for partial block reduction.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002531 ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00002532 C.getIntTypeForBitwidth(32, /* Signed */ true),
2533 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002534 FunctionArgList Args;
2535 Args.push_back(&ReduceListArg);
2536 Args.push_back(&NumWarpsArg);
2537
Alexey Bataev9ff80832018-04-16 20:16:21 +00002538 const CGFunctionInfo &CGFI =
2539 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002540 auto *Fn = llvm::Function::Create(
2541 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2542 "_omp_reduction_inter_warp_copy_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002543 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002544 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002545 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002546 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002547
Alexey Bataev9ff80832018-04-16 20:16:21 +00002548 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002549
2550 // This array is used as a medium to transfer, one reduce element at a time,
2551 // the data from the first lane of every warp to lanes in the first warp
2552 // in order to perform the final step of a reduction in a parallel region
2553 // (reduction across warps). The array is placed in NVPTX __shared__ memory
2554 // for reduced latency, as well as to have a distinct copy for concurrently
2555 // executing target regions. The array is declared with common linkage so
2556 // as to be shared across compilation units.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002557 StringRef TransferMediumName =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002558 "__openmp_nvptx_data_transfer_temporary_storage";
2559 llvm::GlobalVariable *TransferMedium =
2560 M.getGlobalVariable(TransferMediumName);
2561 if (!TransferMedium) {
2562 auto *Ty = llvm::ArrayType::get(CGM.Int64Ty, WarpSize);
2563 unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
2564 TransferMedium = new llvm::GlobalVariable(
2565 M, Ty,
2566 /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage,
2567 llvm::Constant::getNullValue(Ty), TransferMediumName,
2568 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
2569 SharedAddressSpace);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002570 CGM.addCompilerUsedGlobal(TransferMedium);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002571 }
2572
2573 // Get the CUDA thread id of the current OpenMP thread on the GPU.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002574 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002575 // nvptx_lane_id = nvptx_id % warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00002576 llvm::Value *LaneID = getNVPTXLaneID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002577 // nvptx_warp_id = nvptx_id / warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00002578 llvm::Value *WarpID = getNVPTXWarpID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002579
2580 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2581 Address LocalReduceList(
2582 Bld.CreatePointerBitCastOrAddrSpaceCast(
2583 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
2584 C.VoidPtrTy, SourceLocation()),
2585 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
2586 CGF.getPointerAlign());
2587
2588 unsigned Idx = 0;
Alexey Bataev9ff80832018-04-16 20:16:21 +00002589 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002590 //
2591 // Warp master copies reduce element to transfer medium in __shared__
2592 // memory.
2593 //
2594 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
2595 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
2596 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
2597
2598 // if (lane_id == 0)
Alexey Bataev9ff80832018-04-16 20:16:21 +00002599 llvm::Value *IsWarpMaster = Bld.CreateIsNull(LaneID, "warp_master");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002600 Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
2601 CGF.EmitBlock(ThenBB);
2602
2603 // Reduce element = LocalReduceList[i]
2604 Address ElemPtrPtrAddr =
2605 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
2606 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
2607 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
2608 // elemptr = (type[i]*)(elemptrptr)
2609 Address ElemPtr =
2610 Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
2611 ElemPtr = Bld.CreateElementBitCast(
2612 ElemPtr, CGF.ConvertTypeForMem(Private->getType()));
2613 // elem = *elemptr
2614 llvm::Value *Elem = CGF.EmitLoadOfScalar(
2615 ElemPtr, /*Volatile=*/false, Private->getType(), SourceLocation());
2616
2617 // Get pointer to location in transfer medium.
2618 // MediumPtr = &medium[warp_id]
2619 llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
2620 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
2621 Address MediumPtr(MediumPtrVal, C.getTypeAlignInChars(Private->getType()));
2622 // Casting to actual data type.
2623 // MediumPtr = (type[i]*)MediumPtrAddr;
2624 MediumPtr = Bld.CreateElementBitCast(
2625 MediumPtr, CGF.ConvertTypeForMem(Private->getType()));
2626
2627 //*MediumPtr = elem
2628 Bld.CreateStore(Elem, MediumPtr);
2629
2630 Bld.CreateBr(MergeBB);
2631
2632 CGF.EmitBlock(ElseBB);
2633 Bld.CreateBr(MergeBB);
2634
2635 CGF.EmitBlock(MergeBB);
2636
2637 Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
2638 llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
2639 AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, SourceLocation());
2640
Alexey Bataev9ff80832018-04-16 20:16:21 +00002641 llvm::Value *NumActiveThreads = Bld.CreateNSWMul(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002642 NumWarpsVal, getNVPTXWarpSize(CGF), "num_active_threads");
2643 // named_barrier_sync(ParallelBarrierID, num_active_threads)
2644 syncParallelThreads(CGF, NumActiveThreads);
2645
2646 //
2647 // Warp 0 copies reduce element from transfer medium.
2648 //
2649 llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
2650 llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
2651 llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
2652
2653 // Up to 32 threads in warp 0 are active.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002654 llvm::Value *IsActiveThread =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002655 Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
2656 Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
2657
2658 CGF.EmitBlock(W0ThenBB);
2659
2660 // SrcMediumPtr = &medium[tid]
2661 llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
2662 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
2663 Address SrcMediumPtr(SrcMediumPtrVal,
2664 C.getTypeAlignInChars(Private->getType()));
2665 // SrcMediumVal = *SrcMediumPtr;
2666 SrcMediumPtr = Bld.CreateElementBitCast(
2667 SrcMediumPtr, CGF.ConvertTypeForMem(Private->getType()));
2668 llvm::Value *SrcMediumValue = CGF.EmitLoadOfScalar(
2669 SrcMediumPtr, /*Volatile=*/false, Private->getType(), SourceLocation());
2670
2671 // TargetElemPtr = (type[i]*)(SrcDataAddr[i])
2672 Address TargetElemPtrPtr =
2673 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
2674 llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
2675 TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
2676 Address TargetElemPtr =
2677 Address(TargetElemPtrVal, C.getTypeAlignInChars(Private->getType()));
2678 TargetElemPtr = Bld.CreateElementBitCast(
2679 TargetElemPtr, CGF.ConvertTypeForMem(Private->getType()));
2680
2681 // *TargetElemPtr = SrcMediumVal;
2682 CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
2683 Private->getType());
2684 Bld.CreateBr(W0MergeBB);
2685
2686 CGF.EmitBlock(W0ElseBB);
2687 Bld.CreateBr(W0MergeBB);
2688
2689 CGF.EmitBlock(W0MergeBB);
2690
2691 // While warp 0 copies values from transfer medium, all other warps must
2692 // wait.
2693 syncParallelThreads(CGF, NumActiveThreads);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002694 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002695 }
2696
2697 CGF.FinishFunction();
2698 return Fn;
2699}
2700
2701/// Emit a helper that reduces data across two OpenMP threads (lanes)
2702/// in the same warp. It uses shuffle instructions to copy over data from
2703/// a remote lane's stack. The reduction algorithm performed is specified
2704/// by the fourth parameter.
2705///
2706/// Algorithm Versions.
2707/// Full Warp Reduce (argument value 0):
2708/// This algorithm assumes that all 32 lanes are active and gathers
2709/// data from these 32 lanes, producing a single resultant value.
2710/// Contiguous Partial Warp Reduce (argument value 1):
2711/// This algorithm assumes that only a *contiguous* subset of lanes
2712/// are active. This happens for the last warp in a parallel region
2713/// when the user specified num_threads is not an integer multiple of
2714/// 32. This contiguous subset always starts with the zeroth lane.
2715/// Partial Warp Reduce (argument value 2):
2716/// This algorithm gathers data from any number of lanes at any position.
2717/// All reduced values are stored in the lowest possible lane. The set
2718/// of problems every algorithm addresses is a super set of those
2719/// addressable by algorithms with a lower version number. Overhead
2720/// increases as algorithm version increases.
2721///
2722/// Terminology
2723/// Reduce element:
2724/// Reduce element refers to the individual data field with primitive
2725/// data types to be combined and reduced across threads.
2726/// Reduce list:
2727/// Reduce list refers to a collection of local, thread-private
2728/// reduce elements.
2729/// Remote Reduce list:
2730/// Remote Reduce list refers to a collection of remote (relative to
2731/// the current thread) reduce elements.
2732///
2733/// We distinguish between three states of threads that are important to
2734/// the implementation of this function.
2735/// Alive threads:
2736/// Threads in a warp executing the SIMT instruction, as distinguished from
2737/// threads that are inactive due to divergent control flow.
2738/// Active threads:
2739/// The minimal set of threads that has to be alive upon entry to this
2740/// function. The computation is correct iff active threads are alive.
2741/// Some threads are alive but they are not active because they do not
2742/// contribute to the computation in any useful manner. Turning them off
2743/// may introduce control flow overheads without any tangible benefits.
2744/// Effective threads:
2745/// In order to comply with the argument requirements of the shuffle
2746/// function, we must keep all lanes holding data alive. But at most
2747/// half of them perform value aggregation; we refer to this half of
2748/// threads as effective. The other half is simply handing off their
2749/// data.
2750///
2751/// Procedure
2752/// Value shuffle:
2753/// In this step active threads transfer data from higher lane positions
2754/// in the warp to lower lane positions, creating Remote Reduce list.
2755/// Value aggregation:
2756/// In this step, effective threads combine their thread local Reduce list
2757/// with Remote Reduce list and store the result in the thread local
2758/// Reduce list.
2759/// Value copy:
2760/// In this step, we deal with the assumption made by algorithm 2
2761/// (i.e. contiguity assumption). When we have an odd number of lanes
2762/// active, say 2k+1, only k threads will be effective and therefore k
2763/// new values will be produced. However, the Reduce list owned by the
2764/// (2k+1)th thread is ignored in the value aggregation. Therefore
2765/// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
2766/// that the contiguity assumption still holds.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002767static llvm::Value *emitShuffleAndReduceFunction(
2768 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
2769 QualType ReductionArrayTy, llvm::Value *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002770 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002771
2772 // Thread local Reduce list used to host the values of data to be reduced.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002773 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2774 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002775 // Current lane id; could be logical.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002776 ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
2777 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002778 // Offset of the remote source lane relative to the current lane.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002779 ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2780 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002781 // Algorithm version. This is expected to be known at compile time.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002782 ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2783 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002784 FunctionArgList Args;
2785 Args.push_back(&ReduceListArg);
2786 Args.push_back(&LaneIDArg);
2787 Args.push_back(&RemoteLaneOffsetArg);
2788 Args.push_back(&AlgoVerArg);
2789
Alexey Bataev9ff80832018-04-16 20:16:21 +00002790 const CGFunctionInfo &CGFI =
2791 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002792 auto *Fn = llvm::Function::Create(
2793 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2794 "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002795 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002796 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002797 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002798 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002799
Alexey Bataev9ff80832018-04-16 20:16:21 +00002800 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002801
2802 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2803 Address LocalReduceList(
2804 Bld.CreatePointerBitCastOrAddrSpaceCast(
2805 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
2806 C.VoidPtrTy, SourceLocation()),
2807 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
2808 CGF.getPointerAlign());
2809
2810 Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
2811 llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
2812 AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
2813
2814 Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
2815 llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
2816 AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
2817
2818 Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
2819 llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
2820 AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
2821
2822 // Create a local thread-private variable to host the Reduce list
2823 // from a remote lane.
2824 Address RemoteReduceList =
2825 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
2826
2827 // This loop iterates through the list of reduce elements and copies,
2828 // element by element, from a remote lane in the warp to RemoteReduceList,
2829 // hosted on the thread's stack.
2830 emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
2831 LocalReduceList, RemoteReduceList,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002832 {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
2833 /*ScratchpadIndex=*/nullptr,
2834 /*ScratchpadWidth=*/nullptr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002835
2836 // The actions to be performed on the Remote Reduce list is dependent
2837 // on the algorithm version.
2838 //
2839 // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
2840 // LaneId % 2 == 0 && Offset > 0):
2841 // do the reduction value aggregation
2842 //
2843 // The thread local variable Reduce list is mutated in place to host the
2844 // reduced data, which is the aggregated value produced from local and
2845 // remote lanes.
2846 //
2847 // Note that AlgoVer is expected to be a constant integer known at compile
2848 // time.
2849 // When AlgoVer==0, the first conjunction evaluates to true, making
2850 // the entire predicate true during compile time.
2851 // When AlgoVer==1, the second conjunction has only the second part to be
2852 // evaluated during runtime. Other conjunctions evaluates to false
2853 // during compile time.
2854 // When AlgoVer==2, the third conjunction has only the second part to be
2855 // evaluated during runtime. Other conjunctions evaluates to false
2856 // during compile time.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002857 llvm::Value *CondAlgo0 = Bld.CreateIsNull(AlgoVerArgVal);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002858
Alexey Bataev9ff80832018-04-16 20:16:21 +00002859 llvm::Value *Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
2860 llvm::Value *CondAlgo1 = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002861 Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
2862
Alexey Bataev9ff80832018-04-16 20:16:21 +00002863 llvm::Value *Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
2864 llvm::Value *CondAlgo2 = Bld.CreateAnd(
2865 Algo2, Bld.CreateIsNull(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1))));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002866 CondAlgo2 = Bld.CreateAnd(
2867 CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
2868
Alexey Bataev9ff80832018-04-16 20:16:21 +00002869 llvm::Value *CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002870 CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
2871
2872 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
2873 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
2874 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
2875 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
2876
2877 CGF.EmitBlock(ThenBB);
2878 // reduce_function(LocalReduceList, RemoteReduceList)
2879 llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2880 LocalReduceList.getPointer(), CGF.VoidPtrTy);
2881 llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2882 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002883 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
2884 CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002885 Bld.CreateBr(MergeBB);
2886
2887 CGF.EmitBlock(ElseBB);
2888 Bld.CreateBr(MergeBB);
2889
2890 CGF.EmitBlock(MergeBB);
2891
2892 // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
2893 // Reduce list.
2894 Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
Alexey Bataev9ff80832018-04-16 20:16:21 +00002895 llvm::Value *CondCopy = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002896 Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
2897
2898 llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
2899 llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
2900 llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
2901 Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
2902
2903 CGF.EmitBlock(CpyThenBB);
2904 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
2905 RemoteReduceList, LocalReduceList);
2906 Bld.CreateBr(CpyMergeBB);
2907
2908 CGF.EmitBlock(CpyElseBB);
2909 Bld.CreateBr(CpyMergeBB);
2910
2911 CGF.EmitBlock(CpyMergeBB);
2912
2913 CGF.FinishFunction();
2914 return Fn;
2915}
2916
2917///
2918/// Design of OpenMP reductions on the GPU
2919///
2920/// Consider a typical OpenMP program with one or more reduction
2921/// clauses:
2922///
2923/// float foo;
2924/// double bar;
2925/// #pragma omp target teams distribute parallel for \
2926/// reduction(+:foo) reduction(*:bar)
2927/// for (int i = 0; i < N; i++) {
2928/// foo += A[i]; bar *= B[i];
2929/// }
2930///
2931/// where 'foo' and 'bar' are reduced across all OpenMP threads in
2932/// all teams. In our OpenMP implementation on the NVPTX device an
2933/// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
2934/// within a team are mapped to CUDA threads within a threadblock.
2935/// Our goal is to efficiently aggregate values across all OpenMP
2936/// threads such that:
2937///
2938/// - the compiler and runtime are logically concise, and
2939/// - the reduction is performed efficiently in a hierarchical
2940/// manner as follows: within OpenMP threads in the same warp,
2941/// across warps in a threadblock, and finally across teams on
2942/// the NVPTX device.
2943///
2944/// Introduction to Decoupling
2945///
2946/// We would like to decouple the compiler and the runtime so that the
2947/// latter is ignorant of the reduction variables (number, data types)
2948/// and the reduction operators. This allows a simpler interface
2949/// and implementation while still attaining good performance.
2950///
2951/// Pseudocode for the aforementioned OpenMP program generated by the
2952/// compiler is as follows:
2953///
2954/// 1. Create private copies of reduction variables on each OpenMP
2955/// thread: 'foo_private', 'bar_private'
2956/// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
2957/// to it and writes the result in 'foo_private' and 'bar_private'
2958/// respectively.
2959/// 3. Call the OpenMP runtime on the GPU to reduce within a team
2960/// and store the result on the team master:
2961///
2962/// __kmpc_nvptx_parallel_reduce_nowait(...,
2963/// reduceData, shuffleReduceFn, interWarpCpyFn)
2964///
2965/// where:
2966/// struct ReduceData {
2967/// double *foo;
2968/// double *bar;
2969/// } reduceData
2970/// reduceData.foo = &foo_private
2971/// reduceData.bar = &bar_private
2972///
2973/// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
2974/// auxiliary functions generated by the compiler that operate on
2975/// variables of type 'ReduceData'. They aid the runtime perform
2976/// algorithmic steps in a data agnostic manner.
2977///
2978/// 'shuffleReduceFn' is a pointer to a function that reduces data
2979/// of type 'ReduceData' across two OpenMP threads (lanes) in the
2980/// same warp. It takes the following arguments as input:
2981///
2982/// a. variable of type 'ReduceData' on the calling lane,
2983/// b. its lane_id,
2984/// c. an offset relative to the current lane_id to generate a
2985/// remote_lane_id. The remote lane contains the second
2986/// variable of type 'ReduceData' that is to be reduced.
2987/// d. an algorithm version parameter determining which reduction
2988/// algorithm to use.
2989///
2990/// 'shuffleReduceFn' retrieves data from the remote lane using
2991/// efficient GPU shuffle intrinsics and reduces, using the
2992/// algorithm specified by the 4th parameter, the two operands
2993/// element-wise. The result is written to the first operand.
2994///
2995/// Different reduction algorithms are implemented in different
2996/// runtime functions, all calling 'shuffleReduceFn' to perform
2997/// the essential reduction step. Therefore, based on the 4th
2998/// parameter, this function behaves slightly differently to
2999/// cooperate with the runtime to ensure correctness under
3000/// different circumstances.
3001///
3002/// 'InterWarpCpyFn' is a pointer to a function that transfers
3003/// reduced variables across warps. It tunnels, through CUDA
3004/// shared memory, the thread-private data of type 'ReduceData'
3005/// from lane 0 of each warp to a lane in the first warp.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003006/// 4. Call the OpenMP runtime on the GPU to reduce across teams.
3007/// The last team writes the global reduced value to memory.
3008///
3009/// ret = __kmpc_nvptx_teams_reduce_nowait(...,
3010/// reduceData, shuffleReduceFn, interWarpCpyFn,
3011/// scratchpadCopyFn, loadAndReduceFn)
3012///
3013/// 'scratchpadCopyFn' is a helper that stores reduced
3014/// data from the team master to a scratchpad array in
3015/// global memory.
3016///
3017/// 'loadAndReduceFn' is a helper that loads data from
3018/// the scratchpad array and reduces it with the input
3019/// operand.
3020///
3021/// These compiler generated functions hide address
3022/// calculation and alignment information from the runtime.
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003023/// 5. if ret == 1:
3024/// The team master of the last team stores the reduced
3025/// result to the globals in memory.
3026/// foo += reduceData.foo; bar *= reduceData.bar
3027///
3028///
3029/// Warp Reduction Algorithms
3030///
3031/// On the warp level, we have three algorithms implemented in the
3032/// OpenMP runtime depending on the number of active lanes:
3033///
3034/// Full Warp Reduction
3035///
3036/// The reduce algorithm within a warp where all lanes are active
3037/// is implemented in the runtime as follows:
3038///
3039/// full_warp_reduce(void *reduce_data,
3040/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3041/// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
3042/// ShuffleReduceFn(reduce_data, 0, offset, 0);
3043/// }
3044///
3045/// The algorithm completes in log(2, WARPSIZE) steps.
3046///
3047/// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
3048/// not used therefore we save instructions by not retrieving lane_id
3049/// from the corresponding special registers. The 4th parameter, which
3050/// represents the version of the algorithm being used, is set to 0 to
3051/// signify full warp reduction.
3052///
3053/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3054///
3055/// #reduce_elem refers to an element in the local lane's data structure
3056/// #remote_elem is retrieved from a remote lane
3057/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3058/// reduce_elem = reduce_elem REDUCE_OP remote_elem;
3059///
3060/// Contiguous Partial Warp Reduction
3061///
3062/// This reduce algorithm is used within a warp where only the first
3063/// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
3064/// number of OpenMP threads in a parallel region is not a multiple of
3065/// WARPSIZE. The algorithm is implemented in the runtime as follows:
3066///
3067/// void
3068/// contiguous_partial_reduce(void *reduce_data,
3069/// kmp_ShuffleReductFctPtr ShuffleReduceFn,
3070/// int size, int lane_id) {
3071/// int curr_size;
3072/// int offset;
3073/// curr_size = size;
3074/// mask = curr_size/2;
3075/// while (offset>0) {
3076/// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
3077/// curr_size = (curr_size+1)/2;
3078/// offset = curr_size/2;
3079/// }
3080/// }
3081///
3082/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3083///
3084/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3085/// if (lane_id < offset)
3086/// reduce_elem = reduce_elem REDUCE_OP remote_elem
3087/// else
3088/// reduce_elem = remote_elem
3089///
3090/// This algorithm assumes that the data to be reduced are located in a
3091/// contiguous subset of lanes starting from the first. When there is
3092/// an odd number of active lanes, the data in the last lane is not
3093/// aggregated with any other lane's dat but is instead copied over.
3094///
3095/// Dispersed Partial Warp Reduction
3096///
3097/// This algorithm is used within a warp when any discontiguous subset of
3098/// lanes are active. It is used to implement the reduction operation
3099/// across lanes in an OpenMP simd region or in a nested parallel region.
3100///
3101/// void
3102/// dispersed_partial_reduce(void *reduce_data,
3103/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3104/// int size, remote_id;
3105/// int logical_lane_id = number_of_active_lanes_before_me() * 2;
3106/// do {
3107/// remote_id = next_active_lane_id_right_after_me();
3108/// # the above function returns 0 of no active lane
3109/// # is present right after the current lane.
3110/// size = number_of_active_lanes_in_this_warp();
3111/// logical_lane_id /= 2;
3112/// ShuffleReduceFn(reduce_data, logical_lane_id,
3113/// remote_id-1-threadIdx.x, 2);
3114/// } while (logical_lane_id % 2 == 0 && size > 1);
3115/// }
3116///
3117/// There is no assumption made about the initial state of the reduction.
3118/// Any number of lanes (>=1) could be active at any position. The reduction
3119/// result is returned in the first active lane.
3120///
3121/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3122///
3123/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3124/// if (lane_id % 2 == 0 && offset > 0)
3125/// reduce_elem = reduce_elem REDUCE_OP remote_elem
3126/// else
3127/// reduce_elem = remote_elem
3128///
3129///
3130/// Intra-Team Reduction
3131///
3132/// This function, as implemented in the runtime call
3133/// '__kmpc_nvptx_parallel_reduce_nowait', aggregates data across OpenMP
3134/// threads in a team. It first reduces within a warp using the
3135/// aforementioned algorithms. We then proceed to gather all such
3136/// reduced values at the first warp.
3137///
3138/// The runtime makes use of the function 'InterWarpCpyFn', which copies
3139/// data from each of the "warp master" (zeroth lane of each warp, where
3140/// warp-reduced data is held) to the zeroth warp. This step reduces (in
3141/// a mathematical sense) the problem of reduction across warp masters in
3142/// a block to the problem of warp reduction.
3143///
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003144///
3145/// Inter-Team Reduction
3146///
3147/// Once a team has reduced its data to a single value, it is stored in
3148/// a global scratchpad array. Since each team has a distinct slot, this
3149/// can be done without locking.
3150///
3151/// The last team to write to the scratchpad array proceeds to reduce the
3152/// scratchpad array. One or more workers in the last team use the helper
3153/// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
3154/// the k'th worker reduces every k'th element.
3155///
3156/// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait' to
3157/// reduce across workers and compute a globally reduced value.
3158///
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003159void CGOpenMPRuntimeNVPTX::emitReduction(
3160 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
3161 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
3162 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
3163 if (!CGF.HaveInsertPoint())
3164 return;
3165
3166 bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003167 bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
Alexey Bataevfac26cf2018-05-02 20:03:27 +00003168 bool SimdReduction = isOpenMPSimdDirective(Options.ReductionKind);
3169 assert((TeamsReduction || ParallelReduction || SimdReduction) &&
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003170 "Invalid reduction selection in emitReduction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003171
Alexey Bataev9ff80832018-04-16 20:16:21 +00003172 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003173
3174 // 1. Build a list of reduction variables.
3175 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3176 auto Size = RHSExprs.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00003177 for (const Expr *E : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003178 if (E->getType()->isVariablyModifiedType())
3179 // Reserve place for array size.
3180 ++Size;
3181 }
3182 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
3183 QualType ReductionArrayTy =
3184 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3185 /*IndexTypeQuals=*/0);
3186 Address ReductionList =
3187 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3188 auto IPriv = Privates.begin();
3189 unsigned Idx = 0;
3190 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
3191 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3192 CGF.getPointerSize());
3193 CGF.Builder.CreateStore(
3194 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3195 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
3196 Elem);
3197 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3198 // Store array size.
3199 ++Idx;
3200 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3201 CGF.getPointerSize());
3202 llvm::Value *Size = CGF.Builder.CreateIntCast(
3203 CGF.getVLASize(
3204 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
Sander de Smalen891af03a2018-02-03 13:55:59 +00003205 .NumElts,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003206 CGF.SizeTy, /*isSigned=*/false);
3207 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3208 Elem);
3209 }
3210 }
3211
3212 // 2. Emit reduce_func().
Alexey Bataev9ff80832018-04-16 20:16:21 +00003213 llvm::Value *ReductionFn = emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003214 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
3215 Privates, LHSExprs, RHSExprs, ReductionOps);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003216
3217 // 4. Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
3218 // RedList, shuffle_reduce_func, interwarp_copy_func);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003219 llvm::Value *ThreadId = getThreadID(CGF, Loc);
3220 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
3221 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003222 ReductionList.getPointer(), CGF.VoidPtrTy);
3223
Alexey Bataev9ff80832018-04-16 20:16:21 +00003224 llvm::Value *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003225 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003226 llvm::Value *InterWarpCopyFn =
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003227 emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003228
Alexey Bataevfac26cf2018-05-02 20:03:27 +00003229 llvm::Value *Args[] = {ThreadId,
3230 CGF.Builder.getInt32(RHSExprs.size()),
3231 ReductionArrayTySize,
3232 RL,
3233 ShuffleAndReduceFn,
3234 InterWarpCopyFn};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003235
Alexey Bataevfac26cf2018-05-02 20:03:27 +00003236 llvm::Value *Res = nullptr;
3237 if (ParallelReduction)
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003238 Res = CGF.EmitRuntimeCall(
3239 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_reduce_nowait),
3240 Args);
Alexey Bataevfac26cf2018-05-02 20:03:27 +00003241 else if (SimdReduction)
3242 Res = CGF.EmitRuntimeCall(
3243 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_simd_reduce_nowait),
3244 Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003245
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003246 if (TeamsReduction) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003247 llvm::Value *ScratchPadCopyFn =
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003248 emitCopyToScratchpad(CGM, Privates, ReductionArrayTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003249 llvm::Value *LoadAndReduceFn = emitReduceScratchpadFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003250 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003251
3252 llvm::Value *Args[] = {ThreadId,
3253 CGF.Builder.getInt32(RHSExprs.size()),
3254 ReductionArrayTySize,
3255 RL,
3256 ShuffleAndReduceFn,
3257 InterWarpCopyFn,
3258 ScratchPadCopyFn,
3259 LoadAndReduceFn};
3260 Res = CGF.EmitRuntimeCall(
3261 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_teams_reduce_nowait),
3262 Args);
3263 }
3264
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003265 // 5. Build switch(res)
Alexey Bataev9ff80832018-04-16 20:16:21 +00003266 llvm::BasicBlock *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
3267 llvm::SwitchInst *SwInst =
3268 CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003269
3270 // 6. Build case 1: where we have reduced values in the master
3271 // thread in each team.
3272 // __kmpc_end_reduce{_nowait}(<gtid>);
3273 // break;
Alexey Bataev9ff80832018-04-16 20:16:21 +00003274 llvm::BasicBlock *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003275 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
3276 CGF.EmitBlock(Case1BB);
3277
3278 // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
3279 llvm::Value *EndArgs[] = {ThreadId};
Alexey Bataev9ff80832018-04-16 20:16:21 +00003280 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003281 this](CodeGenFunction &CGF, PrePostActionTy &Action) {
3282 auto IPriv = Privates.begin();
3283 auto ILHS = LHSExprs.begin();
3284 auto IRHS = RHSExprs.begin();
Alexey Bataev9ff80832018-04-16 20:16:21 +00003285 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003286 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
3287 cast<DeclRefExpr>(*IRHS));
3288 ++IPriv;
3289 ++ILHS;
3290 ++IRHS;
3291 }
3292 };
3293 RegionCodeGenTy RCG(CodeGen);
3294 NVPTXActionTy Action(
3295 nullptr, llvm::None,
3296 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_reduce_nowait),
3297 EndArgs);
3298 RCG.setAction(Action);
3299 RCG(CGF);
3300 CGF.EmitBranch(DefaultBB);
3301 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
3302}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003303
3304const VarDecl *
3305CGOpenMPRuntimeNVPTX::translateParameter(const FieldDecl *FD,
3306 const VarDecl *NativeParam) const {
3307 if (!NativeParam->getType()->isReferenceType())
3308 return NativeParam;
3309 QualType ArgType = NativeParam->getType();
3310 QualifierCollector QC;
3311 const Type *NonQualTy = QC.strip(ArgType);
3312 QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
3313 if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
3314 if (Attr->getCaptureKind() == OMPC_map) {
3315 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
3316 LangAS::opencl_global);
3317 }
3318 }
3319 ArgType = CGM.getContext().getPointerType(PointeeTy);
3320 QC.addRestrict();
3321 enum { NVPTX_local_addr = 5 };
Alexander Richardson6d989432017-10-15 18:48:14 +00003322 QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003323 ArgType = QC.apply(CGM.getContext(), ArgType);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003324 if (isa<ImplicitParamDecl>(NativeParam))
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003325 return ImplicitParamDecl::Create(
3326 CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
3327 NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003328 return ParmVarDecl::Create(
3329 CGM.getContext(),
3330 const_cast<DeclContext *>(NativeParam->getDeclContext()),
3331 NativeParam->getLocStart(), NativeParam->getLocation(),
3332 NativeParam->getIdentifier(), ArgType,
3333 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003334}
3335
3336Address
3337CGOpenMPRuntimeNVPTX::getParameterAddress(CodeGenFunction &CGF,
3338 const VarDecl *NativeParam,
3339 const VarDecl *TargetParam) const {
3340 assert(NativeParam != TargetParam &&
3341 NativeParam->getType()->isReferenceType() &&
3342 "Native arg must not be the same as target arg.");
3343 Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
3344 QualType NativeParamType = NativeParam->getType();
3345 QualifierCollector QC;
3346 const Type *NonQualTy = QC.strip(NativeParamType);
3347 QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
3348 unsigned NativePointeeAddrSpace =
Alexander Richardson6d989432017-10-15 18:48:14 +00003349 CGF.getContext().getTargetAddressSpace(NativePointeeTy);
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00003350 QualType TargetTy = TargetParam->getType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003351 llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00003352 LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003353 // First cast to generic.
3354 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3355 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
3356 /*AddrSpace=*/0));
3357 // Cast from generic to native address space.
3358 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3359 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
3360 NativePointeeAddrSpace));
3361 Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
3362 CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00003363 NativeParamType);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003364 return NativeParamAddr;
3365}
3366
3367void CGOpenMPRuntimeNVPTX::emitOutlinedFunctionCall(
Alexey Bataev3c595a62017-08-14 15:01:03 +00003368 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003369 ArrayRef<llvm::Value *> Args) const {
3370 SmallVector<llvm::Value *, 4> TargetArgs;
Alexey Bataev07ed94a2017-08-15 14:34:04 +00003371 TargetArgs.reserve(Args.size());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003372 auto *FnType =
3373 cast<llvm::FunctionType>(OutlinedFn->getType()->getPointerElementType());
3374 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
Alexey Bataev07ed94a2017-08-15 14:34:04 +00003375 if (FnType->isVarArg() && FnType->getNumParams() <= I) {
3376 TargetArgs.append(std::next(Args.begin(), I), Args.end());
3377 break;
3378 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003379 llvm::Type *TargetType = FnType->getParamType(I);
3380 llvm::Value *NativeArg = Args[I];
3381 if (!TargetType->isPointerTy()) {
3382 TargetArgs.emplace_back(NativeArg);
3383 continue;
3384 }
3385 llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataevc99042b2018-03-15 18:10:54 +00003386 NativeArg,
3387 NativeArg->getType()->getPointerElementType()->getPointerTo());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003388 TargetArgs.emplace_back(
3389 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
3390 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00003391 CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003392}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003393
3394/// Emit function which wraps the outline parallel region
3395/// and controls the arguments which are passed to this function.
3396/// The wrapper ensures that the outlined function is called
3397/// with the correct arguments when data is shared.
3398llvm::Function *CGOpenMPRuntimeNVPTX::createParallelDataSharingWrapper(
3399 llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
3400 ASTContext &Ctx = CGM.getContext();
3401 const auto &CS = *D.getCapturedStmt(OMPD_parallel);
3402
3403 // Create a function that takes as argument the source thread.
3404 FunctionArgList WrapperArgs;
3405 QualType Int16QTy =
3406 Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
3407 QualType Int32QTy =
3408 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
3409 ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getLocStart(),
3410 /*Id=*/nullptr, Int16QTy,
3411 ImplicitParamDecl::Other);
3412 ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getLocStart(),
3413 /*Id=*/nullptr, Int32QTy,
3414 ImplicitParamDecl::Other);
3415 WrapperArgs.emplace_back(&ParallelLevelArg);
3416 WrapperArgs.emplace_back(&WrapperArg);
3417
Alexey Bataev9ff80832018-04-16 20:16:21 +00003418 const CGFunctionInfo &CGFI =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003419 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
3420
3421 auto *Fn = llvm::Function::Create(
3422 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataev9ff80832018-04-16 20:16:21 +00003423 Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
Alexey Bataevc99042b2018-03-15 18:10:54 +00003424 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003425 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003426 Fn->setDoesNotRecurse();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003427
3428 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3429 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
3430 D.getLocStart(), D.getLocStart());
3431
3432 const auto *RD = CS.getCapturedRecordDecl();
3433 auto CurField = RD->field_begin();
3434
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00003435 Address ZeroAddr = CGF.CreateMemTemp(
3436 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
3437 /*Name*/ ".zero.addr");
3438 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003439 // Get the array of arguments.
3440 SmallVector<llvm::Value *, 8> Args;
3441
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00003442 Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).getPointer());
3443 Args.emplace_back(ZeroAddr.getPointer());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003444
3445 CGBuilderTy &Bld = CGF.Builder;
3446 auto CI = CS.capture_begin();
3447
3448 // Use global memory for data sharing.
3449 // Handle passing of global args to workers.
3450 Address GlobalArgs =
3451 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
3452 llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
3453 llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
3454 CGF.EmitRuntimeCall(
3455 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_get_shared_variables),
3456 DataSharingArgs);
3457
3458 // Retrieve the shared variables from the list of references returned
3459 // by the runtime. Pass the variables to the outlined function.
Alexey Bataev17314212018-03-20 15:41:05 +00003460 Address SharedArgListAddress = Address::invalid();
3461 if (CS.capture_size() > 0 ||
3462 isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
3463 SharedArgListAddress = CGF.EmitLoadOfPointer(
3464 GlobalArgs, CGF.getContext()
3465 .getPointerType(CGF.getContext().getPointerType(
3466 CGF.getContext().VoidPtrTy))
3467 .castAs<PointerType>());
3468 }
3469 unsigned Idx = 0;
3470 if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
3471 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
3472 CGF.getPointerSize());
3473 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
3474 Src, CGF.SizeTy->getPointerTo());
3475 llvm::Value *LB = CGF.EmitLoadOfScalar(
3476 TypedAddress,
3477 /*Volatile=*/false,
3478 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
3479 cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
3480 Args.emplace_back(LB);
3481 ++Idx;
3482 Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
3483 CGF.getPointerSize());
3484 TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
3485 Src, CGF.SizeTy->getPointerTo());
3486 llvm::Value *UB = CGF.EmitLoadOfScalar(
3487 TypedAddress,
3488 /*Volatile=*/false,
3489 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
3490 cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
3491 Args.emplace_back(UB);
3492 ++Idx;
3493 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003494 if (CS.capture_size() > 0) {
3495 ASTContext &CGFContext = CGF.getContext();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003496 for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
3497 QualType ElemTy = CurField->getType();
Alexey Bataev17314212018-03-20 15:41:05 +00003498 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx,
3499 CGF.getPointerSize());
3500 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003501 Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)));
3502 llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
3503 /*Volatile=*/false,
3504 CGFContext.getPointerType(ElemTy),
3505 CI->getLocation());
Alexey Bataev2091ca62018-04-23 17:33:41 +00003506 if (CI->capturesVariableByCopy() &&
3507 !CI->getCapturedVar()->getType()->isAnyPointerType()) {
Alexey Bataev17314212018-03-20 15:41:05 +00003508 Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
3509 CI->getLocation());
3510 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003511 Args.emplace_back(Arg);
3512 }
3513 }
3514
3515 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedParallelFn, Args);
3516 CGF.FinishFunction();
3517 return Fn;
3518}
3519
3520void CGOpenMPRuntimeNVPTX::emitFunctionProlog(CodeGenFunction &CGF,
3521 const Decl *D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00003522 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
3523 return;
3524
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003525 assert(D && "Expected function or captured|block decl.");
3526 assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
3527 "Function is registered already.");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003528 const Stmt *Body = nullptr;
Alexey Bataevc99042b2018-03-15 18:10:54 +00003529 bool NeedToDelayGlobalization = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003530 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3531 Body = FD->getBody();
3532 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
3533 Body = BD->getBody();
3534 } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
3535 Body = CD->getBody();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003536 NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003537 }
3538 if (!Body)
3539 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003540 CheckVarsEscapingDeclContext VarChecker(CGF);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003541 VarChecker.Visit(Body);
3542 const RecordDecl *GlobalizedVarsRecord = VarChecker.getGlobalizedRecord();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003543 ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
3544 VarChecker.getEscapedVariableLengthDecls();
3545 if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003546 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +00003547 auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
3548 I->getSecond().MappedParams =
3549 llvm::make_unique<CodeGenFunction::OMPMapVars>();
3550 I->getSecond().GlobalRecord = GlobalizedVarsRecord;
3551 I->getSecond().EscapedParameters.insert(
3552 VarChecker.getEscapedParameters().begin(),
3553 VarChecker.getEscapedParameters().end());
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003554 I->getSecond().EscapedVariableLengthDecls.append(
3555 EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
Alexey Bataevc99042b2018-03-15 18:10:54 +00003556 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003557 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003558 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003559 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataevc99042b2018-03-15 18:10:54 +00003560 Data.insert(std::make_pair(VD, std::make_pair(FD, Address::invalid())));
3561 }
3562 if (!NeedToDelayGlobalization) {
3563 emitGenericVarsProlog(CGF, D->getLocStart());
3564 struct GlobalizationScope final : EHScopeStack::Cleanup {
3565 GlobalizationScope() = default;
3566
3567 void Emit(CodeGenFunction &CGF, Flags flags) override {
3568 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
3569 .emitGenericVarsEpilog(CGF);
3570 }
3571 };
3572 CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003573 }
3574}
3575
3576Address CGOpenMPRuntimeNVPTX::getAddressOfLocalVariable(CodeGenFunction &CGF,
3577 const VarDecl *VD) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00003578 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
3579 return Address::invalid();
3580
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003581 VD = VD->getCanonicalDecl();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003582 auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
3583 if (I == FunctionGlobalizedDecls.end())
3584 return Address::invalid();
Alexey Bataevc99042b2018-03-15 18:10:54 +00003585 auto VDI = I->getSecond().LocalVarData.find(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003586 if (VDI != I->getSecond().LocalVarData.end())
3587 return VDI->second.second;
3588 if (VD->hasAttrs()) {
3589 for (specific_attr_iterator<OMPReferencedVarAttr> IT(VD->attr_begin()),
3590 E(VD->attr_end());
3591 IT != E; ++IT) {
3592 auto VDI = I->getSecond().LocalVarData.find(
3593 cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
3594 ->getCanonicalDecl());
3595 if (VDI != I->getSecond().LocalVarData.end())
3596 return VDI->second.second;
3597 }
3598 }
3599 return Address::invalid();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003600}
3601
3602void CGOpenMPRuntimeNVPTX::functionFinished(CodeGenFunction &CGF) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003603 FunctionGlobalizedDecls.erase(CGF.CurFn);
3604 CGOpenMPRuntime::functionFinished(CGF);
3605}