Bug Summary

File:clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
Warning:line 4811, column 8
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CGOpenMPRuntimeNVPTX.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-11/lib/clang/11.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-11/lib/clang/11.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/lib/CodeGen -fdebug-prefix-map=/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-03-09-184146-41876-1 -x c++ /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
1//===---- CGOpenMPRuntimeNVPTX.cpp - Interface to OpenMP NVPTX Runtimes ---===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This provides a class for OpenMP runtime code generation specialized to NVPTX
10// targets.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGOpenMPRuntimeNVPTX.h"
15#include "CodeGenFunction.h"
16#include "clang/AST/Attr.h"
17#include "clang/AST/DeclOpenMP.h"
18#include "clang/AST/StmtOpenMP.h"
19#include "clang/AST/StmtVisitor.h"
20#include "clang/Basic/Cuda.h"
21#include "llvm/ADT/SmallPtrSet.h"
22#include "llvm/IR/IntrinsicsNVPTX.h"
23
24using namespace clang;
25using namespace CodeGen;
26using namespace llvm::omp;
27
28namespace {
29enum OpenMPRTLFunctionNVPTX {
30 /// Call to void __kmpc_kernel_init(kmp_int32 thread_limit,
31 /// int16_t RequiresOMPRuntime);
32 OMPRTL_NVPTX__kmpc_kernel_init,
33 /// Call to void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
34 OMPRTL_NVPTX__kmpc_kernel_deinit,
35 /// Call to void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
36 /// int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
37 OMPRTL_NVPTX__kmpc_spmd_kernel_init,
38 /// Call to void __kmpc_spmd_kernel_deinit_v2(int16_t RequiresOMPRuntime);
39 OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2,
40 /// Call to void __kmpc_kernel_prepare_parallel(void
41 /// *outlined_function, int16_t
42 /// IsOMPRuntimeInitialized);
43 OMPRTL_NVPTX__kmpc_kernel_prepare_parallel,
44 /// Call to bool __kmpc_kernel_parallel(void **outlined_function,
45 /// int16_t IsOMPRuntimeInitialized);
46 OMPRTL_NVPTX__kmpc_kernel_parallel,
47 /// Call to void __kmpc_kernel_end_parallel();
48 OMPRTL_NVPTX__kmpc_kernel_end_parallel,
49 /// Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
50 /// global_tid);
51 OMPRTL_NVPTX__kmpc_serialized_parallel,
52 /// Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
53 /// global_tid);
54 OMPRTL_NVPTX__kmpc_end_serialized_parallel,
55 /// Call to int32_t __kmpc_shuffle_int32(int32_t element,
56 /// int16_t lane_offset, int16_t warp_size);
57 OMPRTL_NVPTX__kmpc_shuffle_int32,
58 /// Call to int64_t __kmpc_shuffle_int64(int64_t element,
59 /// int16_t lane_offset, int16_t warp_size);
60 OMPRTL_NVPTX__kmpc_shuffle_int64,
61 /// Call to __kmpc_nvptx_parallel_reduce_nowait_v2(ident_t *loc, kmp_int32
62 /// global_tid, kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
63 /// void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
64 /// lane_offset, int16_t shortCircuit),
65 /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num));
66 OMPRTL_NVPTX__kmpc_nvptx_parallel_reduce_nowait_v2,
67 /// Call to __kmpc_nvptx_teams_reduce_nowait_v2(ident_t *loc, kmp_int32
68 /// global_tid, void *global_buffer, int32_t num_of_records, void*
69 /// reduce_data,
70 /// void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
71 /// lane_offset, int16_t shortCircuit),
72 /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num), void
73 /// (*kmp_ListToGlobalCpyFctPtr)(void *buffer, int idx, void *reduce_data),
74 /// void (*kmp_GlobalToListCpyFctPtr)(void *buffer, int idx,
75 /// void *reduce_data), void (*kmp_GlobalToListCpyPtrsFctPtr)(void *buffer,
76 /// int idx, void *reduce_data), void (*kmp_GlobalToListRedFctPtr)(void
77 /// *buffer, int idx, void *reduce_data));
78 OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_v2,
79 /// Call to __kmpc_nvptx_end_reduce_nowait(int32_t global_tid);
80 OMPRTL_NVPTX__kmpc_end_reduce_nowait,
81 /// Call to void __kmpc_data_sharing_init_stack();
82 OMPRTL_NVPTX__kmpc_data_sharing_init_stack,
83 /// Call to void __kmpc_data_sharing_init_stack_spmd();
84 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd,
85 /// Call to void* __kmpc_data_sharing_coalesced_push_stack(size_t size,
86 /// int16_t UseSharedMemory);
87 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack,
88 /// Call to void __kmpc_data_sharing_pop_stack(void *a);
89 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack,
90 /// Call to void __kmpc_begin_sharing_variables(void ***args,
91 /// size_t n_args);
92 OMPRTL_NVPTX__kmpc_begin_sharing_variables,
93 /// Call to void __kmpc_end_sharing_variables();
94 OMPRTL_NVPTX__kmpc_end_sharing_variables,
95 /// Call to void __kmpc_get_shared_variables(void ***GlobalArgs)
96 OMPRTL_NVPTX__kmpc_get_shared_variables,
97 /// Call to uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32
98 /// global_tid);
99 OMPRTL_NVPTX__kmpc_parallel_level,
100 /// Call to int8_t __kmpc_is_spmd_exec_mode();
101 OMPRTL_NVPTX__kmpc_is_spmd_exec_mode,
102 /// Call to void __kmpc_get_team_static_memory(int16_t isSPMDExecutionMode,
103 /// const void *buf, size_t size, int16_t is_shared, const void **res);
104 OMPRTL_NVPTX__kmpc_get_team_static_memory,
105 /// Call to void __kmpc_restore_team_static_memory(int16_t
106 /// isSPMDExecutionMode, int16_t is_shared);
107 OMPRTL_NVPTX__kmpc_restore_team_static_memory,
108 /// Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
109 OMPRTL__kmpc_barrier,
110 /// Call to void __kmpc_barrier_simple_spmd(ident_t *loc, kmp_int32
111 /// global_tid);
112 OMPRTL__kmpc_barrier_simple_spmd,
113 /// Call to int32_t __kmpc_warp_active_thread_mask(void);
114 OMPRTL_NVPTX__kmpc_warp_active_thread_mask,
115 /// Call to void __kmpc_syncwarp(int32_t Mask);
116 OMPRTL_NVPTX__kmpc_syncwarp,
117};
118
119/// Pre(post)-action for different OpenMP constructs specialized for NVPTX.
120class NVPTXActionTy final : public PrePostActionTy {
121 llvm::FunctionCallee EnterCallee = nullptr;
122 ArrayRef<llvm::Value *> EnterArgs;
123 llvm::FunctionCallee ExitCallee = nullptr;
124 ArrayRef<llvm::Value *> ExitArgs;
125 bool Conditional = false;
126 llvm::BasicBlock *ContBlock = nullptr;
127
128public:
129 NVPTXActionTy(llvm::FunctionCallee EnterCallee,
130 ArrayRef<llvm::Value *> EnterArgs,
131 llvm::FunctionCallee ExitCallee,
132 ArrayRef<llvm::Value *> ExitArgs, bool Conditional = false)
133 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
134 ExitArgs(ExitArgs), Conditional(Conditional) {}
135 void Enter(CodeGenFunction &CGF) override {
136 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
137 if (Conditional) {
138 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
139 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
140 ContBlock = CGF.createBasicBlock("omp_if.end");
141 // Generate the branch (If-stmt)
142 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
143 CGF.EmitBlock(ThenBlock);
144 }
145 }
146 void Done(CodeGenFunction &CGF) {
147 // Emit the rest of blocks/branches
148 CGF.EmitBranch(ContBlock);
149 CGF.EmitBlock(ContBlock, true);
150 }
151 void Exit(CodeGenFunction &CGF) override {
152 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
153 }
154};
155
156/// A class to track the execution mode when codegening directives within
157/// a target region. The appropriate mode (SPMD|NON-SPMD) is set on entry
158/// to the target region and used by containing directives such as 'parallel'
159/// to emit optimized code.
160class ExecutionRuntimeModesRAII {
161private:
162 CGOpenMPRuntimeNVPTX::ExecutionMode SavedExecMode =
163 CGOpenMPRuntimeNVPTX::EM_Unknown;
164 CGOpenMPRuntimeNVPTX::ExecutionMode &ExecMode;
165 bool SavedRuntimeMode = false;
166 bool *RuntimeMode = nullptr;
167
168public:
169 /// Constructor for Non-SPMD mode.
170 ExecutionRuntimeModesRAII(CGOpenMPRuntimeNVPTX::ExecutionMode &ExecMode)
171 : ExecMode(ExecMode) {
172 SavedExecMode = ExecMode;
173 ExecMode = CGOpenMPRuntimeNVPTX::EM_NonSPMD;
174 }
175 /// Constructor for SPMD mode.
176 ExecutionRuntimeModesRAII(CGOpenMPRuntimeNVPTX::ExecutionMode &ExecMode,
177 bool &RuntimeMode, bool FullRuntimeMode)
178 : ExecMode(ExecMode), RuntimeMode(&RuntimeMode) {
179 SavedExecMode = ExecMode;
180 SavedRuntimeMode = RuntimeMode;
181 ExecMode = CGOpenMPRuntimeNVPTX::EM_SPMD;
182 RuntimeMode = FullRuntimeMode;
183 }
184 ~ExecutionRuntimeModesRAII() {
185 ExecMode = SavedExecMode;
186 if (RuntimeMode)
187 *RuntimeMode = SavedRuntimeMode;
188 }
189};
190
191/// GPU Configuration: This information can be derived from cuda registers,
192/// however, providing compile time constants helps generate more efficient
193/// code. For all practical purposes this is fine because the configuration
194/// is the same for all known NVPTX architectures.
195enum MachineConfiguration : unsigned {
196 WarpSize = 32,
197 /// Number of bits required to represent a lane identifier, which is
198 /// computed as log_2(WarpSize).
199 LaneIDBits = 5,
200 LaneIDMask = WarpSize - 1,
201
202 /// Global memory alignment for performance.
203 GlobalMemoryAlignment = 128,
204
205 /// Maximal size of the shared memory buffer.
206 SharedMemorySize = 128,
207};
208
209static const ValueDecl *getPrivateItem(const Expr *RefExpr) {
210 RefExpr = RefExpr->IgnoreParens();
211 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr)) {
212 const Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
213 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
214 Base = TempASE->getBase()->IgnoreParenImpCasts();
215 RefExpr = Base;
216 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr)) {
217 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
218 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
219 Base = TempOASE->getBase()->IgnoreParenImpCasts();
220 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
221 Base = TempASE->getBase()->IgnoreParenImpCasts();
222 RefExpr = Base;
223 }
224 RefExpr = RefExpr->IgnoreParenImpCasts();
225 if (const auto *DE = dyn_cast<DeclRefExpr>(RefExpr))
226 return cast<ValueDecl>(DE->getDecl()->getCanonicalDecl());
227 const auto *ME = cast<MemberExpr>(RefExpr);
228 return cast<ValueDecl>(ME->getMemberDecl()->getCanonicalDecl());
229}
230
231
232static RecordDecl *buildRecordForGlobalizedVars(
233 ASTContext &C, ArrayRef<const ValueDecl *> EscapedDecls,
234 ArrayRef<const ValueDecl *> EscapedDeclsForTeams,
235 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
236 &MappedDeclsFields, int BufSize) {
237 using VarsDataTy = std::pair<CharUnits /*Align*/, const ValueDecl *>;
238 if (EscapedDecls.empty() && EscapedDeclsForTeams.empty())
239 return nullptr;
240 SmallVector<VarsDataTy, 4> GlobalizedVars;
241 for (const ValueDecl *D : EscapedDecls)
242 GlobalizedVars.emplace_back(
243 CharUnits::fromQuantity(std::max(
244 C.getDeclAlign(D).getQuantity(),
245 static_cast<CharUnits::QuantityType>(GlobalMemoryAlignment))),
246 D);
247 for (const ValueDecl *D : EscapedDeclsForTeams)
248 GlobalizedVars.emplace_back(C.getDeclAlign(D), D);
249 llvm::stable_sort(GlobalizedVars, [](VarsDataTy L, VarsDataTy R) {
250 return L.first > R.first;
251 });
252
253 // Build struct _globalized_locals_ty {
254 // /* globalized vars */[WarSize] align (max(decl_align,
255 // GlobalMemoryAlignment))
256 // /* globalized vars */ for EscapedDeclsForTeams
257 // };
258 RecordDecl *GlobalizedRD = C.buildImplicitRecord("_globalized_locals_ty");
259 GlobalizedRD->startDefinition();
260 llvm::SmallPtrSet<const ValueDecl *, 16> SingleEscaped(
261 EscapedDeclsForTeams.begin(), EscapedDeclsForTeams.end());
262 for (const auto &Pair : GlobalizedVars) {
263 const ValueDecl *VD = Pair.second;
264 QualType Type = VD->getType();
265 if (Type->isLValueReferenceType())
266 Type = C.getPointerType(Type.getNonReferenceType());
267 else
268 Type = Type.getNonReferenceType();
269 SourceLocation Loc = VD->getLocation();
270 FieldDecl *Field;
271 if (SingleEscaped.count(VD)) {
272 Field = FieldDecl::Create(
273 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
274 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
275 /*BW=*/nullptr, /*Mutable=*/false,
276 /*InitStyle=*/ICIS_NoInit);
277 Field->setAccess(AS_public);
278 if (VD->hasAttrs()) {
279 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
280 E(VD->getAttrs().end());
281 I != E; ++I)
282 Field->addAttr(*I);
283 }
284 } else {
285 llvm::APInt ArraySize(32, BufSize);
286 Type = C.getConstantArrayType(Type, ArraySize, nullptr, ArrayType::Normal,
287 0);
288 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 llvm::APInt Align(32, std::max(C.getDeclAlign(VD).getQuantity(),
295 static_cast<CharUnits::QuantityType>(
296 GlobalMemoryAlignment)));
297 Field->addAttr(AlignedAttr::CreateImplicit(
298 C, /*IsAlignmentExpr=*/true,
299 IntegerLiteral::Create(C, Align,
300 C.getIntTypeForBitwidth(32, /*Signed=*/0),
301 SourceLocation()),
302 {}, AttributeCommonInfo::AS_GNU, AlignedAttr::GNU_aligned));
303 }
304 GlobalizedRD->addDecl(Field);
305 MappedDeclsFields.try_emplace(VD, Field);
306 }
307 GlobalizedRD->completeDefinition();
308 return GlobalizedRD;
309}
310
311/// Get the list of variables that can escape their declaration context.
312class CheckVarsEscapingDeclContext final
313 : public ConstStmtVisitor<CheckVarsEscapingDeclContext> {
314 CodeGenFunction &CGF;
315 llvm::SetVector<const ValueDecl *> EscapedDecls;
316 llvm::SetVector<const ValueDecl *> EscapedVariableLengthDecls;
317 llvm::SmallPtrSet<const Decl *, 4> EscapedParameters;
318 RecordDecl *GlobalizedRD = nullptr;
319 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
320 bool AllEscaped = false;
321 bool IsForCombinedParallelRegion = false;
322
323 void markAsEscaped(const ValueDecl *VD) {
324 // Do not globalize declare target variables.
325 if (!isa<VarDecl>(VD) ||
326 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
327 return;
328 VD = cast<ValueDecl>(VD->getCanonicalDecl());
329 // Use user-specified allocation.
330 if (VD->hasAttrs() && VD->hasAttr<OMPAllocateDeclAttr>())
331 return;
332 // Variables captured by value must be globalized.
333 if (auto *CSI = CGF.CapturedStmtInfo) {
334 if (const FieldDecl *FD = CSI->lookup(cast<VarDecl>(VD))) {
335 // Check if need to capture the variable that was already captured by
336 // value in the outer region.
337 if (!IsForCombinedParallelRegion) {
338 if (!FD->hasAttrs())
339 return;
340 const auto *Attr = FD->getAttr<OMPCaptureKindAttr>();
341 if (!Attr)
342 return;
343 if (((Attr->getCaptureKind() != OMPC_map) &&
344 !isOpenMPPrivate(
345 static_cast<OpenMPClauseKind>(Attr->getCaptureKind()))) ||
346 ((Attr->getCaptureKind() == OMPC_map) &&
347 !FD->getType()->isAnyPointerType()))
348 return;
349 }
350 if (!FD->getType()->isReferenceType()) {
351 assert(!VD->getType()->isVariablyModifiedType() &&((!VD->getType()->isVariablyModifiedType() && "Parameter captured by value with variably modified type"
) ? static_cast<void> (0) : __assert_fail ("!VD->getType()->isVariablyModifiedType() && \"Parameter captured by value with variably modified type\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 352, __PRETTY_FUNCTION__))
352 "Parameter captured by value with variably modified type")((!VD->getType()->isVariablyModifiedType() && "Parameter captured by value with variably modified type"
) ? static_cast<void> (0) : __assert_fail ("!VD->getType()->isVariablyModifiedType() && \"Parameter captured by value with variably modified type\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 352, __PRETTY_FUNCTION__))
;
353 EscapedParameters.insert(VD);
354 } else if (!IsForCombinedParallelRegion) {
355 return;
356 }
357 }
358 }
359 if ((!CGF.CapturedStmtInfo ||
360 (IsForCombinedParallelRegion && CGF.CapturedStmtInfo)) &&
361 VD->getType()->isReferenceType())
362 // Do not globalize variables with reference type.
363 return;
364 if (VD->getType()->isVariablyModifiedType())
365 EscapedVariableLengthDecls.insert(VD);
366 else
367 EscapedDecls.insert(VD);
368 }
369
370 void VisitValueDecl(const ValueDecl *VD) {
371 if (VD->getType()->isLValueReferenceType())
372 markAsEscaped(VD);
373 if (const auto *VarD = dyn_cast<VarDecl>(VD)) {
374 if (!isa<ParmVarDecl>(VarD) && VarD->hasInit()) {
375 const bool SavedAllEscaped = AllEscaped;
376 AllEscaped = VD->getType()->isLValueReferenceType();
377 Visit(VarD->getInit());
378 AllEscaped = SavedAllEscaped;
379 }
380 }
381 }
382 void VisitOpenMPCapturedStmt(const CapturedStmt *S,
383 ArrayRef<OMPClause *> Clauses,
384 bool IsCombinedParallelRegion) {
385 if (!S)
386 return;
387 for (const CapturedStmt::Capture &C : S->captures()) {
388 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
389 const ValueDecl *VD = C.getCapturedVar();
390 bool SavedIsForCombinedParallelRegion = IsForCombinedParallelRegion;
391 if (IsCombinedParallelRegion) {
392 // Check if the variable is privatized in the combined construct and
393 // those private copies must be shared in the inner parallel
394 // directive.
395 IsForCombinedParallelRegion = false;
396 for (const OMPClause *C : Clauses) {
397 if (!isOpenMPPrivate(C->getClauseKind()) ||
398 C->getClauseKind() == OMPC_reduction ||
399 C->getClauseKind() == OMPC_linear ||
400 C->getClauseKind() == OMPC_private)
401 continue;
402 ArrayRef<const Expr *> Vars;
403 if (const auto *PC = dyn_cast<OMPFirstprivateClause>(C))
404 Vars = PC->getVarRefs();
405 else if (const auto *PC = dyn_cast<OMPLastprivateClause>(C))
406 Vars = PC->getVarRefs();
407 else
408 llvm_unreachable("Unexpected clause.")::llvm::llvm_unreachable_internal("Unexpected clause.", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 408)
;
409 for (const auto *E : Vars) {
410 const Decl *D =
411 cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
412 if (D == VD->getCanonicalDecl()) {
413 IsForCombinedParallelRegion = true;
414 break;
415 }
416 }
417 if (IsForCombinedParallelRegion)
418 break;
419 }
420 }
421 markAsEscaped(VD);
422 if (isa<OMPCapturedExprDecl>(VD))
423 VisitValueDecl(VD);
424 IsForCombinedParallelRegion = SavedIsForCombinedParallelRegion;
425 }
426 }
427 }
428
429 void buildRecordForGlobalizedVars(bool IsInTTDRegion) {
430 assert(!GlobalizedRD &&((!GlobalizedRD && "Record for globalized variables is built already."
) ? static_cast<void> (0) : __assert_fail ("!GlobalizedRD && \"Record for globalized variables is built already.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 431, __PRETTY_FUNCTION__))
431 "Record for globalized variables is built already.")((!GlobalizedRD && "Record for globalized variables is built already."
) ? static_cast<void> (0) : __assert_fail ("!GlobalizedRD && \"Record for globalized variables is built already.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 431, __PRETTY_FUNCTION__))
;
432 ArrayRef<const ValueDecl *> EscapedDeclsForParallel, EscapedDeclsForTeams;
433 if (IsInTTDRegion)
434 EscapedDeclsForTeams = EscapedDecls.getArrayRef();
435 else
436 EscapedDeclsForParallel = EscapedDecls.getArrayRef();
437 GlobalizedRD = ::buildRecordForGlobalizedVars(
438 CGF.getContext(), EscapedDeclsForParallel, EscapedDeclsForTeams,
439 MappedDeclsFields, WarpSize);
440 }
441
442public:
443 CheckVarsEscapingDeclContext(CodeGenFunction &CGF,
444 ArrayRef<const ValueDecl *> TeamsReductions)
445 : CGF(CGF), EscapedDecls(TeamsReductions.begin(), TeamsReductions.end()) {
446 }
447 virtual ~CheckVarsEscapingDeclContext() = default;
448 void VisitDeclStmt(const DeclStmt *S) {
449 if (!S)
450 return;
451 for (const Decl *D : S->decls())
452 if (const auto *VD = dyn_cast_or_null<ValueDecl>(D))
453 VisitValueDecl(VD);
454 }
455 void VisitOMPExecutableDirective(const OMPExecutableDirective *D) {
456 if (!D)
457 return;
458 if (!D->hasAssociatedStmt())
459 return;
460 if (const auto *S =
461 dyn_cast_or_null<CapturedStmt>(D->getAssociatedStmt())) {
462 // Do not analyze directives that do not actually require capturing,
463 // like `omp for` or `omp simd` directives.
464 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
465 getOpenMPCaptureRegions(CaptureRegions, D->getDirectiveKind());
466 if (CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown) {
467 VisitStmt(S->getCapturedStmt());
468 return;
469 }
470 VisitOpenMPCapturedStmt(
471 S, D->clauses(),
472 CaptureRegions.back() == OMPD_parallel &&
473 isOpenMPDistributeDirective(D->getDirectiveKind()));
474 }
475 }
476 void VisitCapturedStmt(const CapturedStmt *S) {
477 if (!S)
478 return;
479 for (const CapturedStmt::Capture &C : S->captures()) {
480 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
481 const ValueDecl *VD = C.getCapturedVar();
482 markAsEscaped(VD);
483 if (isa<OMPCapturedExprDecl>(VD))
484 VisitValueDecl(VD);
485 }
486 }
487 }
488 void VisitLambdaExpr(const LambdaExpr *E) {
489 if (!E)
490 return;
491 for (const LambdaCapture &C : E->captures()) {
492 if (C.capturesVariable()) {
493 if (C.getCaptureKind() == LCK_ByRef) {
494 const ValueDecl *VD = C.getCapturedVar();
495 markAsEscaped(VD);
496 if (E->isInitCapture(&C) || isa<OMPCapturedExprDecl>(VD))
497 VisitValueDecl(VD);
498 }
499 }
500 }
501 }
502 void VisitBlockExpr(const BlockExpr *E) {
503 if (!E)
504 return;
505 for (const BlockDecl::Capture &C : E->getBlockDecl()->captures()) {
506 if (C.isByRef()) {
507 const VarDecl *VD = C.getVariable();
508 markAsEscaped(VD);
509 if (isa<OMPCapturedExprDecl>(VD) || VD->isInitCapture())
510 VisitValueDecl(VD);
511 }
512 }
513 }
514 void VisitCallExpr(const CallExpr *E) {
515 if (!E)
516 return;
517 for (const Expr *Arg : E->arguments()) {
518 if (!Arg)
519 continue;
520 if (Arg->isLValue()) {
521 const bool SavedAllEscaped = AllEscaped;
522 AllEscaped = true;
523 Visit(Arg);
524 AllEscaped = SavedAllEscaped;
525 } else {
526 Visit(Arg);
527 }
528 }
529 Visit(E->getCallee());
530 }
531 void VisitDeclRefExpr(const DeclRefExpr *E) {
532 if (!E)
533 return;
534 const ValueDecl *VD = E->getDecl();
535 if (AllEscaped)
536 markAsEscaped(VD);
537 if (isa<OMPCapturedExprDecl>(VD))
538 VisitValueDecl(VD);
539 else if (const auto *VarD = dyn_cast<VarDecl>(VD))
540 if (VarD->isInitCapture())
541 VisitValueDecl(VD);
542 }
543 void VisitUnaryOperator(const UnaryOperator *E) {
544 if (!E)
545 return;
546 if (E->getOpcode() == UO_AddrOf) {
547 const bool SavedAllEscaped = AllEscaped;
548 AllEscaped = true;
549 Visit(E->getSubExpr());
550 AllEscaped = SavedAllEscaped;
551 } else {
552 Visit(E->getSubExpr());
553 }
554 }
555 void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
556 if (!E)
557 return;
558 if (E->getCastKind() == CK_ArrayToPointerDecay) {
559 const bool SavedAllEscaped = AllEscaped;
560 AllEscaped = true;
561 Visit(E->getSubExpr());
562 AllEscaped = SavedAllEscaped;
563 } else {
564 Visit(E->getSubExpr());
565 }
566 }
567 void VisitExpr(const Expr *E) {
568 if (!E)
569 return;
570 bool SavedAllEscaped = AllEscaped;
571 if (!E->isLValue())
572 AllEscaped = false;
573 for (const Stmt *Child : E->children())
574 if (Child)
575 Visit(Child);
576 AllEscaped = SavedAllEscaped;
577 }
578 void VisitStmt(const Stmt *S) {
579 if (!S)
580 return;
581 for (const Stmt *Child : S->children())
582 if (Child)
583 Visit(Child);
584 }
585
586 /// Returns the record that handles all the escaped local variables and used
587 /// instead of their original storage.
588 const RecordDecl *getGlobalizedRecord(bool IsInTTDRegion) {
589 if (!GlobalizedRD)
590 buildRecordForGlobalizedVars(IsInTTDRegion);
591 return GlobalizedRD;
592 }
593
594 /// Returns the field in the globalized record for the escaped variable.
595 const FieldDecl *getFieldForGlobalizedVar(const ValueDecl *VD) const {
596 assert(GlobalizedRD &&((GlobalizedRD && "Record for globalized variables must be generated already."
) ? static_cast<void> (0) : __assert_fail ("GlobalizedRD && \"Record for globalized variables must be generated already.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 597, __PRETTY_FUNCTION__))
597 "Record for globalized variables must be generated already.")((GlobalizedRD && "Record for globalized variables must be generated already."
) ? static_cast<void> (0) : __assert_fail ("GlobalizedRD && \"Record for globalized variables must be generated already.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 597, __PRETTY_FUNCTION__))
;
598 auto I = MappedDeclsFields.find(VD);
599 if (I == MappedDeclsFields.end())
600 return nullptr;
601 return I->getSecond();
602 }
603
604 /// Returns the list of the escaped local variables/parameters.
605 ArrayRef<const ValueDecl *> getEscapedDecls() const {
606 return EscapedDecls.getArrayRef();
607 }
608
609 /// Checks if the escaped local variable is actually a parameter passed by
610 /// value.
611 const llvm::SmallPtrSetImpl<const Decl *> &getEscapedParameters() const {
612 return EscapedParameters;
613 }
614
615 /// Returns the list of the escaped variables with the variably modified
616 /// types.
617 ArrayRef<const ValueDecl *> getEscapedVariableLengthDecls() const {
618 return EscapedVariableLengthDecls.getArrayRef();
619 }
620};
621} // anonymous namespace
622
623/// Get the GPU warp size.
624static llvm::Value *getNVPTXWarpSize(CodeGenFunction &CGF) {
625 return CGF.EmitRuntimeCall(
626 llvm::Intrinsic::getDeclaration(
627 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_warpsize),
628 "nvptx_warp_size");
629}
630
631/// Get the id of the current thread on the GPU.
632static llvm::Value *getNVPTXThreadID(CodeGenFunction &CGF) {
633 return CGF.EmitRuntimeCall(
634 llvm::Intrinsic::getDeclaration(
635 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_tid_x),
636 "nvptx_tid");
637}
638
639/// Get the id of the warp in the block.
640/// We assume that the warp size is 32, which is always the case
641/// on the NVPTX device, to generate more efficient code.
642static llvm::Value *getNVPTXWarpID(CodeGenFunction &CGF) {
643 CGBuilderTy &Bld = CGF.Builder;
644 return Bld.CreateAShr(getNVPTXThreadID(CGF), LaneIDBits, "nvptx_warp_id");
645}
646
647/// Get the id of the current lane in the Warp.
648/// We assume that the warp size is 32, which is always the case
649/// on the NVPTX device, to generate more efficient code.
650static llvm::Value *getNVPTXLaneID(CodeGenFunction &CGF) {
651 CGBuilderTy &Bld = CGF.Builder;
652 return Bld.CreateAnd(getNVPTXThreadID(CGF), Bld.getInt32(LaneIDMask),
653 "nvptx_lane_id");
654}
655
656/// Get the maximum number of threads in a block of the GPU.
657static llvm::Value *getNVPTXNumThreads(CodeGenFunction &CGF) {
658 return CGF.EmitRuntimeCall(
659 llvm::Intrinsic::getDeclaration(
660 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_ntid_x),
661 "nvptx_num_threads");
662}
663
664/// Get the value of the thread_limit clause in the teams directive.
665/// For the 'generic' execution mode, the runtime encodes thread_limit in
666/// the launch parameters, always starting thread_limit+warpSize threads per
667/// CTA. The threads in the last warp are reserved for master execution.
668/// For the 'spmd' execution mode, all threads in a CTA are part of the team.
669static llvm::Value *getThreadLimit(CodeGenFunction &CGF,
670 bool IsInSPMDExecutionMode = false) {
671 CGBuilderTy &Bld = CGF.Builder;
672 return IsInSPMDExecutionMode
673 ? getNVPTXNumThreads(CGF)
674 : Bld.CreateNUWSub(getNVPTXNumThreads(CGF), getNVPTXWarpSize(CGF),
675 "thread_limit");
676}
677
678/// Get the thread id of the OMP master thread.
679/// The master thread id is the first thread (lane) of the last warp in the
680/// GPU block. Warp size is assumed to be some power of 2.
681/// Thread id is 0 indexed.
682/// E.g: If NumThreads is 33, master id is 32.
683/// If NumThreads is 64, master id is 32.
684/// If NumThreads is 1024, master id is 992.
685static llvm::Value *getMasterThreadID(CodeGenFunction &CGF) {
686 CGBuilderTy &Bld = CGF.Builder;
687 llvm::Value *NumThreads = getNVPTXNumThreads(CGF);
688
689 // We assume that the warp size is a power of 2.
690 llvm::Value *Mask = Bld.CreateNUWSub(getNVPTXWarpSize(CGF), Bld.getInt32(1));
691
692 return Bld.CreateAnd(Bld.CreateNUWSub(NumThreads, Bld.getInt32(1)),
693 Bld.CreateNot(Mask), "master_tid");
694}
695
696CGOpenMPRuntimeNVPTX::WorkerFunctionState::WorkerFunctionState(
697 CodeGenModule &CGM, SourceLocation Loc)
698 : WorkerFn(nullptr), CGFI(CGM.getTypes().arrangeNullaryFunction()),
699 Loc(Loc) {
700 createWorkerFunction(CGM);
701}
702
703void CGOpenMPRuntimeNVPTX::WorkerFunctionState::createWorkerFunction(
704 CodeGenModule &CGM) {
705 // Create an worker function with no arguments.
706
707 WorkerFn = llvm::Function::Create(
708 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
709 /*placeholder=*/"_worker", &CGM.getModule());
710 CGM.SetInternalFunctionAttributes(GlobalDecl(), WorkerFn, CGFI);
711 WorkerFn->setDoesNotRecurse();
712}
713
714CGOpenMPRuntimeNVPTX::ExecutionMode
715CGOpenMPRuntimeNVPTX::getExecutionMode() const {
716 return CurrentExecutionMode;
717}
718
719static CGOpenMPRuntimeNVPTX::DataSharingMode
720getDataSharingMode(CodeGenModule &CGM) {
721 return CGM.getLangOpts().OpenMPCUDAMode ? CGOpenMPRuntimeNVPTX::CUDA
722 : CGOpenMPRuntimeNVPTX::Generic;
723}
724
725/// Check for inner (nested) SPMD construct, if any
726static bool hasNestedSPMDDirective(ASTContext &Ctx,
727 const OMPExecutableDirective &D) {
728 const auto *CS = D.getInnermostCapturedStmt();
729 const auto *Body =
730 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
731 const Stmt *ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
732
733 if (const auto *NestedDir =
734 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
735 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
736 switch (D.getDirectiveKind()) {
737 case OMPD_target:
738 if (isOpenMPParallelDirective(DKind))
739 return true;
740 if (DKind == OMPD_teams) {
741 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
742 /*IgnoreCaptured=*/true);
743 if (!Body)
744 return false;
745 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
746 if (const auto *NND =
747 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
748 DKind = NND->getDirectiveKind();
749 if (isOpenMPParallelDirective(DKind))
750 return true;
751 }
752 }
753 return false;
754 case OMPD_target_teams:
755 return isOpenMPParallelDirective(DKind);
756 case OMPD_target_simd:
757 case OMPD_target_parallel:
758 case OMPD_target_parallel_for:
759 case OMPD_target_parallel_for_simd:
760 case OMPD_target_teams_distribute:
761 case OMPD_target_teams_distribute_simd:
762 case OMPD_target_teams_distribute_parallel_for:
763 case OMPD_target_teams_distribute_parallel_for_simd:
764 case OMPD_parallel:
765 case OMPD_for:
766 case OMPD_parallel_for:
767 case OMPD_parallel_master:
768 case OMPD_parallel_sections:
769 case OMPD_for_simd:
770 case OMPD_parallel_for_simd:
771 case OMPD_cancel:
772 case OMPD_cancellation_point:
773 case OMPD_ordered:
774 case OMPD_threadprivate:
775 case OMPD_allocate:
776 case OMPD_task:
777 case OMPD_simd:
778 case OMPD_sections:
779 case OMPD_section:
780 case OMPD_single:
781 case OMPD_master:
782 case OMPD_critical:
783 case OMPD_taskyield:
784 case OMPD_barrier:
785 case OMPD_taskwait:
786 case OMPD_taskgroup:
787 case OMPD_atomic:
788 case OMPD_flush:
789 case OMPD_depobj:
790 case OMPD_teams:
791 case OMPD_target_data:
792 case OMPD_target_exit_data:
793 case OMPD_target_enter_data:
794 case OMPD_distribute:
795 case OMPD_distribute_simd:
796 case OMPD_distribute_parallel_for:
797 case OMPD_distribute_parallel_for_simd:
798 case OMPD_teams_distribute:
799 case OMPD_teams_distribute_simd:
800 case OMPD_teams_distribute_parallel_for:
801 case OMPD_teams_distribute_parallel_for_simd:
802 case OMPD_target_update:
803 case OMPD_declare_simd:
804 case OMPD_declare_variant:
805 case OMPD_declare_target:
806 case OMPD_end_declare_target:
807 case OMPD_declare_reduction:
808 case OMPD_declare_mapper:
809 case OMPD_taskloop:
810 case OMPD_taskloop_simd:
811 case OMPD_master_taskloop:
812 case OMPD_master_taskloop_simd:
813 case OMPD_parallel_master_taskloop:
814 case OMPD_parallel_master_taskloop_simd:
815 case OMPD_requires:
816 case OMPD_unknown:
817 llvm_unreachable("Unexpected directive.")::llvm::llvm_unreachable_internal("Unexpected directive.", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 817)
;
818 }
819 }
820
821 return false;
822}
823
824static bool supportsSPMDExecutionMode(ASTContext &Ctx,
825 const OMPExecutableDirective &D) {
826 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
827 switch (DirectiveKind) {
828 case OMPD_target:
829 case OMPD_target_teams:
830 return hasNestedSPMDDirective(Ctx, D);
831 case OMPD_target_parallel:
832 case OMPD_target_parallel_for:
833 case OMPD_target_parallel_for_simd:
834 case OMPD_target_teams_distribute_parallel_for:
835 case OMPD_target_teams_distribute_parallel_for_simd:
836 case OMPD_target_simd:
837 case OMPD_target_teams_distribute_simd:
838 return true;
839 case OMPD_target_teams_distribute:
840 return false;
841 case OMPD_parallel:
842 case OMPD_for:
843 case OMPD_parallel_for:
844 case OMPD_parallel_master:
845 case OMPD_parallel_sections:
846 case OMPD_for_simd:
847 case OMPD_parallel_for_simd:
848 case OMPD_cancel:
849 case OMPD_cancellation_point:
850 case OMPD_ordered:
851 case OMPD_threadprivate:
852 case OMPD_allocate:
853 case OMPD_task:
854 case OMPD_simd:
855 case OMPD_sections:
856 case OMPD_section:
857 case OMPD_single:
858 case OMPD_master:
859 case OMPD_critical:
860 case OMPD_taskyield:
861 case OMPD_barrier:
862 case OMPD_taskwait:
863 case OMPD_taskgroup:
864 case OMPD_atomic:
865 case OMPD_flush:
866 case OMPD_depobj:
867 case OMPD_teams:
868 case OMPD_target_data:
869 case OMPD_target_exit_data:
870 case OMPD_target_enter_data:
871 case OMPD_distribute:
872 case OMPD_distribute_simd:
873 case OMPD_distribute_parallel_for:
874 case OMPD_distribute_parallel_for_simd:
875 case OMPD_teams_distribute:
876 case OMPD_teams_distribute_simd:
877 case OMPD_teams_distribute_parallel_for:
878 case OMPD_teams_distribute_parallel_for_simd:
879 case OMPD_target_update:
880 case OMPD_declare_simd:
881 case OMPD_declare_variant:
882 case OMPD_declare_target:
883 case OMPD_end_declare_target:
884 case OMPD_declare_reduction:
885 case OMPD_declare_mapper:
886 case OMPD_taskloop:
887 case OMPD_taskloop_simd:
888 case OMPD_master_taskloop:
889 case OMPD_master_taskloop_simd:
890 case OMPD_parallel_master_taskloop:
891 case OMPD_parallel_master_taskloop_simd:
892 case OMPD_requires:
893 case OMPD_unknown:
894 break;
895 }
896 llvm_unreachable(::llvm::llvm_unreachable_internal("Unknown programming model for OpenMP directive on NVPTX target."
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 897)
897 "Unknown programming model for OpenMP directive on NVPTX target.")::llvm::llvm_unreachable_internal("Unknown programming model for OpenMP directive on NVPTX target."
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 897)
;
898}
899
900/// Check if the directive is loops based and has schedule clause at all or has
901/// static scheduling.
902static bool hasStaticScheduling(const OMPExecutableDirective &D) {
903 assert(isOpenMPWorksharingDirective(D.getDirectiveKind()) &&((isOpenMPWorksharingDirective(D.getDirectiveKind()) &&
isOpenMPLoopDirective(D.getDirectiveKind()) && "Expected loop-based directive."
) ? static_cast<void> (0) : __assert_fail ("isOpenMPWorksharingDirective(D.getDirectiveKind()) && isOpenMPLoopDirective(D.getDirectiveKind()) && \"Expected loop-based directive.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 905, __PRETTY_FUNCTION__))
904 isOpenMPLoopDirective(D.getDirectiveKind()) &&((isOpenMPWorksharingDirective(D.getDirectiveKind()) &&
isOpenMPLoopDirective(D.getDirectiveKind()) && "Expected loop-based directive."
) ? static_cast<void> (0) : __assert_fail ("isOpenMPWorksharingDirective(D.getDirectiveKind()) && isOpenMPLoopDirective(D.getDirectiveKind()) && \"Expected loop-based directive.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 905, __PRETTY_FUNCTION__))
905 "Expected loop-based directive.")((isOpenMPWorksharingDirective(D.getDirectiveKind()) &&
isOpenMPLoopDirective(D.getDirectiveKind()) && "Expected loop-based directive."
) ? static_cast<void> (0) : __assert_fail ("isOpenMPWorksharingDirective(D.getDirectiveKind()) && isOpenMPLoopDirective(D.getDirectiveKind()) && \"Expected loop-based directive.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 905, __PRETTY_FUNCTION__))
;
906 return !D.hasClausesOfKind<OMPOrderedClause>() &&
907 (!D.hasClausesOfKind<OMPScheduleClause>() ||
908 llvm::any_of(D.getClausesOfKind<OMPScheduleClause>(),
909 [](const OMPScheduleClause *C) {
910 return C->getScheduleKind() == OMPC_SCHEDULE_static;
911 }));
912}
913
914/// Check for inner (nested) lightweight runtime construct, if any
915static bool hasNestedLightweightDirective(ASTContext &Ctx,
916 const OMPExecutableDirective &D) {
917 assert(supportsSPMDExecutionMode(Ctx, D) && "Expected SPMD mode directive.")((supportsSPMDExecutionMode(Ctx, D) && "Expected SPMD mode directive."
) ? static_cast<void> (0) : __assert_fail ("supportsSPMDExecutionMode(Ctx, D) && \"Expected SPMD mode directive.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 917, __PRETTY_FUNCTION__))
;
918 const auto *CS = D.getInnermostCapturedStmt();
919 const auto *Body =
920 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
921 const Stmt *ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
922
923 if (const auto *NestedDir =
924 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
925 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
926 switch (D.getDirectiveKind()) {
927 case OMPD_target:
928 if (isOpenMPParallelDirective(DKind) &&
929 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
930 hasStaticScheduling(*NestedDir))
931 return true;
932 if (DKind == OMPD_teams_distribute_simd || DKind == OMPD_simd)
933 return true;
934 if (DKind == OMPD_parallel) {
935 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
936 /*IgnoreCaptured=*/true);
937 if (!Body)
938 return false;
939 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
940 if (const auto *NND =
941 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
942 DKind = NND->getDirectiveKind();
943 if (isOpenMPWorksharingDirective(DKind) &&
944 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
945 return true;
946 }
947 } else if (DKind == OMPD_teams) {
948 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
949 /*IgnoreCaptured=*/true);
950 if (!Body)
951 return false;
952 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
953 if (const auto *NND =
954 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
955 DKind = NND->getDirectiveKind();
956 if (isOpenMPParallelDirective(DKind) &&
957 isOpenMPWorksharingDirective(DKind) &&
958 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
959 return true;
960 if (DKind == OMPD_parallel) {
961 Body = NND->getInnermostCapturedStmt()->IgnoreContainers(
962 /*IgnoreCaptured=*/true);
963 if (!Body)
964 return false;
965 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
966 if (const auto *NND =
967 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
968 DKind = NND->getDirectiveKind();
969 if (isOpenMPWorksharingDirective(DKind) &&
970 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
971 return true;
972 }
973 }
974 }
975 }
976 return false;
977 case OMPD_target_teams:
978 if (isOpenMPParallelDirective(DKind) &&
979 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
980 hasStaticScheduling(*NestedDir))
981 return true;
982 if (DKind == OMPD_distribute_simd || DKind == OMPD_simd)
983 return true;
984 if (DKind == OMPD_parallel) {
985 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
986 /*IgnoreCaptured=*/true);
987 if (!Body)
988 return false;
989 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
990 if (const auto *NND =
991 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
992 DKind = NND->getDirectiveKind();
993 if (isOpenMPWorksharingDirective(DKind) &&
994 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
995 return true;
996 }
997 }
998 return false;
999 case OMPD_target_parallel:
1000 if (DKind == OMPD_simd)
1001 return true;
1002 return isOpenMPWorksharingDirective(DKind) &&
1003 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NestedDir);
1004 case OMPD_target_teams_distribute:
1005 case OMPD_target_simd:
1006 case OMPD_target_parallel_for:
1007 case OMPD_target_parallel_for_simd:
1008 case OMPD_target_teams_distribute_simd:
1009 case OMPD_target_teams_distribute_parallel_for:
1010 case OMPD_target_teams_distribute_parallel_for_simd:
1011 case OMPD_parallel:
1012 case OMPD_for:
1013 case OMPD_parallel_for:
1014 case OMPD_parallel_master:
1015 case OMPD_parallel_sections:
1016 case OMPD_for_simd:
1017 case OMPD_parallel_for_simd:
1018 case OMPD_cancel:
1019 case OMPD_cancellation_point:
1020 case OMPD_ordered:
1021 case OMPD_threadprivate:
1022 case OMPD_allocate:
1023 case OMPD_task:
1024 case OMPD_simd:
1025 case OMPD_sections:
1026 case OMPD_section:
1027 case OMPD_single:
1028 case OMPD_master:
1029 case OMPD_critical:
1030 case OMPD_taskyield:
1031 case OMPD_barrier:
1032 case OMPD_taskwait:
1033 case OMPD_taskgroup:
1034 case OMPD_atomic:
1035 case OMPD_flush:
1036 case OMPD_depobj:
1037 case OMPD_teams:
1038 case OMPD_target_data:
1039 case OMPD_target_exit_data:
1040 case OMPD_target_enter_data:
1041 case OMPD_distribute:
1042 case OMPD_distribute_simd:
1043 case OMPD_distribute_parallel_for:
1044 case OMPD_distribute_parallel_for_simd:
1045 case OMPD_teams_distribute:
1046 case OMPD_teams_distribute_simd:
1047 case OMPD_teams_distribute_parallel_for:
1048 case OMPD_teams_distribute_parallel_for_simd:
1049 case OMPD_target_update:
1050 case OMPD_declare_simd:
1051 case OMPD_declare_variant:
1052 case OMPD_declare_target:
1053 case OMPD_end_declare_target:
1054 case OMPD_declare_reduction:
1055 case OMPD_declare_mapper:
1056 case OMPD_taskloop:
1057 case OMPD_taskloop_simd:
1058 case OMPD_master_taskloop:
1059 case OMPD_master_taskloop_simd:
1060 case OMPD_parallel_master_taskloop:
1061 case OMPD_parallel_master_taskloop_simd:
1062 case OMPD_requires:
1063 case OMPD_unknown:
1064 llvm_unreachable("Unexpected directive.")::llvm::llvm_unreachable_internal("Unexpected directive.", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 1064)
;
1065 }
1066 }
1067
1068 return false;
1069}
1070
1071/// Checks if the construct supports lightweight runtime. It must be SPMD
1072/// construct + inner loop-based construct with static scheduling.
1073static bool supportsLightweightRuntime(ASTContext &Ctx,
1074 const OMPExecutableDirective &D) {
1075 if (!supportsSPMDExecutionMode(Ctx, D))
1076 return false;
1077 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
1078 switch (DirectiveKind) {
1079 case OMPD_target:
1080 case OMPD_target_teams:
1081 case OMPD_target_parallel:
1082 return hasNestedLightweightDirective(Ctx, D);
1083 case OMPD_target_parallel_for:
1084 case OMPD_target_parallel_for_simd:
1085 case OMPD_target_teams_distribute_parallel_for:
1086 case OMPD_target_teams_distribute_parallel_for_simd:
1087 // (Last|First)-privates must be shared in parallel region.
1088 return hasStaticScheduling(D);
1089 case OMPD_target_simd:
1090 case OMPD_target_teams_distribute_simd:
1091 return true;
1092 case OMPD_target_teams_distribute:
1093 return false;
1094 case OMPD_parallel:
1095 case OMPD_for:
1096 case OMPD_parallel_for:
1097 case OMPD_parallel_master:
1098 case OMPD_parallel_sections:
1099 case OMPD_for_simd:
1100 case OMPD_parallel_for_simd:
1101 case OMPD_cancel:
1102 case OMPD_cancellation_point:
1103 case OMPD_ordered:
1104 case OMPD_threadprivate:
1105 case OMPD_allocate:
1106 case OMPD_task:
1107 case OMPD_simd:
1108 case OMPD_sections:
1109 case OMPD_section:
1110 case OMPD_single:
1111 case OMPD_master:
1112 case OMPD_critical:
1113 case OMPD_taskyield:
1114 case OMPD_barrier:
1115 case OMPD_taskwait:
1116 case OMPD_taskgroup:
1117 case OMPD_atomic:
1118 case OMPD_flush:
1119 case OMPD_depobj:
1120 case OMPD_teams:
1121 case OMPD_target_data:
1122 case OMPD_target_exit_data:
1123 case OMPD_target_enter_data:
1124 case OMPD_distribute:
1125 case OMPD_distribute_simd:
1126 case OMPD_distribute_parallel_for:
1127 case OMPD_distribute_parallel_for_simd:
1128 case OMPD_teams_distribute:
1129 case OMPD_teams_distribute_simd:
1130 case OMPD_teams_distribute_parallel_for:
1131 case OMPD_teams_distribute_parallel_for_simd:
1132 case OMPD_target_update:
1133 case OMPD_declare_simd:
1134 case OMPD_declare_variant:
1135 case OMPD_declare_target:
1136 case OMPD_end_declare_target:
1137 case OMPD_declare_reduction:
1138 case OMPD_declare_mapper:
1139 case OMPD_taskloop:
1140 case OMPD_taskloop_simd:
1141 case OMPD_master_taskloop:
1142 case OMPD_master_taskloop_simd:
1143 case OMPD_parallel_master_taskloop:
1144 case OMPD_parallel_master_taskloop_simd:
1145 case OMPD_requires:
1146 case OMPD_unknown:
1147 break;
1148 }
1149 llvm_unreachable(::llvm::llvm_unreachable_internal("Unknown programming model for OpenMP directive on NVPTX target."
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 1150)
1150 "Unknown programming model for OpenMP directive on NVPTX target.")::llvm::llvm_unreachable_internal("Unknown programming model for OpenMP directive on NVPTX target."
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 1150)
;
1151}
1152
1153void CGOpenMPRuntimeNVPTX::emitNonSPMDKernel(const OMPExecutableDirective &D,
1154 StringRef ParentName,
1155 llvm::Function *&OutlinedFn,
1156 llvm::Constant *&OutlinedFnID,
1157 bool IsOffloadEntry,
1158 const RegionCodeGenTy &CodeGen) {
1159 ExecutionRuntimeModesRAII ModeRAII(CurrentExecutionMode);
1160 EntryFunctionState EST;
1161 WorkerFunctionState WST(CGM, D.getBeginLoc());
1162 Work.clear();
1163 WrapperFunctionsMap.clear();
1164
1165 // Emit target region as a standalone region.
1166 class NVPTXPrePostActionTy : public PrePostActionTy {
1167 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1168 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST;
1169
1170 public:
1171 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
1172 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST)
1173 : EST(EST), WST(WST) {}
1174 void Enter(CodeGenFunction &CGF) override {
1175 auto &RT =
1176 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
1177 RT.emitNonSPMDEntryHeader(CGF, EST, WST);
1178 // Skip target region initialization.
1179 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
1180 }
1181 void Exit(CodeGenFunction &CGF) override {
1182 auto &RT =
1183 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
1184 RT.clearLocThreadIdInsertPt(CGF);
1185 RT.emitNonSPMDEntryFooter(CGF, EST);
1186 }
1187 } Action(EST, WST);
1188 CodeGen.setAction(Action);
1189 IsInTTDRegion = true;
1190 // Reserve place for the globalized memory.
1191 GlobalizedRecords.emplace_back();
1192 if (!KernelStaticGlobalized) {
1193 KernelStaticGlobalized = new llvm::GlobalVariable(
1194 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1195 llvm::GlobalValue::InternalLinkage,
1196 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1197 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1198 llvm::GlobalValue::NotThreadLocal,
1199 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1200 }
1201 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1202 IsOffloadEntry, CodeGen);
1203 IsInTTDRegion = false;
1204
1205 // Now change the name of the worker function to correspond to this target
1206 // region's entry function.
1207 WST.WorkerFn->setName(Twine(OutlinedFn->getName(), "_worker"));
1208
1209 // Create the worker function
1210 emitWorkerFunction(WST);
1211}
1212
1213// Setup NVPTX threads for master-worker OpenMP scheme.
1214void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryHeader(CodeGenFunction &CGF,
1215 EntryFunctionState &EST,
1216 WorkerFunctionState &WST) {
1217 CGBuilderTy &Bld = CGF.Builder;
1218
1219 llvm::BasicBlock *WorkerBB = CGF.createBasicBlock(".worker");
1220 llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
1221 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
1222 EST.ExitBB = CGF.createBasicBlock(".exit");
1223
1224 llvm::Value *IsWorker =
1225 Bld.CreateICmpULT(getNVPTXThreadID(CGF), getThreadLimit(CGF));
1226 Bld.CreateCondBr(IsWorker, WorkerBB, MasterCheckBB);
1227
1228 CGF.EmitBlock(WorkerBB);
1229 emitCall(CGF, WST.Loc, WST.WorkerFn);
1230 CGF.EmitBranch(EST.ExitBB);
1231
1232 CGF.EmitBlock(MasterCheckBB);
1233 llvm::Value *IsMaster =
1234 Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
1235 Bld.CreateCondBr(IsMaster, MasterBB, EST.ExitBB);
1236
1237 CGF.EmitBlock(MasterBB);
1238 IsInTargetMasterThreadRegion = true;
1239 // SEQUENTIAL (MASTER) REGION START
1240 // First action in sequential region:
1241 // Initialize the state of the OpenMP runtime library on the GPU.
1242 // TODO: Optimize runtime initialization and pass in correct value.
1243 llvm::Value *Args[] = {getThreadLimit(CGF),
1244 Bld.getInt16(/*RequiresOMPRuntime=*/1)};
1245 CGF.EmitRuntimeCall(
1246 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_init), Args);
1247
1248 // For data sharing, we need to initialize the stack.
1249 CGF.EmitRuntimeCall(
1250 createNVPTXRuntimeFunction(
1251 OMPRTL_NVPTX__kmpc_data_sharing_init_stack));
1252
1253 emitGenericVarsProlog(CGF, WST.Loc);
1254}
1255
1256void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryFooter(CodeGenFunction &CGF,
1257 EntryFunctionState &EST) {
1258 IsInTargetMasterThreadRegion = false;
1259 if (!CGF.HaveInsertPoint())
1260 return;
1261
1262 emitGenericVarsEpilog(CGF);
1263
1264 if (!EST.ExitBB)
1265 EST.ExitBB = CGF.createBasicBlock(".exit");
1266
1267 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".termination.notifier");
1268 CGF.EmitBranch(TerminateBB);
1269
1270 CGF.EmitBlock(TerminateBB);
1271 // Signal termination condition.
1272 // TODO: Optimize runtime initialization and pass in correct value.
1273 llvm::Value *Args[] = {CGF.Builder.getInt16(/*IsOMPRuntimeInitialized=*/1)};
1274 CGF.EmitRuntimeCall(
1275 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_deinit), Args);
1276 // Barrier to terminate worker threads.
1277 syncCTAThreads(CGF);
1278 // Master thread jumps to exit point.
1279 CGF.EmitBranch(EST.ExitBB);
1280
1281 CGF.EmitBlock(EST.ExitBB);
1282 EST.ExitBB = nullptr;
1283}
1284
1285void CGOpenMPRuntimeNVPTX::emitSPMDKernel(const OMPExecutableDirective &D,
1286 StringRef ParentName,
1287 llvm::Function *&OutlinedFn,
1288 llvm::Constant *&OutlinedFnID,
1289 bool IsOffloadEntry,
1290 const RegionCodeGenTy &CodeGen) {
1291 ExecutionRuntimeModesRAII ModeRAII(
1292 CurrentExecutionMode, RequiresFullRuntime,
1293 CGM.getLangOpts().OpenMPCUDAForceFullRuntime ||
1294 !supportsLightweightRuntime(CGM.getContext(), D));
1295 EntryFunctionState EST;
1296
1297 // Emit target region as a standalone region.
1298 class NVPTXPrePostActionTy : public PrePostActionTy {
1299 CGOpenMPRuntimeNVPTX &RT;
1300 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1301 const OMPExecutableDirective &D;
1302
1303 public:
1304 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT,
1305 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
1306 const OMPExecutableDirective &D)
1307 : RT(RT), EST(EST), D(D) {}
1308 void Enter(CodeGenFunction &CGF) override {
1309 RT.emitSPMDEntryHeader(CGF, EST, D);
1310 // Skip target region initialization.
1311 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
1312 }
1313 void Exit(CodeGenFunction &CGF) override {
1314 RT.clearLocThreadIdInsertPt(CGF);
1315 RT.emitSPMDEntryFooter(CGF, EST);
1316 }
1317 } Action(*this, EST, D);
1318 CodeGen.setAction(Action);
1319 IsInTTDRegion = true;
1320 // Reserve place for the globalized memory.
1321 GlobalizedRecords.emplace_back();
1322 if (!KernelStaticGlobalized) {
1323 KernelStaticGlobalized = new llvm::GlobalVariable(
1324 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1325 llvm::GlobalValue::InternalLinkage,
1326 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1327 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1328 llvm::GlobalValue::NotThreadLocal,
1329 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1330 }
1331 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1332 IsOffloadEntry, CodeGen);
1333 IsInTTDRegion = false;
1334}
1335
1336void CGOpenMPRuntimeNVPTX::emitSPMDEntryHeader(
1337 CodeGenFunction &CGF, EntryFunctionState &EST,
1338 const OMPExecutableDirective &D) {
1339 CGBuilderTy &Bld = CGF.Builder;
1340
1341 // Setup BBs in entry function.
1342 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute");
1343 EST.ExitBB = CGF.createBasicBlock(".exit");
1344
1345 llvm::Value *Args[] = {getThreadLimit(CGF, /*IsInSPMDExecutionMode=*/true),
1346 /*RequiresOMPRuntime=*/
1347 Bld.getInt16(RequiresFullRuntime ? 1 : 0),
1348 /*RequiresDataSharing=*/Bld.getInt16(0)};
1349 CGF.EmitRuntimeCall(
1350 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_init), Args);
1351
1352 if (RequiresFullRuntime) {
1353 // For data sharing, we need to initialize the stack.
1354 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1355 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd));
1356 }
1357
1358 CGF.EmitBranch(ExecuteBB);
1359
1360 CGF.EmitBlock(ExecuteBB);
1361
1362 IsInTargetMasterThreadRegion = true;
1363}
1364
1365void CGOpenMPRuntimeNVPTX::emitSPMDEntryFooter(CodeGenFunction &CGF,
1366 EntryFunctionState &EST) {
1367 IsInTargetMasterThreadRegion = false;
1368 if (!CGF.HaveInsertPoint())
1369 return;
1370
1371 if (!EST.ExitBB)
1372 EST.ExitBB = CGF.createBasicBlock(".exit");
1373
1374 llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit");
1375 CGF.EmitBranch(OMPDeInitBB);
1376
1377 CGF.EmitBlock(OMPDeInitBB);
1378 // DeInitialize the OMP state in the runtime; called by all active threads.
1379 llvm::Value *Args[] = {/*RequiresOMPRuntime=*/
1380 CGF.Builder.getInt16(RequiresFullRuntime ? 1 : 0)};
1381 CGF.EmitRuntimeCall(
1382 createNVPTXRuntimeFunction(
1383 OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2), Args);
1384 CGF.EmitBranch(EST.ExitBB);
1385
1386 CGF.EmitBlock(EST.ExitBB);
1387 EST.ExitBB = nullptr;
1388}
1389
1390// Create a unique global variable to indicate the execution mode of this target
1391// region. The execution mode is either 'generic', or 'spmd' depending on the
1392// target directive. This variable is picked up by the offload library to setup
1393// the device appropriately before kernel launch. If the execution mode is
1394// 'generic', the runtime reserves one warp for the master, otherwise, all
1395// warps participate in parallel work.
1396static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
1397 bool Mode) {
1398 auto *GVMode =
1399 new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
1400 llvm::GlobalValue::WeakAnyLinkage,
1401 llvm::ConstantInt::get(CGM.Int8Ty, Mode ? 0 : 1),
1402 Twine(Name, "_exec_mode"));
1403 CGM.addCompilerUsedGlobal(GVMode);
1404}
1405
1406void CGOpenMPRuntimeNVPTX::emitWorkerFunction(WorkerFunctionState &WST) {
1407 ASTContext &Ctx = CGM.getContext();
1408
1409 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
1410 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, WST.CGFI, {},
1411 WST.Loc, WST.Loc);
1412 emitWorkerLoop(CGF, WST);
1413 CGF.FinishFunction();
1414}
1415
1416void CGOpenMPRuntimeNVPTX::emitWorkerLoop(CodeGenFunction &CGF,
1417 WorkerFunctionState &WST) {
1418 //
1419 // The workers enter this loop and wait for parallel work from the master.
1420 // When the master encounters a parallel region it sets up the work + variable
1421 // arguments, and wakes up the workers. The workers first check to see if
1422 // they are required for the parallel region, i.e., within the # of requested
1423 // parallel threads. The activated workers load the variable arguments and
1424 // execute the parallel work.
1425 //
1426
1427 CGBuilderTy &Bld = CGF.Builder;
1428
1429 llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work");
1430 llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers");
1431 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel");
1432 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel");
1433 llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel");
1434 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1435
1436 CGF.EmitBranch(AwaitBB);
1437
1438 // Workers wait for work from master.
1439 CGF.EmitBlock(AwaitBB);
1440 // Wait for parallel work
1441 syncCTAThreads(CGF);
1442
1443 Address WorkFn =
1444 CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn");
1445 Address ExecStatus =
1446 CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status");
1447 CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0));
1448 CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy));
1449
1450 // TODO: Optimize runtime initialization and pass in correct value.
1451 llvm::Value *Args[] = {WorkFn.getPointer(),
1452 /*RequiresOMPRuntime=*/Bld.getInt16(1)};
1453 llvm::Value *Ret = CGF.EmitRuntimeCall(
1454 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args);
1455 Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus);
1456
1457 // On termination condition (workid == 0), exit loop.
1458 llvm::Value *WorkID = Bld.CreateLoad(WorkFn);
1459 llvm::Value *ShouldTerminate = Bld.CreateIsNull(WorkID, "should_terminate");
1460 Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB);
1461
1462 // Activate requested workers.
1463 CGF.EmitBlock(SelectWorkersBB);
1464 llvm::Value *IsActive =
1465 Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active");
1466 Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB);
1467
1468 // Signal start of parallel region.
1469 CGF.EmitBlock(ExecuteBB);
1470 // Skip initialization.
1471 setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
1472
1473 // Process work items: outlined parallel functions.
1474 for (llvm::Function *W : Work) {
1475 // Try to match this outlined function.
1476 llvm::Value *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy);
1477
1478 llvm::Value *WorkFnMatch =
1479 Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match");
1480
1481 llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn");
1482 llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next");
1483 Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB);
1484
1485 // Execute this outlined function.
1486 CGF.EmitBlock(ExecuteFNBB);
1487
1488 // Insert call to work function via shared wrapper. The shared
1489 // wrapper takes two arguments:
1490 // - the parallelism level;
1491 // - the thread ID;
1492 emitCall(CGF, WST.Loc, W,
1493 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
1494
1495 // Go to end of parallel region.
1496 CGF.EmitBranch(TerminateBB);
1497
1498 CGF.EmitBlock(CheckNextBB);
1499 }
1500 // Default case: call to outlined function through pointer if the target
1501 // region makes a declare target call that may contain an orphaned parallel
1502 // directive.
1503 auto *ParallelFnTy =
1504 llvm::FunctionType::get(CGM.VoidTy, {CGM.Int16Ty, CGM.Int32Ty},
1505 /*isVarArg=*/false);
1506 llvm::Value *WorkFnCast =
1507 Bld.CreateBitCast(WorkID, ParallelFnTy->getPointerTo());
1508 // Insert call to work function via shared wrapper. The shared
1509 // wrapper takes two arguments:
1510 // - the parallelism level;
1511 // - the thread ID;
1512 emitCall(CGF, WST.Loc, {ParallelFnTy, WorkFnCast},
1513 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
1514 // Go to end of parallel region.
1515 CGF.EmitBranch(TerminateBB);
1516
1517 // Signal end of parallel region.
1518 CGF.EmitBlock(TerminateBB);
1519 CGF.EmitRuntimeCall(
1520 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_end_parallel),
1521 llvm::None);
1522 CGF.EmitBranch(BarrierBB);
1523
1524 // All active and inactive workers wait at a barrier after parallel region.
1525 CGF.EmitBlock(BarrierBB);
1526 // Barrier after parallel region.
1527 syncCTAThreads(CGF);
1528 CGF.EmitBranch(AwaitBB);
1529
1530 // Exit target region.
1531 CGF.EmitBlock(ExitBB);
1532 // Skip initialization.
1533 clearLocThreadIdInsertPt(CGF);
1534}
1535
1536/// Returns specified OpenMP runtime function for the current OpenMP
1537/// implementation. Specialized for the NVPTX device.
1538/// \param Function OpenMP runtime function.
1539/// \return Specified function.
1540llvm::FunctionCallee
1541CGOpenMPRuntimeNVPTX::createNVPTXRuntimeFunction(unsigned Function) {
1542 llvm::FunctionCallee RTLFn = nullptr;
1543 switch (static_cast<OpenMPRTLFunctionNVPTX>(Function)) {
1544 case OMPRTL_NVPTX__kmpc_kernel_init: {
1545 // Build void __kmpc_kernel_init(kmp_int32 thread_limit, int16_t
1546 // RequiresOMPRuntime);
1547 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty};
1548 auto *FnTy =
1549 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1550 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_init");
1551 break;
1552 }
1553 case OMPRTL_NVPTX__kmpc_kernel_deinit: {
1554 // Build void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
1555 llvm::Type *TypeParams[] = {CGM.Int16Ty};
1556 auto *FnTy =
1557 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1558 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_deinit");
1559 break;
1560 }
1561 case OMPRTL_NVPTX__kmpc_spmd_kernel_init: {
1562 // Build void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
1563 // int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
1564 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
1565 auto *FnTy =
1566 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1567 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_init");
1568 break;
1569 }
1570 case OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2: {
1571 // Build void __kmpc_spmd_kernel_deinit_v2(int16_t RequiresOMPRuntime);
1572 llvm::Type *TypeParams[] = {CGM.Int16Ty};
1573 auto *FnTy =
1574 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1575 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_deinit_v2");
1576 break;
1577 }
1578 case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: {
1579 /// Build void __kmpc_kernel_prepare_parallel(
1580 /// void *outlined_function, int16_t IsOMPRuntimeInitialized);
1581 llvm::Type *TypeParams[] = {CGM.Int8PtrTy, CGM.Int16Ty};
1582 auto *FnTy =
1583 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1584 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_prepare_parallel");
1585 break;
1586 }
1587 case OMPRTL_NVPTX__kmpc_kernel_parallel: {
1588 /// Build bool __kmpc_kernel_parallel(void **outlined_function,
1589 /// int16_t IsOMPRuntimeInitialized);
1590 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy, CGM.Int16Ty};
1591 llvm::Type *RetTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
1592 auto *FnTy =
1593 llvm::FunctionType::get(RetTy, TypeParams, /*isVarArg*/ false);
1594 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_parallel");
1595 break;
1596 }
1597 case OMPRTL_NVPTX__kmpc_kernel_end_parallel: {
1598 /// Build void __kmpc_kernel_end_parallel();
1599 auto *FnTy =
1600 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1601 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_end_parallel");
1602 break;
1603 }
1604 case OMPRTL_NVPTX__kmpc_serialized_parallel: {
1605 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1606 // global_tid);
1607 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1608 auto *FnTy =
1609 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1610 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1611 break;
1612 }
1613 case OMPRTL_NVPTX__kmpc_end_serialized_parallel: {
1614 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1615 // global_tid);
1616 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1617 auto *FnTy =
1618 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1619 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1620 break;
1621 }
1622 case OMPRTL_NVPTX__kmpc_shuffle_int32: {
1623 // Build int32_t __kmpc_shuffle_int32(int32_t element,
1624 // int16_t lane_offset, int16_t warp_size);
1625 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
1626 auto *FnTy =
1627 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1628 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int32");
1629 break;
1630 }
1631 case OMPRTL_NVPTX__kmpc_shuffle_int64: {
1632 // Build int64_t __kmpc_shuffle_int64(int64_t element,
1633 // int16_t lane_offset, int16_t warp_size);
1634 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int16Ty, CGM.Int16Ty};
1635 auto *FnTy =
1636 llvm::FunctionType::get(CGM.Int64Ty, TypeParams, /*isVarArg*/ false);
1637 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int64");
1638 break;
1639 }
1640 case OMPRTL_NVPTX__kmpc_nvptx_parallel_reduce_nowait_v2: {
1641 // Build int32_t kmpc_nvptx_parallel_reduce_nowait_v2(ident_t *loc,
1642 // kmp_int32 global_tid, kmp_int32 num_vars, size_t reduce_size, void*
1643 // reduce_data, void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t
1644 // lane_id, int16_t lane_offset, int16_t Algorithm Version), void
1645 // (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
1646 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1647 CGM.Int16Ty, CGM.Int16Ty};
1648 auto *ShuffleReduceFnTy =
1649 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1650 /*isVarArg=*/false);
1651 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1652 auto *InterWarpCopyFnTy =
1653 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1654 /*isVarArg=*/false);
1655 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1656 CGM.Int32Ty,
1657 CGM.Int32Ty,
1658 CGM.SizeTy,
1659 CGM.VoidPtrTy,
1660 ShuffleReduceFnTy->getPointerTo(),
1661 InterWarpCopyFnTy->getPointerTo()};
1662 auto *FnTy =
1663 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1664 RTLFn = CGM.CreateRuntimeFunction(
1665 FnTy, /*Name=*/"__kmpc_nvptx_parallel_reduce_nowait_v2");
1666 break;
1667 }
1668 case OMPRTL_NVPTX__kmpc_end_reduce_nowait: {
1669 // Build __kmpc_end_reduce_nowait(kmp_int32 global_tid);
1670 llvm::Type *TypeParams[] = {CGM.Int32Ty};
1671 auto *FnTy =
1672 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1673 RTLFn = CGM.CreateRuntimeFunction(
1674 FnTy, /*Name=*/"__kmpc_nvptx_end_reduce_nowait");
1675 break;
1676 }
1677 case OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_v2: {
1678 // Build int32_t __kmpc_nvptx_teams_reduce_nowait_v2(ident_t *loc, kmp_int32
1679 // global_tid, void *global_buffer, int32_t num_of_records, void*
1680 // reduce_data,
1681 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1682 // lane_offset, int16_t shortCircuit),
1683 // void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num), void
1684 // (*kmp_ListToGlobalCpyFctPtr)(void *buffer, int idx, void *reduce_data),
1685 // void (*kmp_GlobalToListCpyFctPtr)(void *buffer, int idx,
1686 // void *reduce_data), void (*kmp_GlobalToListCpyPtrsFctPtr)(void *buffer,
1687 // int idx, void *reduce_data), void (*kmp_GlobalToListRedFctPtr)(void
1688 // *buffer, int idx, void *reduce_data));
1689 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1690 CGM.Int16Ty, CGM.Int16Ty};
1691 auto *ShuffleReduceFnTy =
1692 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1693 /*isVarArg=*/false);
1694 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1695 auto *InterWarpCopyFnTy =
1696 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1697 /*isVarArg=*/false);
1698 llvm::Type *GlobalListTypeParams[] = {CGM.VoidPtrTy, CGM.IntTy,
1699 CGM.VoidPtrTy};
1700 auto *GlobalListFnTy =
1701 llvm::FunctionType::get(CGM.VoidTy, GlobalListTypeParams,
1702 /*isVarArg=*/false);
1703 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1704 CGM.Int32Ty,
1705 CGM.VoidPtrTy,
1706 CGM.Int32Ty,
1707 CGM.VoidPtrTy,
1708 ShuffleReduceFnTy->getPointerTo(),
1709 InterWarpCopyFnTy->getPointerTo(),
1710 GlobalListFnTy->getPointerTo(),
1711 GlobalListFnTy->getPointerTo(),
1712 GlobalListFnTy->getPointerTo(),
1713 GlobalListFnTy->getPointerTo()};
1714 auto *FnTy =
1715 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1716 RTLFn = CGM.CreateRuntimeFunction(
1717 FnTy, /*Name=*/"__kmpc_nvptx_teams_reduce_nowait_v2");
1718 break;
1719 }
1720 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack: {
1721 /// Build void __kmpc_data_sharing_init_stack();
1722 auto *FnTy =
1723 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1724 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack");
1725 break;
1726 }
1727 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd: {
1728 /// Build void __kmpc_data_sharing_init_stack_spmd();
1729 auto *FnTy =
1730 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1731 RTLFn =
1732 CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack_spmd");
1733 break;
1734 }
1735 case OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack: {
1736 // Build void *__kmpc_data_sharing_coalesced_push_stack(size_t size,
1737 // int16_t UseSharedMemory);
1738 llvm::Type *TypeParams[] = {CGM.SizeTy, CGM.Int16Ty};
1739 auto *FnTy =
1740 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1741 RTLFn = CGM.CreateRuntimeFunction(
1742 FnTy, /*Name=*/"__kmpc_data_sharing_coalesced_push_stack");
1743 break;
1744 }
1745 case OMPRTL_NVPTX__kmpc_data_sharing_pop_stack: {
1746 // Build void __kmpc_data_sharing_pop_stack(void *a);
1747 llvm::Type *TypeParams[] = {CGM.VoidPtrTy};
1748 auto *FnTy =
1749 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1750 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1751 /*Name=*/"__kmpc_data_sharing_pop_stack");
1752 break;
1753 }
1754 case OMPRTL_NVPTX__kmpc_begin_sharing_variables: {
1755 /// Build void __kmpc_begin_sharing_variables(void ***args,
1756 /// size_t n_args);
1757 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo(), CGM.SizeTy};
1758 auto *FnTy =
1759 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1760 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_begin_sharing_variables");
1761 break;
1762 }
1763 case OMPRTL_NVPTX__kmpc_end_sharing_variables: {
1764 /// Build void __kmpc_end_sharing_variables();
1765 auto *FnTy =
1766 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1767 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_sharing_variables");
1768 break;
1769 }
1770 case OMPRTL_NVPTX__kmpc_get_shared_variables: {
1771 /// Build void __kmpc_get_shared_variables(void ***GlobalArgs);
1772 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo()};
1773 auto *FnTy =
1774 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1775 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_shared_variables");
1776 break;
1777 }
1778 case OMPRTL_NVPTX__kmpc_parallel_level: {
1779 // Build uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32 global_tid);
1780 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1781 auto *FnTy =
1782 llvm::FunctionType::get(CGM.Int16Ty, TypeParams, /*isVarArg*/ false);
1783 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_parallel_level");
1784 break;
1785 }
1786 case OMPRTL_NVPTX__kmpc_is_spmd_exec_mode: {
1787 // Build int8_t __kmpc_is_spmd_exec_mode();
1788 auto *FnTy = llvm::FunctionType::get(CGM.Int8Ty, /*isVarArg=*/false);
1789 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_is_spmd_exec_mode");
1790 break;
1791 }
1792 case OMPRTL_NVPTX__kmpc_get_team_static_memory: {
1793 // Build void __kmpc_get_team_static_memory(int16_t isSPMDExecutionMode,
1794 // const void *buf, size_t size, int16_t is_shared, const void **res);
1795 llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.VoidPtrTy, CGM.SizeTy,
1796 CGM.Int16Ty, CGM.VoidPtrPtrTy};
1797 auto *FnTy =
1798 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1799 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_team_static_memory");
1800 break;
1801 }
1802 case OMPRTL_NVPTX__kmpc_restore_team_static_memory: {
1803 // Build void __kmpc_restore_team_static_memory(int16_t isSPMDExecutionMode,
1804 // int16_t is_shared);
1805 llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.Int16Ty};
1806 auto *FnTy =
1807 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1808 RTLFn =
1809 CGM.CreateRuntimeFunction(FnTy, "__kmpc_restore_team_static_memory");
1810 break;
1811 }
1812 case OMPRTL__kmpc_barrier: {
1813 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
1814 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1815 auto *FnTy =
1816 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1817 RTLFn =
1818 CGM.CreateConvergentRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1819 break;
1820 }
1821 case OMPRTL__kmpc_barrier_simple_spmd: {
1822 // Build void __kmpc_barrier_simple_spmd(ident_t *loc, kmp_int32
1823 // global_tid);
1824 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1825 auto *FnTy =
1826 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1827 RTLFn = CGM.CreateConvergentRuntimeFunction(
1828 FnTy, /*Name*/ "__kmpc_barrier_simple_spmd");
1829 break;
1830 }
1831 case OMPRTL_NVPTX__kmpc_warp_active_thread_mask: {
1832 // Build int32_t __kmpc_warp_active_thread_mask(void);
1833 auto *FnTy =
1834 llvm::FunctionType::get(CGM.Int32Ty, llvm::None, /*isVarArg=*/false);
1835 RTLFn = CGM.CreateConvergentRuntimeFunction(FnTy, "__kmpc_warp_active_thread_mask");
1836 break;
1837 }
1838 case OMPRTL_NVPTX__kmpc_syncwarp: {
1839 // Build void __kmpc_syncwarp(kmp_int32 Mask);
1840 auto *FnTy =
1841 llvm::FunctionType::get(CGM.VoidTy, CGM.Int32Ty, /*isVarArg=*/false);
1842 RTLFn = CGM.CreateConvergentRuntimeFunction(FnTy, "__kmpc_syncwarp");
1843 break;
1844 }
1845 }
1846 return RTLFn;
1847}
1848
1849void CGOpenMPRuntimeNVPTX::createOffloadEntry(llvm::Constant *ID,
1850 llvm::Constant *Addr,
1851 uint64_t Size, int32_t,
1852 llvm::GlobalValue::LinkageTypes) {
1853 // TODO: Add support for global variables on the device after declare target
1854 // support.
1855 if (!isa<llvm::Function>(Addr))
1856 return;
1857 llvm::Module &M = CGM.getModule();
1858 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1859
1860 // Get "nvvm.annotations" metadata node
1861 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
1862
1863 llvm::Metadata *MDVals[] = {
1864 llvm::ConstantAsMetadata::get(Addr), llvm::MDString::get(Ctx, "kernel"),
1865 llvm::ConstantAsMetadata::get(
1866 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))};
1867 // Append metadata to nvvm.annotations
1868 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
1869}
1870
1871void CGOpenMPRuntimeNVPTX::emitTargetOutlinedFunction(
1872 const OMPExecutableDirective &D, StringRef ParentName,
1873 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
1874 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
1875 if (!IsOffloadEntry) // Nothing to do.
1876 return;
1877
1878 assert(!ParentName.empty() && "Invalid target region parent name!")((!ParentName.empty() && "Invalid target region parent name!"
) ? static_cast<void> (0) : __assert_fail ("!ParentName.empty() && \"Invalid target region parent name!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 1878, __PRETTY_FUNCTION__))
;
1879
1880 bool Mode = supportsSPMDExecutionMode(CGM.getContext(), D);
1881 if (Mode)
1882 emitSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1883 CodeGen);
1884 else
1885 emitNonSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1886 CodeGen);
1887
1888 setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode);
1889}
1890
1891namespace {
1892LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE()using ::llvm::BitmaskEnumDetail::operator~; using ::llvm::BitmaskEnumDetail
::operator|; using ::llvm::BitmaskEnumDetail::operator&; using
::llvm::BitmaskEnumDetail::operator^; using ::llvm::BitmaskEnumDetail
::operator|=; using ::llvm::BitmaskEnumDetail::operator&=
; using ::llvm::BitmaskEnumDetail::operator^=
;
1893/// Enum for accesseing the reserved_2 field of the ident_t struct.
1894enum ModeFlagsTy : unsigned {
1895 /// Bit set to 1 when in SPMD mode.
1896 KMP_IDENT_SPMD_MODE = 0x01,
1897 /// Bit set to 1 when a simplified runtime is used.
1898 KMP_IDENT_SIMPLE_RT_MODE = 0x02,
1899 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/KMP_IDENT_SIMPLE_RT_MODE)LLVM_BITMASK_LARGEST_ENUMERATOR = KMP_IDENT_SIMPLE_RT_MODE
1900};
1901
1902/// Special mode Undefined. Is the combination of Non-SPMD mode + SimpleRuntime.
1903static const ModeFlagsTy UndefinedMode =
1904 (~KMP_IDENT_SPMD_MODE) & KMP_IDENT_SIMPLE_RT_MODE;
1905} // anonymous namespace
1906
1907unsigned CGOpenMPRuntimeNVPTX::getDefaultLocationReserved2Flags() const {
1908 switch (getExecutionMode()) {
1909 case EM_SPMD:
1910 if (requiresFullRuntime())
1911 return KMP_IDENT_SPMD_MODE & (~KMP_IDENT_SIMPLE_RT_MODE);
1912 return KMP_IDENT_SPMD_MODE | KMP_IDENT_SIMPLE_RT_MODE;
1913 case EM_NonSPMD:
1914 assert(requiresFullRuntime() && "Expected full runtime.")((requiresFullRuntime() && "Expected full runtime.") ?
static_cast<void> (0) : __assert_fail ("requiresFullRuntime() && \"Expected full runtime.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 1914, __PRETTY_FUNCTION__))
;
1915 return (~KMP_IDENT_SPMD_MODE) & (~KMP_IDENT_SIMPLE_RT_MODE);
1916 case EM_Unknown:
1917 return UndefinedMode;
1918 }
1919 llvm_unreachable("Unknown flags are requested.")::llvm::llvm_unreachable_internal("Unknown flags are requested."
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 1919)
;
1920}
1921
1922bool CGOpenMPRuntimeNVPTX::tryEmitDeclareVariant(const GlobalDecl &NewGD,
1923 const GlobalDecl &OldGD,
1924 llvm::GlobalValue *OrigAddr,
1925 bool IsForDefinition) {
1926 // Emit the function in OldGD with the body from NewGD, if NewGD is defined.
1927 auto *NewFD = cast<FunctionDecl>(NewGD.getDecl());
1928 if (NewFD->isDefined()) {
1929 CGM.emitOpenMPDeviceFunctionRedefinition(OldGD, NewGD, OrigAddr);
1930 return true;
1931 }
1932 return false;
1933}
1934
1935CGOpenMPRuntimeNVPTX::CGOpenMPRuntimeNVPTX(CodeGenModule &CGM)
1936 : CGOpenMPRuntime(CGM, "_", "$") {
1937 if (!CGM.getLangOpts().OpenMPIsDevice)
1938 llvm_unreachable("OpenMP NVPTX can only handle device code.")::llvm::llvm_unreachable_internal("OpenMP NVPTX can only handle device code."
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 1938)
;
1939}
1940
1941void CGOpenMPRuntimeNVPTX::emitProcBindClause(CodeGenFunction &CGF,
1942 ProcBindKind ProcBind,
1943 SourceLocation Loc) {
1944 // Do nothing in case of SPMD mode and L0 parallel.
1945 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
1946 return;
1947
1948 CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc);
1949}
1950
1951void CGOpenMPRuntimeNVPTX::emitNumThreadsClause(CodeGenFunction &CGF,
1952 llvm::Value *NumThreads,
1953 SourceLocation Loc) {
1954 // Do nothing in case of SPMD mode and L0 parallel.
1955 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
1956 return;
1957
1958 CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc);
1959}
1960
1961void CGOpenMPRuntimeNVPTX::emitNumTeamsClause(CodeGenFunction &CGF,
1962 const Expr *NumTeams,
1963 const Expr *ThreadLimit,
1964 SourceLocation Loc) {}
1965
1966llvm::Function *CGOpenMPRuntimeNVPTX::emitParallelOutlinedFunction(
1967 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1968 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1969 // Emit target region as a standalone region.
1970 class NVPTXPrePostActionTy : public PrePostActionTy {
1971 bool &IsInParallelRegion;
1972 bool PrevIsInParallelRegion;
1973
1974 public:
1975 NVPTXPrePostActionTy(bool &IsInParallelRegion)
1976 : IsInParallelRegion(IsInParallelRegion) {}
1977 void Enter(CodeGenFunction &CGF) override {
1978 PrevIsInParallelRegion = IsInParallelRegion;
1979 IsInParallelRegion = true;
1980 }
1981 void Exit(CodeGenFunction &CGF) override {
1982 IsInParallelRegion = PrevIsInParallelRegion;
1983 }
1984 } Action(IsInParallelRegion);
1985 CodeGen.setAction(Action);
1986 bool PrevIsInTTDRegion = IsInTTDRegion;
1987 IsInTTDRegion = false;
1988 bool PrevIsInTargetMasterThreadRegion = IsInTargetMasterThreadRegion;
1989 IsInTargetMasterThreadRegion = false;
1990 auto *OutlinedFun =
1991 cast<llvm::Function>(CGOpenMPRuntime::emitParallelOutlinedFunction(
1992 D, ThreadIDVar, InnermostKind, CodeGen));
1993 if (CGM.getLangOpts().Optimize) {
1994 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
1995 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
1996 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
1997 }
1998 IsInTargetMasterThreadRegion = PrevIsInTargetMasterThreadRegion;
1999 IsInTTDRegion = PrevIsInTTDRegion;
2000 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD &&
2001 !IsInParallelRegion) {
2002 llvm::Function *WrapperFun =
2003 createParallelDataSharingWrapper(OutlinedFun, D);
2004 WrapperFunctionsMap[OutlinedFun] = WrapperFun;
2005 }
2006
2007 return OutlinedFun;
2008}
2009
2010/// Get list of lastprivate variables from the teams distribute ... or
2011/// teams {distribute ...} directives.
2012static void
2013getDistributeLastprivateVars(ASTContext &Ctx, const OMPExecutableDirective &D,
2014 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
2015 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&((isOpenMPTeamsDirective(D.getDirectiveKind()) && "expected teams directive."
) ? static_cast<void> (0) : __assert_fail ("isOpenMPTeamsDirective(D.getDirectiveKind()) && \"expected teams directive.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 2016, __PRETTY_FUNCTION__))
2016 "expected teams directive.")((isOpenMPTeamsDirective(D.getDirectiveKind()) && "expected teams directive."
) ? static_cast<void> (0) : __assert_fail ("isOpenMPTeamsDirective(D.getDirectiveKind()) && \"expected teams directive.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 2016, __PRETTY_FUNCTION__))
;
2017 const OMPExecutableDirective *Dir = &D;
2018 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
2019 if (const Stmt *S = CGOpenMPRuntime::getSingleCompoundChild(
2020 Ctx,
2021 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
2022 /*IgnoreCaptured=*/true))) {
2023 Dir = dyn_cast_or_null<OMPExecutableDirective>(S);
2024 if (Dir && !isOpenMPDistributeDirective(Dir->getDirectiveKind()))
2025 Dir = nullptr;
2026 }
2027 }
2028 if (!Dir)
2029 return;
2030 for (const auto *C : Dir->getClausesOfKind<OMPLastprivateClause>()) {
2031 for (const Expr *E : C->getVarRefs())
2032 Vars.push_back(getPrivateItem(E));
2033 }
2034}
2035
2036/// Get list of reduction variables from the teams ... directives.
2037static void
2038getTeamsReductionVars(ASTContext &Ctx, const OMPExecutableDirective &D,
2039 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
2040 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&((isOpenMPTeamsDirective(D.getDirectiveKind()) && "expected teams directive."
) ? static_cast<void> (0) : __assert_fail ("isOpenMPTeamsDirective(D.getDirectiveKind()) && \"expected teams directive.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 2041, __PRETTY_FUNCTION__))
2041 "expected teams directive.")((isOpenMPTeamsDirective(D.getDirectiveKind()) && "expected teams directive."
) ? static_cast<void> (0) : __assert_fail ("isOpenMPTeamsDirective(D.getDirectiveKind()) && \"expected teams directive.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 2041, __PRETTY_FUNCTION__))
;
2042 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
2043 for (const Expr *E : C->privates())
2044 Vars.push_back(getPrivateItem(E));
2045 }
2046}
2047
2048llvm::Function *CGOpenMPRuntimeNVPTX::emitTeamsOutlinedFunction(
2049 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
2050 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
2051 SourceLocation Loc = D.getBeginLoc();
2052
2053 const RecordDecl *GlobalizedRD = nullptr;
2054 llvm::SmallVector<const ValueDecl *, 4> LastPrivatesReductions;
2055 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
2056 // Globalize team reductions variable unconditionally in all modes.
2057 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
2058 getTeamsReductionVars(CGM.getContext(), D, LastPrivatesReductions);
2059 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
2060 getDistributeLastprivateVars(CGM.getContext(), D, LastPrivatesReductions);
2061 if (!LastPrivatesReductions.empty()) {
2062 GlobalizedRD = ::buildRecordForGlobalizedVars(
2063 CGM.getContext(), llvm::None, LastPrivatesReductions,
2064 MappedDeclsFields, WarpSize);
2065 }
2066 } else if (!LastPrivatesReductions.empty()) {
2067 assert(!TeamAndReductions.first &&((!TeamAndReductions.first && "Previous team declaration is not expected."
) ? static_cast<void> (0) : __assert_fail ("!TeamAndReductions.first && \"Previous team declaration is not expected.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 2068, __PRETTY_FUNCTION__))
2068 "Previous team declaration is not expected.")((!TeamAndReductions.first && "Previous team declaration is not expected."
) ? static_cast<void> (0) : __assert_fail ("!TeamAndReductions.first && \"Previous team declaration is not expected.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 2068, __PRETTY_FUNCTION__))
;
2069 TeamAndReductions.first = D.getCapturedStmt(OMPD_teams)->getCapturedDecl();
2070 std::swap(TeamAndReductions.second, LastPrivatesReductions);
2071 }
2072
2073 // Emit target region as a standalone region.
2074 class NVPTXPrePostActionTy : public PrePostActionTy {
2075 SourceLocation &Loc;
2076 const RecordDecl *GlobalizedRD;
2077 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2078 &MappedDeclsFields;
2079
2080 public:
2081 NVPTXPrePostActionTy(
2082 SourceLocation &Loc, const RecordDecl *GlobalizedRD,
2083 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2084 &MappedDeclsFields)
2085 : Loc(Loc), GlobalizedRD(GlobalizedRD),
2086 MappedDeclsFields(MappedDeclsFields) {}
2087 void Enter(CodeGenFunction &CGF) override {
2088 auto &Rt =
2089 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
2090 if (GlobalizedRD) {
2091 auto I = Rt.FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
2092 I->getSecond().GlobalRecord = GlobalizedRD;
2093 I->getSecond().MappedParams =
2094 std::make_unique<CodeGenFunction::OMPMapVars>();
2095 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
2096 for (const auto &Pair : MappedDeclsFields) {
2097 assert(Pair.getFirst()->isCanonicalDecl() &&((Pair.getFirst()->isCanonicalDecl() && "Expected canonical declaration"
) ? static_cast<void> (0) : __assert_fail ("Pair.getFirst()->isCanonicalDecl() && \"Expected canonical declaration\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 2098, __PRETTY_FUNCTION__))
2098 "Expected canonical declaration")((Pair.getFirst()->isCanonicalDecl() && "Expected canonical declaration"
) ? static_cast<void> (0) : __assert_fail ("Pair.getFirst()->isCanonicalDecl() && \"Expected canonical declaration\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 2098, __PRETTY_FUNCTION__))
;
2099 Data.insert(std::make_pair(Pair.getFirst(),
2100 MappedVarData(Pair.getSecond(),
2101 /*IsOnePerTeam=*/true)));
2102 }
2103 }
2104 Rt.emitGenericVarsProlog(CGF, Loc);
2105 }
2106 void Exit(CodeGenFunction &CGF) override {
2107 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
2108 .emitGenericVarsEpilog(CGF);
2109 }
2110 } Action(Loc, GlobalizedRD, MappedDeclsFields);
2111 CodeGen.setAction(Action);
2112 llvm::Function *OutlinedFun = CGOpenMPRuntime::emitTeamsOutlinedFunction(
2113 D, ThreadIDVar, InnermostKind, CodeGen);
2114 if (CGM.getLangOpts().Optimize) {
2115 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
2116 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
2117 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
2118 }
2119
2120 return OutlinedFun;
2121}
2122
2123void CGOpenMPRuntimeNVPTX::emitGenericVarsProlog(CodeGenFunction &CGF,
2124 SourceLocation Loc,
2125 bool WithSPMDCheck) {
2126 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2127 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
2128 return;
2129
2130 CGBuilderTy &Bld = CGF.Builder;
2131
2132 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
2133 if (I == FunctionGlobalizedDecls.end())
2134 return;
2135 if (const RecordDecl *GlobalizedVarsRecord = I->getSecond().GlobalRecord) {
2136 QualType GlobalRecTy = CGM.getContext().getRecordType(GlobalizedVarsRecord);
2137 QualType SecGlobalRecTy;
2138
2139 // Recover pointer to this function's global record. The runtime will
2140 // handle the specifics of the allocation of the memory.
2141 // Use actual memory size of the record including the padding
2142 // for alignment purposes.
2143 unsigned Alignment =
2144 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
2145 unsigned GlobalRecordSize =
2146 CGM.getContext().getTypeSizeInChars(GlobalRecTy).getQuantity();
2147 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
2148
2149 llvm::PointerType *GlobalRecPtrTy =
2150 CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo();
2151 llvm::Value *GlobalRecCastAddr;
2152 llvm::Value *IsTTD = nullptr;
2153 if (!IsInTTDRegion &&
2154 (WithSPMDCheck ||
2155 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
2156 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2157 llvm::BasicBlock *SPMDBB = CGF.createBasicBlock(".spmd");
2158 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
2159 if (I->getSecond().SecondaryGlobalRecord.hasValue()) {
2160 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2161 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2162 llvm::Value *PL = CGF.EmitRuntimeCall(
2163 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2164 {RTLoc, ThreadID});
2165 IsTTD = Bld.CreateIsNull(PL);
2166 }
2167 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2168 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
2169 Bld.CreateCondBr(IsSPMD, SPMDBB, NonSPMDBB);
2170 // There is no need to emit line number for unconditional branch.
2171 (void)ApplyDebugLocation::CreateEmpty(CGF);
2172 CGF.EmitBlock(SPMDBB);
2173 Address RecPtr = Address(llvm::ConstantPointerNull::get(GlobalRecPtrTy),
2174 CharUnits::fromQuantity(Alignment));
2175 CGF.EmitBranch(ExitBB);
2176 // There is no need to emit line number for unconditional branch.
2177 (void)ApplyDebugLocation::CreateEmpty(CGF);
2178 CGF.EmitBlock(NonSPMDBB);
2179 llvm::Value *Size = llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize);
2180 if (const RecordDecl *SecGlobalizedVarsRecord =
2181 I->getSecond().SecondaryGlobalRecord.getValueOr(nullptr)) {
2182 SecGlobalRecTy =
2183 CGM.getContext().getRecordType(SecGlobalizedVarsRecord);
2184
2185 // Recover pointer to this function's global record. The runtime will
2186 // handle the specifics of the allocation of the memory.
2187 // Use actual memory size of the record including the padding
2188 // for alignment purposes.
2189 unsigned Alignment =
2190 CGM.getContext().getTypeAlignInChars(SecGlobalRecTy).getQuantity();
2191 unsigned GlobalRecordSize =
2192 CGM.getContext().getTypeSizeInChars(SecGlobalRecTy).getQuantity();
2193 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
2194 Size = Bld.CreateSelect(
2195 IsTTD, llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize), Size);
2196 }
2197 // TODO: allow the usage of shared memory to be controlled by
2198 // the user, for now, default to global.
2199 llvm::Value *GlobalRecordSizeArg[] = {
2200 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
2201 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2202 createNVPTXRuntimeFunction(
2203 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2204 GlobalRecordSizeArg);
2205 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2206 GlobalRecValue, GlobalRecPtrTy);
2207 CGF.EmitBlock(ExitBB);
2208 auto *Phi = Bld.CreatePHI(GlobalRecPtrTy,
2209 /*NumReservedValues=*/2, "_select_stack");
2210 Phi->addIncoming(RecPtr.getPointer(), SPMDBB);
2211 Phi->addIncoming(GlobalRecCastAddr, NonSPMDBB);
2212 GlobalRecCastAddr = Phi;
2213 I->getSecond().GlobalRecordAddr = Phi;
2214 I->getSecond().IsInSPMDModeFlag = IsSPMD;
2215 } else if (IsInTTDRegion) {
2216 assert(GlobalizedRecords.back().Records.size() < 2 &&((GlobalizedRecords.back().Records.size() < 2 && "Expected less than 2 globalized records: one for target and one "
"for teams.") ? static_cast<void> (0) : __assert_fail (
"GlobalizedRecords.back().Records.size() < 2 && \"Expected less than 2 globalized records: one for target and one \" \"for teams.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 2218, __PRETTY_FUNCTION__))
2217 "Expected less than 2 globalized records: one for target and one "((GlobalizedRecords.back().Records.size() < 2 && "Expected less than 2 globalized records: one for target and one "
"for teams.") ? static_cast<void> (0) : __assert_fail (
"GlobalizedRecords.back().Records.size() < 2 && \"Expected less than 2 globalized records: one for target and one \" \"for teams.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 2218, __PRETTY_FUNCTION__))
2218 "for teams.")((GlobalizedRecords.back().Records.size() < 2 && "Expected less than 2 globalized records: one for target and one "
"for teams.") ? static_cast<void> (0) : __assert_fail (
"GlobalizedRecords.back().Records.size() < 2 && \"Expected less than 2 globalized records: one for target and one \" \"for teams.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 2218, __PRETTY_FUNCTION__))
;
2219 unsigned Offset = 0;
2220 for (const RecordDecl *RD : GlobalizedRecords.back().Records) {
2221 QualType RDTy = CGM.getContext().getRecordType(RD);
2222 unsigned Alignment =
2223 CGM.getContext().getTypeAlignInChars(RDTy).getQuantity();
2224 unsigned Size = CGM.getContext().getTypeSizeInChars(RDTy).getQuantity();
2225 Offset =
2226 llvm::alignTo(llvm::alignTo(Offset, Alignment) + Size, Alignment);
2227 }
2228 unsigned Alignment =
2229 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
2230 Offset = llvm::alignTo(Offset, Alignment);
2231 GlobalizedRecords.back().Records.push_back(GlobalizedVarsRecord);
2232 ++GlobalizedRecords.back().RegionCounter;
2233 if (GlobalizedRecords.back().Records.size() == 1) {
2234 assert(KernelStaticGlobalized &&((KernelStaticGlobalized && "Kernel static pointer must be initialized already."
) ? static_cast<void> (0) : __assert_fail ("KernelStaticGlobalized && \"Kernel static pointer must be initialized already.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 2235, __PRETTY_FUNCTION__))
2235 "Kernel static pointer must be initialized already.")((KernelStaticGlobalized && "Kernel static pointer must be initialized already."
) ? static_cast<void> (0) : __assert_fail ("KernelStaticGlobalized && \"Kernel static pointer must be initialized already.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 2235, __PRETTY_FUNCTION__))
;
2236 auto *UseSharedMemory = new llvm::GlobalVariable(
2237 CGM.getModule(), CGM.Int16Ty, /*isConstant=*/true,
2238 llvm::GlobalValue::InternalLinkage, nullptr,
2239 "_openmp_static_kernel$is_shared");
2240 UseSharedMemory->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2241 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2242 /*DestWidth=*/16, /*Signed=*/0);
2243 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2244 Address(UseSharedMemory,
2245 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2246 /*Volatile=*/false, Int16Ty, Loc);
2247 auto *StaticGlobalized = new llvm::GlobalVariable(
2248 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2249 llvm::GlobalValue::CommonLinkage, nullptr);
2250 auto *RecSize = new llvm::GlobalVariable(
2251 CGM.getModule(), CGM.SizeTy, /*isConstant=*/true,
2252 llvm::GlobalValue::InternalLinkage, nullptr,
2253 "_openmp_static_kernel$size");
2254 RecSize->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2255 llvm::Value *Ld = CGF.EmitLoadOfScalar(
2256 Address(RecSize, CGM.getSizeAlign()), /*Volatile=*/false,
2257 CGM.getContext().getSizeType(), Loc);
2258 llvm::Value *ResAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2259 KernelStaticGlobalized, CGM.VoidPtrPtrTy);
2260 llvm::Value *GlobalRecordSizeArg[] = {
2261 llvm::ConstantInt::get(
2262 CGM.Int16Ty,
2263 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD ? 1 : 0),
2264 StaticGlobalized, Ld, IsInSharedMemory, ResAddr};
2265 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2266 OMPRTL_NVPTX__kmpc_get_team_static_memory),
2267 GlobalRecordSizeArg);
2268 GlobalizedRecords.back().Buffer = StaticGlobalized;
2269 GlobalizedRecords.back().RecSize = RecSize;
2270 GlobalizedRecords.back().UseSharedMemory = UseSharedMemory;
2271 GlobalizedRecords.back().Loc = Loc;
2272 }
2273 assert(KernelStaticGlobalized && "Global address must be set already.")((KernelStaticGlobalized && "Global address must be set already."
) ? static_cast<void> (0) : __assert_fail ("KernelStaticGlobalized && \"Global address must be set already.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 2273, __PRETTY_FUNCTION__))
;
2274 Address FrameAddr = CGF.EmitLoadOfPointer(
2275 Address(KernelStaticGlobalized, CGM.getPointerAlign()),
2276 CGM.getContext()
2277 .getPointerType(CGM.getContext().VoidPtrTy)
2278 .castAs<PointerType>());
2279 llvm::Value *GlobalRecValue =
2280 Bld.CreateConstInBoundsGEP(FrameAddr, Offset).getPointer();
2281 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2282 I->getSecond().IsInSPMDModeFlag = nullptr;
2283 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2284 GlobalRecValue, CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo());
2285 } else {
2286 // TODO: allow the usage of shared memory to be controlled by
2287 // the user, for now, default to global.
2288 llvm::Value *GlobalRecordSizeArg[] = {
2289 llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize),
2290 CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
2291 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2292 createNVPTXRuntimeFunction(
2293 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2294 GlobalRecordSizeArg);
2295 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2296 GlobalRecValue, GlobalRecPtrTy);
2297 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2298 I->getSecond().IsInSPMDModeFlag = nullptr;
2299 }
2300 LValue Base =
2301 CGF.MakeNaturalAlignPointeeAddrLValue(GlobalRecCastAddr, GlobalRecTy);
2302
2303 // Emit the "global alloca" which is a GEP from the global declaration
2304 // record using the pointer returned by the runtime.
2305 LValue SecBase;
2306 decltype(I->getSecond().LocalVarData)::const_iterator SecIt;
2307 if (IsTTD) {
2308 SecIt = I->getSecond().SecondaryLocalVarData->begin();
2309 llvm::PointerType *SecGlobalRecPtrTy =
2310 CGF.ConvertTypeForMem(SecGlobalRecTy)->getPointerTo();
2311 SecBase = CGF.MakeNaturalAlignPointeeAddrLValue(
2312 Bld.CreatePointerBitCastOrAddrSpaceCast(
2313 I->getSecond().GlobalRecordAddr, SecGlobalRecPtrTy),
2314 SecGlobalRecTy);
2315 }
2316 for (auto &Rec : I->getSecond().LocalVarData) {
2317 bool EscapedParam = I->getSecond().EscapedParameters.count(Rec.first);
2318 llvm::Value *ParValue;
2319 if (EscapedParam) {
2320 const auto *VD = cast<VarDecl>(Rec.first);
2321 LValue ParLVal =
2322 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
2323 ParValue = CGF.EmitLoadOfScalar(ParLVal, Loc);
2324 }
2325 LValue VarAddr = CGF.EmitLValueForField(Base, Rec.second.FD);
2326 // Emit VarAddr basing on lane-id if required.
2327 QualType VarTy;
2328 if (Rec.second.IsOnePerTeam) {
2329 VarTy = Rec.second.FD->getType();
2330 } else {
2331 llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(
2332 VarAddr.getAddress(CGF).getPointer(),
2333 {Bld.getInt32(0), getNVPTXLaneID(CGF)});
2334 VarTy =
2335 Rec.second.FD->getType()->castAsArrayTypeUnsafe()->getElementType();
2336 VarAddr = CGF.MakeAddrLValue(
2337 Address(Ptr, CGM.getContext().getDeclAlign(Rec.first)), VarTy,
2338 AlignmentSource::Decl);
2339 }
2340 Rec.second.PrivateAddr = VarAddr.getAddress(CGF);
2341 if (!IsInTTDRegion &&
2342 (WithSPMDCheck ||
2343 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
2344 assert(I->getSecond().IsInSPMDModeFlag &&((I->getSecond().IsInSPMDModeFlag && "Expected unknown execution mode or required SPMD check."
) ? static_cast<void> (0) : __assert_fail ("I->getSecond().IsInSPMDModeFlag && \"Expected unknown execution mode or required SPMD check.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 2345, __PRETTY_FUNCTION__))
2345 "Expected unknown execution mode or required SPMD check.")((I->getSecond().IsInSPMDModeFlag && "Expected unknown execution mode or required SPMD check."
) ? static_cast<void> (0) : __assert_fail ("I->getSecond().IsInSPMDModeFlag && \"Expected unknown execution mode or required SPMD check.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 2345, __PRETTY_FUNCTION__))
;
2346 if (IsTTD) {
2347 assert(SecIt->second.IsOnePerTeam &&((SecIt->second.IsOnePerTeam && "Secondary glob data must be one per team."
) ? static_cast<void> (0) : __assert_fail ("SecIt->second.IsOnePerTeam && \"Secondary glob data must be one per team.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 2348, __PRETTY_FUNCTION__))
2348 "Secondary glob data must be one per team.")((SecIt->second.IsOnePerTeam && "Secondary glob data must be one per team."
) ? static_cast<void> (0) : __assert_fail ("SecIt->second.IsOnePerTeam && \"Secondary glob data must be one per team.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 2348, __PRETTY_FUNCTION__))
;
2349 LValue SecVarAddr = CGF.EmitLValueForField(SecBase, SecIt->second.FD);
2350 VarAddr.setAddress(
2351 Address(Bld.CreateSelect(IsTTD, SecVarAddr.getPointer(CGF),
2352 VarAddr.getPointer(CGF)),
2353 VarAddr.getAlignment()));
2354 Rec.second.PrivateAddr = VarAddr.getAddress(CGF);
2355 }
2356 Address GlobalPtr = Rec.second.PrivateAddr;
2357 Address LocalAddr = CGF.CreateMemTemp(VarTy, Rec.second.FD->getName());
2358 Rec.second.PrivateAddr = Address(
2359 Bld.CreateSelect(I->getSecond().IsInSPMDModeFlag,
2360 LocalAddr.getPointer(), GlobalPtr.getPointer()),
2361 LocalAddr.getAlignment());
2362 }
2363 if (EscapedParam) {
2364 const auto *VD = cast<VarDecl>(Rec.first);
2365 CGF.EmitStoreOfScalar(ParValue, VarAddr);
2366 I->getSecond().MappedParams->setVarAddr(CGF, VD,
2367 VarAddr.getAddress(CGF));
2368 }
2369 if (IsTTD)
2370 ++SecIt;
2371 }
2372 }
2373 for (const ValueDecl *VD : I->getSecond().EscapedVariableLengthDecls) {
2374 // Recover pointer to this function's global record. The runtime will
2375 // handle the specifics of the allocation of the memory.
2376 // Use actual memory size of the record including the padding
2377 // for alignment purposes.
2378 CGBuilderTy &Bld = CGF.Builder;
2379 llvm::Value *Size = CGF.getTypeSize(VD->getType());
2380 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2381 Size = Bld.CreateNUWAdd(
2382 Size, llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity() - 1));
2383 llvm::Value *AlignVal =
2384 llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity());
2385 Size = Bld.CreateUDiv(Size, AlignVal);
2386 Size = Bld.CreateNUWMul(Size, AlignVal);
2387 // TODO: allow the usage of shared memory to be controlled by
2388 // the user, for now, default to global.
2389 llvm::Value *GlobalRecordSizeArg[] = {
2390 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
2391 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2392 createNVPTXRuntimeFunction(
2393 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2394 GlobalRecordSizeArg);
2395 llvm::Value *GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2396 GlobalRecValue, CGF.ConvertTypeForMem(VD->getType())->getPointerTo());
2397 LValue Base = CGF.MakeAddrLValue(GlobalRecCastAddr, VD->getType(),
2398 CGM.getContext().getDeclAlign(VD),
2399 AlignmentSource::Decl);
2400 I->getSecond().MappedParams->setVarAddr(CGF, cast<VarDecl>(VD),
2401 Base.getAddress(CGF));
2402 I->getSecond().EscapedVariableLengthDeclsAddrs.emplace_back(GlobalRecValue);
2403 }
2404 I->getSecond().MappedParams->apply(CGF);
2405}
2406
2407void CGOpenMPRuntimeNVPTX::emitGenericVarsEpilog(CodeGenFunction &CGF,
2408 bool WithSPMDCheck) {
2409 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2410 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
2411 return;
2412
2413 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
2414 if (I != FunctionGlobalizedDecls.end()) {
2415 I->getSecond().MappedParams->restore(CGF);
2416 if (!CGF.HaveInsertPoint())
2417 return;
2418 for (llvm::Value *Addr :
2419 llvm::reverse(I->getSecond().EscapedVariableLengthDeclsAddrs)) {
2420 CGF.EmitRuntimeCall(
2421 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2422 Addr);
2423 }
2424 if (I->getSecond().GlobalRecordAddr) {
2425 if (!IsInTTDRegion &&
2426 (WithSPMDCheck ||
2427 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
2428 CGBuilderTy &Bld = CGF.Builder;
2429 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2430 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
2431 Bld.CreateCondBr(I->getSecond().IsInSPMDModeFlag, ExitBB, NonSPMDBB);
2432 // There is no need to emit line number for unconditional branch.
2433 (void)ApplyDebugLocation::CreateEmpty(CGF);
2434 CGF.EmitBlock(NonSPMDBB);
2435 CGF.EmitRuntimeCall(
2436 createNVPTXRuntimeFunction(
2437 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2438 CGF.EmitCastToVoidPtr(I->getSecond().GlobalRecordAddr));
2439 CGF.EmitBlock(ExitBB);
2440 } else if (IsInTTDRegion) {
2441 assert(GlobalizedRecords.back().RegionCounter > 0 &&((GlobalizedRecords.back().RegionCounter > 0 && "region counter must be > 0."
) ? static_cast<void> (0) : __assert_fail ("GlobalizedRecords.back().RegionCounter > 0 && \"region counter must be > 0.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 2442, __PRETTY_FUNCTION__))
2442 "region counter must be > 0.")((GlobalizedRecords.back().RegionCounter > 0 && "region counter must be > 0."
) ? static_cast<void> (0) : __assert_fail ("GlobalizedRecords.back().RegionCounter > 0 && \"region counter must be > 0.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 2442, __PRETTY_FUNCTION__))
;
2443 --GlobalizedRecords.back().RegionCounter;
2444 // Emit the restore function only in the target region.
2445 if (GlobalizedRecords.back().RegionCounter == 0) {
2446 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2447 /*DestWidth=*/16, /*Signed=*/0);
2448 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2449 Address(GlobalizedRecords.back().UseSharedMemory,
2450 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2451 /*Volatile=*/false, Int16Ty, GlobalizedRecords.back().Loc);
2452 llvm::Value *Args[] = {
2453 llvm::ConstantInt::get(
2454 CGM.Int16Ty,
2455 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD ? 1 : 0),
2456 IsInSharedMemory};
2457 CGF.EmitRuntimeCall(
2458 createNVPTXRuntimeFunction(
2459 OMPRTL_NVPTX__kmpc_restore_team_static_memory),
2460 Args);
2461 }
2462 } else {
2463 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2464 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2465 I->getSecond().GlobalRecordAddr);
2466 }
2467 }
2468 }
2469}
2470
2471void CGOpenMPRuntimeNVPTX::emitTeamsCall(CodeGenFunction &CGF,
2472 const OMPExecutableDirective &D,
2473 SourceLocation Loc,
2474 llvm::Function *OutlinedFn,
2475 ArrayRef<llvm::Value *> CapturedVars) {
2476 if (!CGF.HaveInsertPoint())
2477 return;
2478
2479 Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2480 /*Name=*/".zero.addr");
2481 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2482 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2483 OutlinedFnArgs.push_back(emitThreadIDAddress(CGF, Loc).getPointer());
2484 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2485 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2486 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2487}
2488
2489void CGOpenMPRuntimeNVPTX::emitParallelCall(
2490 CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
2491 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2492 if (!CGF.HaveInsertPoint())
2493 return;
2494
2495 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
2496 emitSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
2497 else
2498 emitNonSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
2499}
2500
2501void CGOpenMPRuntimeNVPTX::emitNonSPMDParallelCall(
2502 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2503 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2504 llvm::Function *Fn = cast<llvm::Function>(OutlinedFn);
2505
2506 // Force inline this outlined function at its call site.
2507 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
2508
2509 Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2510 /*Name=*/".zero.addr");
2511 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2512 // ThreadId for serialized parallels is 0.
2513 Address ThreadIDAddr = ZeroAddr;
2514 auto &&CodeGen = [this, Fn, CapturedVars, Loc, &ThreadIDAddr](
2515 CodeGenFunction &CGF, PrePostActionTy &Action) {
2516 Action.Enter(CGF);
2517
2518 Address ZeroAddr =
2519 CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2520 /*Name=*/".bound.zero.addr");
2521 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2522 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2523 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2524 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2525 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2526 emitOutlinedFunctionCall(CGF, Loc, Fn, OutlinedFnArgs);
2527 };
2528 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2529 PrePostActionTy &) {
2530
2531 RegionCodeGenTy RCG(CodeGen);
2532 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2533 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2534 llvm::Value *Args[] = {RTLoc, ThreadID};
2535
2536 NVPTXActionTy Action(
2537 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2538 Args,
2539 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2540 Args);
2541 RCG.setAction(Action);
2542 RCG(CGF);
2543 };
2544
2545 auto &&L0ParallelGen = [this, CapturedVars, Fn](CodeGenFunction &CGF,
2546 PrePostActionTy &Action) {
2547 CGBuilderTy &Bld = CGF.Builder;
2548 llvm::Function *WFn = WrapperFunctionsMap[Fn];
2549 assert(WFn && "Wrapper function does not exist!")((WFn && "Wrapper function does not exist!") ? static_cast
<void> (0) : __assert_fail ("WFn && \"Wrapper function does not exist!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 2549, __PRETTY_FUNCTION__))
;
2550 llvm::Value *ID = Bld.CreateBitOrPointerCast(WFn, CGM.Int8PtrTy);
2551
2552 // Prepare for parallel region. Indicate the outlined function.
2553 llvm::Value *Args[] = {ID, /*RequiresOMPRuntime=*/Bld.getInt16(1)};
2554 CGF.EmitRuntimeCall(
2555 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_prepare_parallel),
2556 Args);
2557
2558 // Create a private scope that will globalize the arguments
2559 // passed from the outside of the target region.
2560 CodeGenFunction::OMPPrivateScope PrivateArgScope(CGF);
2561
2562 // There's something to share.
2563 if (!CapturedVars.empty()) {
2564 // Prepare for parallel region. Indicate the outlined function.
2565 Address SharedArgs =
2566 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "shared_arg_refs");
2567 llvm::Value *SharedArgsPtr = SharedArgs.getPointer();
2568
2569 llvm::Value *DataSharingArgs[] = {
2570 SharedArgsPtr,
2571 llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size())};
2572 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2573 OMPRTL_NVPTX__kmpc_begin_sharing_variables),
2574 DataSharingArgs);
2575
2576 // Store variable address in a list of references to pass to workers.
2577 unsigned Idx = 0;
2578 ASTContext &Ctx = CGF.getContext();
2579 Address SharedArgListAddress = CGF.EmitLoadOfPointer(
2580 SharedArgs, Ctx.getPointerType(Ctx.getPointerType(Ctx.VoidPtrTy))
2581 .castAs<PointerType>());
2582 for (llvm::Value *V : CapturedVars) {
2583 Address Dst = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
2584 llvm::Value *PtrV;
2585 if (V->getType()->isIntegerTy())
2586 PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
2587 else
2588 PtrV = Bld.CreatePointerBitCastOrAddrSpaceCast(V, CGF.VoidPtrTy);
2589 CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
2590 Ctx.getPointerType(Ctx.VoidPtrTy));
2591 ++Idx;
2592 }
2593 }
2594
2595 // Activate workers. This barrier is used by the master to signal
2596 // work for the workers.
2597 syncCTAThreads(CGF);
2598
2599 // OpenMP [2.5, Parallel Construct, p.49]
2600 // There is an implied barrier at the end of a parallel region. After the
2601 // end of a parallel region, only the master thread of the team resumes
2602 // execution of the enclosing task region.
2603 //
2604 // The master waits at this barrier until all workers are done.
2605 syncCTAThreads(CGF);
2606
2607 if (!CapturedVars.empty())
2608 CGF.EmitRuntimeCall(
2609 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_sharing_variables));
2610
2611 // Remember for post-processing in worker loop.
2612 Work.emplace_back(WFn);
2613 };
2614
2615 auto &&LNParallelGen = [this, Loc, &SeqGen, &L0ParallelGen](
2616 CodeGenFunction &CGF, PrePostActionTy &Action) {
2617 if (IsInParallelRegion) {
2618 SeqGen(CGF, Action);
2619 } else if (IsInTargetMasterThreadRegion) {
2620 L0ParallelGen(CGF, Action);
2621 } else {
2622 // Check for master and then parallelism:
2623 // if (__kmpc_is_spmd_exec_mode() || __kmpc_parallel_level(loc, gtid)) {
2624 // Serialized execution.
2625 // } else {
2626 // Worker call.
2627 // }
2628 CGBuilderTy &Bld = CGF.Builder;
2629 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2630 llvm::BasicBlock *SeqBB = CGF.createBasicBlock(".sequential");
2631 llvm::BasicBlock *ParallelCheckBB = CGF.createBasicBlock(".parcheck");
2632 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
2633 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2634 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
2635 Bld.CreateCondBr(IsSPMD, SeqBB, ParallelCheckBB);
2636 // There is no need to emit line number for unconditional branch.
2637 (void)ApplyDebugLocation::CreateEmpty(CGF);
2638 CGF.EmitBlock(ParallelCheckBB);
2639 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2640 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2641 llvm::Value *PL = CGF.EmitRuntimeCall(
2642 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2643 {RTLoc, ThreadID});
2644 llvm::Value *Res = Bld.CreateIsNotNull(PL);
2645 Bld.CreateCondBr(Res, SeqBB, MasterBB);
2646 CGF.EmitBlock(SeqBB);
2647 SeqGen(CGF, Action);
2648 CGF.EmitBranch(ExitBB);
2649 // There is no need to emit line number for unconditional branch.
2650 (void)ApplyDebugLocation::CreateEmpty(CGF);
2651 CGF.EmitBlock(MasterBB);
2652 L0ParallelGen(CGF, Action);
2653 CGF.EmitBranch(ExitBB);
2654 // There is no need to emit line number for unconditional branch.
2655 (void)ApplyDebugLocation::CreateEmpty(CGF);
2656 // Emit the continuation block for code after the if.
2657 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2658 }
2659 };
2660
2661 if (IfCond) {
2662 emitIfClause(CGF, IfCond, LNParallelGen, SeqGen);
2663 } else {
2664 CodeGenFunction::RunCleanupsScope Scope(CGF);
2665 RegionCodeGenTy ThenRCG(LNParallelGen);
2666 ThenRCG(CGF);
2667 }
2668}
2669
2670void CGOpenMPRuntimeNVPTX::emitSPMDParallelCall(
2671 CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
2672 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2673 // Just call the outlined function to execute the parallel region.
2674 // OutlinedFn(&GTid, &zero, CapturedStruct);
2675 //
2676 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2677
2678 Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2679 /*Name=*/".zero.addr");
2680 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2681 // ThreadId for serialized parallels is 0.
2682 Address ThreadIDAddr = ZeroAddr;
2683 auto &&CodeGen = [this, OutlinedFn, CapturedVars, Loc, &ThreadIDAddr](
2684 CodeGenFunction &CGF, PrePostActionTy &Action) {
2685 Action.Enter(CGF);
2686
2687 Address ZeroAddr =
2688 CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2689 /*Name=*/".bound.zero.addr");
2690 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2691 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2692 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2693 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2694 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2695 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2696 };
2697 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2698 PrePostActionTy &) {
2699
2700 RegionCodeGenTy RCG(CodeGen);
2701 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2702 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2703 llvm::Value *Args[] = {RTLoc, ThreadID};
2704
2705 NVPTXActionTy Action(
2706 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2707 Args,
2708 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2709 Args);
2710 RCG.setAction(Action);
2711 RCG(CGF);
2712 };
2713
2714 if (IsInTargetMasterThreadRegion) {
2715 // In the worker need to use the real thread id.
2716 ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
2717 RegionCodeGenTy RCG(CodeGen);
2718 RCG(CGF);
2719 } else {
2720 // If we are not in the target region, it is definitely L2 parallelism or
2721 // more, because for SPMD mode we always has L1 parallel level, sowe don't
2722 // need to check for orphaned directives.
2723 RegionCodeGenTy RCG(SeqGen);
2724 RCG(CGF);
2725 }
2726}
2727
2728void CGOpenMPRuntimeNVPTX::syncCTAThreads(CodeGenFunction &CGF) {
2729 // Always emit simple barriers!
2730 if (!CGF.HaveInsertPoint())
2731 return;
2732 // Build call __kmpc_barrier_simple_spmd(nullptr, 0);
2733 // This function does not use parameters, so we can emit just default values.
2734 llvm::Value *Args[] = {
2735 llvm::ConstantPointerNull::get(
2736 cast<llvm::PointerType>(getIdentTyPointerTy())),
2737 llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/0, /*isSigned=*/true)};
2738 llvm::CallInst *Call = CGF.EmitRuntimeCall(
2739 createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier_simple_spmd), Args);
2740 Call->setConvergent();
2741}
2742
2743void CGOpenMPRuntimeNVPTX::emitBarrierCall(CodeGenFunction &CGF,
2744 SourceLocation Loc,
2745 OpenMPDirectiveKind Kind, bool,
2746 bool) {
2747 // Always emit simple barriers!
2748 if (!CGF.HaveInsertPoint())
2749 return;
2750 // Build call __kmpc_cancel_barrier(loc, thread_id);
2751 unsigned Flags = getDefaultFlagsForBarriers(Kind);
2752 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2753 getThreadID(CGF, Loc)};
2754 llvm::CallInst *Call = CGF.EmitRuntimeCall(
2755 createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier), Args);
2756 Call->setConvergent();
2757}
2758
2759void CGOpenMPRuntimeNVPTX::emitCriticalRegion(
2760 CodeGenFunction &CGF, StringRef CriticalName,
2761 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
2762 const Expr *Hint) {
2763 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
2764 llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
2765 llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
2766 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
2767 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
2768
2769 // Get the mask of active threads in the warp.
2770 llvm::Value *Mask = CGF.EmitRuntimeCall(
2771 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_warp_active_thread_mask));
2772 // Fetch team-local id of the thread.
2773 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
2774
2775 // Get the width of the team.
2776 llvm::Value *TeamWidth = getNVPTXNumThreads(CGF);
2777
2778 // Initialize the counter variable for the loop.
2779 QualType Int32Ty =
2780 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
2781 Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
2782 LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
2783 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
2784 /*isInit=*/true);
2785
2786 // Block checks if loop counter exceeds upper bound.
2787 CGF.EmitBlock(LoopBB);
2788 llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2789 llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
2790 CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
2791
2792 // Block tests which single thread should execute region, and which threads
2793 // should go straight to synchronisation point.
2794 CGF.EmitBlock(TestBB);
2795 CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2796 llvm::Value *CmpThreadToCounter =
2797 CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
2798 CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
2799
2800 // Block emits the body of the critical region.
2801 CGF.EmitBlock(BodyBB);
2802
2803 // Output the critical statement.
2804 CGOpenMPRuntime::emitCriticalRegion(CGF, CriticalName, CriticalOpGen, Loc,
2805 Hint);
2806
2807 // After the body surrounded by the critical region, the single executing
2808 // thread will jump to the synchronisation point.
2809 // Block waits for all threads in current team to finish then increments the
2810 // counter variable and returns to the loop.
2811 CGF.EmitBlock(SyncBB);
2812 // Reconverge active threads in the warp.
2813 (void)CGF.EmitRuntimeCall(
2814 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_syncwarp), Mask);
2815
2816 llvm::Value *IncCounterVal =
2817 CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
2818 CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
2819 CGF.EmitBranch(LoopBB);
2820
2821 // Block that is reached when all threads in the team complete the region.
2822 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2823}
2824
2825/// Cast value to the specified type.
2826static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
2827 QualType ValTy, QualType CastTy,
2828 SourceLocation Loc) {
2829 assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&((!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
"Cast type must sized.") ? static_cast<void> (0) : __assert_fail
("!CGF.getContext().getTypeSizeInChars(CastTy).isZero() && \"Cast type must sized.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 2830, __PRETTY_FUNCTION__))
2830 "Cast type must sized.")((!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
"Cast type must sized.") ? static_cast<void> (0) : __assert_fail
("!CGF.getContext().getTypeSizeInChars(CastTy).isZero() && \"Cast type must sized.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 2830, __PRETTY_FUNCTION__))
;
2831 assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&((!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
"Val type must sized.") ? static_cast<void> (0) : __assert_fail
("!CGF.getContext().getTypeSizeInChars(ValTy).isZero() && \"Val type must sized.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 2832, __PRETTY_FUNCTION__))
2832 "Val type must sized.")((!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
"Val type must sized.") ? static_cast<void> (0) : __assert_fail
("!CGF.getContext().getTypeSizeInChars(ValTy).isZero() && \"Val type must sized.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 2832, __PRETTY_FUNCTION__))
;
2833 llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
2834 if (ValTy == CastTy)
2835 return Val;
2836 if (CGF.getContext().getTypeSizeInChars(ValTy) ==
2837 CGF.getContext().getTypeSizeInChars(CastTy))
2838 return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
2839 if (CastTy->isIntegerType() && ValTy->isIntegerType())
2840 return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
2841 CastTy->hasSignedIntegerRepresentation());
2842 Address CastItem = CGF.CreateMemTemp(CastTy);
2843 Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2844 CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
2845 CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy);
2846 return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc);
2847}
2848
2849/// This function creates calls to one of two shuffle functions to copy
2850/// variables between lanes in a warp.
2851static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
2852 llvm::Value *Elem,
2853 QualType ElemType,
2854 llvm::Value *Offset,
2855 SourceLocation Loc) {
2856 CodeGenModule &CGM = CGF.CGM;
2857 CGBuilderTy &Bld = CGF.Builder;
2858 CGOpenMPRuntimeNVPTX &RT =
2859 *(static_cast<CGOpenMPRuntimeNVPTX *>(&CGM.getOpenMPRuntime()));
2860
2861 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2862 assert(Size.getQuantity() <= 8 &&((Size.getQuantity() <= 8 && "Unsupported bitwidth in shuffle instruction."
) ? static_cast<void> (0) : __assert_fail ("Size.getQuantity() <= 8 && \"Unsupported bitwidth in shuffle instruction.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 2863, __PRETTY_FUNCTION__))
2863 "Unsupported bitwidth in shuffle instruction.")((Size.getQuantity() <= 8 && "Unsupported bitwidth in shuffle instruction."
) ? static_cast<void> (0) : __assert_fail ("Size.getQuantity() <= 8 && \"Unsupported bitwidth in shuffle instruction.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 2863, __PRETTY_FUNCTION__))
;
2864
2865 OpenMPRTLFunctionNVPTX ShuffleFn = Size.getQuantity() <= 4
2866 ? OMPRTL_NVPTX__kmpc_shuffle_int32
2867 : OMPRTL_NVPTX__kmpc_shuffle_int64;
2868
2869 // Cast all types to 32- or 64-bit values before calling shuffle routines.
2870 QualType CastTy = CGF.getContext().getIntTypeForBitwidth(
2871 Size.getQuantity() <= 4 ? 32 : 64, /*Signed=*/1);
2872 llvm::Value *ElemCast = castValueToType(CGF, Elem, ElemType, CastTy, Loc);
2873 llvm::Value *WarpSize =
2874 Bld.CreateIntCast(getNVPTXWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
2875
2876 llvm::Value *ShuffledVal = CGF.EmitRuntimeCall(
2877 RT.createNVPTXRuntimeFunction(ShuffleFn), {ElemCast, Offset, WarpSize});
2878
2879 return castValueToType(CGF, ShuffledVal, CastTy, ElemType, Loc);
2880}
2881
2882static void shuffleAndStore(CodeGenFunction &CGF, Address SrcAddr,
2883 Address DestAddr, QualType ElemType,
2884 llvm::Value *Offset, SourceLocation Loc) {
2885 CGBuilderTy &Bld = CGF.Builder;
2886
2887 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2888 // Create the loop over the big sized data.
2889 // ptr = (void*)Elem;
2890 // ptrEnd = (void*) Elem + 1;
2891 // Step = 8;
2892 // while (ptr + Step < ptrEnd)
2893 // shuffle((int64_t)*ptr);
2894 // Step = 4;
2895 // while (ptr + Step < ptrEnd)
2896 // shuffle((int32_t)*ptr);
2897 // ...
2898 Address ElemPtr = DestAddr;
2899 Address Ptr = SrcAddr;
2900 Address PtrEnd = Bld.CreatePointerBitCastOrAddrSpaceCast(
2901 Bld.CreateConstGEP(SrcAddr, 1), CGF.VoidPtrTy);
2902 for (int IntSize = 8; IntSize >= 1; IntSize /= 2) {
2903 if (Size < CharUnits::fromQuantity(IntSize))
2904 continue;
2905 QualType IntType = CGF.getContext().getIntTypeForBitwidth(
2906 CGF.getContext().toBits(CharUnits::fromQuantity(IntSize)),
2907 /*Signed=*/1);
2908 llvm::Type *IntTy = CGF.ConvertTypeForMem(IntType);
2909 Ptr = Bld.CreatePointerBitCastOrAddrSpaceCast(Ptr, IntTy->getPointerTo());
2910 ElemPtr =
2911 Bld.CreatePointerBitCastOrAddrSpaceCast(ElemPtr, IntTy->getPointerTo());
2912 if (Size.getQuantity() / IntSize > 1) {
2913 llvm::BasicBlock *PreCondBB = CGF.createBasicBlock(".shuffle.pre_cond");
2914 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".shuffle.then");
2915 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".shuffle.exit");
2916 llvm::BasicBlock *CurrentBB = Bld.GetInsertBlock();
2917 CGF.EmitBlock(PreCondBB);
2918 llvm::PHINode *PhiSrc =
2919 Bld.CreatePHI(Ptr.getType(), /*NumReservedValues=*/2);
2920 PhiSrc->addIncoming(Ptr.getPointer(), CurrentBB);
2921 llvm::PHINode *PhiDest =
2922 Bld.CreatePHI(ElemPtr.getType(), /*NumReservedValues=*/2);
2923 PhiDest->addIncoming(ElemPtr.getPointer(), CurrentBB);
2924 Ptr = Address(PhiSrc, Ptr.getAlignment());
2925 ElemPtr = Address(PhiDest, ElemPtr.getAlignment());
2926 llvm::Value *PtrDiff = Bld.CreatePtrDiff(
2927 PtrEnd.getPointer(), Bld.CreatePointerBitCastOrAddrSpaceCast(
2928 Ptr.getPointer(), CGF.VoidPtrTy));
2929 Bld.CreateCondBr(Bld.CreateICmpSGT(PtrDiff, Bld.getInt64(IntSize - 1)),
2930 ThenBB, ExitBB);
2931 CGF.EmitBlock(ThenBB);
2932 llvm::Value *Res = createRuntimeShuffleFunction(
2933 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2934 IntType, Offset, Loc);
2935 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
2936 Address LocalPtr = Bld.CreateConstGEP(Ptr, 1);
2937 Address LocalElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
2938 PhiSrc->addIncoming(LocalPtr.getPointer(), ThenBB);
2939 PhiDest->addIncoming(LocalElemPtr.getPointer(), ThenBB);
2940 CGF.EmitBranch(PreCondBB);
2941 CGF.EmitBlock(ExitBB);
2942 } else {
2943 llvm::Value *Res = createRuntimeShuffleFunction(
2944 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2945 IntType, Offset, Loc);
2946 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
2947 Ptr = Bld.CreateConstGEP(Ptr, 1);
2948 ElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
2949 }
2950 Size = Size % IntSize;
2951 }
2952}
2953
2954namespace {
2955enum CopyAction : unsigned {
2956 // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
2957 // the warp using shuffle instructions.
2958 RemoteLaneToThread,
2959 // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
2960 ThreadCopy,
2961 // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
2962 ThreadToScratchpad,
2963 // ScratchpadToThread: Copy from a scratchpad array in global memory
2964 // containing team-reduced data to a thread's stack.
2965 ScratchpadToThread,
2966};
2967} // namespace
2968
2969struct CopyOptionsTy {
2970 llvm::Value *RemoteLaneOffset;
2971 llvm::Value *ScratchpadIndex;
2972 llvm::Value *ScratchpadWidth;
2973};
2974
2975/// Emit instructions to copy a Reduce list, which contains partially
2976/// aggregated values, in the specified direction.
2977static void emitReductionListCopy(
2978 CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
2979 ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
2980 CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
2981
2982 CodeGenModule &CGM = CGF.CGM;
2983 ASTContext &C = CGM.getContext();
2984 CGBuilderTy &Bld = CGF.Builder;
2985
2986 llvm::Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
2987 llvm::Value *ScratchpadIndex = CopyOptions.ScratchpadIndex;
2988 llvm::Value *ScratchpadWidth = CopyOptions.ScratchpadWidth;
2989
2990 // Iterates, element-by-element, through the source Reduce list and
2991 // make a copy.
2992 unsigned Idx = 0;
2993 unsigned Size = Privates.size();
2994 for (const Expr *Private : Privates) {
2995 Address SrcElementAddr = Address::invalid();
2996 Address DestElementAddr = Address::invalid();
2997 Address DestElementPtrAddr = Address::invalid();
2998 // Should we shuffle in an element from a remote lane?
2999 bool ShuffleInElement = false;
3000 // Set to true to update the pointer in the dest Reduce list to a
3001 // newly created element.
3002 bool UpdateDestListPtr = false;
3003 // Increment the src or dest pointer to the scratchpad, for each
3004 // new element.
3005 bool IncrScratchpadSrc = false;
3006 bool IncrScratchpadDest = false;
3007
3008 switch (Action) {
3009 case RemoteLaneToThread: {
3010 // Step 1.1: Get the address for the src element in the Reduce list.
3011 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
3012 SrcElementAddr = CGF.EmitLoadOfPointer(
3013 SrcElementPtrAddr,
3014 C.getPointerType(Private->getType())->castAs<PointerType>());
3015
3016 // Step 1.2: Create a temporary to store the element in the destination
3017 // Reduce list.
3018 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
3019 DestElementAddr =
3020 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
3021 ShuffleInElement = true;
3022 UpdateDestListPtr = true;
3023 break;
3024 }
3025 case ThreadCopy: {
3026 // Step 1.1: Get the address for the src element in the Reduce list.
3027 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
3028 SrcElementAddr = CGF.EmitLoadOfPointer(
3029 SrcElementPtrAddr,
3030 C.getPointerType(Private->getType())->castAs<PointerType>());
3031
3032 // Step 1.2: Get the address for dest element. The destination
3033 // element has already been created on the thread's stack.
3034 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
3035 DestElementAddr = CGF.EmitLoadOfPointer(
3036 DestElementPtrAddr,
3037 C.getPointerType(Private->getType())->castAs<PointerType>());
3038 break;
3039 }
3040 case ThreadToScratchpad: {
3041 // Step 1.1: Get the address for the src element in the Reduce list.
3042 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
3043 SrcElementAddr = CGF.EmitLoadOfPointer(
3044 SrcElementPtrAddr,
3045 C.getPointerType(Private->getType())->castAs<PointerType>());
3046
3047 // Step 1.2: Get the address for dest element:
3048 // address = base + index * ElementSizeInChars.
3049 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
3050 llvm::Value *CurrentOffset =
3051 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
3052 llvm::Value *ScratchPadElemAbsolutePtrVal =
3053 Bld.CreateNUWAdd(DestBase.getPointer(), CurrentOffset);
3054 ScratchPadElemAbsolutePtrVal =
3055 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
3056 DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
3057 C.getTypeAlignInChars(Private->getType()));
3058 IncrScratchpadDest = true;
3059 break;
3060 }
3061 case ScratchpadToThread: {
3062 // Step 1.1: Get the address for the src element in the scratchpad.
3063 // address = base + index * ElementSizeInChars.
3064 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
3065 llvm::Value *CurrentOffset =
3066 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
3067 llvm::Value *ScratchPadElemAbsolutePtrVal =
3068 Bld.CreateNUWAdd(SrcBase.getPointer(), CurrentOffset);
3069 ScratchPadElemAbsolutePtrVal =
3070 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
3071 SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
3072 C.getTypeAlignInChars(Private->getType()));
3073 IncrScratchpadSrc = true;
3074
3075 // Step 1.2: Create a temporary to store the element in the destination
3076 // Reduce list.
3077 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
3078 DestElementAddr =
3079 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
3080 UpdateDestListPtr = true;
3081 break;
3082 }
3083 }
3084
3085 // Regardless of src and dest of copy, we emit the load of src
3086 // element as this is required in all directions
3087 SrcElementAddr = Bld.CreateElementBitCast(
3088 SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
3089 DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
3090 SrcElementAddr.getElementType());
3091
3092 // Now that all active lanes have read the element in the
3093 // Reduce list, shuffle over the value from the remote lane.
3094 if (ShuffleInElement) {
3095 shuffleAndStore(CGF, SrcElementAddr, DestElementAddr, Private->getType(),
3096 RemoteLaneOffset, Private->getExprLoc());
3097 } else {
3098 switch (CGF.getEvaluationKind(Private->getType())) {
3099 case TEK_Scalar: {
3100 llvm::Value *Elem =
3101 CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false,
3102 Private->getType(), Private->getExprLoc());
3103 // Store the source element value to the dest element address.
3104 CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false,
3105 Private->getType());
3106 break;
3107 }
3108 case TEK_Complex: {
3109 CodeGenFunction::ComplexPairTy Elem = CGF.EmitLoadOfComplex(
3110 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3111 Private->getExprLoc());
3112 CGF.EmitStoreOfComplex(
3113 Elem, CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3114 /*isInit=*/false);
3115 break;
3116 }
3117 case TEK_Aggregate:
3118 CGF.EmitAggregateCopy(
3119 CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3120 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3121 Private->getType(), AggValueSlot::DoesNotOverlap);
3122 break;
3123 }
3124 }
3125
3126 // Step 3.1: Modify reference in dest Reduce list as needed.
3127 // Modifying the reference in Reduce list to point to the newly
3128 // created element. The element is live in the current function
3129 // scope and that of functions it invokes (i.e., reduce_function).
3130 // RemoteReduceData[i] = (void*)&RemoteElem
3131 if (UpdateDestListPtr) {
3132 CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
3133 DestElementAddr.getPointer(), CGF.VoidPtrTy),
3134 DestElementPtrAddr, /*Volatile=*/false,
3135 C.VoidPtrTy);
3136 }
3137
3138 // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
3139 // address of the next element in scratchpad memory, unless we're currently
3140 // processing the last one. Memory alignment is also taken care of here.
3141 if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
3142 llvm::Value *ScratchpadBasePtr =
3143 IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
3144 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
3145 ScratchpadBasePtr = Bld.CreateNUWAdd(
3146 ScratchpadBasePtr,
3147 Bld.CreateNUWMul(ScratchpadWidth, ElementSizeInChars));
3148
3149 // Take care of global memory alignment for performance
3150 ScratchpadBasePtr = Bld.CreateNUWSub(
3151 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3152 ScratchpadBasePtr = Bld.CreateUDiv(
3153 ScratchpadBasePtr,
3154 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
3155 ScratchpadBasePtr = Bld.CreateNUWAdd(
3156 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3157 ScratchpadBasePtr = Bld.CreateNUWMul(
3158 ScratchpadBasePtr,
3159 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
3160
3161 if (IncrScratchpadDest)
3162 DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3163 else /* IncrScratchpadSrc = true */
3164 SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3165 }
3166
3167 ++Idx;
3168 }
3169}
3170
3171/// This function emits a helper that gathers Reduce lists from the first
3172/// lane of every active warp to lanes in the first warp.
3173///
3174/// void inter_warp_copy_func(void* reduce_data, num_warps)
3175/// shared smem[warp_size];
3176/// For all data entries D in reduce_data:
3177/// sync
3178/// If (I am the first lane in each warp)
3179/// Copy my local D to smem[warp_id]
3180/// sync
3181/// if (I am the first warp)
3182/// Copy smem[thread_id] to my local D
3183static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
3184 ArrayRef<const Expr *> Privates,
3185 QualType ReductionArrayTy,
3186 SourceLocation Loc) {
3187 ASTContext &C = CGM.getContext();
3188 llvm::Module &M = CGM.getModule();
3189
3190 // ReduceList: thread local Reduce list.
3191 // At the stage of the computation when this function is called, partially
3192 // aggregated values reside in the first lane of every active warp.
3193 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3194 C.VoidPtrTy, ImplicitParamDecl::Other);
3195 // NumWarps: number of warps active in the parallel region. This could
3196 // be smaller than 32 (max warps in a CTA) for partial block reduction.
3197 ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3198 C.getIntTypeForBitwidth(32, /* Signed */ true),
3199 ImplicitParamDecl::Other);
3200 FunctionArgList Args;
3201 Args.push_back(&ReduceListArg);
3202 Args.push_back(&NumWarpsArg);
3203
3204 const CGFunctionInfo &CGFI =
3205 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3206 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
3207 llvm::GlobalValue::InternalLinkage,
3208 "_omp_reduction_inter_warp_copy_func", &M);
3209 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3210 Fn->setDoesNotRecurse();
3211 CodeGenFunction CGF(CGM);
3212 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3213
3214 CGBuilderTy &Bld = CGF.Builder;
3215
3216 // This array is used as a medium to transfer, one reduce element at a time,
3217 // the data from the first lane of every warp to lanes in the first warp
3218 // in order to perform the final step of a reduction in a parallel region
3219 // (reduction across warps). The array is placed in NVPTX __shared__ memory
3220 // for reduced latency, as well as to have a distinct copy for concurrently
3221 // executing target regions. The array is declared with common linkage so
3222 // as to be shared across compilation units.
3223 StringRef TransferMediumName =
3224 "__openmp_nvptx_data_transfer_temporary_storage";
3225 llvm::GlobalVariable *TransferMedium =
3226 M.getGlobalVariable(TransferMediumName);
3227 if (!TransferMedium) {
3228 auto *Ty = llvm::ArrayType::get(CGM.Int32Ty, WarpSize);
3229 unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
3230 TransferMedium = new llvm::GlobalVariable(
3231 M, Ty, /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage,
3232 llvm::Constant::getNullValue(Ty), TransferMediumName,
3233 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3234 SharedAddressSpace);
3235 CGM.addCompilerUsedGlobal(TransferMedium);
3236 }
3237
3238 // Get the CUDA thread id of the current OpenMP thread on the GPU.
3239 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
3240 // nvptx_lane_id = nvptx_id % warpsize
3241 llvm::Value *LaneID = getNVPTXLaneID(CGF);
3242 // nvptx_warp_id = nvptx_id / warpsize
3243 llvm::Value *WarpID = getNVPTXWarpID(CGF);
3244
3245 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3246 Address LocalReduceList(
3247 Bld.CreatePointerBitCastOrAddrSpaceCast(
3248 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3249 C.VoidPtrTy, Loc),
3250 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3251 CGF.getPointerAlign());
3252
3253 unsigned Idx = 0;
3254 for (const Expr *Private : Privates) {
3255 //
3256 // Warp master copies reduce element to transfer medium in __shared__
3257 // memory.
3258 //
3259 unsigned RealTySize =
3260 C.getTypeSizeInChars(Private->getType())
3261 .alignTo(C.getTypeAlignInChars(Private->getType()))
3262 .getQuantity();
3263 for (unsigned TySize = 4; TySize > 0 && RealTySize > 0; TySize /=2) {
3264 unsigned NumIters = RealTySize / TySize;
3265 if (NumIters == 0)
3266 continue;
3267 QualType CType = C.getIntTypeForBitwidth(
3268 C.toBits(CharUnits::fromQuantity(TySize)), /*Signed=*/1);
3269 llvm::Type *CopyType = CGF.ConvertTypeForMem(CType);
3270 CharUnits Align = CharUnits::fromQuantity(TySize);
3271 llvm::Value *Cnt = nullptr;
3272 Address CntAddr = Address::invalid();
3273 llvm::BasicBlock *PrecondBB = nullptr;
3274 llvm::BasicBlock *ExitBB = nullptr;
3275 if (NumIters > 1) {
3276 CntAddr = CGF.CreateMemTemp(C.IntTy, ".cnt.addr");
3277 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.IntTy), CntAddr,
3278 /*Volatile=*/false, C.IntTy);
3279 PrecondBB = CGF.createBasicBlock("precond");
3280 ExitBB = CGF.createBasicBlock("exit");
3281 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("body");
3282 // There is no need to emit line number for unconditional branch.
3283 (void)ApplyDebugLocation::CreateEmpty(CGF);
3284 CGF.EmitBlock(PrecondBB);
3285 Cnt = CGF.EmitLoadOfScalar(CntAddr, /*Volatile=*/false, C.IntTy, Loc);
3286 llvm::Value *Cmp =
3287 Bld.CreateICmpULT(Cnt, llvm::ConstantInt::get(CGM.IntTy, NumIters));
3288 Bld.CreateCondBr(Cmp, BodyBB, ExitBB);
3289 CGF.EmitBlock(BodyBB);
3290 }
3291 // kmpc_barrier.
3292 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3293 /*EmitChecks=*/false,
3294 /*ForceSimpleCall=*/true);
3295 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3296 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3297 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
3298
3299 // if (lane_id == 0)
3300 llvm::Value *IsWarpMaster = Bld.CreateIsNull(LaneID, "warp_master");
3301 Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
3302 CGF.EmitBlock(ThenBB);
3303
3304 // Reduce element = LocalReduceList[i]
3305 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
3306 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3307 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3308 // elemptr = ((CopyType*)(elemptrptr)) + I
3309 Address ElemPtr = Address(ElemPtrPtr, Align);
3310 ElemPtr = Bld.CreateElementBitCast(ElemPtr, CopyType);
3311 if (NumIters > 1) {
3312 ElemPtr = Address(Bld.CreateGEP(ElemPtr.getPointer(), Cnt),
3313 ElemPtr.getAlignment());
3314 }
3315
3316 // Get pointer to location in transfer medium.
3317 // MediumPtr = &medium[warp_id]
3318 llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
3319 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
3320 Address MediumPtr(MediumPtrVal, Align);
3321 // Casting to actual data type.
3322 // MediumPtr = (CopyType*)MediumPtrAddr;
3323 MediumPtr = Bld.CreateElementBitCast(MediumPtr, CopyType);
3324
3325 // elem = *elemptr
3326 //*MediumPtr = elem
3327 llvm::Value *Elem =
3328 CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false, CType, Loc);
3329 // Store the source element value to the dest element address.
3330 CGF.EmitStoreOfScalar(Elem, MediumPtr, /*Volatile=*/true, CType);
3331
3332 Bld.CreateBr(MergeBB);
3333
3334 CGF.EmitBlock(ElseBB);
3335 Bld.CreateBr(MergeBB);
3336
3337 CGF.EmitBlock(MergeBB);
3338
3339 // kmpc_barrier.
3340 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3341 /*EmitChecks=*/false,
3342 /*ForceSimpleCall=*/true);
3343
3344 //
3345 // Warp 0 copies reduce element from transfer medium.
3346 //
3347 llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
3348 llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
3349 llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
3350
3351 Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
3352 llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
3353 AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, Loc);
3354
3355 // Up to 32 threads in warp 0 are active.
3356 llvm::Value *IsActiveThread =
3357 Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
3358 Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
3359
3360 CGF.EmitBlock(W0ThenBB);
3361
3362 // SrcMediumPtr = &medium[tid]
3363 llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
3364 TransferMedium,
3365 {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
3366 Address SrcMediumPtr(SrcMediumPtrVal, Align);
3367 // SrcMediumVal = *SrcMediumPtr;
3368 SrcMediumPtr = Bld.CreateElementBitCast(SrcMediumPtr, CopyType);
3369
3370 // TargetElemPtr = (CopyType*)(SrcDataAddr[i]) + I
3371 Address TargetElemPtrPtr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
3372 llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
3373 TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, Loc);
3374 Address TargetElemPtr = Address(TargetElemPtrVal, Align);
3375 TargetElemPtr = Bld.CreateElementBitCast(TargetElemPtr, CopyType);
3376 if (NumIters > 1) {
3377 TargetElemPtr = Address(Bld.CreateGEP(TargetElemPtr.getPointer(), Cnt),
3378 TargetElemPtr.getAlignment());
3379 }
3380
3381 // *TargetElemPtr = SrcMediumVal;
3382 llvm::Value *SrcMediumValue =
3383 CGF.EmitLoadOfScalar(SrcMediumPtr, /*Volatile=*/true, CType, Loc);
3384 CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
3385 CType);
3386 Bld.CreateBr(W0MergeBB);
3387
3388 CGF.EmitBlock(W0ElseBB);
3389 Bld.CreateBr(W0MergeBB);
3390
3391 CGF.EmitBlock(W0MergeBB);
3392
3393 if (NumIters > 1) {
3394 Cnt = Bld.CreateNSWAdd(Cnt, llvm::ConstantInt::get(CGM.IntTy, /*V=*/1));
3395 CGF.EmitStoreOfScalar(Cnt, CntAddr, /*Volatile=*/false, C.IntTy);
3396 CGF.EmitBranch(PrecondBB);
3397 (void)ApplyDebugLocation::CreateEmpty(CGF);
3398 CGF.EmitBlock(ExitBB);
3399 }
3400 RealTySize %= TySize;
3401 }
3402 ++Idx;
3403 }
3404
3405 CGF.FinishFunction();
3406 return Fn;
3407}
3408
3409/// Emit a helper that reduces data across two OpenMP threads (lanes)
3410/// in the same warp. It uses shuffle instructions to copy over data from
3411/// a remote lane's stack. The reduction algorithm performed is specified
3412/// by the fourth parameter.
3413///
3414/// Algorithm Versions.
3415/// Full Warp Reduce (argument value 0):
3416/// This algorithm assumes that all 32 lanes are active and gathers
3417/// data from these 32 lanes, producing a single resultant value.
3418/// Contiguous Partial Warp Reduce (argument value 1):
3419/// This algorithm assumes that only a *contiguous* subset of lanes
3420/// are active. This happens for the last warp in a parallel region
3421/// when the user specified num_threads is not an integer multiple of
3422/// 32. This contiguous subset always starts with the zeroth lane.
3423/// Partial Warp Reduce (argument value 2):
3424/// This algorithm gathers data from any number of lanes at any position.
3425/// All reduced values are stored in the lowest possible lane. The set
3426/// of problems every algorithm addresses is a super set of those
3427/// addressable by algorithms with a lower version number. Overhead
3428/// increases as algorithm version increases.
3429///
3430/// Terminology
3431/// Reduce element:
3432/// Reduce element refers to the individual data field with primitive
3433/// data types to be combined and reduced across threads.
3434/// Reduce list:
3435/// Reduce list refers to a collection of local, thread-private
3436/// reduce elements.
3437/// Remote Reduce list:
3438/// Remote Reduce list refers to a collection of remote (relative to
3439/// the current thread) reduce elements.
3440///
3441/// We distinguish between three states of threads that are important to
3442/// the implementation of this function.
3443/// Alive threads:
3444/// Threads in a warp executing the SIMT instruction, as distinguished from
3445/// threads that are inactive due to divergent control flow.
3446/// Active threads:
3447/// The minimal set of threads that has to be alive upon entry to this
3448/// function. The computation is correct iff active threads are alive.
3449/// Some threads are alive but they are not active because they do not
3450/// contribute to the computation in any useful manner. Turning them off
3451/// may introduce control flow overheads without any tangible benefits.
3452/// Effective threads:
3453/// In order to comply with the argument requirements of the shuffle
3454/// function, we must keep all lanes holding data alive. But at most
3455/// half of them perform value aggregation; we refer to this half of
3456/// threads as effective. The other half is simply handing off their
3457/// data.
3458///
3459/// Procedure
3460/// Value shuffle:
3461/// In this step active threads transfer data from higher lane positions
3462/// in the warp to lower lane positions, creating Remote Reduce list.
3463/// Value aggregation:
3464/// In this step, effective threads combine their thread local Reduce list
3465/// with Remote Reduce list and store the result in the thread local
3466/// Reduce list.
3467/// Value copy:
3468/// In this step, we deal with the assumption made by algorithm 2
3469/// (i.e. contiguity assumption). When we have an odd number of lanes
3470/// active, say 2k+1, only k threads will be effective and therefore k
3471/// new values will be produced. However, the Reduce list owned by the
3472/// (2k+1)th thread is ignored in the value aggregation. Therefore
3473/// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
3474/// that the contiguity assumption still holds.
3475static llvm::Function *emitShuffleAndReduceFunction(
3476 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3477 QualType ReductionArrayTy, llvm::Function *ReduceFn, SourceLocation Loc) {
3478 ASTContext &C = CGM.getContext();
3479
3480 // Thread local Reduce list used to host the values of data to be reduced.
3481 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3482 C.VoidPtrTy, ImplicitParamDecl::Other);
3483 // Current lane id; could be logical.
3484 ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
3485 ImplicitParamDecl::Other);
3486 // Offset of the remote source lane relative to the current lane.
3487 ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3488 C.ShortTy, ImplicitParamDecl::Other);
3489 // Algorithm version. This is expected to be known at compile time.
3490 ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3491 C.ShortTy, ImplicitParamDecl::Other);
3492 FunctionArgList Args;
3493 Args.push_back(&ReduceListArg);
3494 Args.push_back(&LaneIDArg);
3495 Args.push_back(&RemoteLaneOffsetArg);
3496 Args.push_back(&AlgoVerArg);
3497
3498 const CGFunctionInfo &CGFI =
3499 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3500 auto *Fn = llvm::Function::Create(
3501 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3502 "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
3503 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3504 Fn->setDoesNotRecurse();
3505 if (CGM.getLangOpts().Optimize) {
3506 Fn->removeFnAttr(llvm::Attribute::NoInline);
3507 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
3508 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
3509 }
3510
3511 CodeGenFunction CGF(CGM);
3512 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3513
3514 CGBuilderTy &Bld = CGF.Builder;
3515
3516 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3517 Address LocalReduceList(
3518 Bld.CreatePointerBitCastOrAddrSpaceCast(
3519 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3520 C.VoidPtrTy, SourceLocation()),
3521 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3522 CGF.getPointerAlign());
3523
3524 Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
3525 llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
3526 AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3527
3528 Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
3529 llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
3530 AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3531
3532 Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
3533 llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
3534 AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3535
3536 // Create a local thread-private variable to host the Reduce list
3537 // from a remote lane.
3538 Address RemoteReduceList =
3539 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
3540
3541 // This loop iterates through the list of reduce elements and copies,
3542 // element by element, from a remote lane in the warp to RemoteReduceList,
3543 // hosted on the thread's stack.
3544 emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
3545 LocalReduceList, RemoteReduceList,
3546 {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
3547 /*ScratchpadIndex=*/nullptr,
3548 /*ScratchpadWidth=*/nullptr});
3549
3550 // The actions to be performed on the Remote Reduce list is dependent
3551 // on the algorithm version.
3552 //
3553 // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
3554 // LaneId % 2 == 0 && Offset > 0):
3555 // do the reduction value aggregation
3556 //
3557 // The thread local variable Reduce list is mutated in place to host the
3558 // reduced data, which is the aggregated value produced from local and
3559 // remote lanes.
3560 //
3561 // Note that AlgoVer is expected to be a constant integer known at compile
3562 // time.
3563 // When AlgoVer==0, the first conjunction evaluates to true, making
3564 // the entire predicate true during compile time.
3565 // When AlgoVer==1, the second conjunction has only the second part to be
3566 // evaluated during runtime. Other conjunctions evaluates to false
3567 // during compile time.
3568 // When AlgoVer==2, the third conjunction has only the second part to be
3569 // evaluated during runtime. Other conjunctions evaluates to false
3570 // during compile time.
3571 llvm::Value *CondAlgo0 = Bld.CreateIsNull(AlgoVerArgVal);
3572
3573 llvm::Value *Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
3574 llvm::Value *CondAlgo1 = Bld.CreateAnd(
3575 Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
3576
3577 llvm::Value *Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
3578 llvm::Value *CondAlgo2 = Bld.CreateAnd(
3579 Algo2, Bld.CreateIsNull(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1))));
3580 CondAlgo2 = Bld.CreateAnd(
3581 CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
3582
3583 llvm::Value *CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
3584 CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
3585
3586 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3587 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3588 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
3589 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
3590
3591 CGF.EmitBlock(ThenBB);
3592 // reduce_function(LocalReduceList, RemoteReduceList)
3593 llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3594 LocalReduceList.getPointer(), CGF.VoidPtrTy);
3595 llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3596 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
3597 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3598 CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
3599 Bld.CreateBr(MergeBB);
3600
3601 CGF.EmitBlock(ElseBB);
3602 Bld.CreateBr(MergeBB);
3603
3604 CGF.EmitBlock(MergeBB);
3605
3606 // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
3607 // Reduce list.
3608 Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
3609 llvm::Value *CondCopy = Bld.CreateAnd(
3610 Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
3611
3612 llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
3613 llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
3614 llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
3615 Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
3616
3617 CGF.EmitBlock(CpyThenBB);
3618 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
3619 RemoteReduceList, LocalReduceList);
3620 Bld.CreateBr(CpyMergeBB);
3621
3622 CGF.EmitBlock(CpyElseBB);
3623 Bld.CreateBr(CpyMergeBB);
3624
3625 CGF.EmitBlock(CpyMergeBB);
3626
3627 CGF.FinishFunction();
3628 return Fn;
3629}
3630
3631/// This function emits a helper that copies all the reduction variables from
3632/// the team into the provided global buffer for the reduction variables.
3633///
3634/// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
3635/// For all data entries D in reduce_data:
3636/// Copy local D to buffer.D[Idx]
3637static llvm::Value *emitListToGlobalCopyFunction(
3638 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3639 QualType ReductionArrayTy, SourceLocation Loc,
3640 const RecordDecl *TeamReductionRec,
3641 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3642 &VarFieldMap) {
3643 ASTContext &C = CGM.getContext();
3644
3645 // Buffer: global reduction buffer.
3646 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3647 C.VoidPtrTy, ImplicitParamDecl::Other);
3648 // Idx: index of the buffer.
3649 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3650 ImplicitParamDecl::Other);
3651 // ReduceList: thread local Reduce list.
3652 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3653 C.VoidPtrTy, ImplicitParamDecl::Other);
3654 FunctionArgList Args;
3655 Args.push_back(&BufferArg);
3656 Args.push_back(&IdxArg);
3657 Args.push_back(&ReduceListArg);
3658
3659 const CGFunctionInfo &CGFI =
3660 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3661 auto *Fn = llvm::Function::Create(
3662 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3663 "_omp_reduction_list_to_global_copy_func", &CGM.getModule());
3664 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3665 Fn->setDoesNotRecurse();
3666 CodeGenFunction CGF(CGM);
3667 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3668
3669 CGBuilderTy &Bld = CGF.Builder;
3670
3671 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3672 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3673 Address LocalReduceList(
3674 Bld.CreatePointerBitCastOrAddrSpaceCast(
3675 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3676 C.VoidPtrTy, Loc),
3677 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3678 CGF.getPointerAlign());
3679 QualType StaticTy = C.getRecordType(TeamReductionRec);
3680 llvm::Type *LLVMReductionsBufferTy =
3681 CGM.getTypes().ConvertTypeForMem(StaticTy);
3682 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3683 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3684 LLVMReductionsBufferTy->getPointerTo());
3685 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3686 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3687 /*Volatile=*/false, C.IntTy,
3688 Loc)};
3689 unsigned Idx = 0;
3690 for (const Expr *Private : Privates) {
3691 // Reduce element = LocalReduceList[i]
3692 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
3693 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3694 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3695 // elemptr = ((CopyType*)(elemptrptr)) + I
3696 ElemPtrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3697 ElemPtrPtr, CGF.ConvertTypeForMem(Private->getType())->getPointerTo());
3698 Address ElemPtr =
3699 Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
3700 const ValueDecl *VD = cast<DeclRefExpr>(Private)->getDecl();
3701 // Global = Buffer.VD[Idx];
3702 const FieldDecl *FD = VarFieldMap.lookup(VD);
3703 LValue GlobLVal = CGF.EmitLValueForField(
3704 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3705 llvm::Value *BufferPtr =
3706 Bld.CreateInBoundsGEP(GlobLVal.getPointer(CGF), Idxs);
3707 GlobLVal.setAddress(Address(BufferPtr, GlobLVal.getAlignment()));
3708 switch (CGF.getEvaluationKind(Private->getType())) {
3709 case TEK_Scalar: {
3710 llvm::Value *V = CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false,
3711 Private->getType(), Loc);
3712 CGF.EmitStoreOfScalar(V, GlobLVal);
3713 break;
3714 }
3715 case TEK_Complex: {
3716 CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(
3717 CGF.MakeAddrLValue(ElemPtr, Private->getType()), Loc);
3718 CGF.EmitStoreOfComplex(V, GlobLVal, /*isInit=*/false);
3719 break;
3720 }
3721 case TEK_Aggregate:
3722 CGF.EmitAggregateCopy(GlobLVal,
3723 CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3724 Private->getType(), AggValueSlot::DoesNotOverlap);
3725 break;
3726 }
3727 ++Idx;
3728 }
3729
3730 CGF.FinishFunction();
3731 return Fn;
3732}
3733
3734/// This function emits a helper that reduces all the reduction variables from
3735/// the team into the provided global buffer for the reduction variables.
3736///
3737/// void list_to_global_reduce_func(void *buffer, int Idx, void *reduce_data)
3738/// void *GlobPtrs[];
3739/// GlobPtrs[0] = (void*)&buffer.D0[Idx];
3740/// ...
3741/// GlobPtrs[N] = (void*)&buffer.DN[Idx];
3742/// reduce_function(GlobPtrs, reduce_data);
3743static llvm::Value *emitListToGlobalReduceFunction(
3744 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3745 QualType ReductionArrayTy, SourceLocation Loc,
3746 const RecordDecl *TeamReductionRec,
3747 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3748 &VarFieldMap,
3749 llvm::Function *ReduceFn) {
3750 ASTContext &C = CGM.getContext();
3751
3752 // Buffer: global reduction buffer.
3753 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3754 C.VoidPtrTy, ImplicitParamDecl::Other);
3755 // Idx: index of the buffer.
3756 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3757 ImplicitParamDecl::Other);
3758 // ReduceList: thread local Reduce list.
3759 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3760 C.VoidPtrTy, ImplicitParamDecl::Other);
3761 FunctionArgList Args;
3762 Args.push_back(&BufferArg);
3763 Args.push_back(&IdxArg);
3764 Args.push_back(&ReduceListArg);
3765
3766 const CGFunctionInfo &CGFI =
3767 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3768 auto *Fn = llvm::Function::Create(
3769 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3770 "_omp_reduction_list_to_global_reduce_func", &CGM.getModule());
3771 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3772 Fn->setDoesNotRecurse();
3773 CodeGenFunction CGF(CGM);
3774 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3775
3776 CGBuilderTy &Bld = CGF.Builder;
3777
3778 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3779 QualType StaticTy = C.getRecordType(TeamReductionRec);
3780 llvm::Type *LLVMReductionsBufferTy =
3781 CGM.getTypes().ConvertTypeForMem(StaticTy);
3782 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3783 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3784 LLVMReductionsBufferTy->getPointerTo());
3785
3786 // 1. Build a list of reduction variables.
3787 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3788 Address ReductionList =
3789 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3790 auto IPriv = Privates.begin();
3791 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3792 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3793 /*Volatile=*/false, C.IntTy,
3794 Loc)};
3795 unsigned Idx = 0;
3796 for (unsigned I = 0, E = Privates.size(); I < E; ++I, ++IPriv, ++Idx) {
3797 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3798 // Global = Buffer.VD[Idx];
3799 const ValueDecl *VD = cast<DeclRefExpr>(*IPriv)->getDecl();
3800 const FieldDecl *FD = VarFieldMap.lookup(VD);
3801 LValue GlobLVal = CGF.EmitLValueForField(
3802 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3803 llvm::Value *BufferPtr =
3804 Bld.CreateInBoundsGEP(GlobLVal.getPointer(CGF), Idxs);
3805 llvm::Value *Ptr = CGF.EmitCastToVoidPtr(BufferPtr);
3806 CGF.EmitStoreOfScalar(Ptr, Elem, /*Volatile=*/false, C.VoidPtrTy);
3807 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3808 // Store array size.
3809 ++Idx;
3810 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3811 llvm::Value *Size = CGF.Builder.CreateIntCast(
3812 CGF.getVLASize(
3813 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3814 .NumElts,
3815 CGF.SizeTy, /*isSigned=*/false);
3816 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3817 Elem);
3818 }
3819 }
3820
3821 // Call reduce_function(GlobalReduceList, ReduceList)
3822 llvm::Value *GlobalReduceList =
3823 CGF.EmitCastToVoidPtr(ReductionList.getPointer());
3824 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3825 llvm::Value *ReducedPtr = CGF.EmitLoadOfScalar(
3826 AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
3827 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3828 CGF, Loc, ReduceFn, {GlobalReduceList, ReducedPtr});
3829 CGF.FinishFunction();
3830 return Fn;
3831}
3832
3833/// This function emits a helper that copies all the reduction variables from
3834/// the team into the provided global buffer for the reduction variables.
3835///
3836/// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
3837/// For all data entries D in reduce_data:
3838/// Copy buffer.D[Idx] to local D;
3839static llvm::Value *emitGlobalToListCopyFunction(
3840 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3841 QualType ReductionArrayTy, SourceLocation Loc,
3842 const RecordDecl *TeamReductionRec,
3843 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3844 &VarFieldMap) {
3845 ASTContext &C = CGM.getContext();
3846
3847 // Buffer: global reduction buffer.
3848 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3849 C.VoidPtrTy, ImplicitParamDecl::Other);
3850 // Idx: index of the buffer.
3851 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3852 ImplicitParamDecl::Other);
3853 // ReduceList: thread local Reduce list.
3854 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3855 C.VoidPtrTy, ImplicitParamDecl::Other);
3856 FunctionArgList Args;
3857 Args.push_back(&BufferArg);
3858 Args.push_back(&IdxArg);
3859 Args.push_back(&ReduceListArg);
3860
3861 const CGFunctionInfo &CGFI =
3862 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3863 auto *Fn = llvm::Function::Create(
3864 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3865 "_omp_reduction_global_to_list_copy_func", &CGM.getModule());
3866 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3867 Fn->setDoesNotRecurse();
3868 CodeGenFunction CGF(CGM);
3869 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3870
3871 CGBuilderTy &Bld = CGF.Builder;
3872
3873 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3874 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3875 Address LocalReduceList(
3876 Bld.CreatePointerBitCastOrAddrSpaceCast(
3877 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3878 C.VoidPtrTy, Loc),
3879 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3880 CGF.getPointerAlign());
3881 QualType StaticTy = C.getRecordType(TeamReductionRec);
3882 llvm::Type *LLVMReductionsBufferTy =
3883 CGM.getTypes().ConvertTypeForMem(StaticTy);
3884 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3885 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3886 LLVMReductionsBufferTy->getPointerTo());
3887
3888 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3889 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3890 /*Volatile=*/false, C.IntTy,
3891 Loc)};
3892 unsigned Idx = 0;
3893 for (const Expr *Private : Privates) {
3894 // Reduce element = LocalReduceList[i]
3895 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
3896 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3897 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3898 // elemptr = ((CopyType*)(elemptrptr)) + I
3899 ElemPtrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3900 ElemPtrPtr, CGF.ConvertTypeForMem(Private->getType())->getPointerTo());
3901 Address ElemPtr =
3902 Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
3903 const ValueDecl *VD = cast<DeclRefExpr>(Private)->getDecl();
3904 // Global = Buffer.VD[Idx];
3905 const FieldDecl *FD = VarFieldMap.lookup(VD);
3906 LValue GlobLVal = CGF.EmitLValueForField(
3907 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3908 llvm::Value *BufferPtr =
3909 Bld.CreateInBoundsGEP(GlobLVal.getPointer(CGF), Idxs);
3910 GlobLVal.setAddress(Address(BufferPtr, GlobLVal.getAlignment()));
3911 switch (CGF.getEvaluationKind(Private->getType())) {
3912 case TEK_Scalar: {
3913 llvm::Value *V = CGF.EmitLoadOfScalar(GlobLVal, Loc);
3914 CGF.EmitStoreOfScalar(V, ElemPtr, /*Volatile=*/false, Private->getType());
3915 break;
3916 }
3917 case TEK_Complex: {
3918 CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(GlobLVal, Loc);
3919 CGF.EmitStoreOfComplex(V, CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3920 /*isInit=*/false);
3921 break;
3922 }
3923 case TEK_Aggregate:
3924 CGF.EmitAggregateCopy(CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3925 GlobLVal, Private->getType(),
3926 AggValueSlot::DoesNotOverlap);
3927 break;
3928 }
3929 ++Idx;
3930 }
3931
3932 CGF.FinishFunction();
3933 return Fn;
3934}
3935
3936/// This function emits a helper that reduces all the reduction variables from
3937/// the team into the provided global buffer for the reduction variables.
3938///
3939/// void global_to_list_reduce_func(void *buffer, int Idx, void *reduce_data)
3940/// void *GlobPtrs[];
3941/// GlobPtrs[0] = (void*)&buffer.D0[Idx];
3942/// ...
3943/// GlobPtrs[N] = (void*)&buffer.DN[Idx];
3944/// reduce_function(reduce_data, GlobPtrs);
3945static llvm::Value *emitGlobalToListReduceFunction(
3946 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3947 QualType ReductionArrayTy, SourceLocation Loc,
3948 const RecordDecl *TeamReductionRec,
3949 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3950 &VarFieldMap,
3951 llvm::Function *ReduceFn) {
3952 ASTContext &C = CGM.getContext();
3953
3954 // Buffer: global reduction buffer.
3955 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3956 C.VoidPtrTy, ImplicitParamDecl::Other);
3957 // Idx: index of the buffer.
3958 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3959 ImplicitParamDecl::Other);
3960 // ReduceList: thread local Reduce list.
3961 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3962 C.VoidPtrTy, ImplicitParamDecl::Other);
3963 FunctionArgList Args;
3964 Args.push_back(&BufferArg);
3965 Args.push_back(&IdxArg);
3966 Args.push_back(&ReduceListArg);
3967
3968 const CGFunctionInfo &CGFI =
3969 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3970 auto *Fn = llvm::Function::Create(
3971 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3972 "_omp_reduction_global_to_list_reduce_func", &CGM.getModule());
3973 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3974 Fn->setDoesNotRecurse();
3975 CodeGenFunction CGF(CGM);
3976 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3977
3978 CGBuilderTy &Bld = CGF.Builder;
3979
3980 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3981 QualType StaticTy = C.getRecordType(TeamReductionRec);
3982 llvm::Type *LLVMReductionsBufferTy =
3983 CGM.getTypes().ConvertTypeForMem(StaticTy);
3984 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3985 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3986 LLVMReductionsBufferTy->getPointerTo());
3987
3988 // 1. Build a list of reduction variables.
3989 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3990 Address ReductionList =
3991 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3992 auto IPriv = Privates.begin();
3993 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3994 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3995 /*Volatile=*/false, C.IntTy,
3996 Loc)};
3997 unsigned Idx = 0;
3998 for (unsigned I = 0, E = Privates.size(); I < E; ++I, ++IPriv, ++Idx) {
3999 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
4000 // Global = Buffer.VD[Idx];
4001 const ValueDecl *VD = cast<DeclRefExpr>(*IPriv)->getDecl();
4002 const FieldDecl *FD = VarFieldMap.lookup(VD);
4003 LValue GlobLVal = CGF.EmitLValueForField(
4004 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
4005 llvm::Value *BufferPtr =
4006 Bld.CreateInBoundsGEP(GlobLVal.getPointer(CGF), Idxs);
4007 llvm::Value *Ptr = CGF.EmitCastToVoidPtr(BufferPtr);
4008 CGF.EmitStoreOfScalar(Ptr, Elem, /*Volatile=*/false, C.VoidPtrTy);
4009 if ((*IPriv)->getType()->isVariablyModifiedType()) {
4010 // Store array size.
4011 ++Idx;
4012 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
4013 llvm::Value *Size = CGF.Builder.CreateIntCast(
4014 CGF.getVLASize(
4015 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
4016 .NumElts,
4017 CGF.SizeTy, /*isSigned=*/false);
4018 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
4019 Elem);
4020 }
4021 }
4022
4023 // Call reduce_function(ReduceList, GlobalReduceList)
4024 llvm::Value *GlobalReduceList =
4025 CGF.EmitCastToVoidPtr(ReductionList.getPointer());
4026 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
4027 llvm::Value *ReducedPtr = CGF.EmitLoadOfScalar(
4028 AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
4029 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
4030 CGF, Loc, ReduceFn, {ReducedPtr, GlobalReduceList});
4031 CGF.FinishFunction();
4032 return Fn;
4033}
4034
4035///
4036/// Design of OpenMP reductions on the GPU
4037///
4038/// Consider a typical OpenMP program with one or more reduction
4039/// clauses:
4040///
4041/// float foo;
4042/// double bar;
4043/// #pragma omp target teams distribute parallel for \
4044/// reduction(+:foo) reduction(*:bar)
4045/// for (int i = 0; i < N; i++) {
4046/// foo += A[i]; bar *= B[i];
4047/// }
4048///
4049/// where 'foo' and 'bar' are reduced across all OpenMP threads in
4050/// all teams. In our OpenMP implementation on the NVPTX device an
4051/// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
4052/// within a team are mapped to CUDA threads within a threadblock.
4053/// Our goal is to efficiently aggregate values across all OpenMP
4054/// threads such that:
4055///
4056/// - the compiler and runtime are logically concise, and
4057/// - the reduction is performed efficiently in a hierarchical
4058/// manner as follows: within OpenMP threads in the same warp,
4059/// across warps in a threadblock, and finally across teams on
4060/// the NVPTX device.
4061///
4062/// Introduction to Decoupling
4063///
4064/// We would like to decouple the compiler and the runtime so that the
4065/// latter is ignorant of the reduction variables (number, data types)
4066/// and the reduction operators. This allows a simpler interface
4067/// and implementation while still attaining good performance.
4068///
4069/// Pseudocode for the aforementioned OpenMP program generated by the
4070/// compiler is as follows:
4071///
4072/// 1. Create private copies of reduction variables on each OpenMP
4073/// thread: 'foo_private', 'bar_private'
4074/// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
4075/// to it and writes the result in 'foo_private' and 'bar_private'
4076/// respectively.
4077/// 3. Call the OpenMP runtime on the GPU to reduce within a team
4078/// and store the result on the team master:
4079///
4080/// __kmpc_nvptx_parallel_reduce_nowait_v2(...,
4081/// reduceData, shuffleReduceFn, interWarpCpyFn)
4082///
4083/// where:
4084/// struct ReduceData {
4085/// double *foo;
4086/// double *bar;
4087/// } reduceData
4088/// reduceData.foo = &foo_private
4089/// reduceData.bar = &bar_private
4090///
4091/// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
4092/// auxiliary functions generated by the compiler that operate on
4093/// variables of type 'ReduceData'. They aid the runtime perform
4094/// algorithmic steps in a data agnostic manner.
4095///
4096/// 'shuffleReduceFn' is a pointer to a function that reduces data
4097/// of type 'ReduceData' across two OpenMP threads (lanes) in the
4098/// same warp. It takes the following arguments as input:
4099///
4100/// a. variable of type 'ReduceData' on the calling lane,
4101/// b. its lane_id,
4102/// c. an offset relative to the current lane_id to generate a
4103/// remote_lane_id. The remote lane contains the second
4104/// variable of type 'ReduceData' that is to be reduced.
4105/// d. an algorithm version parameter determining which reduction
4106/// algorithm to use.
4107///
4108/// 'shuffleReduceFn' retrieves data from the remote lane using
4109/// efficient GPU shuffle intrinsics and reduces, using the
4110/// algorithm specified by the 4th parameter, the two operands
4111/// element-wise. The result is written to the first operand.
4112///
4113/// Different reduction algorithms are implemented in different
4114/// runtime functions, all calling 'shuffleReduceFn' to perform
4115/// the essential reduction step. Therefore, based on the 4th
4116/// parameter, this function behaves slightly differently to
4117/// cooperate with the runtime to ensure correctness under
4118/// different circumstances.
4119///
4120/// 'InterWarpCpyFn' is a pointer to a function that transfers
4121/// reduced variables across warps. It tunnels, through CUDA
4122/// shared memory, the thread-private data of type 'ReduceData'
4123/// from lane 0 of each warp to a lane in the first warp.
4124/// 4. Call the OpenMP runtime on the GPU to reduce across teams.
4125/// The last team writes the global reduced value to memory.
4126///
4127/// ret = __kmpc_nvptx_teams_reduce_nowait(...,
4128/// reduceData, shuffleReduceFn, interWarpCpyFn,
4129/// scratchpadCopyFn, loadAndReduceFn)
4130///
4131/// 'scratchpadCopyFn' is a helper that stores reduced
4132/// data from the team master to a scratchpad array in
4133/// global memory.
4134///
4135/// 'loadAndReduceFn' is a helper that loads data from
4136/// the scratchpad array and reduces it with the input
4137/// operand.
4138///
4139/// These compiler generated functions hide address
4140/// calculation and alignment information from the runtime.
4141/// 5. if ret == 1:
4142/// The team master of the last team stores the reduced
4143/// result to the globals in memory.
4144/// foo += reduceData.foo; bar *= reduceData.bar
4145///
4146///
4147/// Warp Reduction Algorithms
4148///
4149/// On the warp level, we have three algorithms implemented in the
4150/// OpenMP runtime depending on the number of active lanes:
4151///
4152/// Full Warp Reduction
4153///
4154/// The reduce algorithm within a warp where all lanes are active
4155/// is implemented in the runtime as follows:
4156///
4157/// full_warp_reduce(void *reduce_data,
4158/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
4159/// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
4160/// ShuffleReduceFn(reduce_data, 0, offset, 0);
4161/// }
4162///
4163/// The algorithm completes in log(2, WARPSIZE) steps.
4164///
4165/// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
4166/// not used therefore we save instructions by not retrieving lane_id
4167/// from the corresponding special registers. The 4th parameter, which
4168/// represents the version of the algorithm being used, is set to 0 to
4169/// signify full warp reduction.
4170///
4171/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4172///
4173/// #reduce_elem refers to an element in the local lane's data structure
4174/// #remote_elem is retrieved from a remote lane
4175/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4176/// reduce_elem = reduce_elem REDUCE_OP remote_elem;
4177///
4178/// Contiguous Partial Warp Reduction
4179///
4180/// This reduce algorithm is used within a warp where only the first
4181/// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
4182/// number of OpenMP threads in a parallel region is not a multiple of
4183/// WARPSIZE. The algorithm is implemented in the runtime as follows:
4184///
4185/// void
4186/// contiguous_partial_reduce(void *reduce_data,
4187/// kmp_ShuffleReductFctPtr ShuffleReduceFn,
4188/// int size, int lane_id) {
4189/// int curr_size;
4190/// int offset;
4191/// curr_size = size;
4192/// mask = curr_size/2;
4193/// while (offset>0) {
4194/// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
4195/// curr_size = (curr_size+1)/2;
4196/// offset = curr_size/2;
4197/// }
4198/// }
4199///
4200/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4201///
4202/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4203/// if (lane_id < offset)
4204/// reduce_elem = reduce_elem REDUCE_OP remote_elem
4205/// else
4206/// reduce_elem = remote_elem
4207///
4208/// This algorithm assumes that the data to be reduced are located in a
4209/// contiguous subset of lanes starting from the first. When there is
4210/// an odd number of active lanes, the data in the last lane is not
4211/// aggregated with any other lane's dat but is instead copied over.
4212///
4213/// Dispersed Partial Warp Reduction
4214///
4215/// This algorithm is used within a warp when any discontiguous subset of
4216/// lanes are active. It is used to implement the reduction operation
4217/// across lanes in an OpenMP simd region or in a nested parallel region.
4218///
4219/// void
4220/// dispersed_partial_reduce(void *reduce_data,
4221/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
4222/// int size, remote_id;
4223/// int logical_lane_id = number_of_active_lanes_before_me() * 2;
4224/// do {
4225/// remote_id = next_active_lane_id_right_after_me();
4226/// # the above function returns 0 of no active lane
4227/// # is present right after the current lane.
4228/// size = number_of_active_lanes_in_this_warp();
4229/// logical_lane_id /= 2;
4230/// ShuffleReduceFn(reduce_data, logical_lane_id,
4231/// remote_id-1-threadIdx.x, 2);
4232/// } while (logical_lane_id % 2 == 0 && size > 1);
4233/// }
4234///
4235/// There is no assumption made about the initial state of the reduction.
4236/// Any number of lanes (>=1) could be active at any position. The reduction
4237/// result is returned in the first active lane.
4238///
4239/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4240///
4241/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4242/// if (lane_id % 2 == 0 && offset > 0)
4243/// reduce_elem = reduce_elem REDUCE_OP remote_elem
4244/// else
4245/// reduce_elem = remote_elem
4246///
4247///
4248/// Intra-Team Reduction
4249///
4250/// This function, as implemented in the runtime call
4251/// '__kmpc_nvptx_parallel_reduce_nowait_v2', aggregates data across OpenMP
4252/// threads in a team. It first reduces within a warp using the
4253/// aforementioned algorithms. We then proceed to gather all such
4254/// reduced values at the first warp.
4255///
4256/// The runtime makes use of the function 'InterWarpCpyFn', which copies
4257/// data from each of the "warp master" (zeroth lane of each warp, where
4258/// warp-reduced data is held) to the zeroth warp. This step reduces (in
4259/// a mathematical sense) the problem of reduction across warp masters in
4260/// a block to the problem of warp reduction.
4261///
4262///
4263/// Inter-Team Reduction
4264///
4265/// Once a team has reduced its data to a single value, it is stored in
4266/// a global scratchpad array. Since each team has a distinct slot, this
4267/// can be done without locking.
4268///
4269/// The last team to write to the scratchpad array proceeds to reduce the
4270/// scratchpad array. One or more workers in the last team use the helper
4271/// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
4272/// the k'th worker reduces every k'th element.
4273///
4274/// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait_v2' to
4275/// reduce across workers and compute a globally reduced value.
4276///
4277void CGOpenMPRuntimeNVPTX::emitReduction(
4278 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
4279 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
4280 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
4281 if (!CGF.HaveInsertPoint())
4282 return;
4283
4284 bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
4285#ifndef NDEBUG
4286 bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
4287#endif
4288
4289 if (Options.SimpleReduction) {
4290 assert(!TeamsReduction && !ParallelReduction &&((!TeamsReduction && !ParallelReduction && "Invalid reduction selection in emitReduction."
) ? static_cast<void> (0) : __assert_fail ("!TeamsReduction && !ParallelReduction && \"Invalid reduction selection in emitReduction.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 4291, __PRETTY_FUNCTION__))
4291 "Invalid reduction selection in emitReduction.")((!TeamsReduction && !ParallelReduction && "Invalid reduction selection in emitReduction."
) ? static_cast<void> (0) : __assert_fail ("!TeamsReduction && !ParallelReduction && \"Invalid reduction selection in emitReduction.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 4291, __PRETTY_FUNCTION__))
;
4292 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
4293 ReductionOps, Options);
4294 return;
4295 }
4296
4297 assert((TeamsReduction || ParallelReduction) &&(((TeamsReduction || ParallelReduction) && "Invalid reduction selection in emitReduction."
) ? static_cast<void> (0) : __assert_fail ("(TeamsReduction || ParallelReduction) && \"Invalid reduction selection in emitReduction.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 4298, __PRETTY_FUNCTION__))
4298 "Invalid reduction selection in emitReduction.")(((TeamsReduction || ParallelReduction) && "Invalid reduction selection in emitReduction."
) ? static_cast<void> (0) : __assert_fail ("(TeamsReduction || ParallelReduction) && \"Invalid reduction selection in emitReduction.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 4298, __PRETTY_FUNCTION__))
;
4299
4300 // Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
4301 // RedList, shuffle_reduce_func, interwarp_copy_func);
4302 // or
4303 // Build res = __kmpc_reduce_teams_nowait_simple(<loc>, <gtid>, <lck>);
4304 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
4305 llvm::Value *ThreadId = getThreadID(CGF, Loc);
4306
4307 llvm::Value *Res;
4308 ASTContext &C = CGM.getContext();
4309 // 1. Build a list of reduction variables.
4310 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
4311 auto Size = RHSExprs.size();
4312 for (const Expr *E : Privates) {
4313 if (E->getType()->isVariablyModifiedType())
4314 // Reserve place for array size.
4315 ++Size;
4316 }
4317 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
4318 QualType ReductionArrayTy =
4319 C.getConstantArrayType(C.VoidPtrTy, ArraySize, nullptr, ArrayType::Normal,
4320 /*IndexTypeQuals=*/0);
4321 Address ReductionList =
4322 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
4323 auto IPriv = Privates.begin();
4324 unsigned Idx = 0;
4325 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
4326 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
4327 CGF.Builder.CreateStore(
4328 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4329 CGF.EmitLValue(RHSExprs[I]).getPointer(CGF), CGF.VoidPtrTy),
4330 Elem);
4331 if ((*IPriv)->getType()->isVariablyModifiedType()) {
4332 // Store array size.
4333 ++Idx;
4334 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
4335 llvm::Value *Size = CGF.Builder.CreateIntCast(
4336 CGF.getVLASize(
4337 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
4338 .NumElts,
4339 CGF.SizeTy, /*isSigned=*/false);
4340 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
4341 Elem);
4342 }
4343 }
4344
4345 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4346 ReductionList.getPointer(), CGF.VoidPtrTy);
4347 llvm::Function *ReductionFn = emitReductionFunction(
4348 Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
4349 LHSExprs, RHSExprs, ReductionOps);
4350 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
4351 llvm::Function *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
4352 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
4353 llvm::Value *InterWarpCopyFn =
4354 emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
4355
4356 if (ParallelReduction) {
4357 llvm::Value *Args[] = {RTLoc,
4358 ThreadId,
4359 CGF.Builder.getInt32(RHSExprs.size()),
4360 ReductionArrayTySize,
4361 RL,
4362 ShuffleAndReduceFn,
4363 InterWarpCopyFn};
4364
4365 Res = CGF.EmitRuntimeCall(
4366 createNVPTXRuntimeFunction(
4367 OMPRTL_NVPTX__kmpc_nvptx_parallel_reduce_nowait_v2),
4368 Args);
4369 } else {
4370 assert(TeamsReduction && "expected teams reduction.")((TeamsReduction && "expected teams reduction.") ? static_cast
<void> (0) : __assert_fail ("TeamsReduction && \"expected teams reduction.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 4370, __PRETTY_FUNCTION__))
;
4371 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> VarFieldMap;
4372 llvm::SmallVector<const ValueDecl *, 4> PrivatesReductions(Privates.size());
4373 int Cnt = 0;
4374 for (const Expr *DRE : Privates) {
4375 PrivatesReductions[Cnt] = cast<DeclRefExpr>(DRE)->getDecl();
4376 ++Cnt;
4377 }
4378 const RecordDecl *TeamReductionRec = ::buildRecordForGlobalizedVars(
4379 CGM.getContext(), PrivatesReductions, llvm::None, VarFieldMap,
4380 C.getLangOpts().OpenMPCUDAReductionBufNum);
4381 TeamsReductions.push_back(TeamReductionRec);
4382 if (!KernelTeamsReductionPtr) {
4383 KernelTeamsReductionPtr = new llvm::GlobalVariable(
4384 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/true,
4385 llvm::GlobalValue::InternalLinkage, nullptr,
4386 "_openmp_teams_reductions_buffer_$_$ptr");
4387 }
4388 llvm::Value *GlobalBufferPtr = CGF.EmitLoadOfScalar(
4389 Address(KernelTeamsReductionPtr, CGM.getPointerAlign()),
4390 /*Volatile=*/false, C.getPointerType(C.VoidPtrTy), Loc);
4391 llvm::Value *GlobalToBufferCpyFn = ::emitListToGlobalCopyFunction(
4392 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
4393 llvm::Value *GlobalToBufferRedFn = ::emitListToGlobalReduceFunction(
4394 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap,
4395 ReductionFn);
4396 llvm::Value *BufferToGlobalCpyFn = ::emitGlobalToListCopyFunction(
4397 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
4398 llvm::Value *BufferToGlobalRedFn = ::emitGlobalToListReduceFunction(
4399 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap,
4400 ReductionFn);
4401
4402 llvm::Value *Args[] = {
4403 RTLoc,
4404 ThreadId,
4405 GlobalBufferPtr,
4406 CGF.Builder.getInt32(C.getLangOpts().OpenMPCUDAReductionBufNum),
4407 RL,
4408 ShuffleAndReduceFn,
4409 InterWarpCopyFn,
4410 GlobalToBufferCpyFn,
4411 GlobalToBufferRedFn,
4412 BufferToGlobalCpyFn,
4413 BufferToGlobalRedFn};
4414
4415 Res = CGF.EmitRuntimeCall(
4416 createNVPTXRuntimeFunction(
4417 OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_v2),
4418 Args);
4419 }
4420
4421 // 5. Build if (res == 1)
4422 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.reduction.done");
4423 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.then");
4424 llvm::Value *Cond = CGF.Builder.CreateICmpEQ(
4425 Res, llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1));
4426 CGF.Builder.CreateCondBr(Cond, ThenBB, ExitBB);
4427
4428 // 6. Build then branch: where we have reduced values in the master
4429 // thread in each team.
4430 // __kmpc_end_reduce{_nowait}(<gtid>);
4431 // break;
4432 CGF.EmitBlock(ThenBB);
4433
4434 // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
4435 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps,
4436 this](CodeGenFunction &CGF, PrePostActionTy &Action) {
4437 auto IPriv = Privates.begin();
4438 auto ILHS = LHSExprs.begin();
4439 auto IRHS = RHSExprs.begin();
4440 for (const Expr *E : ReductionOps) {
4441 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4442 cast<DeclRefExpr>(*IRHS));
4443 ++IPriv;
4444 ++ILHS;
4445 ++IRHS;
4446 }
4447 };
4448 llvm::Value *EndArgs[] = {ThreadId};
4449 RegionCodeGenTy RCG(CodeGen);
4450 NVPTXActionTy Action(
4451 nullptr, llvm::None,
4452 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_reduce_nowait),
4453 EndArgs);
4454 RCG.setAction(Action);
4455 RCG(CGF);
4456 // There is no need to emit line number for unconditional branch.
4457 (void)ApplyDebugLocation::CreateEmpty(CGF);
4458 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
4459}
4460
4461const VarDecl *
4462CGOpenMPRuntimeNVPTX::translateParameter(const FieldDecl *FD,
4463 const VarDecl *NativeParam) const {
4464 if (!NativeParam->getType()->isReferenceType())
4465 return NativeParam;
4466 QualType ArgType = NativeParam->getType();
4467 QualifierCollector QC;
4468 const Type *NonQualTy = QC.strip(ArgType);
4469 QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4470 if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
4471 if (Attr->getCaptureKind() == OMPC_map) {
4472 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
4473 LangAS::opencl_global);
4474 } else if (Attr->getCaptureKind() == OMPC_firstprivate &&
4475 PointeeTy.isConstant(CGM.getContext())) {
4476 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
4477 LangAS::opencl_generic);
4478 }
4479 }
4480 ArgType = CGM.getContext().getPointerType(PointeeTy);
4481 QC.addRestrict();
4482 enum { NVPTX_local_addr = 5 };
4483 QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
4484 ArgType = QC.apply(CGM.getContext(), ArgType);
4485 if (isa<ImplicitParamDecl>(NativeParam))
4486 return ImplicitParamDecl::Create(
4487 CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
4488 NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
4489 return ParmVarDecl::Create(
4490 CGM.getContext(),
4491 const_cast<DeclContext *>(NativeParam->getDeclContext()),
4492 NativeParam->getBeginLoc(), NativeParam->getLocation(),
4493 NativeParam->getIdentifier(), ArgType,
4494 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
4495}
4496
4497Address
4498CGOpenMPRuntimeNVPTX::getParameterAddress(CodeGenFunction &CGF,
4499 const VarDecl *NativeParam,
4500 const VarDecl *TargetParam) const {
4501 assert(NativeParam != TargetParam &&((NativeParam != TargetParam && NativeParam->getType
()->isReferenceType() && "Native arg must not be the same as target arg."
) ? static_cast<void> (0) : __assert_fail ("NativeParam != TargetParam && NativeParam->getType()->isReferenceType() && \"Native arg must not be the same as target arg.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 4503, __PRETTY_FUNCTION__))
4502 NativeParam->getType()->isReferenceType() &&((NativeParam != TargetParam && NativeParam->getType
()->isReferenceType() && "Native arg must not be the same as target arg."
) ? static_cast<void> (0) : __assert_fail ("NativeParam != TargetParam && NativeParam->getType()->isReferenceType() && \"Native arg must not be the same as target arg.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 4503, __PRETTY_FUNCTION__))
4503 "Native arg must not be the same as target arg.")((NativeParam != TargetParam && NativeParam->getType
()->isReferenceType() && "Native arg must not be the same as target arg."
) ? static_cast<void> (0) : __assert_fail ("NativeParam != TargetParam && NativeParam->getType()->isReferenceType() && \"Native arg must not be the same as target arg.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 4503, __PRETTY_FUNCTION__))
;
4504 Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
4505 QualType NativeParamType = NativeParam->getType();
4506 QualifierCollector QC;
4507 const Type *NonQualTy = QC.strip(NativeParamType);
4508 QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4509 unsigned NativePointeeAddrSpace =
4510 CGF.getContext().getTargetAddressSpace(NativePointeeTy);
4511 QualType TargetTy = TargetParam->getType();
4512 llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
4513 LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
4514 // First cast to generic.
4515 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4516 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4517 /*AddrSpace=*/0));
4518 // Cast from generic to native address space.
4519 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4520 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4521 NativePointeeAddrSpace));
4522 Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
4523 CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
4524 NativeParamType);
4525 return NativeParamAddr;
4526}
4527
4528void CGOpenMPRuntimeNVPTX::emitOutlinedFunctionCall(
4529 CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn,
4530 ArrayRef<llvm::Value *> Args) const {
4531 SmallVector<llvm::Value *, 4> TargetArgs;
4532 TargetArgs.reserve(Args.size());
4533 auto *FnType = OutlinedFn.getFunctionType();
4534 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
4535 if (FnType->isVarArg() && FnType->getNumParams() <= I) {
4536 TargetArgs.append(std::next(Args.begin(), I), Args.end());
4537 break;
4538 }
4539 llvm::Type *TargetType = FnType->getParamType(I);
4540 llvm::Value *NativeArg = Args[I];
4541 if (!TargetType->isPointerTy()) {
4542 TargetArgs.emplace_back(NativeArg);
4543 continue;
4544 }
4545 llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4546 NativeArg,
4547 NativeArg->getType()->getPointerElementType()->getPointerTo());
4548 TargetArgs.emplace_back(
4549 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
4550 }
4551 CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
4552}
4553
4554/// Emit function which wraps the outline parallel region
4555/// and controls the arguments which are passed to this function.
4556/// The wrapper ensures that the outlined function is called
4557/// with the correct arguments when data is shared.
4558llvm::Function *CGOpenMPRuntimeNVPTX::createParallelDataSharingWrapper(
4559 llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
4560 ASTContext &Ctx = CGM.getContext();
4561 const auto &CS = *D.getCapturedStmt(OMPD_parallel);
4562
4563 // Create a function that takes as argument the source thread.
4564 FunctionArgList WrapperArgs;
4565 QualType Int16QTy =
4566 Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
4567 QualType Int32QTy =
4568 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
4569 ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
4570 /*Id=*/nullptr, Int16QTy,
4571 ImplicitParamDecl::Other);
4572 ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
4573 /*Id=*/nullptr, Int32QTy,
4574 ImplicitParamDecl::Other);
4575 WrapperArgs.emplace_back(&ParallelLevelArg);
4576 WrapperArgs.emplace_back(&WrapperArg);
4577
4578 const CGFunctionInfo &CGFI =
4579 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
4580
4581 auto *Fn = llvm::Function::Create(
4582 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
4583 Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
4584 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
4585 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
4586 Fn->setDoesNotRecurse();
4587
4588 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
4589 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
4590 D.getBeginLoc(), D.getBeginLoc());
4591
4592 const auto *RD = CS.getCapturedRecordDecl();
4593 auto CurField = RD->field_begin();
4594
4595 Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
4596 /*Name=*/".zero.addr");
4597 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
4598 // Get the array of arguments.
4599 SmallVector<llvm::Value *, 8> Args;
4600
4601 Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).getPointer());
4602 Args.emplace_back(ZeroAddr.getPointer());
4603
4604 CGBuilderTy &Bld = CGF.Builder;
4605 auto CI = CS.capture_begin();
4606
4607 // Use global memory for data sharing.
4608 // Handle passing of global args to workers.
4609 Address GlobalArgs =
4610 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
4611 llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
4612 llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
4613 CGF.EmitRuntimeCall(
4614 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_get_shared_variables),
4615 DataSharingArgs);
4616
4617 // Retrieve the shared variables from the list of references returned
4618 // by the runtime. Pass the variables to the outlined function.
4619 Address SharedArgListAddress = Address::invalid();
4620 if (CS.capture_size() > 0 ||
4621 isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4622 SharedArgListAddress = CGF.EmitLoadOfPointer(
4623 GlobalArgs, CGF.getContext()
4624 .getPointerType(CGF.getContext().getPointerType(
4625 CGF.getContext().VoidPtrTy))
4626 .castAs<PointerType>());
4627 }
4628 unsigned Idx = 0;
4629 if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4630 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
4631 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4632 Src, CGF.SizeTy->getPointerTo());
4633 llvm::Value *LB = CGF.EmitLoadOfScalar(
4634 TypedAddress,
4635 /*Volatile=*/false,
4636 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4637 cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
4638 Args.emplace_back(LB);
4639 ++Idx;
4640 Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
4641 TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4642 Src, CGF.SizeTy->getPointerTo());
4643 llvm::Value *UB = CGF.EmitLoadOfScalar(
4644 TypedAddress,
4645 /*Volatile=*/false,
4646 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4647 cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
4648 Args.emplace_back(UB);
4649 ++Idx;
4650 }
4651 if (CS.capture_size() > 0) {
4652 ASTContext &CGFContext = CGF.getContext();
4653 for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
4654 QualType ElemTy = CurField->getType();
4655 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx);
4656 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4657 Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)));
4658 llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
4659 /*Volatile=*/false,
4660 CGFContext.getPointerType(ElemTy),
4661 CI->getLocation());
4662 if (CI->capturesVariableByCopy() &&
4663 !CI->getCapturedVar()->getType()->isAnyPointerType()) {
4664 Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
4665 CI->getLocation());
4666 }
4667 Args.emplace_back(Arg);
4668 }
4669 }
4670
4671 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedParallelFn, Args);
4672 CGF.FinishFunction();
4673 return Fn;
4674}
4675
4676void CGOpenMPRuntimeNVPTX::emitFunctionProlog(CodeGenFunction &CGF,
4677 const Decl *D) {
4678 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4679 return;
4680
4681 assert(D && "Expected function or captured|block decl.")((D && "Expected function or captured|block decl.") ?
static_cast<void> (0) : __assert_fail ("D && \"Expected function or captured|block decl.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 4681, __PRETTY_FUNCTION__))
;
4682 assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&((FunctionGlobalizedDecls.count(CGF.CurFn) == 0 && "Function is registered already."
) ? static_cast<void> (0) : __assert_fail ("FunctionGlobalizedDecls.count(CGF.CurFn) == 0 && \"Function is registered already.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 4683, __PRETTY_FUNCTION__))
4683 "Function is registered already.")((FunctionGlobalizedDecls.count(CGF.CurFn) == 0 && "Function is registered already."
) ? static_cast<void> (0) : __assert_fail ("FunctionGlobalizedDecls.count(CGF.CurFn) == 0 && \"Function is registered already.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 4683, __PRETTY_FUNCTION__))
;
4684 assert((!TeamAndReductions.first || TeamAndReductions.first == D) &&(((!TeamAndReductions.first || TeamAndReductions.first == D) &&
"Team is set but not processed.") ? static_cast<void> (
0) : __assert_fail ("(!TeamAndReductions.first || TeamAndReductions.first == D) && \"Team is set but not processed.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 4685, __PRETTY_FUNCTION__))
4685 "Team is set but not processed.")(((!TeamAndReductions.first || TeamAndReductions.first == D) &&
"Team is set but not processed.") ? static_cast<void> (
0) : __assert_fail ("(!TeamAndReductions.first || TeamAndReductions.first == D) && \"Team is set but not processed.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 4685, __PRETTY_FUNCTION__))
;
4686 const Stmt *Body = nullptr;
4687 bool NeedToDelayGlobalization = false;
4688 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4689 Body = FD->getBody();
4690 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
4691 Body = BD->getBody();
4692 } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
4693 Body = CD->getBody();
4694 NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
4695 if (NeedToDelayGlobalization &&
4696 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
4697 return;
4698 }
4699 if (!Body)
4700 return;
4701 CheckVarsEscapingDeclContext VarChecker(CGF, TeamAndReductions.second);
4702 VarChecker.Visit(Body);
4703 const RecordDecl *GlobalizedVarsRecord =
4704 VarChecker.getGlobalizedRecord(IsInTTDRegion);
4705 TeamAndReductions.first = nullptr;
4706 TeamAndReductions.second.clear();
4707 ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
4708 VarChecker.getEscapedVariableLengthDecls();
4709 if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty())
4710 return;
4711 auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
4712 I->getSecond().MappedParams =
4713 std::make_unique<CodeGenFunction::OMPMapVars>();
4714 I->getSecond().GlobalRecord = GlobalizedVarsRecord;
4715 I->getSecond().EscapedParameters.insert(
4716 VarChecker.getEscapedParameters().begin(),
4717 VarChecker.getEscapedParameters().end());
4718 I->getSecond().EscapedVariableLengthDecls.append(
4719 EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
4720 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
4721 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
4722 assert(VD->isCanonicalDecl() && "Expected canonical declaration")((VD->isCanonicalDecl() && "Expected canonical declaration"
) ? static_cast<void> (0) : __assert_fail ("VD->isCanonicalDecl() && \"Expected canonical declaration\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 4722, __PRETTY_FUNCTION__))
;
4723 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
4724 Data.insert(std::make_pair(VD, MappedVarData(FD, IsInTTDRegion)));
4725 }
4726 if (!IsInTTDRegion && !NeedToDelayGlobalization && !IsInParallelRegion) {
4727 CheckVarsEscapingDeclContext VarChecker(CGF, llvm::None);
4728 VarChecker.Visit(Body);
4729 I->getSecond().SecondaryGlobalRecord =
4730 VarChecker.getGlobalizedRecord(/*IsInTTDRegion=*/true);
4731 I->getSecond().SecondaryLocalVarData.emplace();
4732 DeclToAddrMapTy &Data = I->getSecond().SecondaryLocalVarData.getValue();
4733 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
4734 assert(VD->isCanonicalDecl() && "Expected canonical declaration")((VD->isCanonicalDecl() && "Expected canonical declaration"
) ? static_cast<void> (0) : __assert_fail ("VD->isCanonicalDecl() && \"Expected canonical declaration\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 4734, __PRETTY_FUNCTION__))
;
4735 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
4736 Data.insert(
4737 std::make_pair(VD, MappedVarData(FD, /*IsInTTDRegion=*/true)));
4738 }
4739 }
4740 if (!NeedToDelayGlobalization) {
4741 emitGenericVarsProlog(CGF, D->getBeginLoc(), /*WithSPMDCheck=*/true);
4742 struct GlobalizationScope final : EHScopeStack::Cleanup {
4743 GlobalizationScope() = default;
4744
4745 void Emit(CodeGenFunction &CGF, Flags flags) override {
4746 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
4747 .emitGenericVarsEpilog(CGF, /*WithSPMDCheck=*/true);
4748 }
4749 };
4750 CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
4751 }
4752}
4753
4754Address CGOpenMPRuntimeNVPTX::getAddressOfLocalVariable(CodeGenFunction &CGF,
4755 const VarDecl *VD) {
4756 if (VD && VD->hasAttr<OMPAllocateDeclAttr>()) {
1
Assuming 'VD' is null
4757 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
4758 switch (A->getAllocatorType()) {
4759 // Use the default allocator here as by default local vars are
4760 // threadlocal.
4761 case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
4762 case OMPAllocateDeclAttr::OMPThreadMemAlloc:
4763 case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
4764 case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
4765 // Follow the user decision - use default allocation.
4766 return Address::invalid();
4767 case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
4768 // TODO: implement aupport for user-defined allocators.
4769 return Address::invalid();
4770 case OMPAllocateDeclAttr::OMPConstMemAlloc: {
4771 llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
4772 auto *GV = new llvm::GlobalVariable(
4773 CGM.getModule(), VarTy, /*isConstant=*/false,
4774 llvm::GlobalValue::InternalLinkage,
4775 llvm::Constant::getNullValue(VarTy), VD->getName(),
4776 /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
4777 CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant));
4778 CharUnits Align = CGM.getContext().getDeclAlign(VD);
4779 GV->setAlignment(Align.getAsAlign());
4780 return Address(GV, Align);
4781 }
4782 case OMPAllocateDeclAttr::OMPPTeamMemAlloc: {
4783 llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
4784 auto *GV = new llvm::GlobalVariable(
4785 CGM.getModule(), VarTy, /*isConstant=*/false,
4786 llvm::GlobalValue::InternalLinkage,
4787 llvm::Constant::getNullValue(VarTy), VD->getName(),
4788 /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
4789 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
4790 CharUnits Align = CGM.getContext().getDeclAlign(VD);
4791 GV->setAlignment(Align.getAsAlign());
4792 return Address(GV, Align);
4793 }
4794 case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
4795 case OMPAllocateDeclAttr::OMPCGroupMemAlloc: {
4796 llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
4797 auto *GV = new llvm::GlobalVariable(
4798 CGM.getModule(), VarTy, /*isConstant=*/false,
4799 llvm::GlobalValue::InternalLinkage,
4800 llvm::Constant::getNullValue(VarTy), VD->getName());
4801 CharUnits Align = CGM.getContext().getDeclAlign(VD);
4802 GV->setAlignment(Align.getAsAlign());
4803 return Address(GV, Align);
4804 }
4805 }
4806 }
4807
4808 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
2
Taking false branch
4809 return Address::invalid();
4810
4811 VD = VD->getCanonicalDecl();
3
Called C++ object pointer is null
4812 auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
4813 if (I == FunctionGlobalizedDecls.end())
4814 return Address::invalid();
4815 auto VDI = I->getSecond().LocalVarData.find(VD);
4816 if (VDI != I->getSecond().LocalVarData.end())
4817 return VDI->second.PrivateAddr;
4818 if (VD->hasAttrs()) {
4819 for (specific_attr_iterator<OMPReferencedVarAttr> IT(VD->attr_begin()),
4820 E(VD->attr_end());
4821 IT != E; ++IT) {
4822 auto VDI = I->getSecond().LocalVarData.find(
4823 cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
4824 ->getCanonicalDecl());
4825 if (VDI != I->getSecond().LocalVarData.end())
4826 return VDI->second.PrivateAddr;
4827 }
4828 }
4829
4830 return Address::invalid();
4831}
4832
4833void CGOpenMPRuntimeNVPTX::functionFinished(CodeGenFunction &CGF) {
4834 FunctionGlobalizedDecls.erase(CGF.CurFn);
4835 CGOpenMPRuntime::functionFinished(CGF);
4836}
4837
4838void CGOpenMPRuntimeNVPTX::getDefaultDistScheduleAndChunk(
4839 CodeGenFunction &CGF, const OMPLoopDirective &S,
4840 OpenMPDistScheduleClauseKind &ScheduleKind,
4841 llvm::Value *&Chunk) const {
4842 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
4843 ScheduleKind = OMPC_DIST_SCHEDULE_static;
4844 Chunk = CGF.EmitScalarConversion(getNVPTXNumThreads(CGF),
4845 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4846 S.getIterationVariable()->getType(), S.getBeginLoc());
4847 return;
4848 }
4849 CGOpenMPRuntime::getDefaultDistScheduleAndChunk(
4850 CGF, S, ScheduleKind, Chunk);
4851}
4852
4853void CGOpenMPRuntimeNVPTX::getDefaultScheduleAndChunk(
4854 CodeGenFunction &CGF, const OMPLoopDirective &S,
4855 OpenMPScheduleClauseKind &ScheduleKind,
4856 const Expr *&ChunkExpr) const {
4857 ScheduleKind = OMPC_SCHEDULE_static;
4858 // Chunk size is 1 in this case.
4859 llvm::APInt ChunkSize(32, 1);
4860 ChunkExpr = IntegerLiteral::Create(CGF.getContext(), ChunkSize,
4861 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4862 SourceLocation());
4863}
4864
4865void CGOpenMPRuntimeNVPTX::adjustTargetSpecificDataForLambdas(
4866 CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
4867 assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&((isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
" Expected target-based directive.") ? static_cast<void>
(0) : __assert_fail ("isOpenMPTargetExecutionDirective(D.getDirectiveKind()) && \" Expected target-based directive.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 4868, __PRETTY_FUNCTION__))
4868 " Expected target-based directive.")((isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
" Expected target-based directive.") ? static_cast<void>
(0) : __assert_fail ("isOpenMPTargetExecutionDirective(D.getDirectiveKind()) && \" Expected target-based directive.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 4868, __PRETTY_FUNCTION__))
;
4869 const CapturedStmt *CS = D.getCapturedStmt(OMPD_target);
4870 for (const CapturedStmt::Capture &C : CS->captures()) {
4871 // Capture variables captured by reference in lambdas for target-based
4872 // directives.
4873 if (!C.capturesVariable())
4874 continue;
4875 const VarDecl *VD = C.getCapturedVar();
4876 const auto *RD = VD->getType()
4877 .getCanonicalType()
4878 .getNonReferenceType()
4879 ->getAsCXXRecordDecl();
4880 if (!RD || !RD->isLambda())
4881 continue;
4882 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4883 LValue VDLVal;
4884 if (VD->getType().getCanonicalType()->isReferenceType())
4885 VDLVal = CGF.EmitLoadOfReferenceLValue(VDAddr, VD->getType());
4886 else
4887 VDLVal = CGF.MakeAddrLValue(
4888 VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
4889 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4890 FieldDecl *ThisCapture = nullptr;
4891 RD->getCaptureFields(Captures, ThisCapture);
4892 if (ThisCapture && CGF.CapturedStmtInfo->isCXXThisExprCaptured()) {
4893 LValue ThisLVal =
4894 CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
4895 llvm::Value *CXXThis = CGF.LoadCXXThis();
4896 CGF.EmitStoreOfScalar(CXXThis, ThisLVal);
4897 }
4898 for (const LambdaCapture &LC : RD->captures()) {
4899 if (LC.getCaptureKind() != LCK_ByRef)
4900 continue;
4901 const VarDecl *VD = LC.getCapturedVar();
4902 if (!CS->capturesVariable(VD))
4903 continue;
4904 auto It = Captures.find(VD);
4905 assert(It != Captures.end() && "Found lambda capture without field.")((It != Captures.end() && "Found lambda capture without field."
) ? static_cast<void> (0) : __assert_fail ("It != Captures.end() && \"Found lambda capture without field.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 4905, __PRETTY_FUNCTION__))
;
4906 LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
4907 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4908 if (VD->getType().getCanonicalType()->isReferenceType())
4909 VDAddr = CGF.EmitLoadOfReferenceLValue(VDAddr,
4910 VD->getType().getCanonicalType())
4911 .getAddress(CGF);
4912 CGF.EmitStoreOfScalar(VDAddr.getPointer(), VarLVal);
4913 }
4914 }
4915}
4916
4917unsigned CGOpenMPRuntimeNVPTX::getDefaultFirstprivateAddressSpace() const {
4918 return CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant);
4919}
4920
4921bool CGOpenMPRuntimeNVPTX::hasAllocateAttributeForGlobalVar(const VarDecl *VD,
4922 LangAS &AS) {
4923 if (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())
4924 return false;
4925 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
4926 switch(A->getAllocatorType()) {
4927 case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
4928 // Not supported, fallback to the default mem space.
4929 case OMPAllocateDeclAttr::OMPThreadMemAlloc:
4930 case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
4931 case OMPAllocateDeclAttr::OMPCGroupMemAlloc:
4932 case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
4933 case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
4934 AS = LangAS::Default;
4935 return true;
4936 case OMPAllocateDeclAttr::OMPConstMemAlloc:
4937 AS = LangAS::cuda_constant;
4938 return true;
4939 case OMPAllocateDeclAttr::OMPPTeamMemAlloc:
4940 AS = LangAS::cuda_shared;
4941 return true;
4942 case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
4943 llvm_unreachable("Expected predefined allocator for the variables with the "::llvm::llvm_unreachable_internal("Expected predefined allocator for the variables with the "
"static storage.", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 4944)
4944 "static storage.")::llvm::llvm_unreachable_internal("Expected predefined allocator for the variables with the "
"static storage.", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 4944)
;
4945 }
4946 return false;
4947}
4948
4949// Get current CudaArch and ignore any unknown values
4950static CudaArch getCudaArch(CodeGenModule &CGM) {
4951 if (!CGM.getTarget().hasFeature("ptx"))
4952 return CudaArch::UNKNOWN;
4953 llvm::StringMap<bool> Features;
4954 CGM.getTarget().initFeatureMap(Features, CGM.getDiags(),
4955 CGM.getTarget().getTargetOpts().CPU,
4956 CGM.getTarget().getTargetOpts().Features);
4957 for (const auto &Feature : Features) {
4958 if (Feature.getValue()) {
4959 CudaArch Arch = StringToCudaArch(Feature.getKey());
4960 if (Arch != CudaArch::UNKNOWN)
4961 return Arch;
4962 }
4963 }
4964 return CudaArch::UNKNOWN;
4965}
4966
4967/// Check to see if target architecture supports unified addressing which is
4968/// a restriction for OpenMP requires clause "unified_shared_memory".
4969void CGOpenMPRuntimeNVPTX::processRequiresDirective(
4970 const OMPRequiresDecl *D) {
4971 for (const OMPClause *Clause : D->clauselists()) {
4972 if (Clause->getClauseKind() == OMPC_unified_shared_memory) {
4973 CudaArch Arch = getCudaArch(CGM);
4974 switch (Arch) {
4975 case CudaArch::SM_20:
4976 case CudaArch::SM_21:
4977 case CudaArch::SM_30:
4978 case CudaArch::SM_32:
4979 case CudaArch::SM_35:
4980 case CudaArch::SM_37:
4981 case CudaArch::SM_50:
4982 case CudaArch::SM_52:
4983 case CudaArch::SM_53:
4984 case CudaArch::SM_60:
4985 case CudaArch::SM_61:
4986 case CudaArch::SM_62: {
4987 SmallString<256> Buffer;
4988 llvm::raw_svector_ostream Out(Buffer);
4989 Out << "Target architecture " << CudaArchToString(Arch)
4990 << " does not support unified addressing";
4991 CGM.Error(Clause->getBeginLoc(), Out.str());
4992 return;
4993 }
4994 case CudaArch::SM_70:
4995 case CudaArch::SM_72:
4996 case CudaArch::SM_75:
4997 case CudaArch::GFX600:
4998 case CudaArch::GFX601:
4999 case CudaArch::GFX700:
5000 case CudaArch::GFX701:
5001 case CudaArch::GFX702:
5002 case CudaArch::GFX703:
5003 case CudaArch::GFX704:
5004 case CudaArch::GFX801:
5005 case CudaArch::GFX802:
5006 case CudaArch::GFX803:
5007 case CudaArch::GFX810:
5008 case CudaArch::GFX900:
5009 case CudaArch::GFX902:
5010 case CudaArch::GFX904:
5011 case CudaArch::GFX906:
5012 case CudaArch::GFX908:
5013 case CudaArch::GFX909:
5014 case CudaArch::GFX1010:
5015 case CudaArch::GFX1011:
5016 case CudaArch::GFX1012:
5017 case CudaArch::UNKNOWN:
5018 break;
5019 case CudaArch::LAST:
5020 llvm_unreachable("Unexpected Cuda arch.")::llvm::llvm_unreachable_internal("Unexpected Cuda arch.", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 5020)
;
5021 }
5022 }
5023 }
5024 CGOpenMPRuntime::processRequiresDirective(D);
5025}
5026
5027/// Get number of SMs and number of blocks per SM.
5028static std::pair<unsigned, unsigned> getSMsBlocksPerSM(CodeGenModule &CGM) {
5029 std::pair<unsigned, unsigned> Data;
5030 if (CGM.getLangOpts().OpenMPCUDANumSMs)
5031 Data.first = CGM.getLangOpts().OpenMPCUDANumSMs;
5032 if (CGM.getLangOpts().OpenMPCUDABlocksPerSM)
5033 Data.second = CGM.getLangOpts().OpenMPCUDABlocksPerSM;
5034 if (Data.first && Data.second)
5035 return Data;
5036 switch (getCudaArch(CGM)) {
5037 case CudaArch::SM_20:
5038 case CudaArch::SM_21:
5039 case CudaArch::SM_30:
5040 case CudaArch::SM_32:
5041 case CudaArch::SM_35:
5042 case CudaArch::SM_37:
5043 case CudaArch::SM_50:
5044 case CudaArch::SM_52:
5045 case CudaArch::SM_53:
5046 return {16, 16};
5047 case CudaArch::SM_60:
5048 case CudaArch::SM_61:
5049 case CudaArch::SM_62:
5050 return {56, 32};
5051 case CudaArch::SM_70:
5052 case CudaArch::SM_72:
5053 case CudaArch::SM_75:
5054 return {84, 32};
5055 case CudaArch::GFX600:
5056 case CudaArch::GFX601:
5057 case CudaArch::GFX700:
5058 case CudaArch::GFX701:
5059 case CudaArch::GFX702:
5060 case CudaArch::GFX703:
5061 case CudaArch::GFX704:
5062 case CudaArch::GFX801:
5063 case CudaArch::GFX802:
5064 case CudaArch::GFX803:
5065 case CudaArch::GFX810:
5066 case CudaArch::GFX900:
5067 case CudaArch::GFX902:
5068 case CudaArch::GFX904:
5069 case CudaArch::GFX906:
5070 case CudaArch::GFX908:
5071 case CudaArch::GFX909:
5072 case CudaArch::GFX1010:
5073 case CudaArch::GFX1011:
5074 case CudaArch::GFX1012:
5075 case CudaArch::UNKNOWN:
5076 break;
5077 case CudaArch::LAST:
5078 llvm_unreachable("Unexpected Cuda arch.")::llvm::llvm_unreachable_internal("Unexpected Cuda arch.", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 5078)
;
5079 }
5080 llvm_unreachable("Unexpected NVPTX target without ptx feature.")::llvm::llvm_unreachable_internal("Unexpected NVPTX target without ptx feature."
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp"
, 5080)
;
5081}
5082
5083void CGOpenMPRuntimeNVPTX::clear() {
5084 if (!GlobalizedRecords.empty()) {
5085 ASTContext &C = CGM.getContext();
5086 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> GlobalRecs;
5087 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> SharedRecs;
5088 RecordDecl *StaticRD = C.buildImplicitRecord(
5089 "_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
5090 StaticRD->startDefinition();
5091 RecordDecl *SharedStaticRD = C.buildImplicitRecord(
5092 "_shared_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
5093 SharedStaticRD->startDefinition();
5094 for (const GlobalPtrSizeRecsTy &Records : GlobalizedRecords) {
5095 if (Records.Records.empty())
5096 continue;
5097 unsigned Size = 0;
5098 unsigned RecAlignment = 0;
5099 for (const RecordDecl *RD : Records.Records) {
5100 QualType RDTy = C.getRecordType(RD);
5101 unsigned Alignment = C.getTypeAlignInChars(RDTy).getQuantity();
5102 RecAlignment = std::max(RecAlignment, Alignment);
5103 unsigned RecSize = C.getTypeSizeInChars(RDTy).getQuantity();
5104 Size =
5105 llvm::alignTo(llvm::alignTo(Size, Alignment) + RecSize, Alignment);
5106 }
5107 Size = llvm::alignTo(Size, RecAlignment);
5108 llvm::APInt ArySize(/*numBits=*/64, Size);
5109 QualType SubTy = C.getConstantArrayType(
5110 C.CharTy, ArySize, nullptr, ArrayType::Normal, /*IndexTypeQuals=*/0);
5111 const bool UseSharedMemory = Size <= SharedMemorySize;
5112 auto *Field =
5113 FieldDecl::Create(C, UseSharedMemory ? SharedStaticRD : StaticRD,
5114 SourceLocation(), SourceLocation(), nullptr, SubTy,
5115 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
5116 /*BW=*/nullptr, /*Mutable=*/false,
5117 /*InitStyle=*/ICIS_NoInit);
5118 Field->setAccess(AS_public);
5119 if (UseSharedMemory) {
5120 SharedStaticRD->addDecl(Field);
5121 SharedRecs.push_back(&Records);
5122 } else {
5123 StaticRD->addDecl(Field);
5124 GlobalRecs.push_back(&Records);
5125 }
5126 Records.RecSize->setInitializer(llvm::ConstantInt::get(CGM.SizeTy, Size));
5127 Records.UseSharedMemory->setInitializer(
5128 llvm::ConstantInt::get(CGM.Int16Ty, UseSharedMemory ? 1 : 0));
5129 }
5130 // Allocate SharedMemorySize buffer for the shared memory.
5131 // FIXME: nvlink does not handle weak linkage correctly (object with the
5132 // different size are reported as erroneous).
5133 // Restore this code as sson as nvlink is fixed.
5134 if (!SharedStaticRD->field_empty()) {
5135 llvm::APInt ArySize(/*numBits=*/64, SharedMemorySize);
5136 QualType SubTy = C.getConstantArrayType(
5137 C.CharTy, ArySize, nullptr, ArrayType::Normal, /*IndexTypeQuals=*/0);
5138 auto *Field = FieldDecl::Create(
5139 C, SharedStaticRD, SourceLocation(), SourceLocation(), nullptr, SubTy,
5140 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
5141 /*BW=*/nullptr, /*Mutable=*/false,
5142 /*InitStyle=*/ICIS_NoInit);
5143 Field->setAccess(AS_public);
5144 SharedStaticRD->addDecl(Field);
5145 }
5146 SharedStaticRD->completeDefinition();
5147 if (!SharedStaticRD->field_empty()) {
5148 QualType StaticTy = C.getRecordType(SharedStaticRD);
5149 llvm::Type *LLVMStaticTy = CGM.getTypes().ConvertTypeForMem(StaticTy);
5150 auto *GV = new llvm::GlobalVariable(
5151 CGM.getModule(), LLVMStaticTy,
5152 /*isConstant=*/false, llvm::GlobalValue::CommonLinkage,
5153 llvm::Constant::getNullValue(LLVMStaticTy),
5154 "_openmp_shared_static_glob_rd_$_", /*InsertBefore=*/nullptr,
5155 llvm::GlobalValue::NotThreadLocal,
5156 C.getTargetAddressSpace(LangAS::cuda_shared));
5157 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
5158 GV, CGM.VoidPtrTy);
5159 for (const GlobalPtrSizeRecsTy *Rec : SharedRecs) {
5160 Rec->Buffer->replaceAllUsesWith(Replacement);
5161 Rec->Buffer->eraseFromParent();
5162 }
5163 }
5164 StaticRD->completeDefinition();
5165 if (!StaticRD->field_empty()) {
5166 QualType StaticTy = C.getRecordType(StaticRD);
5167 std::pair<unsigned, unsigned> SMsBlockPerSM = getSMsBlocksPerSM(CGM);
5168 llvm::APInt Size1(32, SMsBlockPerSM.second);
5169 QualType Arr1Ty =
5170 C.getConstantArrayType(StaticTy, Size1, nullptr, ArrayType::Normal,
5171 /*IndexTypeQuals=*/0);
5172 llvm::APInt Size2(32, SMsBlockPerSM.first);
5173 QualType Arr2Ty =
5174 C.getConstantArrayType(Arr1Ty, Size2, nullptr, ArrayType::Normal,
5175 /*IndexTypeQuals=*/0);
5176 llvm::Type *LLVMArr2Ty = CGM.getTypes().ConvertTypeForMem(Arr2Ty);
5177 // FIXME: nvlink does not handle weak linkage correctly (object with the
5178 // different size are reported as erroneous).
5179 // Restore CommonLinkage as soon as nvlink is fixed.
5180 auto *GV = new llvm::GlobalVariable(
5181 CGM.getModule(), LLVMArr2Ty,
5182 /*isConstant=*/false, llvm::GlobalValue::InternalLinkage,
5183 llvm::Constant::getNullValue(LLVMArr2Ty),
5184 "_openmp_static_glob_rd_$_");
5185 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
5186 GV, CGM.VoidPtrTy);
5187 for (const GlobalPtrSizeRecsTy *Rec : GlobalRecs) {
5188 Rec->Buffer->replaceAllUsesWith(Replacement);
5189 Rec->Buffer->eraseFromParent();
5190 }
5191 }
5192 }
5193 if (!TeamsReductions.empty()) {
5194 ASTContext &C = CGM.getContext();
5195 RecordDecl *StaticRD = C.buildImplicitRecord(
5196 "_openmp_teams_reduction_type_$_", RecordDecl::TagKind::TTK_Union);
5197 StaticRD->startDefinition();
5198 for (const RecordDecl *TeamReductionRec : TeamsReductions) {
5199 QualType RecTy = C.getRecordType(TeamReductionRec);
5200 auto *Field = FieldDecl::Create(
5201 C, StaticRD, SourceLocation(), SourceLocation(), nullptr, RecTy,
5202 C.getTrivialTypeSourceInfo(RecTy, SourceLocation()),
5203 /*BW=*/nullptr, /*Mutable=*/false,
5204 /*InitStyle=*/ICIS_NoInit);
5205 Field->setAccess(AS_public);
5206 StaticRD->addDecl(Field);
5207 }
5208 StaticRD->completeDefinition();
5209 QualType StaticTy = C.getRecordType(StaticRD);
5210 llvm::Type *LLVMReductionsBufferTy =
5211 CGM.getTypes().ConvertTypeForMem(StaticTy);
5212 // FIXME: nvlink does not handle weak linkage correctly (object with the
5213 // different size are reported as erroneous).
5214 // Restore CommonLinkage as soon as nvlink is fixed.
5215 auto *GV = new llvm::GlobalVariable(
5216 CGM.getModule(), LLVMReductionsBufferTy,
5217 /*isConstant=*/false, llvm::GlobalValue::InternalLinkage,
5218 llvm::Constant::getNullValue(LLVMReductionsBufferTy),
5219 "_openmp_teams_reductions_buffer_$_");
5220 KernelTeamsReductionPtr->setInitializer(
5221 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
5222 CGM.VoidPtrTy));
5223 }
5224 CGOpenMPRuntime::clear();
5225}