blob: 785ed5676066ccb0a23ed37008e57904434e0e03 [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 Bataev0baba9e2018-05-25 20:16:03 +00001848 // if (__kmpc_is_spmd_exec_mode() || __kmpc_parallel_level(loc, gtid)) {
Alexey Bataev673110d2018-05-16 13:36:30 +00001849 // Serialized execution.
Alexey Bataev0baba9e2018-05-25 20:16:03 +00001850 // } else if (master) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001851 // Worker call.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001852 // } else {
1853 // Outlined function call.
1854 // }
1855 CGBuilderTy &Bld = CGF.Builder;
1856 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
Alexey Bataev0baba9e2018-05-25 20:16:03 +00001857 llvm::BasicBlock *SeqBB = CGF.createBasicBlock(".sequential");
1858 llvm::BasicBlock *ParallelCheckBB = CGF.createBasicBlock(".parcheck");
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001859 llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
Alexey Bataev673110d2018-05-16 13:36:30 +00001860 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
1861 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
Alexey Bataev0baba9e2018-05-25 20:16:03 +00001862 Bld.CreateCondBr(IsSPMD, SeqBB, ParallelCheckBB);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001863 // There is no need to emit line number for unconditional branch.
1864 (void)ApplyDebugLocation::CreateEmpty(CGF);
1865 CGF.EmitBlock(ParallelCheckBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001866 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
1867 llvm::Value *ThreadID = getThreadID(CGF, Loc);
1868 llvm::Value *PL = CGF.EmitRuntimeCall(
1869 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
1870 {RTLoc, ThreadID});
1871 llvm::Value *Res = Bld.CreateIsNotNull(PL);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00001872 Bld.CreateCondBr(Res, SeqBB, MasterCheckBB);
1873 CGF.EmitBlock(SeqBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001874 SeqGen(CGF, Action);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00001875 CGF.EmitBranch(ExitBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001876 // There is no need to emit line number for unconditional branch.
1877 (void)ApplyDebugLocation::CreateEmpty(CGF);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00001878 CGF.EmitBlock(MasterCheckBB);
1879 llvm::BasicBlock *MasterThenBB = CGF.createBasicBlock("master.then");
1880 llvm::BasicBlock *ElseBlock = CGF.createBasicBlock("omp_if.else");
1881 llvm::Value *IsMaster =
1882 Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
1883 Bld.CreateCondBr(IsMaster, MasterThenBB, ElseBlock);
1884 CGF.EmitBlock(MasterThenBB);
1885 L0ParallelGen(CGF, Action);
1886 CGF.EmitBranch(ExitBB);
1887 // There is no need to emit line number for unconditional branch.
1888 (void)ApplyDebugLocation::CreateEmpty(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001889 CGF.EmitBlock(ElseBlock);
1890 RCG(CGF);
1891 // There is no need to emit line number for unconditional branch.
1892 (void)ApplyDebugLocation::CreateEmpty(CGF);
1893 // Emit the continuation block for code after the if.
1894 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1895 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001896 };
1897
Alexey Bataev9ff80832018-04-16 20:16:21 +00001898 if (IfCond) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001899 emitOMPIfClause(CGF, IfCond, LNParallelGen, SeqGen);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001900 } else {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001901 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001902 RegionCodeGenTy ThenRCG(LNParallelGen);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001903 ThenRCG(CGF);
1904 }
1905}
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001906
1907void CGOpenMPRuntimeNVPTX::emitSpmdParallelCall(
1908 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
1909 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
1910 // Just call the outlined function to execute the parallel region.
1911 // OutlinedFn(&GTid, &zero, CapturedStruct);
1912 //
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001913 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Carlo Bertolli79712092018-02-28 20:48:35 +00001914
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001915 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
1916 /*DestWidth=*/32, /*Signed=*/1),
1917 ".zero.addr");
Carlo Bertolli79712092018-02-28 20:48:35 +00001918 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001919 Address ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
1920 auto &&CodeGen = [this, OutlinedFn, CapturedVars, Loc, ZeroAddr,
1921 ThreadIDAddr](CodeGenFunction &CGF,
1922 PrePostActionTy &Action) {
1923 Action.Enter(CGF);
1924
1925 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
1926 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
1927 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
1928 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
1929 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
1930 };
1931 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
1932 PrePostActionTy &) {
1933
1934 RegionCodeGenTy RCG(CodeGen);
1935 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
1936 llvm::Value *ThreadID = getThreadID(CGF, Loc);
1937 llvm::Value *Args[] = {RTLoc, ThreadID};
1938
1939 NVPTXActionTy Action(
1940 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
1941 Args,
1942 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
1943 Args);
1944 RCG.setAction(Action);
1945 RCG(CGF);
1946 };
1947
1948 if (IsInTargetMasterThreadRegion) {
1949 RegionCodeGenTy RCG(CodeGen);
1950 RCG(CGF);
1951 } else {
1952 // If we are not in the target region, it is definitely L2 parallelism or
1953 // more, because for SPMD mode we always has L1 parallel level, sowe don't
1954 // need to check for orphaned directives.
1955 RegionCodeGenTy RCG(SeqGen);
1956 RCG(CGF);
1957 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001958}
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001959
Alexey Bataev504fc2d2018-05-07 17:23:05 +00001960void CGOpenMPRuntimeNVPTX::emitCriticalRegion(
1961 CodeGenFunction &CGF, StringRef CriticalName,
1962 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
1963 const Expr *Hint) {
1964 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
1965 llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
1966 llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
1967 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
1968 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
1969
1970 // Fetch team-local id of the thread.
1971 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
1972
1973 // Get the width of the team.
1974 llvm::Value *TeamWidth = getNVPTXNumThreads(CGF);
1975
1976 // Initialize the counter variable for the loop.
1977 QualType Int32Ty =
1978 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
1979 Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
1980 LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
1981 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
1982 /*isInit=*/true);
1983
1984 // Block checks if loop counter exceeds upper bound.
1985 CGF.EmitBlock(LoopBB);
1986 llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
1987 llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
1988 CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
1989
1990 // Block tests which single thread should execute region, and which threads
1991 // should go straight to synchronisation point.
1992 CGF.EmitBlock(TestBB);
1993 CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
1994 llvm::Value *CmpThreadToCounter =
1995 CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
1996 CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
1997
1998 // Block emits the body of the critical region.
1999 CGF.EmitBlock(BodyBB);
2000
2001 // Output the critical statement.
2002 CriticalOpGen(CGF);
2003
2004 // After the body surrounded by the critical region, the single executing
2005 // thread will jump to the synchronisation point.
2006 // Block waits for all threads in current team to finish then increments the
2007 // counter variable and returns to the loop.
2008 CGF.EmitBlock(SyncBB);
2009 getNVPTXCTABarrier(CGF);
2010
2011 llvm::Value *IncCounterVal =
2012 CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
2013 CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
2014 CGF.EmitBranch(LoopBB);
2015
2016 // Block that is reached when all threads in the team complete the region.
2017 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2018}
2019
Alexey Bataevb2575932018-01-04 20:18:55 +00002020/// Cast value to the specified type.
Alexey Bataeva453f362018-03-19 17:53:56 +00002021static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
2022 QualType ValTy, QualType CastTy,
2023 SourceLocation Loc) {
2024 assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
2025 "Cast type must sized.");
2026 assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
2027 "Val type must sized.");
2028 llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
2029 if (ValTy == CastTy)
Alexey Bataevb2575932018-01-04 20:18:55 +00002030 return Val;
Alexey Bataeva453f362018-03-19 17:53:56 +00002031 if (CGF.getContext().getTypeSizeInChars(ValTy) ==
2032 CGF.getContext().getTypeSizeInChars(CastTy))
2033 return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
2034 if (CastTy->isIntegerType() && ValTy->isIntegerType())
2035 return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
2036 CastTy->hasSignedIntegerRepresentation());
2037 Address CastItem = CGF.CreateMemTemp(CastTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002038 Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2039 CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
Alexey Bataeva453f362018-03-19 17:53:56 +00002040 CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy);
2041 return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc);
Alexey Bataevb2575932018-01-04 20:18:55 +00002042}
2043
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002044/// This function creates calls to one of two shuffle functions to copy
2045/// variables between lanes in a warp.
2046static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002047 llvm::Value *Elem,
Alexey Bataeva453f362018-03-19 17:53:56 +00002048 QualType ElemType,
2049 llvm::Value *Offset,
2050 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002051 CodeGenModule &CGM = CGF.CGM;
2052 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002053 CGOpenMPRuntimeNVPTX &RT =
2054 *(static_cast<CGOpenMPRuntimeNVPTX *>(&CGM.getOpenMPRuntime()));
2055
Alexey Bataeva453f362018-03-19 17:53:56 +00002056 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2057 assert(Size.getQuantity() <= 8 &&
2058 "Unsupported bitwidth in shuffle instruction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002059
Alexey Bataeva453f362018-03-19 17:53:56 +00002060 OpenMPRTLFunctionNVPTX ShuffleFn = Size.getQuantity() <= 4
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002061 ? OMPRTL_NVPTX__kmpc_shuffle_int32
2062 : OMPRTL_NVPTX__kmpc_shuffle_int64;
2063
2064 // Cast all types to 32- or 64-bit values before calling shuffle routines.
Alexey Bataeva453f362018-03-19 17:53:56 +00002065 QualType CastTy = CGF.getContext().getIntTypeForBitwidth(
2066 Size.getQuantity() <= 4 ? 32 : 64, /*Signed=*/1);
2067 llvm::Value *ElemCast = castValueToType(CGF, Elem, ElemType, CastTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002068 llvm::Value *WarpSize =
Alexey Bataevb2575932018-01-04 20:18:55 +00002069 Bld.CreateIntCast(getNVPTXWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002070
Alexey Bataev9ff80832018-04-16 20:16:21 +00002071 llvm::Value *ShuffledVal = CGF.EmitRuntimeCall(
2072 RT.createNVPTXRuntimeFunction(ShuffleFn), {ElemCast, Offset, WarpSize});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002073
Alexey Bataeva453f362018-03-19 17:53:56 +00002074 return castValueToType(CGF, ShuffledVal, CastTy, ElemType, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002075}
2076
2077namespace {
2078enum CopyAction : unsigned {
2079 // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
2080 // the warp using shuffle instructions.
2081 RemoteLaneToThread,
2082 // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
2083 ThreadCopy,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002084 // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
2085 ThreadToScratchpad,
2086 // ScratchpadToThread: Copy from a scratchpad array in global memory
2087 // containing team-reduced data to a thread's stack.
2088 ScratchpadToThread,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002089};
2090} // namespace
2091
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002092struct CopyOptionsTy {
2093 llvm::Value *RemoteLaneOffset;
2094 llvm::Value *ScratchpadIndex;
2095 llvm::Value *ScratchpadWidth;
2096};
2097
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002098/// Emit instructions to copy a Reduce list, which contains partially
2099/// aggregated values, in the specified direction.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002100static void emitReductionListCopy(
2101 CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
2102 ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
2103 CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002104
Alexey Bataev9ff80832018-04-16 20:16:21 +00002105 CodeGenModule &CGM = CGF.CGM;
2106 ASTContext &C = CGM.getContext();
2107 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002108
Alexey Bataev9ff80832018-04-16 20:16:21 +00002109 llvm::Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
2110 llvm::Value *ScratchpadIndex = CopyOptions.ScratchpadIndex;
2111 llvm::Value *ScratchpadWidth = CopyOptions.ScratchpadWidth;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002112
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002113 // Iterates, element-by-element, through the source Reduce list and
2114 // make a copy.
2115 unsigned Idx = 0;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002116 unsigned Size = Privates.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00002117 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002118 Address SrcElementAddr = Address::invalid();
2119 Address DestElementAddr = Address::invalid();
2120 Address DestElementPtrAddr = Address::invalid();
2121 // Should we shuffle in an element from a remote lane?
2122 bool ShuffleInElement = false;
2123 // Set to true to update the pointer in the dest Reduce list to a
2124 // newly created element.
2125 bool UpdateDestListPtr = false;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002126 // Increment the src or dest pointer to the scratchpad, for each
2127 // new element.
2128 bool IncrScratchpadSrc = false;
2129 bool IncrScratchpadDest = false;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002130
2131 switch (Action) {
2132 case RemoteLaneToThread: {
2133 // Step 1.1: Get the address for the src element in the Reduce list.
2134 Address SrcElementPtrAddr =
2135 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002136 SrcElementAddr = CGF.EmitLoadOfPointer(
2137 SrcElementPtrAddr,
2138 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002139
2140 // Step 1.2: Create a temporary to store the element in the destination
2141 // Reduce list.
2142 DestElementPtrAddr =
2143 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
2144 DestElementAddr =
2145 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2146 ShuffleInElement = true;
2147 UpdateDestListPtr = true;
2148 break;
2149 }
2150 case ThreadCopy: {
2151 // Step 1.1: Get the address for the src element in the Reduce list.
2152 Address SrcElementPtrAddr =
2153 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002154 SrcElementAddr = CGF.EmitLoadOfPointer(
2155 SrcElementPtrAddr,
2156 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002157
2158 // Step 1.2: Get the address for dest element. The destination
2159 // element has already been created on the thread's stack.
2160 DestElementPtrAddr =
2161 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002162 DestElementAddr = CGF.EmitLoadOfPointer(
2163 DestElementPtrAddr,
2164 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002165 break;
2166 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002167 case ThreadToScratchpad: {
2168 // Step 1.1: Get the address for the src element in the Reduce list.
2169 Address SrcElementPtrAddr =
2170 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002171 SrcElementAddr = CGF.EmitLoadOfPointer(
2172 SrcElementPtrAddr,
2173 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002174
2175 // Step 1.2: Get the address for dest element:
2176 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00002177 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00002178 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002179 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002180 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002181 Bld.CreateNUWAdd(DestBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002182 ScratchPadElemAbsolutePtrVal =
2183 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002184 DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
2185 C.getTypeAlignInChars(Private->getType()));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002186 IncrScratchpadDest = true;
2187 break;
2188 }
2189 case ScratchpadToThread: {
2190 // Step 1.1: Get the address for the src element in the scratchpad.
2191 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00002192 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00002193 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002194 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002195 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002196 Bld.CreateNUWAdd(SrcBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002197 ScratchPadElemAbsolutePtrVal =
2198 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
2199 SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
2200 C.getTypeAlignInChars(Private->getType()));
2201 IncrScratchpadSrc = true;
2202
2203 // Step 1.2: Create a temporary to store the element in the destination
2204 // Reduce list.
2205 DestElementPtrAddr =
2206 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
2207 DestElementAddr =
2208 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2209 UpdateDestListPtr = true;
2210 break;
2211 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002212 }
2213
2214 // Regardless of src and dest of copy, we emit the load of src
2215 // element as this is required in all directions
2216 SrcElementAddr = Bld.CreateElementBitCast(
2217 SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
2218 llvm::Value *Elem =
2219 CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002220 Private->getType(), Private->getExprLoc());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002221
2222 // Now that all active lanes have read the element in the
2223 // Reduce list, shuffle over the value from the remote lane.
Alexey Bataeva453f362018-03-19 17:53:56 +00002224 if (ShuffleInElement) {
2225 Elem =
2226 createRuntimeShuffleFunction(CGF, Elem, Private->getType(),
2227 RemoteLaneOffset, Private->getExprLoc());
2228 }
Alexey Bataevb2575932018-01-04 20:18:55 +00002229
2230 DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
2231 SrcElementAddr.getElementType());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002232
2233 // Store the source element value to the dest element address.
2234 CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false,
2235 Private->getType());
2236
2237 // Step 3.1: Modify reference in dest Reduce list as needed.
2238 // Modifying the reference in Reduce list to point to the newly
2239 // created element. The element is live in the current function
2240 // scope and that of functions it invokes (i.e., reduce_function).
2241 // RemoteReduceData[i] = (void*)&RemoteElem
2242 if (UpdateDestListPtr) {
2243 CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
2244 DestElementAddr.getPointer(), CGF.VoidPtrTy),
2245 DestElementPtrAddr, /*Volatile=*/false,
2246 C.VoidPtrTy);
2247 }
2248
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002249 // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
2250 // address of the next element in scratchpad memory, unless we're currently
2251 // processing the last one. Memory alignment is also taken care of here.
2252 if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
2253 llvm::Value *ScratchpadBasePtr =
2254 IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
Alexey Bataeve290ec02018-04-06 16:03:36 +00002255 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
2256 ScratchpadBasePtr = Bld.CreateNUWAdd(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002257 ScratchpadBasePtr,
Alexey Bataeve290ec02018-04-06 16:03:36 +00002258 Bld.CreateNUWMul(ScratchpadWidth, ElementSizeInChars));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002259
2260 // Take care of global memory alignment for performance
Alexey Bataeve290ec02018-04-06 16:03:36 +00002261 ScratchpadBasePtr = Bld.CreateNUWSub(
2262 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
2263 ScratchpadBasePtr = Bld.CreateUDiv(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002264 ScratchpadBasePtr,
2265 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
Alexey Bataeve290ec02018-04-06 16:03:36 +00002266 ScratchpadBasePtr = Bld.CreateNUWAdd(
2267 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
2268 ScratchpadBasePtr = Bld.CreateNUWMul(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002269 ScratchpadBasePtr,
2270 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
2271
2272 if (IncrScratchpadDest)
2273 DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
2274 else /* IncrScratchpadSrc = true */
2275 SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
2276 }
2277
Alexey Bataev9ff80832018-04-16 20:16:21 +00002278 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002279 }
2280}
2281
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002282/// This function emits a helper that loads data from the scratchpad array
2283/// and (optionally) reduces it with the input operand.
2284///
2285/// load_and_reduce(local, scratchpad, index, width, should_reduce)
2286/// reduce_data remote;
2287/// for elem in remote:
2288/// remote.elem = Scratchpad[elem_id][index]
2289/// if (should_reduce)
2290/// local = local @ remote
2291/// else
2292/// local = remote
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002293static llvm::Value *emitReduceScratchpadFunction(
2294 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
2295 QualType ReductionArrayTy, llvm::Value *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002296 ASTContext &C = CGM.getContext();
2297 QualType Int32Ty = C.getIntTypeForBitwidth(32, /*Signed=*/1);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002298
2299 // Destination of the copy.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002300 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2301 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002302 // Base address of the scratchpad array, with each element storing a
2303 // Reduce list per team.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002304 ImplicitParamDecl ScratchPadArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2305 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002306 // A source index into the scratchpad array.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002307 ImplicitParamDecl IndexArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
2308 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002309 // Row width of an element in the scratchpad array, typically
2310 // the number of teams.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002311 ImplicitParamDecl WidthArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
2312 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002313 // If should_reduce == 1, then it's load AND reduce,
2314 // If should_reduce == 0 (or otherwise), then it only loads (+ copy).
2315 // The latter case is used for initialization.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002316 ImplicitParamDecl ShouldReduceArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2317 Int32Ty, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002318
2319 FunctionArgList Args;
2320 Args.push_back(&ReduceListArg);
2321 Args.push_back(&ScratchPadArg);
2322 Args.push_back(&IndexArg);
2323 Args.push_back(&WidthArg);
2324 Args.push_back(&ShouldReduceArg);
2325
Alexey Bataev9ff80832018-04-16 20:16:21 +00002326 const CGFunctionInfo &CGFI =
2327 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002328 auto *Fn = llvm::Function::Create(
2329 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2330 "_omp_reduction_load_and_reduce", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002331 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002332 Fn->setDoesNotRecurse();
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002333 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002334 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002335
Alexey Bataev9ff80832018-04-16 20:16:21 +00002336 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002337
2338 // Get local Reduce list pointer.
2339 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2340 Address ReduceListAddr(
2341 Bld.CreatePointerBitCastOrAddrSpaceCast(
2342 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002343 C.VoidPtrTy, Loc),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002344 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
2345 CGF.getPointerAlign());
2346
2347 Address AddrScratchPadArg = CGF.GetAddrOfLocalVar(&ScratchPadArg);
2348 llvm::Value *ScratchPadBase = CGF.EmitLoadOfScalar(
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002349 AddrScratchPadArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002350
2351 Address AddrIndexArg = CGF.GetAddrOfLocalVar(&IndexArg);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002352 llvm::Value *IndexVal = Bld.CreateIntCast(
2353 CGF.EmitLoadOfScalar(AddrIndexArg, /*Volatile=*/false, Int32Ty, Loc),
2354 CGM.SizeTy, /*isSigned=*/true);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002355
2356 Address AddrWidthArg = CGF.GetAddrOfLocalVar(&WidthArg);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002357 llvm::Value *WidthVal = Bld.CreateIntCast(
2358 CGF.EmitLoadOfScalar(AddrWidthArg, /*Volatile=*/false, Int32Ty, Loc),
2359 CGM.SizeTy, /*isSigned=*/true);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002360
2361 Address AddrShouldReduceArg = CGF.GetAddrOfLocalVar(&ShouldReduceArg);
2362 llvm::Value *ShouldReduceVal = CGF.EmitLoadOfScalar(
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002363 AddrShouldReduceArg, /*Volatile=*/false, Int32Ty, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002364
2365 // The absolute ptr address to the base addr of the next element to copy.
2366 llvm::Value *CumulativeElemBasePtr =
2367 Bld.CreatePtrToInt(ScratchPadBase, CGM.SizeTy);
2368 Address SrcDataAddr(CumulativeElemBasePtr, CGF.getPointerAlign());
2369
2370 // Create a Remote Reduce list to store the elements read from the
2371 // scratchpad array.
2372 Address RemoteReduceList =
2373 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_red_list");
2374
2375 // Assemble remote Reduce list from scratchpad array.
2376 emitReductionListCopy(ScratchpadToThread, CGF, ReductionArrayTy, Privates,
2377 SrcDataAddr, RemoteReduceList,
2378 {/*RemoteLaneOffset=*/nullptr,
2379 /*ScratchpadIndex=*/IndexVal,
2380 /*ScratchpadWidth=*/WidthVal});
2381
2382 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
2383 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
2384 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
2385
Alexey Bataev9ff80832018-04-16 20:16:21 +00002386 llvm::Value *CondReduce = Bld.CreateIsNotNull(ShouldReduceVal);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002387 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
2388
2389 CGF.EmitBlock(ThenBB);
2390 // We should reduce with the local Reduce list.
2391 // reduce_function(LocalReduceList, RemoteReduceList)
2392 llvm::Value *LocalDataPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2393 ReduceListAddr.getPointer(), CGF.VoidPtrTy);
2394 llvm::Value *RemoteDataPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2395 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002396 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
2397 CGF, Loc, ReduceFn, {LocalDataPtr, RemoteDataPtr});
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002398 Bld.CreateBr(MergeBB);
2399
2400 CGF.EmitBlock(ElseBB);
2401 // No reduction; just copy:
2402 // Local Reduce list = Remote Reduce list.
2403 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
2404 RemoteReduceList, ReduceListAddr);
2405 Bld.CreateBr(MergeBB);
2406
2407 CGF.EmitBlock(MergeBB);
2408
2409 CGF.FinishFunction();
2410 return Fn;
2411}
2412
2413/// This function emits a helper that stores reduced data from the team
2414/// master to a scratchpad array in global memory.
2415///
2416/// for elem in Reduce List:
2417/// scratchpad[elem_id][index] = elem
2418///
Benjamin Kramer674d5792017-05-26 20:08:24 +00002419static llvm::Value *emitCopyToScratchpad(CodeGenModule &CGM,
2420 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002421 QualType ReductionArrayTy,
2422 SourceLocation Loc) {
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002423
Alexey Bataev9ff80832018-04-16 20:16:21 +00002424 ASTContext &C = CGM.getContext();
2425 QualType Int32Ty = C.getIntTypeForBitwidth(32, /*Signed=*/1);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002426
2427 // Source of the copy.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002428 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2429 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002430 // Base address of the scratchpad array, with each element storing a
2431 // Reduce list per team.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002432 ImplicitParamDecl ScratchPadArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2433 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002434 // A destination index into the scratchpad array, typically the team
2435 // identifier.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002436 ImplicitParamDecl IndexArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
2437 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002438 // Row width of an element in the scratchpad array, typically
2439 // the number of teams.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002440 ImplicitParamDecl WidthArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
2441 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002442
2443 FunctionArgList Args;
2444 Args.push_back(&ReduceListArg);
2445 Args.push_back(&ScratchPadArg);
2446 Args.push_back(&IndexArg);
2447 Args.push_back(&WidthArg);
2448
Alexey Bataev9ff80832018-04-16 20:16:21 +00002449 const CGFunctionInfo &CGFI =
2450 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002451 auto *Fn = llvm::Function::Create(
2452 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2453 "_omp_reduction_copy_to_scratchpad", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002454 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002455 Fn->setDoesNotRecurse();
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002456 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002457 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002458
Alexey Bataev9ff80832018-04-16 20:16:21 +00002459 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002460
2461 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2462 Address SrcDataAddr(
2463 Bld.CreatePointerBitCastOrAddrSpaceCast(
2464 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002465 C.VoidPtrTy, Loc),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002466 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
2467 CGF.getPointerAlign());
2468
2469 Address AddrScratchPadArg = CGF.GetAddrOfLocalVar(&ScratchPadArg);
2470 llvm::Value *ScratchPadBase = CGF.EmitLoadOfScalar(
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002471 AddrScratchPadArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002472
2473 Address AddrIndexArg = CGF.GetAddrOfLocalVar(&IndexArg);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002474 llvm::Value *IndexVal = Bld.CreateIntCast(
2475 CGF.EmitLoadOfScalar(AddrIndexArg, /*Volatile=*/false, Int32Ty, Loc),
2476 CGF.SizeTy, /*isSigned=*/true);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002477
2478 Address AddrWidthArg = CGF.GetAddrOfLocalVar(&WidthArg);
2479 llvm::Value *WidthVal =
2480 Bld.CreateIntCast(CGF.EmitLoadOfScalar(AddrWidthArg, /*Volatile=*/false,
2481 Int32Ty, SourceLocation()),
2482 CGF.SizeTy, /*isSigned=*/true);
2483
2484 // The absolute ptr address to the base addr of the next element to copy.
2485 llvm::Value *CumulativeElemBasePtr =
2486 Bld.CreatePtrToInt(ScratchPadBase, CGM.SizeTy);
2487 Address DestDataAddr(CumulativeElemBasePtr, CGF.getPointerAlign());
2488
2489 emitReductionListCopy(ThreadToScratchpad, CGF, ReductionArrayTy, Privates,
2490 SrcDataAddr, DestDataAddr,
2491 {/*RemoteLaneOffset=*/nullptr,
2492 /*ScratchpadIndex=*/IndexVal,
2493 /*ScratchpadWidth=*/WidthVal});
2494
2495 CGF.FinishFunction();
2496 return Fn;
2497}
2498
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002499/// This function emits a helper that gathers Reduce lists from the first
2500/// lane of every active warp to lanes in the first warp.
2501///
2502/// void inter_warp_copy_func(void* reduce_data, num_warps)
2503/// shared smem[warp_size];
2504/// For all data entries D in reduce_data:
2505/// If (I am the first lane in each warp)
2506/// Copy my local D to smem[warp_id]
2507/// sync
2508/// if (I am the first warp)
2509/// Copy smem[thread_id] to my local D
2510/// sync
2511static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
2512 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002513 QualType ReductionArrayTy,
2514 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002515 ASTContext &C = CGM.getContext();
2516 llvm::Module &M = CGM.getModule();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002517
2518 // ReduceList: thread local Reduce list.
2519 // At the stage of the computation when this function is called, partially
2520 // aggregated values reside in the first lane of every active warp.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002521 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2522 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002523 // NumWarps: number of warps active in the parallel region. This could
2524 // be smaller than 32 (max warps in a CTA) for partial block reduction.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002525 ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00002526 C.getIntTypeForBitwidth(32, /* Signed */ true),
2527 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002528 FunctionArgList Args;
2529 Args.push_back(&ReduceListArg);
2530 Args.push_back(&NumWarpsArg);
2531
Alexey Bataev9ff80832018-04-16 20:16:21 +00002532 const CGFunctionInfo &CGFI =
2533 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002534 auto *Fn = llvm::Function::Create(
2535 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2536 "_omp_reduction_inter_warp_copy_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002537 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002538 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002539 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002540 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002541
Alexey Bataev9ff80832018-04-16 20:16:21 +00002542 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002543
2544 // This array is used as a medium to transfer, one reduce element at a time,
2545 // the data from the first lane of every warp to lanes in the first warp
2546 // in order to perform the final step of a reduction in a parallel region
2547 // (reduction across warps). The array is placed in NVPTX __shared__ memory
2548 // for reduced latency, as well as to have a distinct copy for concurrently
2549 // executing target regions. The array is declared with common linkage so
2550 // as to be shared across compilation units.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002551 StringRef TransferMediumName =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002552 "__openmp_nvptx_data_transfer_temporary_storage";
2553 llvm::GlobalVariable *TransferMedium =
2554 M.getGlobalVariable(TransferMediumName);
2555 if (!TransferMedium) {
2556 auto *Ty = llvm::ArrayType::get(CGM.Int64Ty, WarpSize);
2557 unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
2558 TransferMedium = new llvm::GlobalVariable(
2559 M, Ty,
2560 /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage,
2561 llvm::Constant::getNullValue(Ty), TransferMediumName,
2562 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
2563 SharedAddressSpace);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002564 CGM.addCompilerUsedGlobal(TransferMedium);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002565 }
2566
2567 // Get the CUDA thread id of the current OpenMP thread on the GPU.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002568 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002569 // nvptx_lane_id = nvptx_id % warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00002570 llvm::Value *LaneID = getNVPTXLaneID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002571 // nvptx_warp_id = nvptx_id / warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00002572 llvm::Value *WarpID = getNVPTXWarpID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002573
2574 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2575 Address LocalReduceList(
2576 Bld.CreatePointerBitCastOrAddrSpaceCast(
2577 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
2578 C.VoidPtrTy, SourceLocation()),
2579 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
2580 CGF.getPointerAlign());
2581
2582 unsigned Idx = 0;
Alexey Bataev9ff80832018-04-16 20:16:21 +00002583 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002584 //
2585 // Warp master copies reduce element to transfer medium in __shared__
2586 // memory.
2587 //
2588 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
2589 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
2590 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
2591
2592 // if (lane_id == 0)
Alexey Bataev9ff80832018-04-16 20:16:21 +00002593 llvm::Value *IsWarpMaster = Bld.CreateIsNull(LaneID, "warp_master");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002594 Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
2595 CGF.EmitBlock(ThenBB);
2596
2597 // Reduce element = LocalReduceList[i]
2598 Address ElemPtrPtrAddr =
2599 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
2600 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
2601 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
2602 // elemptr = (type[i]*)(elemptrptr)
2603 Address ElemPtr =
2604 Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
2605 ElemPtr = Bld.CreateElementBitCast(
2606 ElemPtr, CGF.ConvertTypeForMem(Private->getType()));
2607 // elem = *elemptr
2608 llvm::Value *Elem = CGF.EmitLoadOfScalar(
2609 ElemPtr, /*Volatile=*/false, Private->getType(), SourceLocation());
2610
2611 // Get pointer to location in transfer medium.
2612 // MediumPtr = &medium[warp_id]
2613 llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
2614 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
2615 Address MediumPtr(MediumPtrVal, C.getTypeAlignInChars(Private->getType()));
2616 // Casting to actual data type.
2617 // MediumPtr = (type[i]*)MediumPtrAddr;
2618 MediumPtr = Bld.CreateElementBitCast(
2619 MediumPtr, CGF.ConvertTypeForMem(Private->getType()));
2620
2621 //*MediumPtr = elem
2622 Bld.CreateStore(Elem, MediumPtr);
2623
2624 Bld.CreateBr(MergeBB);
2625
2626 CGF.EmitBlock(ElseBB);
2627 Bld.CreateBr(MergeBB);
2628
2629 CGF.EmitBlock(MergeBB);
2630
2631 Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
2632 llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
2633 AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, SourceLocation());
2634
Alexey Bataev9ff80832018-04-16 20:16:21 +00002635 llvm::Value *NumActiveThreads = Bld.CreateNSWMul(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002636 NumWarpsVal, getNVPTXWarpSize(CGF), "num_active_threads");
2637 // named_barrier_sync(ParallelBarrierID, num_active_threads)
2638 syncParallelThreads(CGF, NumActiveThreads);
2639
2640 //
2641 // Warp 0 copies reduce element from transfer medium.
2642 //
2643 llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
2644 llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
2645 llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
2646
2647 // Up to 32 threads in warp 0 are active.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002648 llvm::Value *IsActiveThread =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002649 Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
2650 Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
2651
2652 CGF.EmitBlock(W0ThenBB);
2653
2654 // SrcMediumPtr = &medium[tid]
2655 llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
2656 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
2657 Address SrcMediumPtr(SrcMediumPtrVal,
2658 C.getTypeAlignInChars(Private->getType()));
2659 // SrcMediumVal = *SrcMediumPtr;
2660 SrcMediumPtr = Bld.CreateElementBitCast(
2661 SrcMediumPtr, CGF.ConvertTypeForMem(Private->getType()));
2662 llvm::Value *SrcMediumValue = CGF.EmitLoadOfScalar(
2663 SrcMediumPtr, /*Volatile=*/false, Private->getType(), SourceLocation());
2664
2665 // TargetElemPtr = (type[i]*)(SrcDataAddr[i])
2666 Address TargetElemPtrPtr =
2667 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
2668 llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
2669 TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
2670 Address TargetElemPtr =
2671 Address(TargetElemPtrVal, C.getTypeAlignInChars(Private->getType()));
2672 TargetElemPtr = Bld.CreateElementBitCast(
2673 TargetElemPtr, CGF.ConvertTypeForMem(Private->getType()));
2674
2675 // *TargetElemPtr = SrcMediumVal;
2676 CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
2677 Private->getType());
2678 Bld.CreateBr(W0MergeBB);
2679
2680 CGF.EmitBlock(W0ElseBB);
2681 Bld.CreateBr(W0MergeBB);
2682
2683 CGF.EmitBlock(W0MergeBB);
2684
2685 // While warp 0 copies values from transfer medium, all other warps must
2686 // wait.
2687 syncParallelThreads(CGF, NumActiveThreads);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002688 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002689 }
2690
2691 CGF.FinishFunction();
2692 return Fn;
2693}
2694
2695/// Emit a helper that reduces data across two OpenMP threads (lanes)
2696/// in the same warp. It uses shuffle instructions to copy over data from
2697/// a remote lane's stack. The reduction algorithm performed is specified
2698/// by the fourth parameter.
2699///
2700/// Algorithm Versions.
2701/// Full Warp Reduce (argument value 0):
2702/// This algorithm assumes that all 32 lanes are active and gathers
2703/// data from these 32 lanes, producing a single resultant value.
2704/// Contiguous Partial Warp Reduce (argument value 1):
2705/// This algorithm assumes that only a *contiguous* subset of lanes
2706/// are active. This happens for the last warp in a parallel region
2707/// when the user specified num_threads is not an integer multiple of
2708/// 32. This contiguous subset always starts with the zeroth lane.
2709/// Partial Warp Reduce (argument value 2):
2710/// This algorithm gathers data from any number of lanes at any position.
2711/// All reduced values are stored in the lowest possible lane. The set
2712/// of problems every algorithm addresses is a super set of those
2713/// addressable by algorithms with a lower version number. Overhead
2714/// increases as algorithm version increases.
2715///
2716/// Terminology
2717/// Reduce element:
2718/// Reduce element refers to the individual data field with primitive
2719/// data types to be combined and reduced across threads.
2720/// Reduce list:
2721/// Reduce list refers to a collection of local, thread-private
2722/// reduce elements.
2723/// Remote Reduce list:
2724/// Remote Reduce list refers to a collection of remote (relative to
2725/// the current thread) reduce elements.
2726///
2727/// We distinguish between three states of threads that are important to
2728/// the implementation of this function.
2729/// Alive threads:
2730/// Threads in a warp executing the SIMT instruction, as distinguished from
2731/// threads that are inactive due to divergent control flow.
2732/// Active threads:
2733/// The minimal set of threads that has to be alive upon entry to this
2734/// function. The computation is correct iff active threads are alive.
2735/// Some threads are alive but they are not active because they do not
2736/// contribute to the computation in any useful manner. Turning them off
2737/// may introduce control flow overheads without any tangible benefits.
2738/// Effective threads:
2739/// In order to comply with the argument requirements of the shuffle
2740/// function, we must keep all lanes holding data alive. But at most
2741/// half of them perform value aggregation; we refer to this half of
2742/// threads as effective. The other half is simply handing off their
2743/// data.
2744///
2745/// Procedure
2746/// Value shuffle:
2747/// In this step active threads transfer data from higher lane positions
2748/// in the warp to lower lane positions, creating Remote Reduce list.
2749/// Value aggregation:
2750/// In this step, effective threads combine their thread local Reduce list
2751/// with Remote Reduce list and store the result in the thread local
2752/// Reduce list.
2753/// Value copy:
2754/// In this step, we deal with the assumption made by algorithm 2
2755/// (i.e. contiguity assumption). When we have an odd number of lanes
2756/// active, say 2k+1, only k threads will be effective and therefore k
2757/// new values will be produced. However, the Reduce list owned by the
2758/// (2k+1)th thread is ignored in the value aggregation. Therefore
2759/// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
2760/// that the contiguity assumption still holds.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002761static llvm::Value *emitShuffleAndReduceFunction(
2762 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
2763 QualType ReductionArrayTy, llvm::Value *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002764 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002765
2766 // Thread local Reduce list used to host the values of data to be reduced.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002767 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2768 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002769 // Current lane id; could be logical.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002770 ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
2771 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002772 // Offset of the remote source lane relative to the current lane.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002773 ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2774 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002775 // Algorithm version. This is expected to be known at compile time.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002776 ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2777 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002778 FunctionArgList Args;
2779 Args.push_back(&ReduceListArg);
2780 Args.push_back(&LaneIDArg);
2781 Args.push_back(&RemoteLaneOffsetArg);
2782 Args.push_back(&AlgoVerArg);
2783
Alexey Bataev9ff80832018-04-16 20:16:21 +00002784 const CGFunctionInfo &CGFI =
2785 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002786 auto *Fn = llvm::Function::Create(
2787 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2788 "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002789 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002790 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002791 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002792 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002793
Alexey Bataev9ff80832018-04-16 20:16:21 +00002794 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002795
2796 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2797 Address LocalReduceList(
2798 Bld.CreatePointerBitCastOrAddrSpaceCast(
2799 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
2800 C.VoidPtrTy, SourceLocation()),
2801 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
2802 CGF.getPointerAlign());
2803
2804 Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
2805 llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
2806 AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
2807
2808 Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
2809 llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
2810 AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
2811
2812 Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
2813 llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
2814 AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
2815
2816 // Create a local thread-private variable to host the Reduce list
2817 // from a remote lane.
2818 Address RemoteReduceList =
2819 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
2820
2821 // This loop iterates through the list of reduce elements and copies,
2822 // element by element, from a remote lane in the warp to RemoteReduceList,
2823 // hosted on the thread's stack.
2824 emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
2825 LocalReduceList, RemoteReduceList,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002826 {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
2827 /*ScratchpadIndex=*/nullptr,
2828 /*ScratchpadWidth=*/nullptr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002829
2830 // The actions to be performed on the Remote Reduce list is dependent
2831 // on the algorithm version.
2832 //
2833 // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
2834 // LaneId % 2 == 0 && Offset > 0):
2835 // do the reduction value aggregation
2836 //
2837 // The thread local variable Reduce list is mutated in place to host the
2838 // reduced data, which is the aggregated value produced from local and
2839 // remote lanes.
2840 //
2841 // Note that AlgoVer is expected to be a constant integer known at compile
2842 // time.
2843 // When AlgoVer==0, the first conjunction evaluates to true, making
2844 // the entire predicate true during compile time.
2845 // When AlgoVer==1, the second conjunction has only the second part to be
2846 // evaluated during runtime. Other conjunctions evaluates to false
2847 // during compile time.
2848 // When AlgoVer==2, the third conjunction has only the second part to be
2849 // evaluated during runtime. Other conjunctions evaluates to false
2850 // during compile time.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002851 llvm::Value *CondAlgo0 = Bld.CreateIsNull(AlgoVerArgVal);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002852
Alexey Bataev9ff80832018-04-16 20:16:21 +00002853 llvm::Value *Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
2854 llvm::Value *CondAlgo1 = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002855 Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
2856
Alexey Bataev9ff80832018-04-16 20:16:21 +00002857 llvm::Value *Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
2858 llvm::Value *CondAlgo2 = Bld.CreateAnd(
2859 Algo2, Bld.CreateIsNull(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1))));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002860 CondAlgo2 = Bld.CreateAnd(
2861 CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
2862
Alexey Bataev9ff80832018-04-16 20:16:21 +00002863 llvm::Value *CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002864 CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
2865
2866 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
2867 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
2868 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
2869 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
2870
2871 CGF.EmitBlock(ThenBB);
2872 // reduce_function(LocalReduceList, RemoteReduceList)
2873 llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2874 LocalReduceList.getPointer(), CGF.VoidPtrTy);
2875 llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2876 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002877 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
2878 CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002879 Bld.CreateBr(MergeBB);
2880
2881 CGF.EmitBlock(ElseBB);
2882 Bld.CreateBr(MergeBB);
2883
2884 CGF.EmitBlock(MergeBB);
2885
2886 // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
2887 // Reduce list.
2888 Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
Alexey Bataev9ff80832018-04-16 20:16:21 +00002889 llvm::Value *CondCopy = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002890 Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
2891
2892 llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
2893 llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
2894 llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
2895 Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
2896
2897 CGF.EmitBlock(CpyThenBB);
2898 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
2899 RemoteReduceList, LocalReduceList);
2900 Bld.CreateBr(CpyMergeBB);
2901
2902 CGF.EmitBlock(CpyElseBB);
2903 Bld.CreateBr(CpyMergeBB);
2904
2905 CGF.EmitBlock(CpyMergeBB);
2906
2907 CGF.FinishFunction();
2908 return Fn;
2909}
2910
2911///
2912/// Design of OpenMP reductions on the GPU
2913///
2914/// Consider a typical OpenMP program with one or more reduction
2915/// clauses:
2916///
2917/// float foo;
2918/// double bar;
2919/// #pragma omp target teams distribute parallel for \
2920/// reduction(+:foo) reduction(*:bar)
2921/// for (int i = 0; i < N; i++) {
2922/// foo += A[i]; bar *= B[i];
2923/// }
2924///
2925/// where 'foo' and 'bar' are reduced across all OpenMP threads in
2926/// all teams. In our OpenMP implementation on the NVPTX device an
2927/// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
2928/// within a team are mapped to CUDA threads within a threadblock.
2929/// Our goal is to efficiently aggregate values across all OpenMP
2930/// threads such that:
2931///
2932/// - the compiler and runtime are logically concise, and
2933/// - the reduction is performed efficiently in a hierarchical
2934/// manner as follows: within OpenMP threads in the same warp,
2935/// across warps in a threadblock, and finally across teams on
2936/// the NVPTX device.
2937///
2938/// Introduction to Decoupling
2939///
2940/// We would like to decouple the compiler and the runtime so that the
2941/// latter is ignorant of the reduction variables (number, data types)
2942/// and the reduction operators. This allows a simpler interface
2943/// and implementation while still attaining good performance.
2944///
2945/// Pseudocode for the aforementioned OpenMP program generated by the
2946/// compiler is as follows:
2947///
2948/// 1. Create private copies of reduction variables on each OpenMP
2949/// thread: 'foo_private', 'bar_private'
2950/// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
2951/// to it and writes the result in 'foo_private' and 'bar_private'
2952/// respectively.
2953/// 3. Call the OpenMP runtime on the GPU to reduce within a team
2954/// and store the result on the team master:
2955///
2956/// __kmpc_nvptx_parallel_reduce_nowait(...,
2957/// reduceData, shuffleReduceFn, interWarpCpyFn)
2958///
2959/// where:
2960/// struct ReduceData {
2961/// double *foo;
2962/// double *bar;
2963/// } reduceData
2964/// reduceData.foo = &foo_private
2965/// reduceData.bar = &bar_private
2966///
2967/// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
2968/// auxiliary functions generated by the compiler that operate on
2969/// variables of type 'ReduceData'. They aid the runtime perform
2970/// algorithmic steps in a data agnostic manner.
2971///
2972/// 'shuffleReduceFn' is a pointer to a function that reduces data
2973/// of type 'ReduceData' across two OpenMP threads (lanes) in the
2974/// same warp. It takes the following arguments as input:
2975///
2976/// a. variable of type 'ReduceData' on the calling lane,
2977/// b. its lane_id,
2978/// c. an offset relative to the current lane_id to generate a
2979/// remote_lane_id. The remote lane contains the second
2980/// variable of type 'ReduceData' that is to be reduced.
2981/// d. an algorithm version parameter determining which reduction
2982/// algorithm to use.
2983///
2984/// 'shuffleReduceFn' retrieves data from the remote lane using
2985/// efficient GPU shuffle intrinsics and reduces, using the
2986/// algorithm specified by the 4th parameter, the two operands
2987/// element-wise. The result is written to the first operand.
2988///
2989/// Different reduction algorithms are implemented in different
2990/// runtime functions, all calling 'shuffleReduceFn' to perform
2991/// the essential reduction step. Therefore, based on the 4th
2992/// parameter, this function behaves slightly differently to
2993/// cooperate with the runtime to ensure correctness under
2994/// different circumstances.
2995///
2996/// 'InterWarpCpyFn' is a pointer to a function that transfers
2997/// reduced variables across warps. It tunnels, through CUDA
2998/// shared memory, the thread-private data of type 'ReduceData'
2999/// from lane 0 of each warp to a lane in the first warp.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003000/// 4. Call the OpenMP runtime on the GPU to reduce across teams.
3001/// The last team writes the global reduced value to memory.
3002///
3003/// ret = __kmpc_nvptx_teams_reduce_nowait(...,
3004/// reduceData, shuffleReduceFn, interWarpCpyFn,
3005/// scratchpadCopyFn, loadAndReduceFn)
3006///
3007/// 'scratchpadCopyFn' is a helper that stores reduced
3008/// data from the team master to a scratchpad array in
3009/// global memory.
3010///
3011/// 'loadAndReduceFn' is a helper that loads data from
3012/// the scratchpad array and reduces it with the input
3013/// operand.
3014///
3015/// These compiler generated functions hide address
3016/// calculation and alignment information from the runtime.
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003017/// 5. if ret == 1:
3018/// The team master of the last team stores the reduced
3019/// result to the globals in memory.
3020/// foo += reduceData.foo; bar *= reduceData.bar
3021///
3022///
3023/// Warp Reduction Algorithms
3024///
3025/// On the warp level, we have three algorithms implemented in the
3026/// OpenMP runtime depending on the number of active lanes:
3027///
3028/// Full Warp Reduction
3029///
3030/// The reduce algorithm within a warp where all lanes are active
3031/// is implemented in the runtime as follows:
3032///
3033/// full_warp_reduce(void *reduce_data,
3034/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3035/// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
3036/// ShuffleReduceFn(reduce_data, 0, offset, 0);
3037/// }
3038///
3039/// The algorithm completes in log(2, WARPSIZE) steps.
3040///
3041/// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
3042/// not used therefore we save instructions by not retrieving lane_id
3043/// from the corresponding special registers. The 4th parameter, which
3044/// represents the version of the algorithm being used, is set to 0 to
3045/// signify full warp reduction.
3046///
3047/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3048///
3049/// #reduce_elem refers to an element in the local lane's data structure
3050/// #remote_elem is retrieved from a remote lane
3051/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3052/// reduce_elem = reduce_elem REDUCE_OP remote_elem;
3053///
3054/// Contiguous Partial Warp Reduction
3055///
3056/// This reduce algorithm is used within a warp where only the first
3057/// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
3058/// number of OpenMP threads in a parallel region is not a multiple of
3059/// WARPSIZE. The algorithm is implemented in the runtime as follows:
3060///
3061/// void
3062/// contiguous_partial_reduce(void *reduce_data,
3063/// kmp_ShuffleReductFctPtr ShuffleReduceFn,
3064/// int size, int lane_id) {
3065/// int curr_size;
3066/// int offset;
3067/// curr_size = size;
3068/// mask = curr_size/2;
3069/// while (offset>0) {
3070/// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
3071/// curr_size = (curr_size+1)/2;
3072/// offset = curr_size/2;
3073/// }
3074/// }
3075///
3076/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3077///
3078/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3079/// if (lane_id < offset)
3080/// reduce_elem = reduce_elem REDUCE_OP remote_elem
3081/// else
3082/// reduce_elem = remote_elem
3083///
3084/// This algorithm assumes that the data to be reduced are located in a
3085/// contiguous subset of lanes starting from the first. When there is
3086/// an odd number of active lanes, the data in the last lane is not
3087/// aggregated with any other lane's dat but is instead copied over.
3088///
3089/// Dispersed Partial Warp Reduction
3090///
3091/// This algorithm is used within a warp when any discontiguous subset of
3092/// lanes are active. It is used to implement the reduction operation
3093/// across lanes in an OpenMP simd region or in a nested parallel region.
3094///
3095/// void
3096/// dispersed_partial_reduce(void *reduce_data,
3097/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3098/// int size, remote_id;
3099/// int logical_lane_id = number_of_active_lanes_before_me() * 2;
3100/// do {
3101/// remote_id = next_active_lane_id_right_after_me();
3102/// # the above function returns 0 of no active lane
3103/// # is present right after the current lane.
3104/// size = number_of_active_lanes_in_this_warp();
3105/// logical_lane_id /= 2;
3106/// ShuffleReduceFn(reduce_data, logical_lane_id,
3107/// remote_id-1-threadIdx.x, 2);
3108/// } while (logical_lane_id % 2 == 0 && size > 1);
3109/// }
3110///
3111/// There is no assumption made about the initial state of the reduction.
3112/// Any number of lanes (>=1) could be active at any position. The reduction
3113/// result is returned in the first active lane.
3114///
3115/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3116///
3117/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3118/// if (lane_id % 2 == 0 && offset > 0)
3119/// reduce_elem = reduce_elem REDUCE_OP remote_elem
3120/// else
3121/// reduce_elem = remote_elem
3122///
3123///
3124/// Intra-Team Reduction
3125///
3126/// This function, as implemented in the runtime call
3127/// '__kmpc_nvptx_parallel_reduce_nowait', aggregates data across OpenMP
3128/// threads in a team. It first reduces within a warp using the
3129/// aforementioned algorithms. We then proceed to gather all such
3130/// reduced values at the first warp.
3131///
3132/// The runtime makes use of the function 'InterWarpCpyFn', which copies
3133/// data from each of the "warp master" (zeroth lane of each warp, where
3134/// warp-reduced data is held) to the zeroth warp. This step reduces (in
3135/// a mathematical sense) the problem of reduction across warp masters in
3136/// a block to the problem of warp reduction.
3137///
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003138///
3139/// Inter-Team Reduction
3140///
3141/// Once a team has reduced its data to a single value, it is stored in
3142/// a global scratchpad array. Since each team has a distinct slot, this
3143/// can be done without locking.
3144///
3145/// The last team to write to the scratchpad array proceeds to reduce the
3146/// scratchpad array. One or more workers in the last team use the helper
3147/// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
3148/// the k'th worker reduces every k'th element.
3149///
3150/// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait' to
3151/// reduce across workers and compute a globally reduced value.
3152///
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003153void CGOpenMPRuntimeNVPTX::emitReduction(
3154 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
3155 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
3156 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
3157 if (!CGF.HaveInsertPoint())
3158 return;
3159
3160 bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003161 bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
Alexey Bataevfac26cf2018-05-02 20:03:27 +00003162 bool SimdReduction = isOpenMPSimdDirective(Options.ReductionKind);
3163 assert((TeamsReduction || ParallelReduction || SimdReduction) &&
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003164 "Invalid reduction selection in emitReduction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003165
Alexey Bataev9ff80832018-04-16 20:16:21 +00003166 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003167
3168 // 1. Build a list of reduction variables.
3169 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3170 auto Size = RHSExprs.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00003171 for (const Expr *E : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003172 if (E->getType()->isVariablyModifiedType())
3173 // Reserve place for array size.
3174 ++Size;
3175 }
3176 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
3177 QualType ReductionArrayTy =
3178 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3179 /*IndexTypeQuals=*/0);
3180 Address ReductionList =
3181 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3182 auto IPriv = Privates.begin();
3183 unsigned Idx = 0;
3184 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
3185 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3186 CGF.getPointerSize());
3187 CGF.Builder.CreateStore(
3188 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3189 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
3190 Elem);
3191 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3192 // Store array size.
3193 ++Idx;
3194 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3195 CGF.getPointerSize());
3196 llvm::Value *Size = CGF.Builder.CreateIntCast(
3197 CGF.getVLASize(
3198 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
Sander de Smalen891af03a2018-02-03 13:55:59 +00003199 .NumElts,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003200 CGF.SizeTy, /*isSigned=*/false);
3201 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3202 Elem);
3203 }
3204 }
3205
3206 // 2. Emit reduce_func().
Alexey Bataev9ff80832018-04-16 20:16:21 +00003207 llvm::Value *ReductionFn = emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003208 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
3209 Privates, LHSExprs, RHSExprs, ReductionOps);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003210
3211 // 4. Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
3212 // RedList, shuffle_reduce_func, interwarp_copy_func);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003213 llvm::Value *ThreadId = getThreadID(CGF, Loc);
3214 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
3215 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003216 ReductionList.getPointer(), CGF.VoidPtrTy);
3217
Alexey Bataev9ff80832018-04-16 20:16:21 +00003218 llvm::Value *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003219 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003220 llvm::Value *InterWarpCopyFn =
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003221 emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003222
Alexey Bataevfac26cf2018-05-02 20:03:27 +00003223 llvm::Value *Args[] = {ThreadId,
3224 CGF.Builder.getInt32(RHSExprs.size()),
3225 ReductionArrayTySize,
3226 RL,
3227 ShuffleAndReduceFn,
3228 InterWarpCopyFn};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003229
Alexey Bataevfac26cf2018-05-02 20:03:27 +00003230 llvm::Value *Res = nullptr;
3231 if (ParallelReduction)
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003232 Res = CGF.EmitRuntimeCall(
3233 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_reduce_nowait),
3234 Args);
Alexey Bataevfac26cf2018-05-02 20:03:27 +00003235 else if (SimdReduction)
3236 Res = CGF.EmitRuntimeCall(
3237 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_simd_reduce_nowait),
3238 Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003239
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003240 if (TeamsReduction) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003241 llvm::Value *ScratchPadCopyFn =
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003242 emitCopyToScratchpad(CGM, Privates, ReductionArrayTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003243 llvm::Value *LoadAndReduceFn = emitReduceScratchpadFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003244 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003245
3246 llvm::Value *Args[] = {ThreadId,
3247 CGF.Builder.getInt32(RHSExprs.size()),
3248 ReductionArrayTySize,
3249 RL,
3250 ShuffleAndReduceFn,
3251 InterWarpCopyFn,
3252 ScratchPadCopyFn,
3253 LoadAndReduceFn};
3254 Res = CGF.EmitRuntimeCall(
3255 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_teams_reduce_nowait),
3256 Args);
3257 }
3258
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003259 // 5. Build switch(res)
Alexey Bataev9ff80832018-04-16 20:16:21 +00003260 llvm::BasicBlock *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
3261 llvm::SwitchInst *SwInst =
3262 CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003263
3264 // 6. Build case 1: where we have reduced values in the master
3265 // thread in each team.
3266 // __kmpc_end_reduce{_nowait}(<gtid>);
3267 // break;
Alexey Bataev9ff80832018-04-16 20:16:21 +00003268 llvm::BasicBlock *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003269 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
3270 CGF.EmitBlock(Case1BB);
3271
3272 // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
3273 llvm::Value *EndArgs[] = {ThreadId};
Alexey Bataev9ff80832018-04-16 20:16:21 +00003274 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003275 this](CodeGenFunction &CGF, PrePostActionTy &Action) {
3276 auto IPriv = Privates.begin();
3277 auto ILHS = LHSExprs.begin();
3278 auto IRHS = RHSExprs.begin();
Alexey Bataev9ff80832018-04-16 20:16:21 +00003279 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003280 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
3281 cast<DeclRefExpr>(*IRHS));
3282 ++IPriv;
3283 ++ILHS;
3284 ++IRHS;
3285 }
3286 };
3287 RegionCodeGenTy RCG(CodeGen);
3288 NVPTXActionTy Action(
3289 nullptr, llvm::None,
3290 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_reduce_nowait),
3291 EndArgs);
3292 RCG.setAction(Action);
3293 RCG(CGF);
3294 CGF.EmitBranch(DefaultBB);
3295 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
3296}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003297
3298const VarDecl *
3299CGOpenMPRuntimeNVPTX::translateParameter(const FieldDecl *FD,
3300 const VarDecl *NativeParam) const {
3301 if (!NativeParam->getType()->isReferenceType())
3302 return NativeParam;
3303 QualType ArgType = NativeParam->getType();
3304 QualifierCollector QC;
3305 const Type *NonQualTy = QC.strip(ArgType);
3306 QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
3307 if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
3308 if (Attr->getCaptureKind() == OMPC_map) {
3309 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
3310 LangAS::opencl_global);
3311 }
3312 }
3313 ArgType = CGM.getContext().getPointerType(PointeeTy);
3314 QC.addRestrict();
3315 enum { NVPTX_local_addr = 5 };
Alexander Richardson6d989432017-10-15 18:48:14 +00003316 QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003317 ArgType = QC.apply(CGM.getContext(), ArgType);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003318 if (isa<ImplicitParamDecl>(NativeParam))
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003319 return ImplicitParamDecl::Create(
3320 CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
3321 NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003322 return ParmVarDecl::Create(
3323 CGM.getContext(),
3324 const_cast<DeclContext *>(NativeParam->getDeclContext()),
3325 NativeParam->getLocStart(), NativeParam->getLocation(),
3326 NativeParam->getIdentifier(), ArgType,
3327 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003328}
3329
3330Address
3331CGOpenMPRuntimeNVPTX::getParameterAddress(CodeGenFunction &CGF,
3332 const VarDecl *NativeParam,
3333 const VarDecl *TargetParam) const {
3334 assert(NativeParam != TargetParam &&
3335 NativeParam->getType()->isReferenceType() &&
3336 "Native arg must not be the same as target arg.");
3337 Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
3338 QualType NativeParamType = NativeParam->getType();
3339 QualifierCollector QC;
3340 const Type *NonQualTy = QC.strip(NativeParamType);
3341 QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
3342 unsigned NativePointeeAddrSpace =
Alexander Richardson6d989432017-10-15 18:48:14 +00003343 CGF.getContext().getTargetAddressSpace(NativePointeeTy);
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00003344 QualType TargetTy = TargetParam->getType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003345 llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00003346 LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003347 // First cast to generic.
3348 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3349 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
3350 /*AddrSpace=*/0));
3351 // Cast from generic to native address space.
3352 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3353 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
3354 NativePointeeAddrSpace));
3355 Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
3356 CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00003357 NativeParamType);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003358 return NativeParamAddr;
3359}
3360
3361void CGOpenMPRuntimeNVPTX::emitOutlinedFunctionCall(
Alexey Bataev3c595a62017-08-14 15:01:03 +00003362 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003363 ArrayRef<llvm::Value *> Args) const {
3364 SmallVector<llvm::Value *, 4> TargetArgs;
Alexey Bataev07ed94a2017-08-15 14:34:04 +00003365 TargetArgs.reserve(Args.size());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003366 auto *FnType =
3367 cast<llvm::FunctionType>(OutlinedFn->getType()->getPointerElementType());
3368 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
Alexey Bataev07ed94a2017-08-15 14:34:04 +00003369 if (FnType->isVarArg() && FnType->getNumParams() <= I) {
3370 TargetArgs.append(std::next(Args.begin(), I), Args.end());
3371 break;
3372 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003373 llvm::Type *TargetType = FnType->getParamType(I);
3374 llvm::Value *NativeArg = Args[I];
3375 if (!TargetType->isPointerTy()) {
3376 TargetArgs.emplace_back(NativeArg);
3377 continue;
3378 }
3379 llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataevc99042b2018-03-15 18:10:54 +00003380 NativeArg,
3381 NativeArg->getType()->getPointerElementType()->getPointerTo());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003382 TargetArgs.emplace_back(
3383 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
3384 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00003385 CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003386}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003387
3388/// Emit function which wraps the outline parallel region
3389/// and controls the arguments which are passed to this function.
3390/// The wrapper ensures that the outlined function is called
3391/// with the correct arguments when data is shared.
3392llvm::Function *CGOpenMPRuntimeNVPTX::createParallelDataSharingWrapper(
3393 llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
3394 ASTContext &Ctx = CGM.getContext();
3395 const auto &CS = *D.getCapturedStmt(OMPD_parallel);
3396
3397 // Create a function that takes as argument the source thread.
3398 FunctionArgList WrapperArgs;
3399 QualType Int16QTy =
3400 Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
3401 QualType Int32QTy =
3402 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
3403 ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getLocStart(),
3404 /*Id=*/nullptr, Int16QTy,
3405 ImplicitParamDecl::Other);
3406 ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getLocStart(),
3407 /*Id=*/nullptr, Int32QTy,
3408 ImplicitParamDecl::Other);
3409 WrapperArgs.emplace_back(&ParallelLevelArg);
3410 WrapperArgs.emplace_back(&WrapperArg);
3411
Alexey Bataev9ff80832018-04-16 20:16:21 +00003412 const CGFunctionInfo &CGFI =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003413 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
3414
3415 auto *Fn = llvm::Function::Create(
3416 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataev9ff80832018-04-16 20:16:21 +00003417 Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
Alexey Bataevc99042b2018-03-15 18:10:54 +00003418 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003419 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003420 Fn->setDoesNotRecurse();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003421
3422 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3423 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
3424 D.getLocStart(), D.getLocStart());
3425
3426 const auto *RD = CS.getCapturedRecordDecl();
3427 auto CurField = RD->field_begin();
3428
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00003429 Address ZeroAddr = CGF.CreateMemTemp(
3430 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
3431 /*Name*/ ".zero.addr");
3432 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003433 // Get the array of arguments.
3434 SmallVector<llvm::Value *, 8> Args;
3435
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00003436 Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).getPointer());
3437 Args.emplace_back(ZeroAddr.getPointer());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003438
3439 CGBuilderTy &Bld = CGF.Builder;
3440 auto CI = CS.capture_begin();
3441
3442 // Use global memory for data sharing.
3443 // Handle passing of global args to workers.
3444 Address GlobalArgs =
3445 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
3446 llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
3447 llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
3448 CGF.EmitRuntimeCall(
3449 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_get_shared_variables),
3450 DataSharingArgs);
3451
3452 // Retrieve the shared variables from the list of references returned
3453 // by the runtime. Pass the variables to the outlined function.
Alexey Bataev17314212018-03-20 15:41:05 +00003454 Address SharedArgListAddress = Address::invalid();
3455 if (CS.capture_size() > 0 ||
3456 isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
3457 SharedArgListAddress = CGF.EmitLoadOfPointer(
3458 GlobalArgs, CGF.getContext()
3459 .getPointerType(CGF.getContext().getPointerType(
3460 CGF.getContext().VoidPtrTy))
3461 .castAs<PointerType>());
3462 }
3463 unsigned Idx = 0;
3464 if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
3465 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
3466 CGF.getPointerSize());
3467 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
3468 Src, CGF.SizeTy->getPointerTo());
3469 llvm::Value *LB = CGF.EmitLoadOfScalar(
3470 TypedAddress,
3471 /*Volatile=*/false,
3472 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
3473 cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
3474 Args.emplace_back(LB);
3475 ++Idx;
3476 Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
3477 CGF.getPointerSize());
3478 TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
3479 Src, CGF.SizeTy->getPointerTo());
3480 llvm::Value *UB = CGF.EmitLoadOfScalar(
3481 TypedAddress,
3482 /*Volatile=*/false,
3483 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
3484 cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
3485 Args.emplace_back(UB);
3486 ++Idx;
3487 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003488 if (CS.capture_size() > 0) {
3489 ASTContext &CGFContext = CGF.getContext();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003490 for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
3491 QualType ElemTy = CurField->getType();
Alexey Bataev17314212018-03-20 15:41:05 +00003492 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx,
3493 CGF.getPointerSize());
3494 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003495 Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)));
3496 llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
3497 /*Volatile=*/false,
3498 CGFContext.getPointerType(ElemTy),
3499 CI->getLocation());
Alexey Bataev2091ca62018-04-23 17:33:41 +00003500 if (CI->capturesVariableByCopy() &&
3501 !CI->getCapturedVar()->getType()->isAnyPointerType()) {
Alexey Bataev17314212018-03-20 15:41:05 +00003502 Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
3503 CI->getLocation());
3504 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003505 Args.emplace_back(Arg);
3506 }
3507 }
3508
3509 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedParallelFn, Args);
3510 CGF.FinishFunction();
3511 return Fn;
3512}
3513
3514void CGOpenMPRuntimeNVPTX::emitFunctionProlog(CodeGenFunction &CGF,
3515 const Decl *D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00003516 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
3517 return;
3518
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003519 assert(D && "Expected function or captured|block decl.");
3520 assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
3521 "Function is registered already.");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003522 const Stmt *Body = nullptr;
Alexey Bataevc99042b2018-03-15 18:10:54 +00003523 bool NeedToDelayGlobalization = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003524 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3525 Body = FD->getBody();
3526 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
3527 Body = BD->getBody();
3528 } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
3529 Body = CD->getBody();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003530 NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003531 }
3532 if (!Body)
3533 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003534 CheckVarsEscapingDeclContext VarChecker(CGF);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003535 VarChecker.Visit(Body);
3536 const RecordDecl *GlobalizedVarsRecord = VarChecker.getGlobalizedRecord();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003537 ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
3538 VarChecker.getEscapedVariableLengthDecls();
3539 if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003540 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +00003541 auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
3542 I->getSecond().MappedParams =
3543 llvm::make_unique<CodeGenFunction::OMPMapVars>();
3544 I->getSecond().GlobalRecord = GlobalizedVarsRecord;
3545 I->getSecond().EscapedParameters.insert(
3546 VarChecker.getEscapedParameters().begin(),
3547 VarChecker.getEscapedParameters().end());
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003548 I->getSecond().EscapedVariableLengthDecls.append(
3549 EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
Alexey Bataevc99042b2018-03-15 18:10:54 +00003550 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003551 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003552 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003553 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataevc99042b2018-03-15 18:10:54 +00003554 Data.insert(std::make_pair(VD, std::make_pair(FD, Address::invalid())));
3555 }
3556 if (!NeedToDelayGlobalization) {
3557 emitGenericVarsProlog(CGF, D->getLocStart());
3558 struct GlobalizationScope final : EHScopeStack::Cleanup {
3559 GlobalizationScope() = default;
3560
3561 void Emit(CodeGenFunction &CGF, Flags flags) override {
3562 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
3563 .emitGenericVarsEpilog(CGF);
3564 }
3565 };
3566 CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003567 }
3568}
3569
3570Address CGOpenMPRuntimeNVPTX::getAddressOfLocalVariable(CodeGenFunction &CGF,
3571 const VarDecl *VD) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00003572 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
3573 return Address::invalid();
3574
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003575 VD = VD->getCanonicalDecl();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003576 auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
3577 if (I == FunctionGlobalizedDecls.end())
3578 return Address::invalid();
Alexey Bataevc99042b2018-03-15 18:10:54 +00003579 auto VDI = I->getSecond().LocalVarData.find(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003580 if (VDI != I->getSecond().LocalVarData.end())
3581 return VDI->second.second;
3582 if (VD->hasAttrs()) {
3583 for (specific_attr_iterator<OMPReferencedVarAttr> IT(VD->attr_begin()),
3584 E(VD->attr_end());
3585 IT != E; ++IT) {
3586 auto VDI = I->getSecond().LocalVarData.find(
3587 cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
3588 ->getCanonicalDecl());
3589 if (VDI != I->getSecond().LocalVarData.end())
3590 return VDI->second.second;
3591 }
3592 }
3593 return Address::invalid();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003594}
3595
3596void CGOpenMPRuntimeNVPTX::functionFinished(CodeGenFunction &CGF) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003597 FunctionGlobalizedDecls.erase(CGF.CurFn);
3598 CGOpenMPRuntime::functionFinished(CGF);
3599}