blob: d4b599eeff40d7d72ff2b4528620a344102ada52 [file] [log] [blame]
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001//===---- CGOpenMPRuntimeNVPTX.cpp - Interface to OpenMP NVPTX Runtimes ---===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides a class for OpenMP runtime code generation specialized to NVPTX
11// targets.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CGOpenMPRuntimeNVPTX.h"
Carlo Bertollic6872252016-04-04 15:55:02 +000016#include "CodeGenFunction.h"
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000017#include "clang/AST/DeclOpenMP.h"
Carlo Bertollic6872252016-04-04 15:55:02 +000018#include "clang/AST/StmtOpenMP.h"
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000019#include "clang/AST/StmtVisitor.h"
Alexey Bataeve4090182018-11-02 14:54:07 +000020#include "clang/Basic/Cuda.h"
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000021#include "llvm/ADT/SmallPtrSet.h"
Samuel Antao45bfe4c2016-02-08 15:59:20 +000022
23using namespace clang;
24using namespace CodeGen;
25
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +000026namespace {
27enum OpenMPRTLFunctionNVPTX {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000028 /// Call to void __kmpc_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +000029 /// int16_t RequiresOMPRuntime);
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +000030 OMPRTL_NVPTX__kmpc_kernel_init,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000031 /// Call to void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +000032 OMPRTL_NVPTX__kmpc_kernel_deinit,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000033 /// Call to void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +000034 /// int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +000035 OMPRTL_NVPTX__kmpc_spmd_kernel_init,
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +000036 /// Call to void __kmpc_spmd_kernel_deinit_v2(int16_t RequiresOMPRuntime);
37 OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000038 /// Call to void __kmpc_kernel_prepare_parallel(void
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +000039 /// *outlined_function, int16_t
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +000040 /// IsOMPRuntimeInitialized);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000041 OMPRTL_NVPTX__kmpc_kernel_prepare_parallel,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000042 /// Call to bool __kmpc_kernel_parallel(void **outlined_function,
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +000043 /// int16_t IsOMPRuntimeInitialized);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000044 OMPRTL_NVPTX__kmpc_kernel_parallel,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000045 /// Call to void __kmpc_kernel_end_parallel();
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000046 OMPRTL_NVPTX__kmpc_kernel_end_parallel,
47 /// Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
48 /// global_tid);
49 OMPRTL_NVPTX__kmpc_serialized_parallel,
50 /// Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
51 /// global_tid);
52 OMPRTL_NVPTX__kmpc_end_serialized_parallel,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000053 /// Call to int32_t __kmpc_shuffle_int32(int32_t element,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000054 /// int16_t lane_offset, int16_t warp_size);
55 OMPRTL_NVPTX__kmpc_shuffle_int32,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000056 /// Call to int64_t __kmpc_shuffle_int64(int64_t element,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000057 /// int16_t lane_offset, int16_t warp_size);
58 OMPRTL_NVPTX__kmpc_shuffle_int64,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000059 /// Call to __kmpc_nvptx_parallel_reduce_nowait(kmp_int32
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000060 /// global_tid, kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
61 /// void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
62 /// lane_offset, int16_t shortCircuit),
63 /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num));
64 OMPRTL_NVPTX__kmpc_parallel_reduce_nowait,
Alexey Bataeva1166022018-11-27 21:24:54 +000065 /// Call to __kmpc_nvptx_teams_reduce_nowait_simple(ident_t *loc, kmp_int32
66 /// global_tid, kmp_critical_name *lck)
67 OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_simple,
68 /// Call to __kmpc_nvptx_teams_end_reduce_nowait_simple(ident_t *loc,
69 /// kmp_int32 global_tid, kmp_critical_name *lck)
70 OMPRTL_NVPTX__kmpc_nvptx_teams_end_reduce_nowait_simple,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000071 /// Call to __kmpc_nvptx_end_reduce_nowait(int32_t global_tid);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000072 OMPRTL_NVPTX__kmpc_end_reduce_nowait,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000073 /// Call to void __kmpc_data_sharing_init_stack();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000074 OMPRTL_NVPTX__kmpc_data_sharing_init_stack,
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +000075 /// Call to void __kmpc_data_sharing_init_stack_spmd();
76 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd,
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +000077 /// Call to void* __kmpc_data_sharing_coalesced_push_stack(size_t size,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000078 /// int16_t UseSharedMemory);
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +000079 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000080 /// Call to void __kmpc_data_sharing_pop_stack(void *a);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000081 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000082 /// Call to void __kmpc_begin_sharing_variables(void ***args,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000083 /// size_t n_args);
84 OMPRTL_NVPTX__kmpc_begin_sharing_variables,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000085 /// Call to void __kmpc_end_sharing_variables();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000086 OMPRTL_NVPTX__kmpc_end_sharing_variables,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000087 /// Call to void __kmpc_get_shared_variables(void ***GlobalArgs)
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000088 OMPRTL_NVPTX__kmpc_get_shared_variables,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +000089 /// Call to uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32
90 /// global_tid);
91 OMPRTL_NVPTX__kmpc_parallel_level,
Alexey Bataev673110d2018-05-16 13:36:30 +000092 /// Call to int8_t __kmpc_is_spmd_exec_mode();
93 OMPRTL_NVPTX__kmpc_is_spmd_exec_mode,
Alexey Bataeve4090182018-11-02 14:54:07 +000094 /// Call to void __kmpc_get_team_static_memory(const void *buf, size_t size,
95 /// int16_t is_shared, const void **res);
96 OMPRTL_NVPTX__kmpc_get_team_static_memory,
97 /// Call to void __kmpc_restore_team_static_memory(int16_t is_shared);
98 OMPRTL_NVPTX__kmpc_restore_team_static_memory,
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +000099};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000100
101/// Pre(post)-action for different OpenMP constructs specialized for NVPTX.
102class NVPTXActionTy final : public PrePostActionTy {
Alexey Bataev9ff80832018-04-16 20:16:21 +0000103 llvm::Value *EnterCallee = nullptr;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000104 ArrayRef<llvm::Value *> EnterArgs;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000105 llvm::Value *ExitCallee = nullptr;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000106 ArrayRef<llvm::Value *> ExitArgs;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000107 bool Conditional = false;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000108 llvm::BasicBlock *ContBlock = nullptr;
109
110public:
111 NVPTXActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
112 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
113 bool Conditional = false)
114 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
115 ExitArgs(ExitArgs), Conditional(Conditional) {}
116 void Enter(CodeGenFunction &CGF) override {
117 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
118 if (Conditional) {
119 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
120 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
121 ContBlock = CGF.createBasicBlock("omp_if.end");
122 // Generate the branch (If-stmt)
123 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
124 CGF.EmitBlock(ThenBlock);
125 }
126 }
127 void Done(CodeGenFunction &CGF) {
128 // Emit the rest of blocks/branches
129 CGF.EmitBranch(ContBlock);
130 CGF.EmitBlock(ContBlock, true);
131 }
132 void Exit(CodeGenFunction &CGF) override {
133 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
134 }
135};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000136
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000137/// A class to track the execution mode when codegening directives within
138/// a target region. The appropriate mode (SPMD|NON-SPMD) is set on entry
139/// to the target region and used by containing directives such as 'parallel'
140/// to emit optimized code.
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000141class ExecutionRuntimeModesRAII {
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000142private:
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000143 CGOpenMPRuntimeNVPTX::ExecutionMode SavedExecMode =
144 CGOpenMPRuntimeNVPTX::EM_Unknown;
145 CGOpenMPRuntimeNVPTX::ExecutionMode &ExecMode;
146 bool SavedRuntimeMode = false;
147 bool *RuntimeMode = nullptr;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000148
149public:
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000150 /// Constructor for Non-SPMD mode.
151 ExecutionRuntimeModesRAII(CGOpenMPRuntimeNVPTX::ExecutionMode &ExecMode)
152 : ExecMode(ExecMode) {
153 SavedExecMode = ExecMode;
154 ExecMode = CGOpenMPRuntimeNVPTX::EM_NonSPMD;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000155 }
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000156 /// Constructor for SPMD mode.
157 ExecutionRuntimeModesRAII(CGOpenMPRuntimeNVPTX::ExecutionMode &ExecMode,
158 bool &RuntimeMode, bool FullRuntimeMode)
159 : ExecMode(ExecMode), RuntimeMode(&RuntimeMode) {
160 SavedExecMode = ExecMode;
161 SavedRuntimeMode = RuntimeMode;
162 ExecMode = CGOpenMPRuntimeNVPTX::EM_SPMD;
163 RuntimeMode = FullRuntimeMode;
164 }
165 ~ExecutionRuntimeModesRAII() {
166 ExecMode = SavedExecMode;
167 if (RuntimeMode)
168 *RuntimeMode = SavedRuntimeMode;
169 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000170};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000171
172/// GPU Configuration: This information can be derived from cuda registers,
173/// however, providing compile time constants helps generate more efficient
174/// code. For all practical purposes this is fine because the configuration
175/// is the same for all known NVPTX architectures.
176enum MachineConfiguration : unsigned {
177 WarpSize = 32,
178 /// Number of bits required to represent a lane identifier, which is
179 /// computed as log_2(WarpSize).
180 LaneIDBits = 5,
181 LaneIDMask = WarpSize - 1,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +0000182
183 /// Global memory alignment for performance.
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000184 GlobalMemoryAlignment = 128,
Alexey Bataev09c9eea2018-11-09 16:18:04 +0000185
186 /// Maximal size of the shared memory buffer.
187 SharedMemorySize = 128,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000188};
189
190enum NamedBarrier : unsigned {
191 /// Synchronize on this barrier #ID using a named barrier primitive.
192 /// Only the subset of active threads in a parallel region arrive at the
193 /// barrier.
194 NB_Parallel = 1,
195};
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000196
Alexey Bataevf2f39be2018-11-16 19:38:21 +0000197static const ValueDecl *getPrivateItem(const Expr *RefExpr) {
198 RefExpr = RefExpr->IgnoreParens();
199 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr)) {
200 const Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
201 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
202 Base = TempASE->getBase()->IgnoreParenImpCasts();
203 RefExpr = Base;
204 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr)) {
205 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
206 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
207 Base = TempOASE->getBase()->IgnoreParenImpCasts();
208 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
209 Base = TempASE->getBase()->IgnoreParenImpCasts();
210 RefExpr = Base;
211 }
212 RefExpr = RefExpr->IgnoreParenImpCasts();
213 if (const auto *DE = dyn_cast<DeclRefExpr>(RefExpr))
214 return cast<ValueDecl>(DE->getDecl()->getCanonicalDecl());
215 const auto *ME = cast<MemberExpr>(RefExpr);
216 return cast<ValueDecl>(ME->getMemberDecl()->getCanonicalDecl());
217}
218
Alexey Bataev2adecff2018-09-21 14:22:53 +0000219typedef std::pair<CharUnits /*Align*/, const ValueDecl *> VarsDataTy;
220static bool stable_sort_comparator(const VarsDataTy P1, const VarsDataTy P2) {
221 return P1.first > P2.first;
222}
223
224static RecordDecl *buildRecordForGlobalizedVars(
225 ASTContext &C, ArrayRef<const ValueDecl *> EscapedDecls,
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000226 ArrayRef<const ValueDecl *> EscapedDeclsForTeams,
Alexey Bataev2adecff2018-09-21 14:22:53 +0000227 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
228 &MappedDeclsFields) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000229 if (EscapedDecls.empty() && EscapedDeclsForTeams.empty())
Alexey Bataev2adecff2018-09-21 14:22:53 +0000230 return nullptr;
231 SmallVector<VarsDataTy, 4> GlobalizedVars;
232 for (const ValueDecl *D : EscapedDecls)
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000233 GlobalizedVars.emplace_back(
234 CharUnits::fromQuantity(std::max(
235 C.getDeclAlign(D).getQuantity(),
236 static_cast<CharUnits::QuantityType>(GlobalMemoryAlignment))),
237 D);
238 for (const ValueDecl *D : EscapedDeclsForTeams)
Alexey Bataev2adecff2018-09-21 14:22:53 +0000239 GlobalizedVars.emplace_back(C.getDeclAlign(D), D);
240 std::stable_sort(GlobalizedVars.begin(), GlobalizedVars.end(),
241 stable_sort_comparator);
242 // Build struct _globalized_locals_ty {
Alexey Bataevff23bb62018-10-11 18:30:31 +0000243 // /* globalized vars */[WarSize] align (max(decl_align,
244 // GlobalMemoryAlignment))
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000245 // /* globalized vars */ for EscapedDeclsForTeams
Alexey Bataev2adecff2018-09-21 14:22:53 +0000246 // };
247 RecordDecl *GlobalizedRD = C.buildImplicitRecord("_globalized_locals_ty");
248 GlobalizedRD->startDefinition();
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000249 llvm::SmallPtrSet<const ValueDecl *, 16> SingleEscaped(
250 EscapedDeclsForTeams.begin(), EscapedDeclsForTeams.end());
Alexey Bataev2adecff2018-09-21 14:22:53 +0000251 for (const auto &Pair : GlobalizedVars) {
252 const ValueDecl *VD = Pair.second;
253 QualType Type = VD->getType();
254 if (Type->isLValueReferenceType())
255 Type = C.getPointerType(Type.getNonReferenceType());
256 else
257 Type = Type.getNonReferenceType();
258 SourceLocation Loc = VD->getLocation();
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000259 FieldDecl *Field;
260 if (SingleEscaped.count(VD)) {
261 Field = FieldDecl::Create(
262 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
263 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
264 /*BW=*/nullptr, /*Mutable=*/false,
265 /*InitStyle=*/ICIS_NoInit);
266 Field->setAccess(AS_public);
267 if (VD->hasAttrs()) {
268 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
269 E(VD->getAttrs().end());
270 I != E; ++I)
271 Field->addAttr(*I);
272 }
273 } else {
274 llvm::APInt ArraySize(32, WarpSize);
275 Type = C.getConstantArrayType(Type, ArraySize, ArrayType::Normal, 0);
276 Field = FieldDecl::Create(
277 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
278 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
279 /*BW=*/nullptr, /*Mutable=*/false,
280 /*InitStyle=*/ICIS_NoInit);
281 Field->setAccess(AS_public);
282 llvm::APInt Align(32, std::max(C.getDeclAlign(VD).getQuantity(),
283 static_cast<CharUnits::QuantityType>(
284 GlobalMemoryAlignment)));
285 Field->addAttr(AlignedAttr::CreateImplicit(
286 C, AlignedAttr::GNU_aligned, /*IsAlignmentExpr=*/true,
287 IntegerLiteral::Create(C, Align,
288 C.getIntTypeForBitwidth(32, /*Signed=*/0),
289 SourceLocation())));
Alexey Bataev2adecff2018-09-21 14:22:53 +0000290 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000291 GlobalizedRD->addDecl(Field);
Alexey Bataev2adecff2018-09-21 14:22:53 +0000292 MappedDeclsFields.try_emplace(VD, Field);
293 }
294 GlobalizedRD->completeDefinition();
295 return GlobalizedRD;
296}
297
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000298/// Get the list of variables that can escape their declaration context.
299class CheckVarsEscapingDeclContext final
300 : public ConstStmtVisitor<CheckVarsEscapingDeclContext> {
301 CodeGenFunction &CGF;
302 llvm::SetVector<const ValueDecl *> EscapedDecls;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000303 llvm::SetVector<const ValueDecl *> EscapedVariableLengthDecls;
Alexey Bataevc99042b2018-03-15 18:10:54 +0000304 llvm::SmallPtrSet<const Decl *, 4> EscapedParameters;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000305 RecordDecl *GlobalizedRD = nullptr;
306 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000307 bool AllEscaped = false;
Alexey Bataev91433f62018-06-26 17:24:03 +0000308 bool IsForCombinedParallelRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000309
310 void markAsEscaped(const ValueDecl *VD) {
Alexey Bataev03f270c2018-03-30 18:31:07 +0000311 // Do not globalize declare target variables.
Alexey Bataev97b72212018-08-14 18:31:20 +0000312 if (!isa<VarDecl>(VD) ||
313 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataev03f270c2018-03-30 18:31:07 +0000314 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000315 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataevc99042b2018-03-15 18:10:54 +0000316 // Variables captured by value must be globalized.
317 if (auto *CSI = CGF.CapturedStmtInfo) {
Mikael Holmen9f373a32018-03-16 07:27:57 +0000318 if (const FieldDecl *FD = CSI->lookup(cast<VarDecl>(VD))) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000319 // Check if need to capture the variable that was already captured by
320 // value in the outer region.
Alexey Bataev91433f62018-06-26 17:24:03 +0000321 if (!IsForCombinedParallelRegion) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000322 if (!FD->hasAttrs())
323 return;
324 const auto *Attr = FD->getAttr<OMPCaptureKindAttr>();
325 if (!Attr)
326 return;
327 if (!isOpenMPPrivate(
328 static_cast<OpenMPClauseKind>(Attr->getCaptureKind())) ||
329 Attr->getCaptureKind() == OMPC_map)
330 return;
331 }
332 if (!FD->getType()->isReferenceType()) {
333 assert(!VD->getType()->isVariablyModifiedType() &&
334 "Parameter captured by value with variably modified type");
335 EscapedParameters.insert(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000336 } else if (!IsForCombinedParallelRegion) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000337 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000338 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000339 }
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000340 }
341 if ((!CGF.CapturedStmtInfo ||
Alexey Bataev91433f62018-06-26 17:24:03 +0000342 (IsForCombinedParallelRegion && CGF.CapturedStmtInfo)) &&
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000343 VD->getType()->isReferenceType())
344 // Do not globalize variables with reference type.
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000345 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000346 if (VD->getType()->isVariablyModifiedType())
347 EscapedVariableLengthDecls.insert(VD);
348 else
349 EscapedDecls.insert(VD);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000350 }
351
352 void VisitValueDecl(const ValueDecl *VD) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000353 if (VD->getType()->isLValueReferenceType())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000354 markAsEscaped(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000355 if (const auto *VarD = dyn_cast<VarDecl>(VD)) {
356 if (!isa<ParmVarDecl>(VarD) && VarD->hasInit()) {
357 const bool SavedAllEscaped = AllEscaped;
358 AllEscaped = VD->getType()->isLValueReferenceType();
359 Visit(VarD->getInit());
360 AllEscaped = SavedAllEscaped;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000361 }
362 }
363 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000364 void VisitOpenMPCapturedStmt(const CapturedStmt *S,
365 ArrayRef<OMPClause *> Clauses,
366 bool IsCombinedParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000367 if (!S)
368 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000369 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000370 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
371 const ValueDecl *VD = C.getCapturedVar();
Alexey Bataev91433f62018-06-26 17:24:03 +0000372 bool SavedIsForCombinedParallelRegion = IsForCombinedParallelRegion;
373 if (IsCombinedParallelRegion) {
374 // Check if the variable is privatized in the combined construct and
375 // those private copies must be shared in the inner parallel
376 // directive.
377 IsForCombinedParallelRegion = false;
378 for (const OMPClause *C : Clauses) {
379 if (!isOpenMPPrivate(C->getClauseKind()) ||
380 C->getClauseKind() == OMPC_reduction ||
381 C->getClauseKind() == OMPC_linear ||
382 C->getClauseKind() == OMPC_private)
383 continue;
384 ArrayRef<const Expr *> Vars;
385 if (const auto *PC = dyn_cast<OMPFirstprivateClause>(C))
386 Vars = PC->getVarRefs();
387 else if (const auto *PC = dyn_cast<OMPLastprivateClause>(C))
388 Vars = PC->getVarRefs();
389 else
390 llvm_unreachable("Unexpected clause.");
391 for (const auto *E : Vars) {
392 const Decl *D =
393 cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
394 if (D == VD->getCanonicalDecl()) {
395 IsForCombinedParallelRegion = true;
396 break;
397 }
398 }
399 if (IsForCombinedParallelRegion)
400 break;
401 }
402 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000403 markAsEscaped(VD);
404 if (isa<OMPCapturedExprDecl>(VD))
405 VisitValueDecl(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000406 IsForCombinedParallelRegion = SavedIsForCombinedParallelRegion;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000407 }
408 }
409 }
410
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000411 void buildRecordForGlobalizedVars(bool IsInTTDRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000412 assert(!GlobalizedRD &&
413 "Record for globalized variables is built already.");
Alexey Bataevff23bb62018-10-11 18:30:31 +0000414 ArrayRef<const ValueDecl *> EscapedDeclsForParallel, EscapedDeclsForTeams;
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000415 if (IsInTTDRegion)
Alexey Bataevff23bb62018-10-11 18:30:31 +0000416 EscapedDeclsForTeams = EscapedDecls.getArrayRef();
417 else
418 EscapedDeclsForParallel = EscapedDecls.getArrayRef();
Alexey Bataev2adecff2018-09-21 14:22:53 +0000419 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataevff23bb62018-10-11 18:30:31 +0000420 CGF.getContext(), EscapedDeclsForParallel, EscapedDeclsForTeams,
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000421 MappedDeclsFields);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000422 }
423
424public:
Alexey Bataevf2f39be2018-11-16 19:38:21 +0000425 CheckVarsEscapingDeclContext(CodeGenFunction &CGF,
426 ArrayRef<const ValueDecl *> TeamsReductions)
427 : CGF(CGF), EscapedDecls(TeamsReductions.begin(), TeamsReductions.end()) {
428 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000429 virtual ~CheckVarsEscapingDeclContext() = default;
430 void VisitDeclStmt(const DeclStmt *S) {
431 if (!S)
432 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000433 for (const Decl *D : S->decls())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000434 if (const auto *VD = dyn_cast_or_null<ValueDecl>(D))
435 VisitValueDecl(VD);
436 }
437 void VisitOMPExecutableDirective(const OMPExecutableDirective *D) {
438 if (!D)
439 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000440 if (!D->hasAssociatedStmt())
441 return;
442 if (const auto *S =
443 dyn_cast_or_null<CapturedStmt>(D->getAssociatedStmt())) {
444 // Do not analyze directives that do not actually require capturing,
445 // like `omp for` or `omp simd` directives.
446 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
447 getOpenMPCaptureRegions(CaptureRegions, D->getDirectiveKind());
448 if (CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown) {
449 VisitStmt(S->getCapturedStmt());
450 return;
Alexey Bataev673110d2018-05-16 13:36:30 +0000451 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000452 VisitOpenMPCapturedStmt(
453 S, D->clauses(),
454 CaptureRegions.back() == OMPD_parallel &&
455 isOpenMPDistributeDirective(D->getDirectiveKind()));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000456 }
457 }
458 void VisitCapturedStmt(const CapturedStmt *S) {
459 if (!S)
460 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000461 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000462 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
463 const ValueDecl *VD = C.getCapturedVar();
464 markAsEscaped(VD);
465 if (isa<OMPCapturedExprDecl>(VD))
466 VisitValueDecl(VD);
467 }
468 }
469 }
470 void VisitLambdaExpr(const LambdaExpr *E) {
471 if (!E)
472 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000473 for (const LambdaCapture &C : E->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000474 if (C.capturesVariable()) {
475 if (C.getCaptureKind() == LCK_ByRef) {
476 const ValueDecl *VD = C.getCapturedVar();
477 markAsEscaped(VD);
478 if (E->isInitCapture(&C) || isa<OMPCapturedExprDecl>(VD))
479 VisitValueDecl(VD);
480 }
481 }
482 }
483 }
484 void VisitBlockExpr(const BlockExpr *E) {
485 if (!E)
486 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000487 for (const BlockDecl::Capture &C : E->getBlockDecl()->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000488 if (C.isByRef()) {
489 const VarDecl *VD = C.getVariable();
490 markAsEscaped(VD);
491 if (isa<OMPCapturedExprDecl>(VD) || VD->isInitCapture())
492 VisitValueDecl(VD);
493 }
494 }
495 }
496 void VisitCallExpr(const CallExpr *E) {
497 if (!E)
498 return;
499 for (const Expr *Arg : E->arguments()) {
500 if (!Arg)
501 continue;
502 if (Arg->isLValue()) {
503 const bool SavedAllEscaped = AllEscaped;
504 AllEscaped = true;
505 Visit(Arg);
506 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000507 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000508 Visit(Arg);
Alexey Bataev9ff80832018-04-16 20:16:21 +0000509 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000510 }
511 Visit(E->getCallee());
512 }
513 void VisitDeclRefExpr(const DeclRefExpr *E) {
514 if (!E)
515 return;
516 const ValueDecl *VD = E->getDecl();
517 if (AllEscaped)
518 markAsEscaped(VD);
519 if (isa<OMPCapturedExprDecl>(VD))
520 VisitValueDecl(VD);
521 else if (const auto *VarD = dyn_cast<VarDecl>(VD))
522 if (VarD->isInitCapture())
523 VisitValueDecl(VD);
524 }
525 void VisitUnaryOperator(const UnaryOperator *E) {
526 if (!E)
527 return;
528 if (E->getOpcode() == UO_AddrOf) {
529 const bool SavedAllEscaped = AllEscaped;
530 AllEscaped = true;
531 Visit(E->getSubExpr());
532 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000533 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000534 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000535 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000536 }
537 void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
538 if (!E)
539 return;
540 if (E->getCastKind() == CK_ArrayToPointerDecay) {
541 const bool SavedAllEscaped = AllEscaped;
542 AllEscaped = true;
543 Visit(E->getSubExpr());
544 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000545 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000546 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000547 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000548 }
549 void VisitExpr(const Expr *E) {
550 if (!E)
551 return;
552 bool SavedAllEscaped = AllEscaped;
553 if (!E->isLValue())
554 AllEscaped = false;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000555 for (const Stmt *Child : E->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000556 if (Child)
557 Visit(Child);
558 AllEscaped = SavedAllEscaped;
559 }
560 void VisitStmt(const Stmt *S) {
561 if (!S)
562 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000563 for (const Stmt *Child : S->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000564 if (Child)
565 Visit(Child);
566 }
567
Alexey Bataevc99042b2018-03-15 18:10:54 +0000568 /// Returns the record that handles all the escaped local variables and used
569 /// instead of their original storage.
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000570 const RecordDecl *getGlobalizedRecord(bool IsInTTDRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000571 if (!GlobalizedRD)
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000572 buildRecordForGlobalizedVars(IsInTTDRegion);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000573 return GlobalizedRD;
574 }
575
Alexey Bataevc99042b2018-03-15 18:10:54 +0000576 /// Returns the field in the globalized record for the escaped variable.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000577 const FieldDecl *getFieldForGlobalizedVar(const ValueDecl *VD) const {
578 assert(GlobalizedRD &&
579 "Record for globalized variables must be generated already.");
580 auto I = MappedDeclsFields.find(VD);
581 if (I == MappedDeclsFields.end())
582 return nullptr;
583 return I->getSecond();
584 }
585
Alexey Bataevc99042b2018-03-15 18:10:54 +0000586 /// Returns the list of the escaped local variables/parameters.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000587 ArrayRef<const ValueDecl *> getEscapedDecls() const {
588 return EscapedDecls.getArrayRef();
589 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000590
591 /// Checks if the escaped local variable is actually a parameter passed by
592 /// value.
593 const llvm::SmallPtrSetImpl<const Decl *> &getEscapedParameters() const {
594 return EscapedParameters;
595 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000596
597 /// Returns the list of the escaped variables with the variably modified
598 /// types.
599 ArrayRef<const ValueDecl *> getEscapedVariableLengthDecls() const {
600 return EscapedVariableLengthDecls.getArrayRef();
601 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000602};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000603} // anonymous namespace
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000604
605/// Get the GPU warp size.
606static llvm::Value *getNVPTXWarpSize(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000607 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000608 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000609 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_warpsize),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000610 "nvptx_warp_size");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000611}
612
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000613/// Get the id of the current thread on the GPU.
614static llvm::Value *getNVPTXThreadID(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000615 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000616 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000617 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_tid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000618 "nvptx_tid");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000619}
620
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000621/// Get the id of the warp in the block.
622/// We assume that the warp size is 32, which is always the case
623/// on the NVPTX device, to generate more efficient code.
624static llvm::Value *getNVPTXWarpID(CodeGenFunction &CGF) {
625 CGBuilderTy &Bld = CGF.Builder;
626 return Bld.CreateAShr(getNVPTXThreadID(CGF), LaneIDBits, "nvptx_warp_id");
627}
628
629/// Get the id of the current lane in the Warp.
630/// We assume that the warp size is 32, which is always the case
631/// on the NVPTX device, to generate more efficient code.
632static llvm::Value *getNVPTXLaneID(CodeGenFunction &CGF) {
633 CGBuilderTy &Bld = CGF.Builder;
634 return Bld.CreateAnd(getNVPTXThreadID(CGF), Bld.getInt32(LaneIDMask),
635 "nvptx_lane_id");
636}
637
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000638/// Get the maximum number of threads in a block of the GPU.
639static llvm::Value *getNVPTXNumThreads(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000640 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000641 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000642 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_ntid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000643 "nvptx_num_threads");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000644}
645
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000646/// Get barrier to synchronize all threads in a block.
647static void getNVPTXCTABarrier(CodeGenFunction &CGF) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +0000648 llvm::Function *F = llvm::Intrinsic::getDeclaration(
649 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_barrier0);
650 F->addFnAttr(llvm::Attribute::Convergent);
651 CGF.EmitRuntimeCall(F);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000652}
653
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000654/// Get barrier #ID to synchronize selected (multiple of warp size) threads in
655/// a CTA.
656static void getNVPTXBarrier(CodeGenFunction &CGF, int ID,
657 llvm::Value *NumThreads) {
658 CGBuilderTy &Bld = CGF.Builder;
659 llvm::Value *Args[] = {Bld.getInt32(ID), NumThreads};
Alexey Bataevf2f39be2018-11-16 19:38:21 +0000660 llvm::Function *F = llvm::Intrinsic::getDeclaration(
661 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_barrier);
662 F->addFnAttr(llvm::Attribute::Convergent);
663 CGF.EmitRuntimeCall(F, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000664}
665
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000666/// Synchronize all GPU threads in a block.
667static void syncCTAThreads(CodeGenFunction &CGF) { getNVPTXCTABarrier(CGF); }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000668
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000669/// Synchronize worker threads in a parallel region.
670static void syncParallelThreads(CodeGenFunction &CGF, llvm::Value *NumThreads) {
671 return getNVPTXBarrier(CGF, NB_Parallel, NumThreads);
672}
673
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000674/// Get the value of the thread_limit clause in the teams directive.
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000675/// For the 'generic' execution mode, the runtime encodes thread_limit in
676/// the launch parameters, always starting thread_limit+warpSize threads per
677/// CTA. The threads in the last warp are reserved for master execution.
678/// For the 'spmd' execution mode, all threads in a CTA are part of the team.
679static llvm::Value *getThreadLimit(CodeGenFunction &CGF,
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000680 bool IsInSPMDExecutionMode = false) {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000681 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000682 return IsInSPMDExecutionMode
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000683 ? getNVPTXNumThreads(CGF)
Alexey Bataeve290ec02018-04-06 16:03:36 +0000684 : Bld.CreateNUWSub(getNVPTXNumThreads(CGF), getNVPTXWarpSize(CGF),
685 "thread_limit");
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000686}
687
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000688/// Get the thread id of the OMP master thread.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000689/// The master thread id is the first thread (lane) of the last warp in the
690/// GPU block. Warp size is assumed to be some power of 2.
691/// Thread id is 0 indexed.
692/// E.g: If NumThreads is 33, master id is 32.
693/// If NumThreads is 64, master id is 32.
694/// If NumThreads is 1024, master id is 992.
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000695static llvm::Value *getMasterThreadID(CodeGenFunction &CGF) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000696 CGBuilderTy &Bld = CGF.Builder;
697 llvm::Value *NumThreads = getNVPTXNumThreads(CGF);
698
699 // We assume that the warp size is a power of 2.
Alexey Bataeve290ec02018-04-06 16:03:36 +0000700 llvm::Value *Mask = Bld.CreateNUWSub(getNVPTXWarpSize(CGF), Bld.getInt32(1));
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000701
Alexey Bataeve290ec02018-04-06 16:03:36 +0000702 return Bld.CreateAnd(Bld.CreateNUWSub(NumThreads, Bld.getInt32(1)),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000703 Bld.CreateNot(Mask), "master_tid");
704}
705
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000706CGOpenMPRuntimeNVPTX::WorkerFunctionState::WorkerFunctionState(
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000707 CodeGenModule &CGM, SourceLocation Loc)
Alexey Bataev9ff80832018-04-16 20:16:21 +0000708 : WorkerFn(nullptr), CGFI(CGM.getTypes().arrangeNullaryFunction()),
709 Loc(Loc) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000710 createWorkerFunction(CGM);
Vasileios Kalintirise5c09592016-03-22 10:41:20 +0000711}
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000712
713void CGOpenMPRuntimeNVPTX::WorkerFunctionState::createWorkerFunction(
714 CodeGenModule &CGM) {
715 // Create an worker function with no arguments.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000716
717 WorkerFn = llvm::Function::Create(
Alexey Bataev9ff80832018-04-16 20:16:21 +0000718 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataevaee93892018-01-08 20:09:47 +0000719 /*placeholder=*/"_worker", &CGM.getModule());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000720 CGM.SetInternalFunctionAttributes(GlobalDecl(), WorkerFn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +0000721 WorkerFn->setDoesNotRecurse();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000722}
723
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000724CGOpenMPRuntimeNVPTX::ExecutionMode
725CGOpenMPRuntimeNVPTX::getExecutionMode() const {
726 return CurrentExecutionMode;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000727}
728
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000729static CGOpenMPRuntimeNVPTX::DataSharingMode
730getDataSharingMode(CodeGenModule &CGM) {
731 return CGM.getLangOpts().OpenMPCUDAMode ? CGOpenMPRuntimeNVPTX::CUDA
732 : CGOpenMPRuntimeNVPTX::Generic;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000733}
734
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000735// Checks if the expression is constant or does not have non-trivial function
736// calls.
737static bool isTrivial(ASTContext &Ctx, const Expr * E) {
738 // We can skip constant expressions.
739 // We can skip expressions with trivial calls or simple expressions.
740 return (E->isEvaluatable(Ctx, Expr::SE_AllowUndefinedBehavior) ||
741 !E->hasNonTrivialCall(Ctx)) &&
742 !E->HasSideEffects(Ctx, /*IncludePossibleEffects=*/true);
743}
744
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000745/// Checks if the \p Body is the \a CompoundStmt and returns its child statement
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000746/// iff there is only one that is not evaluatable at the compile time.
747static const Stmt *getSingleCompoundChild(ASTContext &Ctx, const Stmt *Body) {
748 if (const auto *C = dyn_cast<CompoundStmt>(Body)) {
749 const Stmt *Child = nullptr;
750 for (const Stmt *S : C->body()) {
751 if (const auto *E = dyn_cast<Expr>(S)) {
752 if (isTrivial(Ctx, E))
753 continue;
754 }
755 // Some of the statements can be ignored.
756 if (isa<AsmStmt>(S) || isa<NullStmt>(S) || isa<OMPFlushDirective>(S) ||
757 isa<OMPBarrierDirective>(S) || isa<OMPTaskyieldDirective>(S))
758 continue;
759 // Analyze declarations.
760 if (const auto *DS = dyn_cast<DeclStmt>(S)) {
761 if (llvm::all_of(DS->decls(), [&Ctx](const Decl *D) {
762 if (isa<EmptyDecl>(D) || isa<DeclContext>(D) ||
763 isa<TypeDecl>(D) || isa<PragmaCommentDecl>(D) ||
764 isa<PragmaDetectMismatchDecl>(D) || isa<UsingDecl>(D) ||
765 isa<UsingDirectiveDecl>(D) ||
766 isa<OMPDeclareReductionDecl>(D) ||
767 isa<OMPThreadPrivateDecl>(D))
768 return true;
769 const auto *VD = dyn_cast<VarDecl>(D);
770 if (!VD)
771 return false;
772 return VD->isConstexpr() ||
773 ((VD->getType().isTrivialType(Ctx) ||
774 VD->getType()->isReferenceType()) &&
775 (!VD->hasInit() || isTrivial(Ctx, VD->getInit())));
776 }))
777 continue;
778 }
779 // Found multiple children - cannot get the one child only.
780 if (Child)
781 return Body;
782 Child = S;
783 }
784 if (Child)
785 return Child;
786 }
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000787 return Body;
788}
789
790/// Check if the parallel directive has an 'if' clause with non-constant or
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000791/// false condition. Also, check if the number of threads is strictly specified
792/// and run those directives in non-SPMD mode.
793static bool hasParallelIfNumThreadsClause(ASTContext &Ctx,
794 const OMPExecutableDirective &D) {
795 if (D.hasClausesOfKind<OMPNumThreadsClause>())
796 return true;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000797 for (const auto *C : D.getClausesOfKind<OMPIfClause>()) {
798 OpenMPDirectiveKind NameModifier = C->getNameModifier();
799 if (NameModifier != OMPD_parallel && NameModifier != OMPD_unknown)
800 continue;
801 const Expr *Cond = C->getCondition();
802 bool Result;
803 if (!Cond->EvaluateAsBooleanCondition(Result, Ctx) || !Result)
804 return true;
805 }
806 return false;
807}
808
809/// Check for inner (nested) SPMD construct, if any
810static bool hasNestedSPMDDirective(ASTContext &Ctx,
811 const OMPExecutableDirective &D) {
812 const auto *CS = D.getInnermostCapturedStmt();
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000813 const auto *Body =
814 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000815 const Stmt *ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000816
817 if (const auto *NestedDir = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
818 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000819 switch (D.getDirectiveKind()) {
820 case OMPD_target:
Alexey Bataevdf093e72018-05-11 19:45:14 +0000821 if (isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000822 !hasParallelIfNumThreadsClause(Ctx, *NestedDir))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000823 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000824 if (DKind == OMPD_teams) {
825 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
826 /*IgnoreCaptured=*/true);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000827 if (!Body)
828 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000829 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000830 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
831 DKind = NND->getDirectiveKind();
Alexey Bataevdf093e72018-05-11 19:45:14 +0000832 if (isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000833 !hasParallelIfNumThreadsClause(Ctx, *NND))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000834 return true;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000835 }
836 }
837 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000838 case OMPD_target_teams:
Alexey Bataevdf093e72018-05-11 19:45:14 +0000839 return isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000840 !hasParallelIfNumThreadsClause(Ctx, *NestedDir);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000841 case OMPD_target_simd:
842 case OMPD_target_parallel:
843 case OMPD_target_parallel_for:
844 case OMPD_target_parallel_for_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000845 case OMPD_target_teams_distribute:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000846 case OMPD_target_teams_distribute_simd:
847 case OMPD_target_teams_distribute_parallel_for:
848 case OMPD_target_teams_distribute_parallel_for_simd:
849 case OMPD_parallel:
850 case OMPD_for:
851 case OMPD_parallel_for:
852 case OMPD_parallel_sections:
853 case OMPD_for_simd:
854 case OMPD_parallel_for_simd:
855 case OMPD_cancel:
856 case OMPD_cancellation_point:
857 case OMPD_ordered:
858 case OMPD_threadprivate:
859 case OMPD_task:
860 case OMPD_simd:
861 case OMPD_sections:
862 case OMPD_section:
863 case OMPD_single:
864 case OMPD_master:
865 case OMPD_critical:
866 case OMPD_taskyield:
867 case OMPD_barrier:
868 case OMPD_taskwait:
869 case OMPD_taskgroup:
870 case OMPD_atomic:
871 case OMPD_flush:
872 case OMPD_teams:
873 case OMPD_target_data:
874 case OMPD_target_exit_data:
875 case OMPD_target_enter_data:
876 case OMPD_distribute:
877 case OMPD_distribute_simd:
878 case OMPD_distribute_parallel_for:
879 case OMPD_distribute_parallel_for_simd:
880 case OMPD_teams_distribute:
881 case OMPD_teams_distribute_simd:
882 case OMPD_teams_distribute_parallel_for:
883 case OMPD_teams_distribute_parallel_for_simd:
884 case OMPD_target_update:
885 case OMPD_declare_simd:
886 case OMPD_declare_target:
887 case OMPD_end_declare_target:
888 case OMPD_declare_reduction:
889 case OMPD_taskloop:
890 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000891 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000892 case OMPD_unknown:
893 llvm_unreachable("Unexpected directive.");
894 }
895 }
896
897 return false;
898}
899
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000900static bool supportsSPMDExecutionMode(ASTContext &Ctx,
901 const OMPExecutableDirective &D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000902 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
903 switch (DirectiveKind) {
904 case OMPD_target:
905 case OMPD_target_teams:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000906 return hasNestedSPMDDirective(Ctx, D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000907 case OMPD_target_parallel:
908 case OMPD_target_parallel_for:
909 case OMPD_target_parallel_for_simd:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000910 case OMPD_target_teams_distribute_parallel_for:
911 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev2adecff2018-09-21 14:22:53 +0000912 return !hasParallelIfNumThreadsClause(Ctx, D);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000913 case OMPD_target_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000914 case OMPD_target_teams_distribute:
915 case OMPD_target_teams_distribute_simd:
916 return false;
917 case OMPD_parallel:
918 case OMPD_for:
919 case OMPD_parallel_for:
920 case OMPD_parallel_sections:
921 case OMPD_for_simd:
922 case OMPD_parallel_for_simd:
923 case OMPD_cancel:
924 case OMPD_cancellation_point:
925 case OMPD_ordered:
926 case OMPD_threadprivate:
927 case OMPD_task:
928 case OMPD_simd:
929 case OMPD_sections:
930 case OMPD_section:
931 case OMPD_single:
932 case OMPD_master:
933 case OMPD_critical:
934 case OMPD_taskyield:
935 case OMPD_barrier:
936 case OMPD_taskwait:
937 case OMPD_taskgroup:
938 case OMPD_atomic:
939 case OMPD_flush:
940 case OMPD_teams:
941 case OMPD_target_data:
942 case OMPD_target_exit_data:
943 case OMPD_target_enter_data:
944 case OMPD_distribute:
945 case OMPD_distribute_simd:
946 case OMPD_distribute_parallel_for:
947 case OMPD_distribute_parallel_for_simd:
948 case OMPD_teams_distribute:
949 case OMPD_teams_distribute_simd:
950 case OMPD_teams_distribute_parallel_for:
951 case OMPD_teams_distribute_parallel_for_simd:
952 case OMPD_target_update:
953 case OMPD_declare_simd:
954 case OMPD_declare_target:
955 case OMPD_end_declare_target:
956 case OMPD_declare_reduction:
957 case OMPD_taskloop:
958 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000959 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000960 case OMPD_unknown:
961 break;
962 }
963 llvm_unreachable(
964 "Unknown programming model for OpenMP directive on NVPTX target.");
965}
966
967/// Check if the directive is loops based and has schedule clause at all or has
968/// static scheduling.
969static bool hasStaticScheduling(const OMPExecutableDirective &D) {
970 assert(isOpenMPWorksharingDirective(D.getDirectiveKind()) &&
971 isOpenMPLoopDirective(D.getDirectiveKind()) &&
972 "Expected loop-based directive.");
973 return !D.hasClausesOfKind<OMPOrderedClause>() &&
974 (!D.hasClausesOfKind<OMPScheduleClause>() ||
975 llvm::any_of(D.getClausesOfKind<OMPScheduleClause>(),
976 [](const OMPScheduleClause *C) {
977 return C->getScheduleKind() == OMPC_SCHEDULE_static;
978 }));
979}
980
981/// Check for inner (nested) lightweight runtime construct, if any
982static bool hasNestedLightweightDirective(ASTContext &Ctx,
983 const OMPExecutableDirective &D) {
984 assert(supportsSPMDExecutionMode(Ctx, D) && "Expected SPMD mode directive.");
985 const auto *CS = D.getInnermostCapturedStmt();
986 const auto *Body =
987 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000988 const Stmt *ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000989
990 if (const auto *NestedDir = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
991 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
992 switch (D.getDirectiveKind()) {
993 case OMPD_target:
994 if (isOpenMPParallelDirective(DKind) &&
995 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
996 hasStaticScheduling(*NestedDir))
997 return true;
998 if (DKind == OMPD_parallel) {
999 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
1000 /*IgnoreCaptured=*/true);
1001 if (!Body)
1002 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001003 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001004 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
1005 DKind = NND->getDirectiveKind();
1006 if (isOpenMPWorksharingDirective(DKind) &&
1007 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
1008 return true;
1009 }
1010 } else if (DKind == OMPD_teams) {
1011 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
1012 /*IgnoreCaptured=*/true);
1013 if (!Body)
1014 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001015 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001016 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
1017 DKind = NND->getDirectiveKind();
1018 if (isOpenMPParallelDirective(DKind) &&
1019 isOpenMPWorksharingDirective(DKind) &&
1020 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
1021 return true;
1022 if (DKind == OMPD_parallel) {
1023 Body = NND->getInnermostCapturedStmt()->IgnoreContainers(
1024 /*IgnoreCaptured=*/true);
1025 if (!Body)
1026 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001027 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001028 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
1029 DKind = NND->getDirectiveKind();
1030 if (isOpenMPWorksharingDirective(DKind) &&
1031 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
1032 return true;
1033 }
1034 }
1035 }
1036 }
1037 return false;
1038 case OMPD_target_teams:
1039 if (isOpenMPParallelDirective(DKind) &&
1040 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
1041 hasStaticScheduling(*NestedDir))
1042 return true;
1043 if (DKind == OMPD_parallel) {
1044 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
1045 /*IgnoreCaptured=*/true);
1046 if (!Body)
1047 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001048 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001049 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
1050 DKind = NND->getDirectiveKind();
1051 if (isOpenMPWorksharingDirective(DKind) &&
1052 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
1053 return true;
1054 }
1055 }
1056 return false;
1057 case OMPD_target_parallel:
1058 return isOpenMPWorksharingDirective(DKind) &&
1059 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NestedDir);
1060 case OMPD_target_teams_distribute:
1061 case OMPD_target_simd:
1062 case OMPD_target_parallel_for:
1063 case OMPD_target_parallel_for_simd:
1064 case OMPD_target_teams_distribute_simd:
1065 case OMPD_target_teams_distribute_parallel_for:
1066 case OMPD_target_teams_distribute_parallel_for_simd:
1067 case OMPD_parallel:
1068 case OMPD_for:
1069 case OMPD_parallel_for:
1070 case OMPD_parallel_sections:
1071 case OMPD_for_simd:
1072 case OMPD_parallel_for_simd:
1073 case OMPD_cancel:
1074 case OMPD_cancellation_point:
1075 case OMPD_ordered:
1076 case OMPD_threadprivate:
1077 case OMPD_task:
1078 case OMPD_simd:
1079 case OMPD_sections:
1080 case OMPD_section:
1081 case OMPD_single:
1082 case OMPD_master:
1083 case OMPD_critical:
1084 case OMPD_taskyield:
1085 case OMPD_barrier:
1086 case OMPD_taskwait:
1087 case OMPD_taskgroup:
1088 case OMPD_atomic:
1089 case OMPD_flush:
1090 case OMPD_teams:
1091 case OMPD_target_data:
1092 case OMPD_target_exit_data:
1093 case OMPD_target_enter_data:
1094 case OMPD_distribute:
1095 case OMPD_distribute_simd:
1096 case OMPD_distribute_parallel_for:
1097 case OMPD_distribute_parallel_for_simd:
1098 case OMPD_teams_distribute:
1099 case OMPD_teams_distribute_simd:
1100 case OMPD_teams_distribute_parallel_for:
1101 case OMPD_teams_distribute_parallel_for_simd:
1102 case OMPD_target_update:
1103 case OMPD_declare_simd:
1104 case OMPD_declare_target:
1105 case OMPD_end_declare_target:
1106 case OMPD_declare_reduction:
1107 case OMPD_taskloop:
1108 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001109 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001110 case OMPD_unknown:
1111 llvm_unreachable("Unexpected directive.");
1112 }
1113 }
1114
1115 return false;
1116}
1117
1118/// Checks if the construct supports lightweight runtime. It must be SPMD
1119/// construct + inner loop-based construct with static scheduling.
1120static bool supportsLightweightRuntime(ASTContext &Ctx,
1121 const OMPExecutableDirective &D) {
1122 if (!supportsSPMDExecutionMode(Ctx, D))
1123 return false;
1124 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
1125 switch (DirectiveKind) {
1126 case OMPD_target:
1127 case OMPD_target_teams:
1128 case OMPD_target_parallel:
1129 return hasNestedLightweightDirective(Ctx, D);
1130 case OMPD_target_parallel_for:
1131 case OMPD_target_parallel_for_simd:
1132 case OMPD_target_teams_distribute_parallel_for:
1133 case OMPD_target_teams_distribute_parallel_for_simd:
1134 // (Last|First)-privates must be shared in parallel region.
1135 return hasStaticScheduling(D);
1136 case OMPD_target_simd:
1137 case OMPD_target_teams_distribute:
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001138 case OMPD_target_teams_distribute_simd:
Alexey Bataevdf093e72018-05-11 19:45:14 +00001139 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001140 case OMPD_parallel:
1141 case OMPD_for:
1142 case OMPD_parallel_for:
1143 case OMPD_parallel_sections:
1144 case OMPD_for_simd:
1145 case OMPD_parallel_for_simd:
1146 case OMPD_cancel:
1147 case OMPD_cancellation_point:
1148 case OMPD_ordered:
1149 case OMPD_threadprivate:
1150 case OMPD_task:
1151 case OMPD_simd:
1152 case OMPD_sections:
1153 case OMPD_section:
1154 case OMPD_single:
1155 case OMPD_master:
1156 case OMPD_critical:
1157 case OMPD_taskyield:
1158 case OMPD_barrier:
1159 case OMPD_taskwait:
1160 case OMPD_taskgroup:
1161 case OMPD_atomic:
1162 case OMPD_flush:
1163 case OMPD_teams:
1164 case OMPD_target_data:
1165 case OMPD_target_exit_data:
1166 case OMPD_target_enter_data:
1167 case OMPD_distribute:
1168 case OMPD_distribute_simd:
1169 case OMPD_distribute_parallel_for:
1170 case OMPD_distribute_parallel_for_simd:
1171 case OMPD_teams_distribute:
1172 case OMPD_teams_distribute_simd:
1173 case OMPD_teams_distribute_parallel_for:
1174 case OMPD_teams_distribute_parallel_for_simd:
1175 case OMPD_target_update:
1176 case OMPD_declare_simd:
1177 case OMPD_declare_target:
1178 case OMPD_end_declare_target:
1179 case OMPD_declare_reduction:
1180 case OMPD_taskloop:
1181 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001182 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001183 case OMPD_unknown:
1184 break;
1185 }
1186 llvm_unreachable(
1187 "Unknown programming model for OpenMP directive on NVPTX target.");
1188}
1189
1190void CGOpenMPRuntimeNVPTX::emitNonSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001191 StringRef ParentName,
1192 llvm::Function *&OutlinedFn,
1193 llvm::Constant *&OutlinedFnID,
1194 bool IsOffloadEntry,
1195 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001196 ExecutionRuntimeModesRAII ModeRAII(CurrentExecutionMode);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001197 EntryFunctionState EST;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001198 WorkerFunctionState WST(CGM, D.getBeginLoc());
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001199 Work.clear();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001200 WrapperFunctionsMap.clear();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001201
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001202 // Emit target region as a standalone region.
1203 class NVPTXPrePostActionTy : public PrePostActionTy {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001204 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1205 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001206
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001207 public:
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001208 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001209 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST)
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001210 : EST(EST), WST(WST) {}
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001211 void Enter(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001212 auto &RT =
1213 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001214 RT.emitNonSPMDEntryHeader(CGF, EST, WST);
1215 // Skip target region initialization.
1216 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001217 }
1218 void Exit(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001219 auto &RT =
1220 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001221 RT.clearLocThreadIdInsertPt(CGF);
1222 RT.emitNonSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001223 }
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001224 } Action(EST, WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001225 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001226 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001227 // Reserve place for the globalized memory.
1228 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001229 if (!KernelStaticGlobalized) {
1230 KernelStaticGlobalized = new llvm::GlobalVariable(
1231 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1232 llvm::GlobalValue::InternalLinkage,
1233 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1234 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1235 llvm::GlobalValue::NotThreadLocal,
1236 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1237 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001238 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1239 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001240 IsInTTDRegion = false;
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001241
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001242 // Now change the name of the worker function to correspond to this target
1243 // region's entry function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001244 WST.WorkerFn->setName(Twine(OutlinedFn->getName(), "_worker"));
Alexey Bataevaee93892018-01-08 20:09:47 +00001245
1246 // Create the worker function
1247 emitWorkerFunction(WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001248}
1249
1250// Setup NVPTX threads for master-worker OpenMP scheme.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001251void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryHeader(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001252 EntryFunctionState &EST,
1253 WorkerFunctionState &WST) {
1254 CGBuilderTy &Bld = CGF.Builder;
1255
1256 llvm::BasicBlock *WorkerBB = CGF.createBasicBlock(".worker");
1257 llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
1258 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
1259 EST.ExitBB = CGF.createBasicBlock(".exit");
1260
Alexey Bataev9ff80832018-04-16 20:16:21 +00001261 llvm::Value *IsWorker =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001262 Bld.CreateICmpULT(getNVPTXThreadID(CGF), getThreadLimit(CGF));
1263 Bld.CreateCondBr(IsWorker, WorkerBB, MasterCheckBB);
1264
1265 CGF.EmitBlock(WorkerBB);
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001266 emitCall(CGF, WST.Loc, WST.WorkerFn);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001267 CGF.EmitBranch(EST.ExitBB);
1268
1269 CGF.EmitBlock(MasterCheckBB);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001270 llvm::Value *IsMaster =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001271 Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
1272 Bld.CreateCondBr(IsMaster, MasterBB, EST.ExitBB);
1273
1274 CGF.EmitBlock(MasterBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001275 IsInTargetMasterThreadRegion = true;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001276 // SEQUENTIAL (MASTER) REGION START
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001277 // First action in sequential region:
1278 // Initialize the state of the OpenMP runtime library on the GPU.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001279 // TODO: Optimize runtime initialization and pass in correct value.
1280 llvm::Value *Args[] = {getThreadLimit(CGF),
1281 Bld.getInt16(/*RequiresOMPRuntime=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001282 CGF.EmitRuntimeCall(
1283 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_init), Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001284
1285 // For data sharing, we need to initialize the stack.
1286 CGF.EmitRuntimeCall(
1287 createNVPTXRuntimeFunction(
1288 OMPRTL_NVPTX__kmpc_data_sharing_init_stack));
1289
Alexey Bataevc99042b2018-03-15 18:10:54 +00001290 emitGenericVarsProlog(CGF, WST.Loc);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001291}
1292
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001293void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001294 EntryFunctionState &EST) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001295 IsInTargetMasterThreadRegion = false;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001296 if (!CGF.HaveInsertPoint())
1297 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001298
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001299 emitGenericVarsEpilog(CGF);
1300
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001301 if (!EST.ExitBB)
1302 EST.ExitBB = CGF.createBasicBlock(".exit");
1303
1304 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".termination.notifier");
1305 CGF.EmitBranch(TerminateBB);
1306
1307 CGF.EmitBlock(TerminateBB);
1308 // Signal termination condition.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001309 // TODO: Optimize runtime initialization and pass in correct value.
1310 llvm::Value *Args[] = {CGF.Builder.getInt16(/*IsOMPRuntimeInitialized=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001311 CGF.EmitRuntimeCall(
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001312 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_deinit), Args);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001313 // Barrier to terminate worker threads.
1314 syncCTAThreads(CGF);
1315 // Master thread jumps to exit point.
1316 CGF.EmitBranch(EST.ExitBB);
1317
1318 CGF.EmitBlock(EST.ExitBB);
1319 EST.ExitBB = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001320}
1321
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001322void CGOpenMPRuntimeNVPTX::emitSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001323 StringRef ParentName,
1324 llvm::Function *&OutlinedFn,
1325 llvm::Constant *&OutlinedFnID,
1326 bool IsOffloadEntry,
1327 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001328 ExecutionRuntimeModesRAII ModeRAII(
1329 CurrentExecutionMode, RequiresFullRuntime,
1330 CGM.getLangOpts().OpenMPCUDAForceFullRuntime ||
1331 !supportsLightweightRuntime(CGM.getContext(), D));
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001332 EntryFunctionState EST;
1333
1334 // Emit target region as a standalone region.
1335 class NVPTXPrePostActionTy : public PrePostActionTy {
1336 CGOpenMPRuntimeNVPTX &RT;
1337 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1338 const OMPExecutableDirective &D;
1339
1340 public:
1341 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT,
1342 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
1343 const OMPExecutableDirective &D)
1344 : RT(RT), EST(EST), D(D) {}
1345 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001346 RT.emitSPMDEntryHeader(CGF, EST, D);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001347 // Skip target region initialization.
1348 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001349 }
1350 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevfd006c42018-10-05 15:08:53 +00001351 RT.clearLocThreadIdInsertPt(CGF);
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001352 RT.emitSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001353 }
1354 } Action(*this, EST, D);
1355 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001356 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001357 // Reserve place for the globalized memory.
1358 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001359 if (!KernelStaticGlobalized) {
1360 KernelStaticGlobalized = new llvm::GlobalVariable(
1361 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1362 llvm::GlobalValue::InternalLinkage,
1363 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1364 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1365 llvm::GlobalValue::NotThreadLocal,
1366 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1367 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001368 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1369 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001370 IsInTTDRegion = false;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001371}
1372
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001373void CGOpenMPRuntimeNVPTX::emitSPMDEntryHeader(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001374 CodeGenFunction &CGF, EntryFunctionState &EST,
1375 const OMPExecutableDirective &D) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001376 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001377
1378 // Setup BBs in entry function.
1379 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute");
1380 EST.ExitBB = CGF.createBasicBlock(".exit");
1381
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001382 llvm::Value *Args[] = {getThreadLimit(CGF, /*IsInSPMDExecutionMode=*/true),
1383 /*RequiresOMPRuntime=*/
1384 Bld.getInt16(RequiresFullRuntime ? 1 : 0),
1385 /*RequiresDataSharing=*/Bld.getInt16(0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001386 CGF.EmitRuntimeCall(
1387 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_init), Args);
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001388
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001389 if (RequiresFullRuntime) {
1390 // For data sharing, we need to initialize the stack.
1391 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1392 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd));
1393 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001394
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001395 CGF.EmitBranch(ExecuteBB);
1396
1397 CGF.EmitBlock(ExecuteBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001398
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001399 IsInTargetMasterThreadRegion = true;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001400}
1401
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001402void CGOpenMPRuntimeNVPTX::emitSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001403 EntryFunctionState &EST) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001404 IsInTargetMasterThreadRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001405 if (!CGF.HaveInsertPoint())
1406 return;
1407
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001408 if (!EST.ExitBB)
1409 EST.ExitBB = CGF.createBasicBlock(".exit");
1410
1411 llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit");
1412 CGF.EmitBranch(OMPDeInitBB);
1413
1414 CGF.EmitBlock(OMPDeInitBB);
1415 // DeInitialize the OMP state in the runtime; called by all active threads.
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001416 llvm::Value *Args[] = {/*RequiresOMPRuntime=*/
1417 CGF.Builder.getInt16(RequiresFullRuntime ? 1 : 0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001418 CGF.EmitRuntimeCall(
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001419 createNVPTXRuntimeFunction(
1420 OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2), Args);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001421 CGF.EmitBranch(EST.ExitBB);
1422
1423 CGF.EmitBlock(EST.ExitBB);
1424 EST.ExitBB = nullptr;
1425}
1426
1427// Create a unique global variable to indicate the execution mode of this target
1428// region. The execution mode is either 'generic', or 'spmd' depending on the
1429// target directive. This variable is picked up by the offload library to setup
1430// the device appropriately before kernel launch. If the execution mode is
1431// 'generic', the runtime reserves one warp for the master, otherwise, all
1432// warps participate in parallel work.
1433static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001434 bool Mode) {
1435 auto *GVMode =
1436 new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
1437 llvm::GlobalValue::WeakAnyLinkage,
1438 llvm::ConstantInt::get(CGM.Int8Ty, Mode ? 0 : 1),
1439 Twine(Name, "_exec_mode"));
Alexey Bataev9ff80832018-04-16 20:16:21 +00001440 CGM.addCompilerUsedGlobal(GVMode);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001441}
1442
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001443void CGOpenMPRuntimeNVPTX::emitWorkerFunction(WorkerFunctionState &WST) {
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +00001444 ASTContext &Ctx = CGM.getContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001445
1446 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001447 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, WST.CGFI, {},
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001448 WST.Loc, WST.Loc);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001449 emitWorkerLoop(CGF, WST);
1450 CGF.FinishFunction();
1451}
1452
1453void CGOpenMPRuntimeNVPTX::emitWorkerLoop(CodeGenFunction &CGF,
1454 WorkerFunctionState &WST) {
1455 //
1456 // The workers enter this loop and wait for parallel work from the master.
1457 // When the master encounters a parallel region it sets up the work + variable
1458 // arguments, and wakes up the workers. The workers first check to see if
1459 // they are required for the parallel region, i.e., within the # of requested
1460 // parallel threads. The activated workers load the variable arguments and
1461 // execute the parallel work.
1462 //
1463
1464 CGBuilderTy &Bld = CGF.Builder;
1465
1466 llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work");
1467 llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers");
1468 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel");
1469 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel");
1470 llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel");
1471 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1472
1473 CGF.EmitBranch(AwaitBB);
1474
1475 // Workers wait for work from master.
1476 CGF.EmitBlock(AwaitBB);
1477 // Wait for parallel work
1478 syncCTAThreads(CGF);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001479
1480 Address WorkFn =
1481 CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn");
1482 Address ExecStatus =
1483 CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status");
1484 CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0));
1485 CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy));
1486
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001487 // TODO: Optimize runtime initialization and pass in correct value.
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001488 llvm::Value *Args[] = {WorkFn.getPointer(),
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001489 /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001490 llvm::Value *Ret = CGF.EmitRuntimeCall(
1491 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args);
1492 Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001493
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001494 // On termination condition (workid == 0), exit loop.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001495 llvm::Value *WorkID = Bld.CreateLoad(WorkFn);
1496 llvm::Value *ShouldTerminate = Bld.CreateIsNull(WorkID, "should_terminate");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001497 Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB);
1498
1499 // Activate requested workers.
1500 CGF.EmitBlock(SelectWorkersBB);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001501 llvm::Value *IsActive =
1502 Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active");
1503 Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001504
1505 // Signal start of parallel region.
1506 CGF.EmitBlock(ExecuteBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001507
1508 // Process work items: outlined parallel functions.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001509 for (llvm::Function *W : Work) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001510 // Try to match this outlined function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001511 llvm::Value *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001512
1513 llvm::Value *WorkFnMatch =
1514 Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match");
1515
1516 llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn");
1517 llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next");
1518 Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB);
1519
1520 // Execute this outlined function.
1521 CGF.EmitBlock(ExecuteFNBB);
1522
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001523 // Insert call to work function via shared wrapper. The shared
1524 // wrapper takes two arguments:
1525 // - the parallelism level;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001526 // - the thread ID;
1527 emitCall(CGF, WST.Loc, W,
1528 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001529
1530 // Go to end of parallel region.
1531 CGF.EmitBranch(TerminateBB);
1532
1533 CGF.EmitBlock(CheckNextBB);
1534 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001535 // Default case: call to outlined function through pointer if the target
1536 // region makes a declare target call that may contain an orphaned parallel
1537 // directive.
1538 auto *ParallelFnTy =
1539 llvm::FunctionType::get(CGM.VoidTy, {CGM.Int16Ty, CGM.Int32Ty},
1540 /*isVarArg=*/false)
1541 ->getPointerTo();
1542 llvm::Value *WorkFnCast = Bld.CreateBitCast(WorkID, ParallelFnTy);
1543 // Insert call to work function via shared wrapper. The shared
1544 // wrapper takes two arguments:
1545 // - the parallelism level;
1546 // - the thread ID;
1547 emitCall(CGF, WST.Loc, WorkFnCast,
1548 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
1549 // Go to end of parallel region.
1550 CGF.EmitBranch(TerminateBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001551
1552 // Signal end of parallel region.
1553 CGF.EmitBlock(TerminateBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001554 CGF.EmitRuntimeCall(
1555 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_end_parallel),
1556 llvm::None);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001557 CGF.EmitBranch(BarrierBB);
1558
1559 // All active and inactive workers wait at a barrier after parallel region.
1560 CGF.EmitBlock(BarrierBB);
1561 // Barrier after parallel region.
1562 syncCTAThreads(CGF);
1563 CGF.EmitBranch(AwaitBB);
1564
1565 // Exit target region.
1566 CGF.EmitBlock(ExitBB);
1567}
1568
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001569/// Returns specified OpenMP runtime function for the current OpenMP
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001570/// implementation. Specialized for the NVPTX device.
1571/// \param Function OpenMP runtime function.
1572/// \return Specified function.
1573llvm::Constant *
1574CGOpenMPRuntimeNVPTX::createNVPTXRuntimeFunction(unsigned Function) {
1575 llvm::Constant *RTLFn = nullptr;
1576 switch (static_cast<OpenMPRTLFunctionNVPTX>(Function)) {
1577 case OMPRTL_NVPTX__kmpc_kernel_init: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001578 // Build void __kmpc_kernel_init(kmp_int32 thread_limit, int16_t
1579 // RequiresOMPRuntime);
1580 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001581 auto *FnTy =
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001582 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1583 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_init");
1584 break;
1585 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001586 case OMPRTL_NVPTX__kmpc_kernel_deinit: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001587 // Build void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
1588 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001589 auto *FnTy =
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001590 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001591 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_deinit");
1592 break;
1593 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001594 case OMPRTL_NVPTX__kmpc_spmd_kernel_init: {
1595 // Build void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001596 // int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001597 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001598 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001599 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1600 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_init");
1601 break;
1602 }
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001603 case OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2: {
1604 // Build void __kmpc_spmd_kernel_deinit_v2(int16_t RequiresOMPRuntime);
1605 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001606 auto *FnTy =
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001607 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1608 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_deinit_v2");
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001609 break;
1610 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001611 case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: {
1612 /// Build void __kmpc_kernel_prepare_parallel(
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001613 /// void *outlined_function, int16_t IsOMPRuntimeInitialized);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001614 llvm::Type *TypeParams[] = {CGM.Int8PtrTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001615 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001616 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1617 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_prepare_parallel");
1618 break;
1619 }
1620 case OMPRTL_NVPTX__kmpc_kernel_parallel: {
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001621 /// Build bool __kmpc_kernel_parallel(void **outlined_function,
1622 /// int16_t IsOMPRuntimeInitialized);
1623 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy, CGM.Int16Ty};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001624 llvm::Type *RetTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001625 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001626 llvm::FunctionType::get(RetTy, TypeParams, /*isVarArg*/ false);
1627 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_parallel");
1628 break;
1629 }
1630 case OMPRTL_NVPTX__kmpc_kernel_end_parallel: {
1631 /// Build void __kmpc_kernel_end_parallel();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001632 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001633 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1634 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_end_parallel");
1635 break;
1636 }
1637 case OMPRTL_NVPTX__kmpc_serialized_parallel: {
1638 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1639 // global_tid);
1640 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001641 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001642 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1643 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1644 break;
1645 }
1646 case OMPRTL_NVPTX__kmpc_end_serialized_parallel: {
1647 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1648 // global_tid);
1649 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001650 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001651 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1652 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1653 break;
1654 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001655 case OMPRTL_NVPTX__kmpc_shuffle_int32: {
1656 // Build int32_t __kmpc_shuffle_int32(int32_t element,
1657 // int16_t lane_offset, int16_t warp_size);
1658 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001659 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001660 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1661 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int32");
1662 break;
1663 }
1664 case OMPRTL_NVPTX__kmpc_shuffle_int64: {
1665 // Build int64_t __kmpc_shuffle_int64(int64_t element,
1666 // int16_t lane_offset, int16_t warp_size);
1667 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001668 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001669 llvm::FunctionType::get(CGM.Int64Ty, TypeParams, /*isVarArg*/ false);
1670 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int64");
1671 break;
1672 }
1673 case OMPRTL_NVPTX__kmpc_parallel_reduce_nowait: {
1674 // Build int32_t kmpc_nvptx_parallel_reduce_nowait(kmp_int32 global_tid,
1675 // kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
1676 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1677 // lane_offset, int16_t Algorithm Version),
1678 // void (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
1679 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1680 CGM.Int16Ty, CGM.Int16Ty};
1681 auto *ShuffleReduceFnTy =
1682 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1683 /*isVarArg=*/false);
1684 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1685 auto *InterWarpCopyFnTy =
1686 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1687 /*isVarArg=*/false);
1688 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1689 CGM.Int32Ty,
1690 CGM.SizeTy,
1691 CGM.VoidPtrTy,
1692 ShuffleReduceFnTy->getPointerTo(),
1693 InterWarpCopyFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001694 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001695 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1696 RTLFn = CGM.CreateRuntimeFunction(
1697 FnTy, /*Name=*/"__kmpc_nvptx_parallel_reduce_nowait");
1698 break;
1699 }
1700 case OMPRTL_NVPTX__kmpc_end_reduce_nowait: {
1701 // Build __kmpc_end_reduce_nowait(kmp_int32 global_tid);
1702 llvm::Type *TypeParams[] = {CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001703 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001704 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1705 RTLFn = CGM.CreateRuntimeFunction(
1706 FnTy, /*Name=*/"__kmpc_nvptx_end_reduce_nowait");
1707 break;
1708 }
Alexey Bataeva1166022018-11-27 21:24:54 +00001709 case OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_simple: {
1710 // Build __kmpc_nvptx_teams_reduce_nowait_simple(ident_t *loc, kmp_int32
1711 // global_tid, kmp_critical_name *lck)
1712 llvm::Type *TypeParams[] = {
1713 getIdentTyPointerTy(), CGM.Int32Ty,
1714 llvm::PointerType::getUnqual(getKmpCriticalNameTy())};
1715 auto *FnTy =
1716 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1717 RTLFn = CGM.CreateRuntimeFunction(
1718 FnTy, /*Name=*/"__kmpc_nvptx_teams_reduce_nowait_simple");
1719 break;
1720 }
1721 case OMPRTL_NVPTX__kmpc_nvptx_teams_end_reduce_nowait_simple: {
1722 // Build __kmpc_nvptx_teams_end_reduce_nowait_simple(ident_t *loc, kmp_int32
1723 // global_tid, kmp_critical_name *lck)
1724 llvm::Type *TypeParams[] = {
1725 getIdentTyPointerTy(), CGM.Int32Ty,
1726 llvm::PointerType::getUnqual(getKmpCriticalNameTy())};
1727 auto *FnTy =
1728 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1729 RTLFn = CGM.CreateRuntimeFunction(
1730 FnTy, /*Name=*/"__kmpc_nvptx_teams_end_reduce_nowait_simple");
1731 break;
1732 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001733 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack: {
1734 /// Build void __kmpc_data_sharing_init_stack();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001735 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001736 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1737 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack");
1738 break;
1739 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001740 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd: {
1741 /// Build void __kmpc_data_sharing_init_stack_spmd();
1742 auto *FnTy =
1743 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001744 RTLFn =
1745 CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack_spmd");
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001746 break;
1747 }
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001748 case OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack: {
1749 // Build void *__kmpc_data_sharing_coalesced_push_stack(size_t size,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001750 // int16_t UseSharedMemory);
1751 llvm::Type *TypeParams[] = {CGM.SizeTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001752 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001753 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1754 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001755 FnTy, /*Name=*/"__kmpc_data_sharing_coalesced_push_stack");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001756 break;
1757 }
1758 case OMPRTL_NVPTX__kmpc_data_sharing_pop_stack: {
1759 // Build void __kmpc_data_sharing_pop_stack(void *a);
1760 llvm::Type *TypeParams[] = {CGM.VoidPtrTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001761 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001762 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1763 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1764 /*Name=*/"__kmpc_data_sharing_pop_stack");
1765 break;
1766 }
1767 case OMPRTL_NVPTX__kmpc_begin_sharing_variables: {
1768 /// Build void __kmpc_begin_sharing_variables(void ***args,
1769 /// size_t n_args);
1770 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo(), CGM.SizeTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001771 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001772 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1773 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_begin_sharing_variables");
1774 break;
1775 }
1776 case OMPRTL_NVPTX__kmpc_end_sharing_variables: {
1777 /// Build void __kmpc_end_sharing_variables();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001778 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001779 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1780 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_sharing_variables");
1781 break;
1782 }
1783 case OMPRTL_NVPTX__kmpc_get_shared_variables: {
1784 /// Build void __kmpc_get_shared_variables(void ***GlobalArgs);
1785 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001786 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001787 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1788 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_shared_variables");
1789 break;
1790 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001791 case OMPRTL_NVPTX__kmpc_parallel_level: {
1792 // Build uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32 global_tid);
1793 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1794 auto *FnTy =
1795 llvm::FunctionType::get(CGM.Int16Ty, TypeParams, /*isVarArg*/ false);
1796 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_parallel_level");
1797 break;
1798 }
Alexey Bataev673110d2018-05-16 13:36:30 +00001799 case OMPRTL_NVPTX__kmpc_is_spmd_exec_mode: {
1800 // Build int8_t __kmpc_is_spmd_exec_mode();
1801 auto *FnTy = llvm::FunctionType::get(CGM.Int8Ty, /*isVarArg=*/false);
1802 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_is_spmd_exec_mode");
1803 break;
1804 }
Alexey Bataeve4090182018-11-02 14:54:07 +00001805 case OMPRTL_NVPTX__kmpc_get_team_static_memory: {
1806 // Build void __kmpc_get_team_static_memory(const void *buf, size_t size,
1807 // int16_t is_shared, const void **res);
1808 llvm::Type *TypeParams[] = {CGM.VoidPtrTy, CGM.SizeTy, CGM.Int16Ty,
1809 CGM.VoidPtrPtrTy};
1810 auto *FnTy =
1811 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1812 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_team_static_memory");
1813 break;
1814 }
1815 case OMPRTL_NVPTX__kmpc_restore_team_static_memory: {
1816 // Build void __kmpc_restore_team_static_memory(int16_t is_shared);
1817 auto *FnTy =
1818 llvm::FunctionType::get(CGM.VoidTy, CGM.Int16Ty, /*isVarArg=*/false);
1819 RTLFn =
1820 CGM.CreateRuntimeFunction(FnTy, "__kmpc_restore_team_static_memory");
1821 break;
1822 }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001823 }
1824 return RTLFn;
1825}
1826
1827void CGOpenMPRuntimeNVPTX::createOffloadEntry(llvm::Constant *ID,
1828 llvm::Constant *Addr,
Alexey Bataev03f270c2018-03-30 18:31:07 +00001829 uint64_t Size, int32_t,
1830 llvm::GlobalValue::LinkageTypes) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001831 // TODO: Add support for global variables on the device after declare target
1832 // support.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001833 if (!isa<llvm::Function>(Addr))
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001834 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +00001835 llvm::Module &M = CGM.getModule();
1836 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001837
1838 // Get "nvvm.annotations" metadata node
Alexey Bataev9ff80832018-04-16 20:16:21 +00001839 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001840
1841 llvm::Metadata *MDVals[] = {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001842 llvm::ConstantAsMetadata::get(Addr), llvm::MDString::get(Ctx, "kernel"),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001843 llvm::ConstantAsMetadata::get(
1844 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))};
1845 // Append metadata to nvvm.annotations
1846 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
1847}
1848
1849void CGOpenMPRuntimeNVPTX::emitTargetOutlinedFunction(
1850 const OMPExecutableDirective &D, StringRef ParentName,
1851 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001852 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001853 if (!IsOffloadEntry) // Nothing to do.
1854 return;
1855
1856 assert(!ParentName.empty() && "Invalid target region parent name!");
1857
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001858 bool Mode = supportsSPMDExecutionMode(CGM.getContext(), D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001859 if (Mode)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001860 emitSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001861 CodeGen);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001862 else
1863 emitNonSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1864 CodeGen);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001865
1866 setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001867}
1868
Alexey Bataevceeaa482018-11-21 21:04:34 +00001869namespace {
1870LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
1871/// Enum for accesseing the reserved_2 field of the ident_t struct.
1872enum ModeFlagsTy : unsigned {
1873 /// Bit set to 1 when in SPMD mode.
1874 KMP_IDENT_SPMD_MODE = 0x01,
1875 /// Bit set to 1 when a simplified runtime is used.
1876 KMP_IDENT_SIMPLE_RT_MODE = 0x02,
1877 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/KMP_IDENT_SIMPLE_RT_MODE)
1878};
1879
1880/// Special mode Undefined. Is the combination of Non-SPMD mode + SimpleRuntime.
1881static const ModeFlagsTy UndefinedMode =
1882 (~KMP_IDENT_SPMD_MODE) & KMP_IDENT_SIMPLE_RT_MODE;
1883} // anonymous namespace
1884
1885unsigned CGOpenMPRuntimeNVPTX::getDefaultLocationReserved2Flags() const {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001886 switch (getExecutionMode()) {
1887 case EM_SPMD:
1888 if (requiresFullRuntime())
1889 return KMP_IDENT_SPMD_MODE & (~KMP_IDENT_SIMPLE_RT_MODE);
1890 return KMP_IDENT_SPMD_MODE | KMP_IDENT_SIMPLE_RT_MODE;
1891 case EM_NonSPMD:
1892 assert(requiresFullRuntime() && "Expected full runtime.");
1893 return (~KMP_IDENT_SPMD_MODE) & (~KMP_IDENT_SIMPLE_RT_MODE);
1894 case EM_Unknown:
1895 return UndefinedMode;
1896 }
1897 llvm_unreachable("Unknown flags are requested.");
Alexey Bataevceeaa482018-11-21 21:04:34 +00001898}
1899
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001900CGOpenMPRuntimeNVPTX::CGOpenMPRuntimeNVPTX(CodeGenModule &CGM)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001901 : CGOpenMPRuntime(CGM, "_", "$") {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001902 if (!CGM.getLangOpts().OpenMPIsDevice)
1903 llvm_unreachable("OpenMP NVPTX can only handle device code.");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001904}
Carlo Bertollic6872252016-04-04 15:55:02 +00001905
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001906void CGOpenMPRuntimeNVPTX::emitProcBindClause(CodeGenFunction &CGF,
1907 OpenMPProcBindClauseKind ProcBind,
1908 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001909 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001910 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001911 return;
1912
1913 CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc);
1914}
1915
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001916void CGOpenMPRuntimeNVPTX::emitNumThreadsClause(CodeGenFunction &CGF,
1917 llvm::Value *NumThreads,
1918 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001919 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001920 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001921 return;
1922
1923 CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc);
1924}
1925
Carlo Bertollic6872252016-04-04 15:55:02 +00001926void CGOpenMPRuntimeNVPTX::emitNumTeamsClause(CodeGenFunction &CGF,
1927 const Expr *NumTeams,
1928 const Expr *ThreadLimit,
1929 SourceLocation Loc) {}
1930
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001931llvm::Value *CGOpenMPRuntimeNVPTX::emitParallelOutlinedFunction(
1932 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1933 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00001934 // Emit target region as a standalone region.
1935 class NVPTXPrePostActionTy : public PrePostActionTy {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001936 bool &IsInParallelRegion;
1937 bool PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001938
1939 public:
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001940 NVPTXPrePostActionTy(bool &IsInParallelRegion)
1941 : IsInParallelRegion(IsInParallelRegion) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00001942 void Enter(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001943 PrevIsInParallelRegion = IsInParallelRegion;
1944 IsInParallelRegion = true;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001945 }
1946 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001947 IsInParallelRegion = PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001948 }
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001949 } Action(IsInParallelRegion);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001950 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001951 bool PrevIsInTTDRegion = IsInTTDRegion;
1952 IsInTTDRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001953 bool PrevIsInTargetMasterThreadRegion = IsInTargetMasterThreadRegion;
1954 IsInTargetMasterThreadRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001955 auto *OutlinedFun =
1956 cast<llvm::Function>(CGOpenMPRuntime::emitParallelOutlinedFunction(
1957 D, ThreadIDVar, InnermostKind, CodeGen));
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001958 IsInTargetMasterThreadRegion = PrevIsInTargetMasterThreadRegion;
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001959 IsInTTDRegion = PrevIsInTTDRegion;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001960 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD &&
1961 !IsInParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001962 llvm::Function *WrapperFun =
1963 createParallelDataSharingWrapper(OutlinedFun, D);
1964 WrapperFunctionsMap[OutlinedFun] = WrapperFun;
1965 }
1966
1967 return OutlinedFun;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001968}
1969
Alexey Bataev2adecff2018-09-21 14:22:53 +00001970/// Get list of lastprivate variables from the teams distribute ... or
1971/// teams {distribute ...} directives.
1972static void
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001973getDistributeLastprivateVars(ASTContext &Ctx, const OMPExecutableDirective &D,
Alexey Bataev2adecff2018-09-21 14:22:53 +00001974 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
1975 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
1976 "expected teams directive.");
1977 const OMPExecutableDirective *Dir = &D;
1978 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
1979 if (const Stmt *S = getSingleCompoundChild(
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001980 Ctx,
Alexey Bataev2adecff2018-09-21 14:22:53 +00001981 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
1982 /*IgnoreCaptured=*/true))) {
1983 Dir = dyn_cast<OMPExecutableDirective>(S);
1984 if (Dir && !isOpenMPDistributeDirective(Dir->getDirectiveKind()))
1985 Dir = nullptr;
1986 }
1987 }
1988 if (!Dir)
1989 return;
Alexey Bataev9ea3c382018-10-09 14:49:00 +00001990 for (const auto *C : Dir->getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00001991 for (const Expr *E : C->getVarRefs())
1992 Vars.push_back(getPrivateItem(E));
1993 }
1994}
1995
1996/// Get list of reduction variables from the teams ... directives.
1997static void
1998getTeamsReductionVars(ASTContext &Ctx, const OMPExecutableDirective &D,
1999 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
2000 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
2001 "expected teams directive.");
2002 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
2003 for (const Expr *E : C->privates())
2004 Vars.push_back(getPrivateItem(E));
Alexey Bataev2adecff2018-09-21 14:22:53 +00002005 }
2006}
2007
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002008llvm::Value *CGOpenMPRuntimeNVPTX::emitTeamsOutlinedFunction(
Carlo Bertollic6872252016-04-04 15:55:02 +00002009 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
2010 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002011 SourceLocation Loc = D.getBeginLoc();
Carlo Bertollic6872252016-04-04 15:55:02 +00002012
Alexey Bataev2adecff2018-09-21 14:22:53 +00002013 const RecordDecl *GlobalizedRD = nullptr;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002014 llvm::SmallVector<const ValueDecl *, 4> LastPrivatesReductions;
Alexey Bataev2adecff2018-09-21 14:22:53 +00002015 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002016 // Globalize team reductions variable unconditionally in all modes.
2017 getTeamsReductionVars(CGM.getContext(), D, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002018 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002019 getDistributeLastprivateVars(CGM.getContext(), D, LastPrivatesReductions);
2020 if (!LastPrivatesReductions.empty()) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002021 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002022 CGM.getContext(), llvm::None, LastPrivatesReductions,
2023 MappedDeclsFields);
2024 }
2025 } else if (!LastPrivatesReductions.empty()) {
2026 assert(!TeamAndReductions.first &&
2027 "Previous team declaration is not expected.");
2028 TeamAndReductions.first = D.getCapturedStmt(OMPD_teams)->getCapturedDecl();
2029 std::swap(TeamAndReductions.second, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002030 }
2031
Alexey Bataevc99042b2018-03-15 18:10:54 +00002032 // Emit target region as a standalone region.
2033 class NVPTXPrePostActionTy : public PrePostActionTy {
2034 SourceLocation &Loc;
Alexey Bataev2adecff2018-09-21 14:22:53 +00002035 const RecordDecl *GlobalizedRD;
2036 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2037 &MappedDeclsFields;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002038
2039 public:
Alexey Bataev2adecff2018-09-21 14:22:53 +00002040 NVPTXPrePostActionTy(
2041 SourceLocation &Loc, const RecordDecl *GlobalizedRD,
2042 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2043 &MappedDeclsFields)
2044 : Loc(Loc), GlobalizedRD(GlobalizedRD),
2045 MappedDeclsFields(MappedDeclsFields) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00002046 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002047 auto &Rt =
2048 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
2049 if (GlobalizedRD) {
2050 auto I = Rt.FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
2051 I->getSecond().GlobalRecord = GlobalizedRD;
2052 I->getSecond().MappedParams =
2053 llvm::make_unique<CodeGenFunction::OMPMapVars>();
2054 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
2055 for (const auto &Pair : MappedDeclsFields) {
2056 assert(Pair.getFirst()->isCanonicalDecl() &&
2057 "Expected canonical declaration");
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002058 Data.insert(std::make_pair(Pair.getFirst(),
2059 MappedVarData(Pair.getSecond(),
2060 /*IsOnePerTeam=*/true)));
Alexey Bataev2adecff2018-09-21 14:22:53 +00002061 }
2062 }
2063 Rt.emitGenericVarsProlog(CGF, Loc);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002064 }
2065 void Exit(CodeGenFunction &CGF) override {
2066 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
2067 .emitGenericVarsEpilog(CGF);
2068 }
Alexey Bataev2adecff2018-09-21 14:22:53 +00002069 } Action(Loc, GlobalizedRD, MappedDeclsFields);
2070 CodeGen.setAction(Action);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002071 llvm::Value *OutlinedFunVal = CGOpenMPRuntime::emitTeamsOutlinedFunction(
2072 D, ThreadIDVar, InnermostKind, CodeGen);
2073 llvm::Function *OutlinedFun = cast<llvm::Function>(OutlinedFunVal);
2074 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00002075 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002076 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
Carlo Bertollic6872252016-04-04 15:55:02 +00002077
2078 return OutlinedFun;
2079}
2080
Alexey Bataevc99042b2018-03-15 18:10:54 +00002081void CGOpenMPRuntimeNVPTX::emitGenericVarsProlog(CodeGenFunction &CGF,
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002082 SourceLocation Loc,
2083 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002084 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2085 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002086 return;
2087
Alexey Bataevc99042b2018-03-15 18:10:54 +00002088 CGBuilderTy &Bld = CGF.Builder;
2089
2090 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
2091 if (I == FunctionGlobalizedDecls.end())
2092 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002093 if (const RecordDecl *GlobalizedVarsRecord = I->getSecond().GlobalRecord) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002094 QualType GlobalRecTy = CGM.getContext().getRecordType(GlobalizedVarsRecord);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002095 QualType SecGlobalRecTy;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002096
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002097 // Recover pointer to this function's global record. The runtime will
2098 // handle the specifics of the allocation of the memory.
2099 // Use actual memory size of the record including the padding
2100 // for alignment purposes.
2101 unsigned Alignment =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002102 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002103 unsigned GlobalRecordSize =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002104 CGM.getContext().getTypeSizeInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002105 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002106
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002107 llvm::PointerType *GlobalRecPtrTy =
2108 CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo();
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002109 llvm::Value *GlobalRecCastAddr;
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002110 llvm::Value *IsTTD = nullptr;
Alexey Bataeve4090182018-11-02 14:54:07 +00002111 if (!IsInTTDRegion &&
2112 (WithSPMDCheck ||
2113 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002114 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2115 llvm::BasicBlock *SPMDBB = CGF.createBasicBlock(".spmd");
2116 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002117 if (I->getSecond().SecondaryGlobalRecord.hasValue()) {
2118 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2119 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2120 llvm::Value *PL = CGF.EmitRuntimeCall(
2121 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2122 {RTLoc, ThreadID});
2123 IsTTD = Bld.CreateIsNull(PL);
2124 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002125 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2126 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
2127 Bld.CreateCondBr(IsSPMD, SPMDBB, NonSPMDBB);
2128 // There is no need to emit line number for unconditional branch.
2129 (void)ApplyDebugLocation::CreateEmpty(CGF);
2130 CGF.EmitBlock(SPMDBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002131 Address RecPtr = Address(llvm::ConstantPointerNull::get(GlobalRecPtrTy),
2132 CharUnits::fromQuantity(Alignment));
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002133 CGF.EmitBranch(ExitBB);
2134 // There is no need to emit line number for unconditional branch.
2135 (void)ApplyDebugLocation::CreateEmpty(CGF);
2136 CGF.EmitBlock(NonSPMDBB);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002137 llvm::Value *Size = llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize);
2138 if (const RecordDecl *SecGlobalizedVarsRecord =
2139 I->getSecond().SecondaryGlobalRecord.getValueOr(nullptr)) {
2140 SecGlobalRecTy =
2141 CGM.getContext().getRecordType(SecGlobalizedVarsRecord);
2142
2143 // Recover pointer to this function's global record. The runtime will
2144 // handle the specifics of the allocation of the memory.
2145 // Use actual memory size of the record including the padding
2146 // for alignment purposes.
2147 unsigned Alignment =
2148 CGM.getContext().getTypeAlignInChars(SecGlobalRecTy).getQuantity();
2149 unsigned GlobalRecordSize =
2150 CGM.getContext().getTypeSizeInChars(SecGlobalRecTy).getQuantity();
2151 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
2152 Size = Bld.CreateSelect(
2153 IsTTD, llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize), Size);
2154 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002155 // TODO: allow the usage of shared memory to be controlled by
2156 // the user, for now, default to global.
2157 llvm::Value *GlobalRecordSizeArg[] = {
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002158 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002159 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2160 createNVPTXRuntimeFunction(
2161 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2162 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002163 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002164 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002165 CGF.EmitBlock(ExitBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002166 auto *Phi = Bld.CreatePHI(GlobalRecPtrTy,
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002167 /*NumReservedValues=*/2, "_select_stack");
2168 Phi->addIncoming(RecPtr.getPointer(), SPMDBB);
2169 Phi->addIncoming(GlobalRecCastAddr, NonSPMDBB);
2170 GlobalRecCastAddr = Phi;
2171 I->getSecond().GlobalRecordAddr = Phi;
2172 I->getSecond().IsInSPMDModeFlag = IsSPMD;
Alexey Bataeve4090182018-11-02 14:54:07 +00002173 } else if (IsInTTDRegion) {
2174 assert(GlobalizedRecords.back().Records.size() < 2 &&
2175 "Expected less than 2 globalized records: one for target and one "
2176 "for teams.");
2177 unsigned Offset = 0;
2178 for (const RecordDecl *RD : GlobalizedRecords.back().Records) {
2179 QualType RDTy = CGM.getContext().getRecordType(RD);
2180 unsigned Alignment =
2181 CGM.getContext().getTypeAlignInChars(RDTy).getQuantity();
2182 unsigned Size = CGM.getContext().getTypeSizeInChars(RDTy).getQuantity();
2183 Offset =
2184 llvm::alignTo(llvm::alignTo(Offset, Alignment) + Size, Alignment);
2185 }
2186 unsigned Alignment =
2187 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
2188 Offset = llvm::alignTo(Offset, Alignment);
2189 GlobalizedRecords.back().Records.push_back(GlobalizedVarsRecord);
2190 ++GlobalizedRecords.back().RegionCounter;
2191 if (GlobalizedRecords.back().Records.size() == 1) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002192 assert(KernelStaticGlobalized &&
2193 "Kernel static pointer must be initialized already.");
2194 auto *UseSharedMemory = new llvm::GlobalVariable(
2195 CGM.getModule(), CGM.Int16Ty, /*isConstant=*/true,
2196 llvm::GlobalValue::InternalLinkage, nullptr,
2197 "_openmp_static_kernel$is_shared");
2198 UseSharedMemory->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2199 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2200 /*DestWidth=*/16, /*Signed=*/0);
2201 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2202 Address(UseSharedMemory,
2203 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2204 /*Volatile=*/false, Int16Ty, Loc);
2205 auto *StaticGlobalized = new llvm::GlobalVariable(
2206 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002207 llvm::GlobalValue::CommonLinkage, nullptr);
Alexey Bataeve4090182018-11-02 14:54:07 +00002208 auto *RecSize = new llvm::GlobalVariable(
2209 CGM.getModule(), CGM.SizeTy, /*isConstant=*/true,
2210 llvm::GlobalValue::InternalLinkage, nullptr,
2211 "_openmp_static_kernel$size");
2212 RecSize->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2213 llvm::Value *Ld = CGF.EmitLoadOfScalar(
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002214 Address(RecSize, CGM.getSizeAlign()), /*Volatile=*/false,
Alexey Bataeve4090182018-11-02 14:54:07 +00002215 CGM.getContext().getSizeType(), Loc);
2216 llvm::Value *ResAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2217 KernelStaticGlobalized, CGM.VoidPtrPtrTy);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002218 llvm::Value *GlobalRecordSizeArg[] = {StaticGlobalized, Ld,
2219 IsInSharedMemory, ResAddr};
Alexey Bataeve4090182018-11-02 14:54:07 +00002220 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2221 OMPRTL_NVPTX__kmpc_get_team_static_memory),
2222 GlobalRecordSizeArg);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002223 GlobalizedRecords.back().Buffer = StaticGlobalized;
Alexey Bataeve4090182018-11-02 14:54:07 +00002224 GlobalizedRecords.back().RecSize = RecSize;
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002225 GlobalizedRecords.back().UseSharedMemory = UseSharedMemory;
2226 GlobalizedRecords.back().Loc = Loc;
Alexey Bataeve4090182018-11-02 14:54:07 +00002227 }
2228 assert(KernelStaticGlobalized && "Global address must be set already.");
2229 Address FrameAddr = CGF.EmitLoadOfPointer(
2230 Address(KernelStaticGlobalized, CGM.getPointerAlign()),
2231 CGM.getContext()
2232 .getPointerType(CGM.getContext().VoidPtrTy)
2233 .castAs<PointerType>());
2234 llvm::Value *GlobalRecValue =
2235 Bld.CreateConstInBoundsGEP(FrameAddr, Offset, CharUnits::One())
2236 .getPointer();
2237 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2238 I->getSecond().IsInSPMDModeFlag = nullptr;
2239 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2240 GlobalRecValue, CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo());
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002241 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002242 // TODO: allow the usage of shared memory to be controlled by
2243 // the user, for now, default to global.
2244 llvm::Value *GlobalRecordSizeArg[] = {
2245 llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize),
2246 CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002247 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2248 createNVPTXRuntimeFunction(
2249 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2250 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002251 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002252 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002253 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2254 I->getSecond().IsInSPMDModeFlag = nullptr;
2255 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002256 LValue Base =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002257 CGF.MakeNaturalAlignPointeeAddrLValue(GlobalRecCastAddr, GlobalRecTy);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002258
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002259 // Emit the "global alloca" which is a GEP from the global declaration
2260 // record using the pointer returned by the runtime.
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002261 LValue SecBase;
2262 decltype(I->getSecond().LocalVarData)::const_iterator SecIt;
2263 if (IsTTD) {
2264 SecIt = I->getSecond().SecondaryLocalVarData->begin();
2265 llvm::PointerType *SecGlobalRecPtrTy =
2266 CGF.ConvertTypeForMem(SecGlobalRecTy)->getPointerTo();
2267 SecBase = CGF.MakeNaturalAlignPointeeAddrLValue(
2268 Bld.CreatePointerBitCastOrAddrSpaceCast(
2269 I->getSecond().GlobalRecordAddr, SecGlobalRecPtrTy),
2270 SecGlobalRecTy);
2271 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002272 for (auto &Rec : I->getSecond().LocalVarData) {
2273 bool EscapedParam = I->getSecond().EscapedParameters.count(Rec.first);
2274 llvm::Value *ParValue;
2275 if (EscapedParam) {
2276 const auto *VD = cast<VarDecl>(Rec.first);
2277 LValue ParLVal =
2278 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
2279 ParValue = CGF.EmitLoadOfScalar(ParLVal, Loc);
2280 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002281 LValue VarAddr = CGF.EmitLValueForField(Base, Rec.second.FD);
2282 // Emit VarAddr basing on lane-id if required.
2283 QualType VarTy;
2284 if (Rec.second.IsOnePerTeam) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002285 VarTy = Rec.second.FD->getType();
2286 } else {
2287 llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(
2288 VarAddr.getAddress().getPointer(),
2289 {Bld.getInt32(0), getNVPTXLaneID(CGF)});
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002290 VarTy =
2291 Rec.second.FD->getType()->castAsArrayTypeUnsafe()->getElementType();
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002292 VarAddr = CGF.MakeAddrLValue(
2293 Address(Ptr, CGM.getContext().getDeclAlign(Rec.first)), VarTy,
2294 AlignmentSource::Decl);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002295 }
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002296 Rec.second.PrivateAddr = VarAddr.getAddress();
Alexey Bataeve4090182018-11-02 14:54:07 +00002297 if (!IsInTTDRegion &&
2298 (WithSPMDCheck ||
2299 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002300 assert(I->getSecond().IsInSPMDModeFlag &&
2301 "Expected unknown execution mode or required SPMD check.");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002302 if (IsTTD) {
2303 assert(SecIt->second.IsOnePerTeam &&
2304 "Secondary glob data must be one per team.");
2305 LValue SecVarAddr = CGF.EmitLValueForField(SecBase, SecIt->second.FD);
2306 VarAddr.setAddress(
2307 Address(Bld.CreateSelect(IsTTD, SecVarAddr.getPointer(),
2308 VarAddr.getPointer()),
2309 VarAddr.getAlignment()));
2310 Rec.second.PrivateAddr = VarAddr.getAddress();
2311 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002312 Address GlobalPtr = Rec.second.PrivateAddr;
2313 Address LocalAddr = CGF.CreateMemTemp(VarTy, Rec.second.FD->getName());
2314 Rec.second.PrivateAddr = Address(
2315 Bld.CreateSelect(I->getSecond().IsInSPMDModeFlag,
2316 LocalAddr.getPointer(), GlobalPtr.getPointer()),
2317 LocalAddr.getAlignment());
2318 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002319 if (EscapedParam) {
2320 const auto *VD = cast<VarDecl>(Rec.first);
2321 CGF.EmitStoreOfScalar(ParValue, VarAddr);
2322 I->getSecond().MappedParams->setVarAddr(CGF, VD, VarAddr.getAddress());
2323 }
Alexey Bataev93a38d62018-10-16 00:09:06 +00002324 if (IsTTD)
2325 ++SecIt;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002326 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002327 }
2328 for (const ValueDecl *VD : I->getSecond().EscapedVariableLengthDecls) {
2329 // Recover pointer to this function's global record. The runtime will
2330 // handle the specifics of the allocation of the memory.
2331 // Use actual memory size of the record including the padding
2332 // for alignment purposes.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002333 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002334 llvm::Value *Size = CGF.getTypeSize(VD->getType());
2335 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2336 Size = Bld.CreateNUWAdd(
2337 Size, llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity() - 1));
2338 llvm::Value *AlignVal =
2339 llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity());
2340 Size = Bld.CreateUDiv(Size, AlignVal);
2341 Size = Bld.CreateNUWMul(Size, AlignVal);
2342 // TODO: allow the usage of shared memory to be controlled by
2343 // the user, for now, default to global.
2344 llvm::Value *GlobalRecordSizeArg[] = {
2345 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
2346 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002347 createNVPTXRuntimeFunction(
2348 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002349 GlobalRecordSizeArg);
2350 llvm::Value *GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2351 GlobalRecValue, CGF.ConvertTypeForMem(VD->getType())->getPointerTo());
2352 LValue Base = CGF.MakeAddrLValue(GlobalRecCastAddr, VD->getType(),
2353 CGM.getContext().getDeclAlign(VD),
2354 AlignmentSource::Decl);
2355 I->getSecond().MappedParams->setVarAddr(CGF, cast<VarDecl>(VD),
2356 Base.getAddress());
2357 I->getSecond().EscapedVariableLengthDeclsAddrs.emplace_back(GlobalRecValue);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002358 }
2359 I->getSecond().MappedParams->apply(CGF);
2360}
2361
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002362void CGOpenMPRuntimeNVPTX::emitGenericVarsEpilog(CodeGenFunction &CGF,
2363 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002364 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2365 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002366 return;
2367
Alexey Bataevc99042b2018-03-15 18:10:54 +00002368 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002369 if (I != FunctionGlobalizedDecls.end()) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00002370 I->getSecond().MappedParams->restore(CGF);
2371 if (!CGF.HaveInsertPoint())
2372 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002373 for (llvm::Value *Addr :
2374 llvm::reverse(I->getSecond().EscapedVariableLengthDeclsAddrs)) {
2375 CGF.EmitRuntimeCall(
2376 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2377 Addr);
2378 }
2379 if (I->getSecond().GlobalRecordAddr) {
Alexey Bataeve4090182018-11-02 14:54:07 +00002380 if (!IsInTTDRegion &&
2381 (WithSPMDCheck ||
2382 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002383 CGBuilderTy &Bld = CGF.Builder;
2384 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2385 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
2386 Bld.CreateCondBr(I->getSecond().IsInSPMDModeFlag, ExitBB, NonSPMDBB);
2387 // There is no need to emit line number for unconditional branch.
2388 (void)ApplyDebugLocation::CreateEmpty(CGF);
2389 CGF.EmitBlock(NonSPMDBB);
2390 CGF.EmitRuntimeCall(
2391 createNVPTXRuntimeFunction(
2392 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2393 CGF.EmitCastToVoidPtr(I->getSecond().GlobalRecordAddr));
2394 CGF.EmitBlock(ExitBB);
Alexey Bataeve4090182018-11-02 14:54:07 +00002395 } else if (IsInTTDRegion) {
2396 assert(GlobalizedRecords.back().RegionCounter > 0 &&
2397 "region counter must be > 0.");
2398 --GlobalizedRecords.back().RegionCounter;
2399 // Emit the restore function only in the target region.
2400 if (GlobalizedRecords.back().RegionCounter == 0) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002401 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2402 /*DestWidth=*/16, /*Signed=*/0);
2403 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2404 Address(GlobalizedRecords.back().UseSharedMemory,
2405 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2406 /*Volatile=*/false, Int16Ty, GlobalizedRecords.back().Loc);
Alexey Bataeve4090182018-11-02 14:54:07 +00002407 CGF.EmitRuntimeCall(
2408 createNVPTXRuntimeFunction(
2409 OMPRTL_NVPTX__kmpc_restore_team_static_memory),
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002410 IsInSharedMemory);
Alexey Bataeve4090182018-11-02 14:54:07 +00002411 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002412 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002413 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2414 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2415 I->getSecond().GlobalRecordAddr);
2416 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002417 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00002418 }
2419}
2420
Carlo Bertollic6872252016-04-04 15:55:02 +00002421void CGOpenMPRuntimeNVPTX::emitTeamsCall(CodeGenFunction &CGF,
2422 const OMPExecutableDirective &D,
2423 SourceLocation Loc,
2424 llvm::Value *OutlinedFn,
2425 ArrayRef<llvm::Value *> CapturedVars) {
2426 if (!CGF.HaveInsertPoint())
2427 return;
2428
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002429 Address ZeroAddr = CGF.CreateMemTemp(
2430 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2431 /*Name*/ ".zero.addr");
Carlo Bertollic6872252016-04-04 15:55:02 +00002432 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2433 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002434 OutlinedFnArgs.push_back(emitThreadIDAddress(CGF, Loc).getPointer());
Carlo Bertollic6872252016-04-04 15:55:02 +00002435 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2436 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002437 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Carlo Bertollic6872252016-04-04 15:55:02 +00002438}
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002439
2440void CGOpenMPRuntimeNVPTX::emitParallelCall(
2441 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2442 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2443 if (!CGF.HaveInsertPoint())
2444 return;
2445
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002446 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002447 emitSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002448 else
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002449 emitNonSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002450}
2451
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002452void CGOpenMPRuntimeNVPTX::emitNonSPMDParallelCall(
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002453 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2454 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2455 llvm::Function *Fn = cast<llvm::Function>(OutlinedFn);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002456
2457 // Force inline this outlined function at its call site.
2458 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
2459
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002460 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2461 /*DestWidth=*/32, /*Signed=*/1),
2462 ".zero.addr");
2463 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002464 // ThreadId for serialized parallels is 0.
2465 Address ThreadIDAddr = ZeroAddr;
2466 auto &&CodeGen = [this, Fn, CapturedVars, Loc, ZeroAddr, &ThreadIDAddr](
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002467 CodeGenFunction &CGF, PrePostActionTy &Action) {
2468 Action.Enter(CGF);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002469
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002470 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2471 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2472 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2473 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2474 emitOutlinedFunctionCall(CGF, Loc, Fn, OutlinedFnArgs);
2475 };
2476 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2477 PrePostActionTy &) {
2478
2479 RegionCodeGenTy RCG(CodeGen);
2480 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2481 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2482 llvm::Value *Args[] = {RTLoc, ThreadID};
2483
2484 NVPTXActionTy Action(
2485 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2486 Args,
2487 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2488 Args);
2489 RCG.setAction(Action);
2490 RCG(CGF);
2491 };
2492
2493 auto &&L0ParallelGen = [this, CapturedVars, Fn](CodeGenFunction &CGF,
2494 PrePostActionTy &Action) {
2495 CGBuilderTy &Bld = CGF.Builder;
2496 llvm::Function *WFn = WrapperFunctionsMap[Fn];
2497 assert(WFn && "Wrapper function does not exist!");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002498 llvm::Value *ID = Bld.CreateBitOrPointerCast(WFn, CGM.Int8PtrTy);
2499
2500 // Prepare for parallel region. Indicate the outlined function.
2501 llvm::Value *Args[] = {ID, /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002502 CGF.EmitRuntimeCall(
2503 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_prepare_parallel),
2504 Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002505
2506 // Create a private scope that will globalize the arguments
2507 // passed from the outside of the target region.
2508 CodeGenFunction::OMPPrivateScope PrivateArgScope(CGF);
2509
2510 // There's somehting to share.
2511 if (!CapturedVars.empty()) {
2512 // Prepare for parallel region. Indicate the outlined function.
2513 Address SharedArgs =
2514 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "shared_arg_refs");
2515 llvm::Value *SharedArgsPtr = SharedArgs.getPointer();
2516
2517 llvm::Value *DataSharingArgs[] = {
2518 SharedArgsPtr,
2519 llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size())};
2520 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2521 OMPRTL_NVPTX__kmpc_begin_sharing_variables),
2522 DataSharingArgs);
2523
2524 // Store variable address in a list of references to pass to workers.
2525 unsigned Idx = 0;
2526 ASTContext &Ctx = CGF.getContext();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002527 Address SharedArgListAddress = CGF.EmitLoadOfPointer(
2528 SharedArgs, Ctx.getPointerType(Ctx.getPointerType(Ctx.VoidPtrTy))
2529 .castAs<PointerType>());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002530 for (llvm::Value *V : CapturedVars) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002531 Address Dst = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
2532 CGF.getPointerSize());
2533 llvm::Value *PtrV;
Alexey Bataev17314212018-03-20 15:41:05 +00002534 if (V->getType()->isIntegerTy())
2535 PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
2536 else
2537 PtrV = Bld.CreatePointerBitCastOrAddrSpaceCast(V, CGF.VoidPtrTy);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002538 CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
2539 Ctx.getPointerType(Ctx.VoidPtrTy));
Alexey Bataevc99042b2018-03-15 18:10:54 +00002540 ++Idx;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002541 }
2542 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002543
2544 // Activate workers. This barrier is used by the master to signal
2545 // work for the workers.
2546 syncCTAThreads(CGF);
2547
2548 // OpenMP [2.5, Parallel Construct, p.49]
2549 // There is an implied barrier at the end of a parallel region. After the
2550 // end of a parallel region, only the master thread of the team resumes
2551 // execution of the enclosing task region.
2552 //
2553 // The master waits at this barrier until all workers are done.
2554 syncCTAThreads(CGF);
2555
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002556 if (!CapturedVars.empty())
2557 CGF.EmitRuntimeCall(
2558 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_sharing_variables));
2559
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002560 // Remember for post-processing in worker loop.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002561 Work.emplace_back(WFn);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002562 };
2563
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002564 auto &&LNParallelGen = [this, Loc, &SeqGen, &L0ParallelGen](
2565 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002566 if (IsInParallelRegion) {
2567 SeqGen(CGF, Action);
2568 } else if (IsInTargetMasterThreadRegion) {
2569 L0ParallelGen(CGF, Action);
2570 } else {
2571 // Check for master and then parallelism:
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002572 // if (__kmpc_is_spmd_exec_mode() || __kmpc_parallel_level(loc, gtid)) {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002573 // Serialized execution.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002574 // } else {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002575 // Worker call.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002576 // }
2577 CGBuilderTy &Bld = CGF.Builder;
2578 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002579 llvm::BasicBlock *SeqBB = CGF.createBasicBlock(".sequential");
2580 llvm::BasicBlock *ParallelCheckBB = CGF.createBasicBlock(".parcheck");
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002581 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
Alexey Bataev673110d2018-05-16 13:36:30 +00002582 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2583 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002584 Bld.CreateCondBr(IsSPMD, SeqBB, ParallelCheckBB);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002585 // There is no need to emit line number for unconditional branch.
2586 (void)ApplyDebugLocation::CreateEmpty(CGF);
2587 CGF.EmitBlock(ParallelCheckBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002588 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2589 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2590 llvm::Value *PL = CGF.EmitRuntimeCall(
2591 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2592 {RTLoc, ThreadID});
2593 llvm::Value *Res = Bld.CreateIsNotNull(PL);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002594 Bld.CreateCondBr(Res, SeqBB, MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002595 CGF.EmitBlock(SeqBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002596 SeqGen(CGF, Action);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002597 CGF.EmitBranch(ExitBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002598 // There is no need to emit line number for unconditional branch.
2599 (void)ApplyDebugLocation::CreateEmpty(CGF);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002600 CGF.EmitBlock(MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002601 L0ParallelGen(CGF, Action);
2602 CGF.EmitBranch(ExitBB);
2603 // There is no need to emit line number for unconditional branch.
2604 (void)ApplyDebugLocation::CreateEmpty(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002605 // Emit the continuation block for code after the if.
2606 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2607 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002608 };
2609
Alexey Bataev9ff80832018-04-16 20:16:21 +00002610 if (IfCond) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002611 emitOMPIfClause(CGF, IfCond, LNParallelGen, SeqGen);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002612 } else {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002613 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002614 RegionCodeGenTy ThenRCG(LNParallelGen);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002615 ThenRCG(CGF);
2616 }
2617}
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002618
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002619void CGOpenMPRuntimeNVPTX::emitSPMDParallelCall(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002620 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2621 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2622 // Just call the outlined function to execute the parallel region.
2623 // OutlinedFn(&GTid, &zero, CapturedStruct);
2624 //
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002625 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Carlo Bertolli79712092018-02-28 20:48:35 +00002626
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002627 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2628 /*DestWidth=*/32, /*Signed=*/1),
2629 ".zero.addr");
Carlo Bertolli79712092018-02-28 20:48:35 +00002630 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002631 // ThreadId for serialized parallels is 0.
2632 Address ThreadIDAddr = ZeroAddr;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002633 auto &&CodeGen = [this, OutlinedFn, CapturedVars, Loc, ZeroAddr,
Alexey Bataev8521ff62018-07-25 20:03:01 +00002634 &ThreadIDAddr](CodeGenFunction &CGF,
2635 PrePostActionTy &Action) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002636 Action.Enter(CGF);
2637
2638 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2639 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2640 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2641 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2642 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2643 };
2644 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2645 PrePostActionTy &) {
2646
2647 RegionCodeGenTy RCG(CodeGen);
2648 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2649 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2650 llvm::Value *Args[] = {RTLoc, ThreadID};
2651
2652 NVPTXActionTy Action(
2653 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2654 Args,
2655 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2656 Args);
2657 RCG.setAction(Action);
2658 RCG(CGF);
2659 };
2660
2661 if (IsInTargetMasterThreadRegion) {
Alexey Bataev8521ff62018-07-25 20:03:01 +00002662 // In the worker need to use the real thread id.
2663 ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002664 RegionCodeGenTy RCG(CodeGen);
2665 RCG(CGF);
2666 } else {
2667 // If we are not in the target region, it is definitely L2 parallelism or
2668 // more, because for SPMD mode we always has L1 parallel level, sowe don't
2669 // need to check for orphaned directives.
2670 RegionCodeGenTy RCG(SeqGen);
2671 RCG(CGF);
2672 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002673}
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002674
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002675void CGOpenMPRuntimeNVPTX::emitCriticalRegion(
2676 CodeGenFunction &CGF, StringRef CriticalName,
2677 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
2678 const Expr *Hint) {
2679 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
2680 llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
2681 llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
2682 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
2683 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
2684
2685 // Fetch team-local id of the thread.
2686 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
2687
2688 // Get the width of the team.
2689 llvm::Value *TeamWidth = getNVPTXNumThreads(CGF);
2690
2691 // Initialize the counter variable for the loop.
2692 QualType Int32Ty =
2693 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
2694 Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
2695 LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
2696 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
2697 /*isInit=*/true);
2698
2699 // Block checks if loop counter exceeds upper bound.
2700 CGF.EmitBlock(LoopBB);
2701 llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2702 llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
2703 CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
2704
2705 // Block tests which single thread should execute region, and which threads
2706 // should go straight to synchronisation point.
2707 CGF.EmitBlock(TestBB);
2708 CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2709 llvm::Value *CmpThreadToCounter =
2710 CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
2711 CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
2712
2713 // Block emits the body of the critical region.
2714 CGF.EmitBlock(BodyBB);
2715
2716 // Output the critical statement.
2717 CriticalOpGen(CGF);
2718
2719 // After the body surrounded by the critical region, the single executing
2720 // thread will jump to the synchronisation point.
2721 // Block waits for all threads in current team to finish then increments the
2722 // counter variable and returns to the loop.
2723 CGF.EmitBlock(SyncBB);
2724 getNVPTXCTABarrier(CGF);
2725
2726 llvm::Value *IncCounterVal =
2727 CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
2728 CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
2729 CGF.EmitBranch(LoopBB);
2730
2731 // Block that is reached when all threads in the team complete the region.
2732 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2733}
2734
Alexey Bataevb2575932018-01-04 20:18:55 +00002735/// Cast value to the specified type.
Alexey Bataeva453f362018-03-19 17:53:56 +00002736static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
2737 QualType ValTy, QualType CastTy,
2738 SourceLocation Loc) {
2739 assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
2740 "Cast type must sized.");
2741 assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
2742 "Val type must sized.");
2743 llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
2744 if (ValTy == CastTy)
Alexey Bataevb2575932018-01-04 20:18:55 +00002745 return Val;
Alexey Bataeva453f362018-03-19 17:53:56 +00002746 if (CGF.getContext().getTypeSizeInChars(ValTy) ==
2747 CGF.getContext().getTypeSizeInChars(CastTy))
2748 return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
2749 if (CastTy->isIntegerType() && ValTy->isIntegerType())
2750 return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
2751 CastTy->hasSignedIntegerRepresentation());
2752 Address CastItem = CGF.CreateMemTemp(CastTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002753 Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2754 CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
Alexey Bataeva453f362018-03-19 17:53:56 +00002755 CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy);
2756 return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc);
Alexey Bataevb2575932018-01-04 20:18:55 +00002757}
2758
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002759/// This function creates calls to one of two shuffle functions to copy
2760/// variables between lanes in a warp.
2761static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002762 llvm::Value *Elem,
Alexey Bataeva453f362018-03-19 17:53:56 +00002763 QualType ElemType,
2764 llvm::Value *Offset,
2765 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002766 CodeGenModule &CGM = CGF.CGM;
2767 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002768 CGOpenMPRuntimeNVPTX &RT =
2769 *(static_cast<CGOpenMPRuntimeNVPTX *>(&CGM.getOpenMPRuntime()));
2770
Alexey Bataeva453f362018-03-19 17:53:56 +00002771 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2772 assert(Size.getQuantity() <= 8 &&
2773 "Unsupported bitwidth in shuffle instruction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002774
Alexey Bataeva453f362018-03-19 17:53:56 +00002775 OpenMPRTLFunctionNVPTX ShuffleFn = Size.getQuantity() <= 4
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002776 ? OMPRTL_NVPTX__kmpc_shuffle_int32
2777 : OMPRTL_NVPTX__kmpc_shuffle_int64;
2778
2779 // Cast all types to 32- or 64-bit values before calling shuffle routines.
Alexey Bataeva453f362018-03-19 17:53:56 +00002780 QualType CastTy = CGF.getContext().getIntTypeForBitwidth(
2781 Size.getQuantity() <= 4 ? 32 : 64, /*Signed=*/1);
2782 llvm::Value *ElemCast = castValueToType(CGF, Elem, ElemType, CastTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002783 llvm::Value *WarpSize =
Alexey Bataevb2575932018-01-04 20:18:55 +00002784 Bld.CreateIntCast(getNVPTXWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002785
Alexey Bataev9ff80832018-04-16 20:16:21 +00002786 llvm::Value *ShuffledVal = CGF.EmitRuntimeCall(
2787 RT.createNVPTXRuntimeFunction(ShuffleFn), {ElemCast, Offset, WarpSize});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002788
Alexey Bataeva453f362018-03-19 17:53:56 +00002789 return castValueToType(CGF, ShuffledVal, CastTy, ElemType, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002790}
2791
Alexey Bataev12c62902018-06-22 19:10:38 +00002792static void shuffleAndStore(CodeGenFunction &CGF, Address SrcAddr,
2793 Address DestAddr, QualType ElemType,
2794 llvm::Value *Offset, SourceLocation Loc) {
2795 CGBuilderTy &Bld = CGF.Builder;
2796
2797 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2798 // Create the loop over the big sized data.
2799 // ptr = (void*)Elem;
2800 // ptrEnd = (void*) Elem + 1;
2801 // Step = 8;
2802 // while (ptr + Step < ptrEnd)
2803 // shuffle((int64_t)*ptr);
2804 // Step = 4;
2805 // while (ptr + Step < ptrEnd)
2806 // shuffle((int32_t)*ptr);
2807 // ...
2808 Address ElemPtr = DestAddr;
2809 Address Ptr = SrcAddr;
2810 Address PtrEnd = Bld.CreatePointerBitCastOrAddrSpaceCast(
2811 Bld.CreateConstGEP(SrcAddr, 1, Size), CGF.VoidPtrTy);
2812 for (int IntSize = 8; IntSize >= 1; IntSize /= 2) {
2813 if (Size < CharUnits::fromQuantity(IntSize))
2814 continue;
2815 QualType IntType = CGF.getContext().getIntTypeForBitwidth(
2816 CGF.getContext().toBits(CharUnits::fromQuantity(IntSize)),
2817 /*Signed=*/1);
2818 llvm::Type *IntTy = CGF.ConvertTypeForMem(IntType);
2819 Ptr = Bld.CreatePointerBitCastOrAddrSpaceCast(Ptr, IntTy->getPointerTo());
2820 ElemPtr =
2821 Bld.CreatePointerBitCastOrAddrSpaceCast(ElemPtr, IntTy->getPointerTo());
2822 if (Size.getQuantity() / IntSize > 1) {
2823 llvm::BasicBlock *PreCondBB = CGF.createBasicBlock(".shuffle.pre_cond");
2824 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".shuffle.then");
2825 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".shuffle.exit");
2826 llvm::BasicBlock *CurrentBB = Bld.GetInsertBlock();
2827 CGF.EmitBlock(PreCondBB);
2828 llvm::PHINode *PhiSrc =
2829 Bld.CreatePHI(Ptr.getType(), /*NumReservedValues=*/2);
2830 PhiSrc->addIncoming(Ptr.getPointer(), CurrentBB);
2831 llvm::PHINode *PhiDest =
2832 Bld.CreatePHI(ElemPtr.getType(), /*NumReservedValues=*/2);
2833 PhiDest->addIncoming(ElemPtr.getPointer(), CurrentBB);
2834 Ptr = Address(PhiSrc, Ptr.getAlignment());
2835 ElemPtr = Address(PhiDest, ElemPtr.getAlignment());
2836 llvm::Value *PtrDiff = Bld.CreatePtrDiff(
2837 PtrEnd.getPointer(), Bld.CreatePointerBitCastOrAddrSpaceCast(
2838 Ptr.getPointer(), CGF.VoidPtrTy));
2839 Bld.CreateCondBr(Bld.CreateICmpSGT(PtrDiff, Bld.getInt64(IntSize - 1)),
2840 ThenBB, ExitBB);
2841 CGF.EmitBlock(ThenBB);
2842 llvm::Value *Res = createRuntimeShuffleFunction(
2843 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2844 IntType, Offset, Loc);
2845 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002846 Address LocalPtr =
2847 Bld.CreateConstGEP(Ptr, 1, CharUnits::fromQuantity(IntSize));
2848 Address LocalElemPtr =
Alexey Bataev12c62902018-06-22 19:10:38 +00002849 Bld.CreateConstGEP(ElemPtr, 1, CharUnits::fromQuantity(IntSize));
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002850 PhiSrc->addIncoming(LocalPtr.getPointer(), ThenBB);
2851 PhiDest->addIncoming(LocalElemPtr.getPointer(), ThenBB);
Alexey Bataev12c62902018-06-22 19:10:38 +00002852 CGF.EmitBranch(PreCondBB);
2853 CGF.EmitBlock(ExitBB);
2854 } else {
2855 llvm::Value *Res = createRuntimeShuffleFunction(
2856 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2857 IntType, Offset, Loc);
2858 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
2859 Ptr = Bld.CreateConstGEP(Ptr, 1, CharUnits::fromQuantity(IntSize));
2860 ElemPtr =
2861 Bld.CreateConstGEP(ElemPtr, 1, CharUnits::fromQuantity(IntSize));
2862 }
2863 Size = Size % IntSize;
2864 }
2865}
2866
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002867namespace {
2868enum CopyAction : unsigned {
2869 // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
2870 // the warp using shuffle instructions.
2871 RemoteLaneToThread,
2872 // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
2873 ThreadCopy,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002874 // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
2875 ThreadToScratchpad,
2876 // ScratchpadToThread: Copy from a scratchpad array in global memory
2877 // containing team-reduced data to a thread's stack.
2878 ScratchpadToThread,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002879};
2880} // namespace
2881
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002882struct CopyOptionsTy {
2883 llvm::Value *RemoteLaneOffset;
2884 llvm::Value *ScratchpadIndex;
2885 llvm::Value *ScratchpadWidth;
2886};
2887
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002888/// Emit instructions to copy a Reduce list, which contains partially
2889/// aggregated values, in the specified direction.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002890static void emitReductionListCopy(
2891 CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
2892 ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
2893 CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002894
Alexey Bataev9ff80832018-04-16 20:16:21 +00002895 CodeGenModule &CGM = CGF.CGM;
2896 ASTContext &C = CGM.getContext();
2897 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002898
Alexey Bataev9ff80832018-04-16 20:16:21 +00002899 llvm::Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
2900 llvm::Value *ScratchpadIndex = CopyOptions.ScratchpadIndex;
2901 llvm::Value *ScratchpadWidth = CopyOptions.ScratchpadWidth;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002902
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002903 // Iterates, element-by-element, through the source Reduce list and
2904 // make a copy.
2905 unsigned Idx = 0;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002906 unsigned Size = Privates.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00002907 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002908 Address SrcElementAddr = Address::invalid();
2909 Address DestElementAddr = Address::invalid();
2910 Address DestElementPtrAddr = Address::invalid();
2911 // Should we shuffle in an element from a remote lane?
2912 bool ShuffleInElement = false;
2913 // Set to true to update the pointer in the dest Reduce list to a
2914 // newly created element.
2915 bool UpdateDestListPtr = false;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002916 // Increment the src or dest pointer to the scratchpad, for each
2917 // new element.
2918 bool IncrScratchpadSrc = false;
2919 bool IncrScratchpadDest = false;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002920
2921 switch (Action) {
2922 case RemoteLaneToThread: {
2923 // Step 1.1: Get the address for the src element in the Reduce list.
2924 Address SrcElementPtrAddr =
2925 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002926 SrcElementAddr = CGF.EmitLoadOfPointer(
2927 SrcElementPtrAddr,
2928 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002929
2930 // Step 1.2: Create a temporary to store the element in the destination
2931 // Reduce list.
2932 DestElementPtrAddr =
2933 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
2934 DestElementAddr =
2935 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2936 ShuffleInElement = true;
2937 UpdateDestListPtr = true;
2938 break;
2939 }
2940 case ThreadCopy: {
2941 // Step 1.1: Get the address for the src element in the Reduce list.
2942 Address SrcElementPtrAddr =
2943 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002944 SrcElementAddr = CGF.EmitLoadOfPointer(
2945 SrcElementPtrAddr,
2946 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002947
2948 // Step 1.2: Get the address for dest element. The destination
2949 // element has already been created on the thread's stack.
2950 DestElementPtrAddr =
2951 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002952 DestElementAddr = CGF.EmitLoadOfPointer(
2953 DestElementPtrAddr,
2954 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002955 break;
2956 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002957 case ThreadToScratchpad: {
2958 // Step 1.1: Get the address for the src element in the Reduce list.
2959 Address SrcElementPtrAddr =
2960 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002961 SrcElementAddr = CGF.EmitLoadOfPointer(
2962 SrcElementPtrAddr,
2963 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002964
2965 // Step 1.2: Get the address for dest element:
2966 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00002967 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00002968 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002969 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002970 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002971 Bld.CreateNUWAdd(DestBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002972 ScratchPadElemAbsolutePtrVal =
2973 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002974 DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
2975 C.getTypeAlignInChars(Private->getType()));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002976 IncrScratchpadDest = true;
2977 break;
2978 }
2979 case ScratchpadToThread: {
2980 // Step 1.1: Get the address for the src element in the scratchpad.
2981 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00002982 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00002983 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002984 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002985 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002986 Bld.CreateNUWAdd(SrcBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002987 ScratchPadElemAbsolutePtrVal =
2988 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
2989 SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
2990 C.getTypeAlignInChars(Private->getType()));
2991 IncrScratchpadSrc = true;
2992
2993 // Step 1.2: Create a temporary to store the element in the destination
2994 // Reduce list.
2995 DestElementPtrAddr =
2996 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
2997 DestElementAddr =
2998 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2999 UpdateDestListPtr = true;
3000 break;
3001 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003002 }
3003
3004 // Regardless of src and dest of copy, we emit the load of src
3005 // element as this is required in all directions
3006 SrcElementAddr = Bld.CreateElementBitCast(
3007 SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
Alexey Bataev12c62902018-06-22 19:10:38 +00003008 DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
3009 SrcElementAddr.getElementType());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003010
3011 // Now that all active lanes have read the element in the
3012 // Reduce list, shuffle over the value from the remote lane.
Alexey Bataeva453f362018-03-19 17:53:56 +00003013 if (ShuffleInElement) {
Alexey Bataev12c62902018-06-22 19:10:38 +00003014 shuffleAndStore(CGF, SrcElementAddr, DestElementAddr, Private->getType(),
3015 RemoteLaneOffset, Private->getExprLoc());
3016 } else {
3017 if (Private->getType()->isScalarType()) {
3018 llvm::Value *Elem =
3019 CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false,
3020 Private->getType(), Private->getExprLoc());
3021 // Store the source element value to the dest element address.
3022 CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false,
3023 Private->getType());
3024 } else {
3025 CGF.EmitAggregateCopy(
3026 CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3027 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3028 Private->getType(), AggValueSlot::DoesNotOverlap);
3029 }
Alexey Bataeva453f362018-03-19 17:53:56 +00003030 }
Alexey Bataevb2575932018-01-04 20:18:55 +00003031
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003032 // Step 3.1: Modify reference in dest Reduce list as needed.
3033 // Modifying the reference in Reduce list to point to the newly
3034 // created element. The element is live in the current function
3035 // scope and that of functions it invokes (i.e., reduce_function).
3036 // RemoteReduceData[i] = (void*)&RemoteElem
3037 if (UpdateDestListPtr) {
3038 CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
3039 DestElementAddr.getPointer(), CGF.VoidPtrTy),
3040 DestElementPtrAddr, /*Volatile=*/false,
3041 C.VoidPtrTy);
3042 }
3043
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003044 // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
3045 // address of the next element in scratchpad memory, unless we're currently
3046 // processing the last one. Memory alignment is also taken care of here.
3047 if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
3048 llvm::Value *ScratchpadBasePtr =
3049 IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
Alexey Bataeve290ec02018-04-06 16:03:36 +00003050 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
3051 ScratchpadBasePtr = Bld.CreateNUWAdd(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003052 ScratchpadBasePtr,
Alexey Bataeve290ec02018-04-06 16:03:36 +00003053 Bld.CreateNUWMul(ScratchpadWidth, ElementSizeInChars));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003054
3055 // Take care of global memory alignment for performance
Alexey Bataeve290ec02018-04-06 16:03:36 +00003056 ScratchpadBasePtr = Bld.CreateNUWSub(
3057 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3058 ScratchpadBasePtr = Bld.CreateUDiv(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003059 ScratchpadBasePtr,
3060 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
Alexey Bataeve290ec02018-04-06 16:03:36 +00003061 ScratchpadBasePtr = Bld.CreateNUWAdd(
3062 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3063 ScratchpadBasePtr = Bld.CreateNUWMul(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003064 ScratchpadBasePtr,
3065 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
3066
3067 if (IncrScratchpadDest)
3068 DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3069 else /* IncrScratchpadSrc = true */
3070 SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3071 }
3072
Alexey Bataev9ff80832018-04-16 20:16:21 +00003073 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003074 }
3075}
3076
3077/// This function emits a helper that gathers Reduce lists from the first
3078/// lane of every active warp to lanes in the first warp.
3079///
3080/// void inter_warp_copy_func(void* reduce_data, num_warps)
3081/// shared smem[warp_size];
3082/// For all data entries D in reduce_data:
3083/// If (I am the first lane in each warp)
3084/// Copy my local D to smem[warp_id]
3085/// sync
3086/// if (I am the first warp)
3087/// Copy smem[thread_id] to my local D
3088/// sync
3089static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
3090 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003091 QualType ReductionArrayTy,
3092 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003093 ASTContext &C = CGM.getContext();
3094 llvm::Module &M = CGM.getModule();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003095
3096 // ReduceList: thread local Reduce list.
3097 // At the stage of the computation when this function is called, partially
3098 // aggregated values reside in the first lane of every active warp.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003099 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3100 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003101 // NumWarps: number of warps active in the parallel region. This could
3102 // be smaller than 32 (max warps in a CTA) for partial block reduction.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003103 ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00003104 C.getIntTypeForBitwidth(32, /* Signed */ true),
3105 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003106 FunctionArgList Args;
3107 Args.push_back(&ReduceListArg);
3108 Args.push_back(&NumWarpsArg);
3109
Alexey Bataev9ff80832018-04-16 20:16:21 +00003110 const CGFunctionInfo &CGFI =
3111 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003112 auto *Fn = llvm::Function::Create(
3113 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3114 "_omp_reduction_inter_warp_copy_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003115 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003116 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003117 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003118 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003119
Alexey Bataev9ff80832018-04-16 20:16:21 +00003120 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003121
3122 // This array is used as a medium to transfer, one reduce element at a time,
3123 // the data from the first lane of every warp to lanes in the first warp
3124 // in order to perform the final step of a reduction in a parallel region
3125 // (reduction across warps). The array is placed in NVPTX __shared__ memory
3126 // for reduced latency, as well as to have a distinct copy for concurrently
3127 // executing target regions. The array is declared with common linkage so
3128 // as to be shared across compilation units.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003129 StringRef TransferMediumName =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003130 "__openmp_nvptx_data_transfer_temporary_storage";
3131 llvm::GlobalVariable *TransferMedium =
3132 M.getGlobalVariable(TransferMediumName);
3133 if (!TransferMedium) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003134 auto *Ty = llvm::ArrayType::get(CGM.Int32Ty, WarpSize);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003135 unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
3136 TransferMedium = new llvm::GlobalVariable(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003137 M, Ty, /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003138 llvm::Constant::getNullValue(Ty), TransferMediumName,
3139 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3140 SharedAddressSpace);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003141 CGM.addCompilerUsedGlobal(TransferMedium);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003142 }
3143
3144 // Get the CUDA thread id of the current OpenMP thread on the GPU.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003145 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003146 // nvptx_lane_id = nvptx_id % warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003147 llvm::Value *LaneID = getNVPTXLaneID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003148 // nvptx_warp_id = nvptx_id / warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003149 llvm::Value *WarpID = getNVPTXWarpID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003150
3151 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3152 Address LocalReduceList(
3153 Bld.CreatePointerBitCastOrAddrSpaceCast(
3154 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003155 C.VoidPtrTy, Loc),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003156 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3157 CGF.getPointerAlign());
3158
3159 unsigned Idx = 0;
Alexey Bataev9ff80832018-04-16 20:16:21 +00003160 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003161 //
3162 // Warp master copies reduce element to transfer medium in __shared__
3163 // memory.
3164 //
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003165 unsigned RealTySize =
3166 C.getTypeSizeInChars(Private->getType())
3167 .alignTo(C.getTypeAlignInChars(Private->getType()))
3168 .getQuantity();
3169 for (unsigned TySize = 4; TySize > 0 && RealTySize > 0; TySize /=2) {
3170 unsigned NumIters = RealTySize / TySize;
3171 if (NumIters == 0)
3172 continue;
3173 QualType CType = C.getIntTypeForBitwidth(
3174 C.toBits(CharUnits::fromQuantity(TySize)), /*Signed=*/1);
3175 llvm::Type *CopyType = CGF.ConvertTypeForMem(CType);
3176 CharUnits Align = CharUnits::fromQuantity(TySize);
3177 llvm::Value *Cnt = nullptr;
3178 Address CntAddr = Address::invalid();
3179 llvm::BasicBlock *PrecondBB = nullptr;
3180 llvm::BasicBlock *ExitBB = nullptr;
3181 if (NumIters > 1) {
3182 CntAddr = CGF.CreateMemTemp(C.IntTy, ".cnt.addr");
3183 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.IntTy), CntAddr,
3184 /*Volatile=*/false, C.IntTy);
3185 PrecondBB = CGF.createBasicBlock("precond");
3186 ExitBB = CGF.createBasicBlock("exit");
3187 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("body");
3188 // There is no need to emit line number for unconditional branch.
3189 (void)ApplyDebugLocation::CreateEmpty(CGF);
3190 CGF.EmitBlock(PrecondBB);
3191 Cnt = CGF.EmitLoadOfScalar(CntAddr, /*Volatile=*/false, C.IntTy, Loc);
3192 llvm::Value *Cmp =
3193 Bld.CreateICmpULT(Cnt, llvm::ConstantInt::get(CGM.IntTy, NumIters));
3194 Bld.CreateCondBr(Cmp, BodyBB, ExitBB);
3195 CGF.EmitBlock(BodyBB);
3196 }
3197 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3198 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3199 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003200
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003201 // if (lane_id == 0)
3202 llvm::Value *IsWarpMaster = Bld.CreateIsNull(LaneID, "warp_master");
3203 Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
3204 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003205
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003206 // Reduce element = LocalReduceList[i]
3207 Address ElemPtrPtrAddr =
3208 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
3209 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3210 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3211 // elemptr = ((CopyType*)(elemptrptr)) + I
3212 Address ElemPtr = Address(ElemPtrPtr, Align);
3213 ElemPtr = Bld.CreateElementBitCast(ElemPtr, CopyType);
3214 if (NumIters > 1) {
3215 ElemPtr = Address(Bld.CreateGEP(ElemPtr.getPointer(), Cnt),
3216 ElemPtr.getAlignment());
3217 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003218
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003219 // Get pointer to location in transfer medium.
3220 // MediumPtr = &medium[warp_id]
3221 llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
3222 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
3223 Address MediumPtr(MediumPtrVal, Align);
3224 // Casting to actual data type.
3225 // MediumPtr = (CopyType*)MediumPtrAddr;
3226 MediumPtr = Bld.CreateElementBitCast(MediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003227
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003228 // elem = *elemptr
3229 //*MediumPtr = elem
3230 llvm::Value *Elem =
3231 CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003232 // Store the source element value to the dest element address.
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003233 CGF.EmitStoreOfScalar(Elem, MediumPtr, /*Volatile=*/true, CType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003234
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003235 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003236
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003237 CGF.EmitBlock(ElseBB);
3238 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003239
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003240 CGF.EmitBlock(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003241
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003242 Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
3243 llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
3244 AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003245
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003246 llvm::Value *NumActiveThreads = Bld.CreateNSWMul(
3247 NumWarpsVal, getNVPTXWarpSize(CGF), "num_active_threads");
3248 // named_barrier_sync(ParallelBarrierID, num_active_threads)
3249 syncParallelThreads(CGF, NumActiveThreads);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003250
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003251 //
3252 // Warp 0 copies reduce element from transfer medium.
3253 //
3254 llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
3255 llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
3256 llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003257
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003258 // Up to 32 threads in warp 0 are active.
3259 llvm::Value *IsActiveThread =
3260 Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
3261 Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003262
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003263 CGF.EmitBlock(W0ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003264
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003265 // SrcMediumPtr = &medium[tid]
3266 llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
3267 TransferMedium,
3268 {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
3269 Address SrcMediumPtr(SrcMediumPtrVal, Align);
3270 // SrcMediumVal = *SrcMediumPtr;
3271 SrcMediumPtr = Bld.CreateElementBitCast(SrcMediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003272
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003273 // TargetElemPtr = (CopyType*)(SrcDataAddr[i]) + I
3274 Address TargetElemPtrPtr =
3275 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
3276 llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
3277 TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, Loc);
3278 Address TargetElemPtr = Address(TargetElemPtrVal, Align);
3279 TargetElemPtr = Bld.CreateElementBitCast(TargetElemPtr, CopyType);
3280 if (NumIters > 1) {
3281 TargetElemPtr = Address(Bld.CreateGEP(TargetElemPtr.getPointer(), Cnt),
3282 TargetElemPtr.getAlignment());
3283 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003284
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003285 // *TargetElemPtr = SrcMediumVal;
3286 llvm::Value *SrcMediumValue =
3287 CGF.EmitLoadOfScalar(SrcMediumPtr, /*Volatile=*/true, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003288 CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003289 CType);
3290 Bld.CreateBr(W0MergeBB);
3291
3292 CGF.EmitBlock(W0ElseBB);
3293 Bld.CreateBr(W0MergeBB);
3294
3295 CGF.EmitBlock(W0MergeBB);
3296
3297 // While warp 0 copies values from transfer medium, all other warps must
3298 // wait.
3299 syncParallelThreads(CGF, NumActiveThreads);
3300 if (NumIters > 1) {
3301 Cnt = Bld.CreateNSWAdd(Cnt, llvm::ConstantInt::get(CGM.IntTy, /*V=*/1));
3302 CGF.EmitStoreOfScalar(Cnt, CntAddr, /*Volatile=*/false, C.IntTy);
3303 CGF.EmitBranch(PrecondBB);
3304 (void)ApplyDebugLocation::CreateEmpty(CGF);
3305 CGF.EmitBlock(ExitBB);
3306 }
3307 RealTySize %= TySize;
Alexey Bataev12c62902018-06-22 19:10:38 +00003308 }
Alexey Bataev9ff80832018-04-16 20:16:21 +00003309 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003310 }
3311
3312 CGF.FinishFunction();
3313 return Fn;
3314}
3315
3316/// Emit a helper that reduces data across two OpenMP threads (lanes)
3317/// in the same warp. It uses shuffle instructions to copy over data from
3318/// a remote lane's stack. The reduction algorithm performed is specified
3319/// by the fourth parameter.
3320///
3321/// Algorithm Versions.
3322/// Full Warp Reduce (argument value 0):
3323/// This algorithm assumes that all 32 lanes are active and gathers
3324/// data from these 32 lanes, producing a single resultant value.
3325/// Contiguous Partial Warp Reduce (argument value 1):
3326/// This algorithm assumes that only a *contiguous* subset of lanes
3327/// are active. This happens for the last warp in a parallel region
3328/// when the user specified num_threads is not an integer multiple of
3329/// 32. This contiguous subset always starts with the zeroth lane.
3330/// Partial Warp Reduce (argument value 2):
3331/// This algorithm gathers data from any number of lanes at any position.
3332/// All reduced values are stored in the lowest possible lane. The set
3333/// of problems every algorithm addresses is a super set of those
3334/// addressable by algorithms with a lower version number. Overhead
3335/// increases as algorithm version increases.
3336///
3337/// Terminology
3338/// Reduce element:
3339/// Reduce element refers to the individual data field with primitive
3340/// data types to be combined and reduced across threads.
3341/// Reduce list:
3342/// Reduce list refers to a collection of local, thread-private
3343/// reduce elements.
3344/// Remote Reduce list:
3345/// Remote Reduce list refers to a collection of remote (relative to
3346/// the current thread) reduce elements.
3347///
3348/// We distinguish between three states of threads that are important to
3349/// the implementation of this function.
3350/// Alive threads:
3351/// Threads in a warp executing the SIMT instruction, as distinguished from
3352/// threads that are inactive due to divergent control flow.
3353/// Active threads:
3354/// The minimal set of threads that has to be alive upon entry to this
3355/// function. The computation is correct iff active threads are alive.
3356/// Some threads are alive but they are not active because they do not
3357/// contribute to the computation in any useful manner. Turning them off
3358/// may introduce control flow overheads without any tangible benefits.
3359/// Effective threads:
3360/// In order to comply with the argument requirements of the shuffle
3361/// function, we must keep all lanes holding data alive. But at most
3362/// half of them perform value aggregation; we refer to this half of
3363/// threads as effective. The other half is simply handing off their
3364/// data.
3365///
3366/// Procedure
3367/// Value shuffle:
3368/// In this step active threads transfer data from higher lane positions
3369/// in the warp to lower lane positions, creating Remote Reduce list.
3370/// Value aggregation:
3371/// In this step, effective threads combine their thread local Reduce list
3372/// with Remote Reduce list and store the result in the thread local
3373/// Reduce list.
3374/// Value copy:
3375/// In this step, we deal with the assumption made by algorithm 2
3376/// (i.e. contiguity assumption). When we have an odd number of lanes
3377/// active, say 2k+1, only k threads will be effective and therefore k
3378/// new values will be produced. However, the Reduce list owned by the
3379/// (2k+1)th thread is ignored in the value aggregation. Therefore
3380/// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
3381/// that the contiguity assumption still holds.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003382static llvm::Value *emitShuffleAndReduceFunction(
3383 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3384 QualType ReductionArrayTy, llvm::Value *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003385 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003386
3387 // Thread local Reduce list used to host the values of data to be reduced.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003388 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3389 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003390 // Current lane id; could be logical.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003391 ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
3392 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003393 // Offset of the remote source lane relative to the current lane.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003394 ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3395 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003396 // Algorithm version. This is expected to be known at compile time.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003397 ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3398 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003399 FunctionArgList Args;
3400 Args.push_back(&ReduceListArg);
3401 Args.push_back(&LaneIDArg);
3402 Args.push_back(&RemoteLaneOffsetArg);
3403 Args.push_back(&AlgoVerArg);
3404
Alexey Bataev9ff80832018-04-16 20:16:21 +00003405 const CGFunctionInfo &CGFI =
3406 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003407 auto *Fn = llvm::Function::Create(
3408 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3409 "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003410 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003411 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003412 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003413 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003414
Alexey Bataev9ff80832018-04-16 20:16:21 +00003415 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003416
3417 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3418 Address LocalReduceList(
3419 Bld.CreatePointerBitCastOrAddrSpaceCast(
3420 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3421 C.VoidPtrTy, SourceLocation()),
3422 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3423 CGF.getPointerAlign());
3424
3425 Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
3426 llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
3427 AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3428
3429 Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
3430 llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
3431 AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3432
3433 Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
3434 llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
3435 AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3436
3437 // Create a local thread-private variable to host the Reduce list
3438 // from a remote lane.
3439 Address RemoteReduceList =
3440 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
3441
3442 // This loop iterates through the list of reduce elements and copies,
3443 // element by element, from a remote lane in the warp to RemoteReduceList,
3444 // hosted on the thread's stack.
3445 emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
3446 LocalReduceList, RemoteReduceList,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003447 {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
3448 /*ScratchpadIndex=*/nullptr,
3449 /*ScratchpadWidth=*/nullptr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003450
3451 // The actions to be performed on the Remote Reduce list is dependent
3452 // on the algorithm version.
3453 //
3454 // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
3455 // LaneId % 2 == 0 && Offset > 0):
3456 // do the reduction value aggregation
3457 //
3458 // The thread local variable Reduce list is mutated in place to host the
3459 // reduced data, which is the aggregated value produced from local and
3460 // remote lanes.
3461 //
3462 // Note that AlgoVer is expected to be a constant integer known at compile
3463 // time.
3464 // When AlgoVer==0, the first conjunction evaluates to true, making
3465 // the entire predicate true during compile time.
3466 // When AlgoVer==1, the second conjunction has only the second part to be
3467 // evaluated during runtime. Other conjunctions evaluates to false
3468 // during compile time.
3469 // When AlgoVer==2, the third conjunction has only the second part to be
3470 // evaluated during runtime. Other conjunctions evaluates to false
3471 // during compile time.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003472 llvm::Value *CondAlgo0 = Bld.CreateIsNull(AlgoVerArgVal);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003473
Alexey Bataev9ff80832018-04-16 20:16:21 +00003474 llvm::Value *Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
3475 llvm::Value *CondAlgo1 = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003476 Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
3477
Alexey Bataev9ff80832018-04-16 20:16:21 +00003478 llvm::Value *Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
3479 llvm::Value *CondAlgo2 = Bld.CreateAnd(
3480 Algo2, Bld.CreateIsNull(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1))));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003481 CondAlgo2 = Bld.CreateAnd(
3482 CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
3483
Alexey Bataev9ff80832018-04-16 20:16:21 +00003484 llvm::Value *CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003485 CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
3486
3487 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3488 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3489 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
3490 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
3491
3492 CGF.EmitBlock(ThenBB);
3493 // reduce_function(LocalReduceList, RemoteReduceList)
3494 llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3495 LocalReduceList.getPointer(), CGF.VoidPtrTy);
3496 llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3497 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003498 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3499 CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003500 Bld.CreateBr(MergeBB);
3501
3502 CGF.EmitBlock(ElseBB);
3503 Bld.CreateBr(MergeBB);
3504
3505 CGF.EmitBlock(MergeBB);
3506
3507 // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
3508 // Reduce list.
3509 Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
Alexey Bataev9ff80832018-04-16 20:16:21 +00003510 llvm::Value *CondCopy = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003511 Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
3512
3513 llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
3514 llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
3515 llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
3516 Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
3517
3518 CGF.EmitBlock(CpyThenBB);
3519 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
3520 RemoteReduceList, LocalReduceList);
3521 Bld.CreateBr(CpyMergeBB);
3522
3523 CGF.EmitBlock(CpyElseBB);
3524 Bld.CreateBr(CpyMergeBB);
3525
3526 CGF.EmitBlock(CpyMergeBB);
3527
3528 CGF.FinishFunction();
3529 return Fn;
3530}
3531
3532///
3533/// Design of OpenMP reductions on the GPU
3534///
3535/// Consider a typical OpenMP program with one or more reduction
3536/// clauses:
3537///
3538/// float foo;
3539/// double bar;
3540/// #pragma omp target teams distribute parallel for \
3541/// reduction(+:foo) reduction(*:bar)
3542/// for (int i = 0; i < N; i++) {
3543/// foo += A[i]; bar *= B[i];
3544/// }
3545///
3546/// where 'foo' and 'bar' are reduced across all OpenMP threads in
3547/// all teams. In our OpenMP implementation on the NVPTX device an
3548/// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
3549/// within a team are mapped to CUDA threads within a threadblock.
3550/// Our goal is to efficiently aggregate values across all OpenMP
3551/// threads such that:
3552///
3553/// - the compiler and runtime are logically concise, and
3554/// - the reduction is performed efficiently in a hierarchical
3555/// manner as follows: within OpenMP threads in the same warp,
3556/// across warps in a threadblock, and finally across teams on
3557/// the NVPTX device.
3558///
3559/// Introduction to Decoupling
3560///
3561/// We would like to decouple the compiler and the runtime so that the
3562/// latter is ignorant of the reduction variables (number, data types)
3563/// and the reduction operators. This allows a simpler interface
3564/// and implementation while still attaining good performance.
3565///
3566/// Pseudocode for the aforementioned OpenMP program generated by the
3567/// compiler is as follows:
3568///
3569/// 1. Create private copies of reduction variables on each OpenMP
3570/// thread: 'foo_private', 'bar_private'
3571/// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
3572/// to it and writes the result in 'foo_private' and 'bar_private'
3573/// respectively.
3574/// 3. Call the OpenMP runtime on the GPU to reduce within a team
3575/// and store the result on the team master:
3576///
3577/// __kmpc_nvptx_parallel_reduce_nowait(...,
3578/// reduceData, shuffleReduceFn, interWarpCpyFn)
3579///
3580/// where:
3581/// struct ReduceData {
3582/// double *foo;
3583/// double *bar;
3584/// } reduceData
3585/// reduceData.foo = &foo_private
3586/// reduceData.bar = &bar_private
3587///
3588/// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
3589/// auxiliary functions generated by the compiler that operate on
3590/// variables of type 'ReduceData'. They aid the runtime perform
3591/// algorithmic steps in a data agnostic manner.
3592///
3593/// 'shuffleReduceFn' is a pointer to a function that reduces data
3594/// of type 'ReduceData' across two OpenMP threads (lanes) in the
3595/// same warp. It takes the following arguments as input:
3596///
3597/// a. variable of type 'ReduceData' on the calling lane,
3598/// b. its lane_id,
3599/// c. an offset relative to the current lane_id to generate a
3600/// remote_lane_id. The remote lane contains the second
3601/// variable of type 'ReduceData' that is to be reduced.
3602/// d. an algorithm version parameter determining which reduction
3603/// algorithm to use.
3604///
3605/// 'shuffleReduceFn' retrieves data from the remote lane using
3606/// efficient GPU shuffle intrinsics and reduces, using the
3607/// algorithm specified by the 4th parameter, the two operands
3608/// element-wise. The result is written to the first operand.
3609///
3610/// Different reduction algorithms are implemented in different
3611/// runtime functions, all calling 'shuffleReduceFn' to perform
3612/// the essential reduction step. Therefore, based on the 4th
3613/// parameter, this function behaves slightly differently to
3614/// cooperate with the runtime to ensure correctness under
3615/// different circumstances.
3616///
3617/// 'InterWarpCpyFn' is a pointer to a function that transfers
3618/// reduced variables across warps. It tunnels, through CUDA
3619/// shared memory, the thread-private data of type 'ReduceData'
3620/// from lane 0 of each warp to a lane in the first warp.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003621/// 4. Call the OpenMP runtime on the GPU to reduce across teams.
3622/// The last team writes the global reduced value to memory.
3623///
3624/// ret = __kmpc_nvptx_teams_reduce_nowait(...,
3625/// reduceData, shuffleReduceFn, interWarpCpyFn,
3626/// scratchpadCopyFn, loadAndReduceFn)
3627///
3628/// 'scratchpadCopyFn' is a helper that stores reduced
3629/// data from the team master to a scratchpad array in
3630/// global memory.
3631///
3632/// 'loadAndReduceFn' is a helper that loads data from
3633/// the scratchpad array and reduces it with the input
3634/// operand.
3635///
3636/// These compiler generated functions hide address
3637/// calculation and alignment information from the runtime.
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003638/// 5. if ret == 1:
3639/// The team master of the last team stores the reduced
3640/// result to the globals in memory.
3641/// foo += reduceData.foo; bar *= reduceData.bar
3642///
3643///
3644/// Warp Reduction Algorithms
3645///
3646/// On the warp level, we have three algorithms implemented in the
3647/// OpenMP runtime depending on the number of active lanes:
3648///
3649/// Full Warp Reduction
3650///
3651/// The reduce algorithm within a warp where all lanes are active
3652/// is implemented in the runtime as follows:
3653///
3654/// full_warp_reduce(void *reduce_data,
3655/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3656/// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
3657/// ShuffleReduceFn(reduce_data, 0, offset, 0);
3658/// }
3659///
3660/// The algorithm completes in log(2, WARPSIZE) steps.
3661///
3662/// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
3663/// not used therefore we save instructions by not retrieving lane_id
3664/// from the corresponding special registers. The 4th parameter, which
3665/// represents the version of the algorithm being used, is set to 0 to
3666/// signify full warp reduction.
3667///
3668/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3669///
3670/// #reduce_elem refers to an element in the local lane's data structure
3671/// #remote_elem is retrieved from a remote lane
3672/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3673/// reduce_elem = reduce_elem REDUCE_OP remote_elem;
3674///
3675/// Contiguous Partial Warp Reduction
3676///
3677/// This reduce algorithm is used within a warp where only the first
3678/// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
3679/// number of OpenMP threads in a parallel region is not a multiple of
3680/// WARPSIZE. The algorithm is implemented in the runtime as follows:
3681///
3682/// void
3683/// contiguous_partial_reduce(void *reduce_data,
3684/// kmp_ShuffleReductFctPtr ShuffleReduceFn,
3685/// int size, int lane_id) {
3686/// int curr_size;
3687/// int offset;
3688/// curr_size = size;
3689/// mask = curr_size/2;
3690/// while (offset>0) {
3691/// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
3692/// curr_size = (curr_size+1)/2;
3693/// offset = curr_size/2;
3694/// }
3695/// }
3696///
3697/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3698///
3699/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3700/// if (lane_id < offset)
3701/// reduce_elem = reduce_elem REDUCE_OP remote_elem
3702/// else
3703/// reduce_elem = remote_elem
3704///
3705/// This algorithm assumes that the data to be reduced are located in a
3706/// contiguous subset of lanes starting from the first. When there is
3707/// an odd number of active lanes, the data in the last lane is not
3708/// aggregated with any other lane's dat but is instead copied over.
3709///
3710/// Dispersed Partial Warp Reduction
3711///
3712/// This algorithm is used within a warp when any discontiguous subset of
3713/// lanes are active. It is used to implement the reduction operation
3714/// across lanes in an OpenMP simd region or in a nested parallel region.
3715///
3716/// void
3717/// dispersed_partial_reduce(void *reduce_data,
3718/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3719/// int size, remote_id;
3720/// int logical_lane_id = number_of_active_lanes_before_me() * 2;
3721/// do {
3722/// remote_id = next_active_lane_id_right_after_me();
3723/// # the above function returns 0 of no active lane
3724/// # is present right after the current lane.
3725/// size = number_of_active_lanes_in_this_warp();
3726/// logical_lane_id /= 2;
3727/// ShuffleReduceFn(reduce_data, logical_lane_id,
3728/// remote_id-1-threadIdx.x, 2);
3729/// } while (logical_lane_id % 2 == 0 && size > 1);
3730/// }
3731///
3732/// There is no assumption made about the initial state of the reduction.
3733/// Any number of lanes (>=1) could be active at any position. The reduction
3734/// result is returned in the first active lane.
3735///
3736/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3737///
3738/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3739/// if (lane_id % 2 == 0 && offset > 0)
3740/// reduce_elem = reduce_elem REDUCE_OP remote_elem
3741/// else
3742/// reduce_elem = remote_elem
3743///
3744///
3745/// Intra-Team Reduction
3746///
3747/// This function, as implemented in the runtime call
3748/// '__kmpc_nvptx_parallel_reduce_nowait', aggregates data across OpenMP
3749/// threads in a team. It first reduces within a warp using the
3750/// aforementioned algorithms. We then proceed to gather all such
3751/// reduced values at the first warp.
3752///
3753/// The runtime makes use of the function 'InterWarpCpyFn', which copies
3754/// data from each of the "warp master" (zeroth lane of each warp, where
3755/// warp-reduced data is held) to the zeroth warp. This step reduces (in
3756/// a mathematical sense) the problem of reduction across warp masters in
3757/// a block to the problem of warp reduction.
3758///
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003759///
3760/// Inter-Team Reduction
3761///
3762/// Once a team has reduced its data to a single value, it is stored in
3763/// a global scratchpad array. Since each team has a distinct slot, this
3764/// can be done without locking.
3765///
3766/// The last team to write to the scratchpad array proceeds to reduce the
3767/// scratchpad array. One or more workers in the last team use the helper
3768/// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
3769/// the k'th worker reduces every k'th element.
3770///
3771/// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait' to
3772/// reduce across workers and compute a globally reduced value.
3773///
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003774void CGOpenMPRuntimeNVPTX::emitReduction(
3775 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
3776 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
3777 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
3778 if (!CGF.HaveInsertPoint())
3779 return;
3780
3781 bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00003782#ifndef NDEBUG
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003783 bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00003784#endif
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003785
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00003786 if (Options.SimpleReduction) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003787 assert(!TeamsReduction && !ParallelReduction &&
3788 "Invalid reduction selection in emitReduction.");
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00003789 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
3790 ReductionOps, Options);
3791 return;
3792 }
3793
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003794 assert((TeamsReduction || ParallelReduction) &&
3795 "Invalid reduction selection in emitReduction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003796
Alexey Bataeva1166022018-11-27 21:24:54 +00003797 // Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003798 // RedList, shuffle_reduce_func, interwarp_copy_func);
Alexey Bataeva1166022018-11-27 21:24:54 +00003799 // or
3800 // Build res = __kmpc_reduce_teams_nowait_simple(<loc>, <gtid>, <lck>);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003801 llvm::Value *ThreadId = getThreadID(CGF, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003802
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003803 llvm::Value *Res;
3804 if (ParallelReduction) {
Alexey Bataeva1166022018-11-27 21:24:54 +00003805 ASTContext &C = CGM.getContext();
3806 // 1. Build a list of reduction variables.
3807 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3808 auto Size = RHSExprs.size();
3809 for (const Expr *E : Privates) {
3810 if (E->getType()->isVariablyModifiedType())
3811 // Reserve place for array size.
3812 ++Size;
3813 }
3814 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
3815 QualType ReductionArrayTy =
3816 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3817 /*IndexTypeQuals=*/0);
3818 Address ReductionList =
3819 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3820 auto IPriv = Privates.begin();
3821 unsigned Idx = 0;
3822 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
3823 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3824 CGF.getPointerSize());
3825 CGF.Builder.CreateStore(
3826 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3827 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
3828 Elem);
3829 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3830 // Store array size.
3831 ++Idx;
3832 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3833 CGF.getPointerSize());
3834 llvm::Value *Size = CGF.Builder.CreateIntCast(
3835 CGF.getVLASize(
3836 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3837 .NumElts,
3838 CGF.SizeTy, /*isSigned=*/false);
3839 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3840 Elem);
3841 }
3842 }
3843
3844 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
3845 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3846 ReductionList.getPointer(), CGF.VoidPtrTy);
3847 llvm::Value *ReductionFn = emitReductionFunction(
3848 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
3849 Privates, LHSExprs, RHSExprs, ReductionOps);
3850 llvm::Value *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
3851 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
3852 llvm::Value *InterWarpCopyFn =
3853 emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
3854
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003855 llvm::Value *Args[] = {ThreadId,
3856 CGF.Builder.getInt32(RHSExprs.size()),
3857 ReductionArrayTySize,
3858 RL,
3859 ShuffleAndReduceFn,
3860 InterWarpCopyFn};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003861
3862 Res = CGF.EmitRuntimeCall(
3863 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_reduce_nowait),
3864 Args);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003865 } else {
3866 assert(TeamsReduction && "expected teams reduction.");
Alexey Bataeva1166022018-11-27 21:24:54 +00003867 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
3868 std::string Name = getName({"reduction"});
3869 llvm::Value *Lock = getCriticalRegionLock(Name);
3870 llvm::Value *Args[] = {RTLoc, ThreadId, Lock};
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003871 Res = CGF.EmitRuntimeCall(
Alexey Bataeva1166022018-11-27 21:24:54 +00003872 createNVPTXRuntimeFunction(
3873 OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_simple),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003874 Args);
3875 }
3876
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003877 // 5. Build if (res == 1)
3878 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.reduction.done");
3879 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.then");
3880 llvm::Value *Cond = CGF.Builder.CreateICmpEQ(
3881 Res, llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1));
3882 CGF.Builder.CreateCondBr(Cond, ThenBB, ExitBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003883
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003884 // 6. Build then branch: where we have reduced values in the master
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003885 // thread in each team.
3886 // __kmpc_end_reduce{_nowait}(<gtid>);
3887 // break;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003888 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003889
3890 // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003891 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003892 this](CodeGenFunction &CGF, PrePostActionTy &Action) {
3893 auto IPriv = Privates.begin();
3894 auto ILHS = LHSExprs.begin();
3895 auto IRHS = RHSExprs.begin();
Alexey Bataev9ff80832018-04-16 20:16:21 +00003896 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003897 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
3898 cast<DeclRefExpr>(*IRHS));
3899 ++IPriv;
3900 ++ILHS;
3901 ++IRHS;
3902 }
3903 };
Alexey Bataeva1166022018-11-27 21:24:54 +00003904 if (ParallelReduction) {
3905 llvm::Value *EndArgs[] = {ThreadId};
3906 RegionCodeGenTy RCG(CodeGen);
3907 NVPTXActionTy Action(
3908 nullptr, llvm::None,
3909 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_reduce_nowait),
3910 EndArgs);
3911 RCG.setAction(Action);
3912 RCG(CGF);
3913 } else {
3914 assert(TeamsReduction && "expected teams reduction.");
3915 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
3916 std::string Name = getName({"reduction"});
3917 llvm::Value *Lock = getCriticalRegionLock(Name);
3918 llvm::Value *EndArgs[] = {RTLoc, ThreadId, Lock};
3919 RegionCodeGenTy RCG(CodeGen);
3920 NVPTXActionTy Action(
3921 nullptr, llvm::None,
3922 createNVPTXRuntimeFunction(
3923 OMPRTL_NVPTX__kmpc_nvptx_teams_end_reduce_nowait_simple),
3924 EndArgs);
3925 RCG.setAction(Action);
3926 RCG(CGF);
3927 }
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003928 // There is no need to emit line number for unconditional branch.
3929 (void)ApplyDebugLocation::CreateEmpty(CGF);
3930 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003931}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003932
3933const VarDecl *
3934CGOpenMPRuntimeNVPTX::translateParameter(const FieldDecl *FD,
3935 const VarDecl *NativeParam) const {
3936 if (!NativeParam->getType()->isReferenceType())
3937 return NativeParam;
3938 QualType ArgType = NativeParam->getType();
3939 QualifierCollector QC;
3940 const Type *NonQualTy = QC.strip(ArgType);
3941 QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
3942 if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
3943 if (Attr->getCaptureKind() == OMPC_map) {
3944 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
3945 LangAS::opencl_global);
3946 }
3947 }
3948 ArgType = CGM.getContext().getPointerType(PointeeTy);
3949 QC.addRestrict();
3950 enum { NVPTX_local_addr = 5 };
Alexander Richardson6d989432017-10-15 18:48:14 +00003951 QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003952 ArgType = QC.apply(CGM.getContext(), ArgType);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003953 if (isa<ImplicitParamDecl>(NativeParam))
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003954 return ImplicitParamDecl::Create(
3955 CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
3956 NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003957 return ParmVarDecl::Create(
3958 CGM.getContext(),
3959 const_cast<DeclContext *>(NativeParam->getDeclContext()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003960 NativeParam->getBeginLoc(), NativeParam->getLocation(),
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003961 NativeParam->getIdentifier(), ArgType,
3962 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003963}
3964
3965Address
3966CGOpenMPRuntimeNVPTX::getParameterAddress(CodeGenFunction &CGF,
3967 const VarDecl *NativeParam,
3968 const VarDecl *TargetParam) const {
3969 assert(NativeParam != TargetParam &&
3970 NativeParam->getType()->isReferenceType() &&
3971 "Native arg must not be the same as target arg.");
3972 Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
3973 QualType NativeParamType = NativeParam->getType();
3974 QualifierCollector QC;
3975 const Type *NonQualTy = QC.strip(NativeParamType);
3976 QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
3977 unsigned NativePointeeAddrSpace =
Alexander Richardson6d989432017-10-15 18:48:14 +00003978 CGF.getContext().getTargetAddressSpace(NativePointeeTy);
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00003979 QualType TargetTy = TargetParam->getType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003980 llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00003981 LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003982 // First cast to generic.
3983 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3984 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
3985 /*AddrSpace=*/0));
3986 // Cast from generic to native address space.
3987 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3988 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
3989 NativePointeeAddrSpace));
3990 Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
3991 CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00003992 NativeParamType);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003993 return NativeParamAddr;
3994}
3995
3996void CGOpenMPRuntimeNVPTX::emitOutlinedFunctionCall(
Alexey Bataev3c595a62017-08-14 15:01:03 +00003997 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003998 ArrayRef<llvm::Value *> Args) const {
3999 SmallVector<llvm::Value *, 4> TargetArgs;
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004000 TargetArgs.reserve(Args.size());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004001 auto *FnType =
4002 cast<llvm::FunctionType>(OutlinedFn->getType()->getPointerElementType());
4003 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004004 if (FnType->isVarArg() && FnType->getNumParams() <= I) {
4005 TargetArgs.append(std::next(Args.begin(), I), Args.end());
4006 break;
4007 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004008 llvm::Type *TargetType = FnType->getParamType(I);
4009 llvm::Value *NativeArg = Args[I];
4010 if (!TargetType->isPointerTy()) {
4011 TargetArgs.emplace_back(NativeArg);
4012 continue;
4013 }
4014 llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataevc99042b2018-03-15 18:10:54 +00004015 NativeArg,
4016 NativeArg->getType()->getPointerElementType()->getPointerTo());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004017 TargetArgs.emplace_back(
4018 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
4019 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00004020 CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004021}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004022
4023/// Emit function which wraps the outline parallel region
4024/// and controls the arguments which are passed to this function.
4025/// The wrapper ensures that the outlined function is called
4026/// with the correct arguments when data is shared.
4027llvm::Function *CGOpenMPRuntimeNVPTX::createParallelDataSharingWrapper(
4028 llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
4029 ASTContext &Ctx = CGM.getContext();
4030 const auto &CS = *D.getCapturedStmt(OMPD_parallel);
4031
4032 // Create a function that takes as argument the source thread.
4033 FunctionArgList WrapperArgs;
4034 QualType Int16QTy =
4035 Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
4036 QualType Int32QTy =
4037 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004038 ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004039 /*Id=*/nullptr, Int16QTy,
4040 ImplicitParamDecl::Other);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004041 ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004042 /*Id=*/nullptr, Int32QTy,
4043 ImplicitParamDecl::Other);
4044 WrapperArgs.emplace_back(&ParallelLevelArg);
4045 WrapperArgs.emplace_back(&WrapperArg);
4046
Alexey Bataev9ff80832018-04-16 20:16:21 +00004047 const CGFunctionInfo &CGFI =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004048 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
4049
4050 auto *Fn = llvm::Function::Create(
4051 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataev9ff80832018-04-16 20:16:21 +00004052 Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004053 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004054 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004055 Fn->setDoesNotRecurse();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004056
4057 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
4058 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004059 D.getBeginLoc(), D.getBeginLoc());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004060
4061 const auto *RD = CS.getCapturedRecordDecl();
4062 auto CurField = RD->field_begin();
4063
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004064 Address ZeroAddr = CGF.CreateMemTemp(
4065 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
4066 /*Name*/ ".zero.addr");
4067 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004068 // Get the array of arguments.
4069 SmallVector<llvm::Value *, 8> Args;
4070
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004071 Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).getPointer());
4072 Args.emplace_back(ZeroAddr.getPointer());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004073
4074 CGBuilderTy &Bld = CGF.Builder;
4075 auto CI = CS.capture_begin();
4076
4077 // Use global memory for data sharing.
4078 // Handle passing of global args to workers.
4079 Address GlobalArgs =
4080 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
4081 llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
4082 llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
4083 CGF.EmitRuntimeCall(
4084 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_get_shared_variables),
4085 DataSharingArgs);
4086
4087 // Retrieve the shared variables from the list of references returned
4088 // by the runtime. Pass the variables to the outlined function.
Alexey Bataev17314212018-03-20 15:41:05 +00004089 Address SharedArgListAddress = Address::invalid();
4090 if (CS.capture_size() > 0 ||
4091 isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4092 SharedArgListAddress = CGF.EmitLoadOfPointer(
4093 GlobalArgs, CGF.getContext()
4094 .getPointerType(CGF.getContext().getPointerType(
4095 CGF.getContext().VoidPtrTy))
4096 .castAs<PointerType>());
4097 }
4098 unsigned Idx = 0;
4099 if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4100 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
4101 CGF.getPointerSize());
4102 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4103 Src, CGF.SizeTy->getPointerTo());
4104 llvm::Value *LB = CGF.EmitLoadOfScalar(
4105 TypedAddress,
4106 /*Volatile=*/false,
4107 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4108 cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
4109 Args.emplace_back(LB);
4110 ++Idx;
4111 Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
4112 CGF.getPointerSize());
4113 TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4114 Src, CGF.SizeTy->getPointerTo());
4115 llvm::Value *UB = CGF.EmitLoadOfScalar(
4116 TypedAddress,
4117 /*Volatile=*/false,
4118 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4119 cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
4120 Args.emplace_back(UB);
4121 ++Idx;
4122 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004123 if (CS.capture_size() > 0) {
4124 ASTContext &CGFContext = CGF.getContext();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004125 for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
4126 QualType ElemTy = CurField->getType();
Alexey Bataev17314212018-03-20 15:41:05 +00004127 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx,
4128 CGF.getPointerSize());
4129 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004130 Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)));
4131 llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
4132 /*Volatile=*/false,
4133 CGFContext.getPointerType(ElemTy),
4134 CI->getLocation());
Alexey Bataev2091ca62018-04-23 17:33:41 +00004135 if (CI->capturesVariableByCopy() &&
4136 !CI->getCapturedVar()->getType()->isAnyPointerType()) {
Alexey Bataev17314212018-03-20 15:41:05 +00004137 Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
4138 CI->getLocation());
4139 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004140 Args.emplace_back(Arg);
4141 }
4142 }
4143
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004144 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedParallelFn, Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004145 CGF.FinishFunction();
4146 return Fn;
4147}
4148
4149void CGOpenMPRuntimeNVPTX::emitFunctionProlog(CodeGenFunction &CGF,
4150 const Decl *D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004151 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4152 return;
4153
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004154 assert(D && "Expected function or captured|block decl.");
4155 assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
4156 "Function is registered already.");
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004157 assert((!TeamAndReductions.first || TeamAndReductions.first == D) &&
4158 "Team is set but not processed.");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004159 const Stmt *Body = nullptr;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004160 bool NeedToDelayGlobalization = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004161 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4162 Body = FD->getBody();
4163 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
4164 Body = BD->getBody();
4165 } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
4166 Body = CD->getBody();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004167 NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
Alexey Bataev2adecff2018-09-21 14:22:53 +00004168 if (NeedToDelayGlobalization &&
4169 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
4170 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004171 }
4172 if (!Body)
4173 return;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004174 CheckVarsEscapingDeclContext VarChecker(CGF, TeamAndReductions.second);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004175 VarChecker.Visit(Body);
Alexey Bataevff23bb62018-10-11 18:30:31 +00004176 const RecordDecl *GlobalizedVarsRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004177 VarChecker.getGlobalizedRecord(IsInTTDRegion);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004178 TeamAndReductions.first = nullptr;
4179 TeamAndReductions.second.clear();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004180 ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
4181 VarChecker.getEscapedVariableLengthDecls();
4182 if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004183 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004184 auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
4185 I->getSecond().MappedParams =
4186 llvm::make_unique<CodeGenFunction::OMPMapVars>();
4187 I->getSecond().GlobalRecord = GlobalizedVarsRecord;
4188 I->getSecond().EscapedParameters.insert(
4189 VarChecker.getEscapedParameters().begin(),
4190 VarChecker.getEscapedParameters().end());
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004191 I->getSecond().EscapedVariableLengthDecls.append(
4192 EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004193 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004194 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004195 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004196 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004197 Data.insert(std::make_pair(VD, MappedVarData(FD, IsInTTDRegion)));
Alexey Bataevc99042b2018-03-15 18:10:54 +00004198 }
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004199 if (!IsInTTDRegion && !NeedToDelayGlobalization && !IsInParallelRegion) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004200 CheckVarsEscapingDeclContext VarChecker(CGF, llvm::None);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004201 VarChecker.Visit(Body);
4202 I->getSecond().SecondaryGlobalRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004203 VarChecker.getGlobalizedRecord(/*IsInTTDRegion=*/true);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004204 I->getSecond().SecondaryLocalVarData.emplace();
4205 DeclToAddrMapTy &Data = I->getSecond().SecondaryLocalVarData.getValue();
4206 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
4207 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
4208 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004209 Data.insert(
4210 std::make_pair(VD, MappedVarData(FD, /*IsInTTDRegion=*/true)));
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004211 }
4212 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00004213 if (!NeedToDelayGlobalization) {
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004214 emitGenericVarsProlog(CGF, D->getBeginLoc(), /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004215 struct GlobalizationScope final : EHScopeStack::Cleanup {
4216 GlobalizationScope() = default;
4217
4218 void Emit(CodeGenFunction &CGF, Flags flags) override {
4219 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004220 .emitGenericVarsEpilog(CGF, /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004221 }
4222 };
4223 CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004224 }
4225}
4226
4227Address CGOpenMPRuntimeNVPTX::getAddressOfLocalVariable(CodeGenFunction &CGF,
4228 const VarDecl *VD) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004229 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4230 return Address::invalid();
4231
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004232 VD = VD->getCanonicalDecl();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004233 auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
4234 if (I == FunctionGlobalizedDecls.end())
4235 return Address::invalid();
Alexey Bataevc99042b2018-03-15 18:10:54 +00004236 auto VDI = I->getSecond().LocalVarData.find(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004237 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004238 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004239 if (VD->hasAttrs()) {
4240 for (specific_attr_iterator<OMPReferencedVarAttr> IT(VD->attr_begin()),
4241 E(VD->attr_end());
4242 IT != E; ++IT) {
4243 auto VDI = I->getSecond().LocalVarData.find(
4244 cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
4245 ->getCanonicalDecl());
4246 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004247 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004248 }
4249 }
4250 return Address::invalid();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004251}
4252
4253void CGOpenMPRuntimeNVPTX::functionFinished(CodeGenFunction &CGF) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004254 FunctionGlobalizedDecls.erase(CGF.CurFn);
4255 CGOpenMPRuntime::functionFinished(CGF);
4256}
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004257
4258void CGOpenMPRuntimeNVPTX::getDefaultDistScheduleAndChunk(
4259 CodeGenFunction &CGF, const OMPLoopDirective &S,
4260 OpenMPDistScheduleClauseKind &ScheduleKind,
4261 llvm::Value *&Chunk) const {
4262 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
4263 ScheduleKind = OMPC_DIST_SCHEDULE_static;
4264 Chunk = CGF.EmitScalarConversion(getNVPTXNumThreads(CGF),
4265 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4266 S.getIterationVariable()->getType(), S.getBeginLoc());
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004267 return;
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004268 }
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004269 CGOpenMPRuntime::getDefaultDistScheduleAndChunk(
4270 CGF, S, ScheduleKind, Chunk);
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004271}
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004272
4273void CGOpenMPRuntimeNVPTX::getDefaultScheduleAndChunk(
4274 CodeGenFunction &CGF, const OMPLoopDirective &S,
4275 OpenMPScheduleClauseKind &ScheduleKind,
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004276 const Expr *&ChunkExpr) const {
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004277 ScheduleKind = OMPC_SCHEDULE_static;
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004278 // Chunk size is 1 in this case.
4279 llvm::APInt ChunkSize(32, 1);
4280 ChunkExpr = IntegerLiteral::Create(CGF.getContext(), ChunkSize,
4281 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4282 SourceLocation());
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004283}
Alexey Bataev60705422018-10-30 15:50:12 +00004284
4285void CGOpenMPRuntimeNVPTX::adjustTargetSpecificDataForLambdas(
4286 CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
4287 assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
4288 " Expected target-based directive.");
4289 const CapturedStmt *CS = D.getCapturedStmt(OMPD_target);
4290 for (const CapturedStmt::Capture &C : CS->captures()) {
4291 // Capture variables captured by reference in lambdas for target-based
4292 // directives.
4293 if (!C.capturesVariable())
4294 continue;
4295 const VarDecl *VD = C.getCapturedVar();
4296 const auto *RD = VD->getType()
4297 .getCanonicalType()
4298 .getNonReferenceType()
4299 ->getAsCXXRecordDecl();
4300 if (!RD || !RD->isLambda())
4301 continue;
4302 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4303 LValue VDLVal;
4304 if (VD->getType().getCanonicalType()->isReferenceType())
4305 VDLVal = CGF.EmitLoadOfReferenceLValue(VDAddr, VD->getType());
4306 else
4307 VDLVal = CGF.MakeAddrLValue(
4308 VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
4309 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4310 FieldDecl *ThisCapture = nullptr;
4311 RD->getCaptureFields(Captures, ThisCapture);
4312 if (ThisCapture && CGF.CapturedStmtInfo->isCXXThisExprCaptured()) {
4313 LValue ThisLVal =
4314 CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
4315 llvm::Value *CXXThis = CGF.LoadCXXThis();
4316 CGF.EmitStoreOfScalar(CXXThis, ThisLVal);
4317 }
4318 for (const LambdaCapture &LC : RD->captures()) {
4319 if (LC.getCaptureKind() != LCK_ByRef)
4320 continue;
4321 const VarDecl *VD = LC.getCapturedVar();
4322 if (!CS->capturesVariable(VD))
4323 continue;
4324 auto It = Captures.find(VD);
4325 assert(It != Captures.end() && "Found lambda capture without field.");
4326 LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
4327 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4328 if (VD->getType().getCanonicalType()->isReferenceType())
4329 VDAddr = CGF.EmitLoadOfReferenceLValue(VDAddr,
4330 VD->getType().getCanonicalType())
4331 .getAddress();
4332 CGF.EmitStoreOfScalar(VDAddr.getPointer(), VarLVal);
4333 }
4334 }
4335}
4336
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004337// Get current CudaArch and ignore any unknown values
4338static CudaArch getCudaArch(CodeGenModule &CGM) {
4339 if (!CGM.getTarget().hasFeature("ptx"))
4340 return CudaArch::UNKNOWN;
4341 llvm::StringMap<bool> Features;
4342 CGM.getTarget().initFeatureMap(Features, CGM.getDiags(),
4343 CGM.getTarget().getTargetOpts().CPU,
4344 CGM.getTarget().getTargetOpts().Features);
4345 for (const auto &Feature : Features) {
4346 if (Feature.getValue()) {
4347 CudaArch Arch = StringToCudaArch(Feature.getKey());
4348 if (Arch != CudaArch::UNKNOWN)
4349 return Arch;
4350 }
4351 }
4352 return CudaArch::UNKNOWN;
4353}
4354
4355/// Check to see if target architecture supports unified addressing which is
4356/// a restriction for OpenMP requires clause "unified_shared_memory".
4357void CGOpenMPRuntimeNVPTX::checkArchForUnifiedAddressing(
4358 CodeGenModule &CGM, const OMPRequiresDecl *D) const {
4359 for (const OMPClause *Clause : D->clauselists()) {
4360 if (Clause->getClauseKind() == OMPC_unified_shared_memory) {
4361 switch (getCudaArch(CGM)) {
4362 case CudaArch::SM_20:
4363 case CudaArch::SM_21:
4364 case CudaArch::SM_30:
4365 case CudaArch::SM_32:
4366 case CudaArch::SM_35:
4367 case CudaArch::SM_37:
4368 case CudaArch::SM_50:
4369 case CudaArch::SM_52:
4370 case CudaArch::SM_53:
4371 case CudaArch::SM_60:
4372 case CudaArch::SM_61:
4373 case CudaArch::SM_62:
4374 CGM.Error(Clause->getBeginLoc(),
4375 "Target architecture does not support unified addressing");
4376 return;
4377 case CudaArch::SM_70:
4378 case CudaArch::SM_72:
4379 case CudaArch::SM_75:
4380 case CudaArch::GFX600:
4381 case CudaArch::GFX601:
4382 case CudaArch::GFX700:
4383 case CudaArch::GFX701:
4384 case CudaArch::GFX702:
4385 case CudaArch::GFX703:
4386 case CudaArch::GFX704:
4387 case CudaArch::GFX801:
4388 case CudaArch::GFX802:
4389 case CudaArch::GFX803:
4390 case CudaArch::GFX810:
4391 case CudaArch::GFX900:
4392 case CudaArch::GFX902:
4393 case CudaArch::GFX904:
4394 case CudaArch::GFX906:
4395 case CudaArch::GFX909:
4396 case CudaArch::UNKNOWN:
4397 break;
4398 case CudaArch::LAST:
4399 llvm_unreachable("Unexpected Cuda arch.");
4400 }
4401 }
4402 }
4403}
4404
Alexey Bataeve4090182018-11-02 14:54:07 +00004405/// Get number of SMs and number of blocks per SM.
4406static std::pair<unsigned, unsigned> getSMsBlocksPerSM(CodeGenModule &CGM) {
4407 std::pair<unsigned, unsigned> Data;
4408 if (CGM.getLangOpts().OpenMPCUDANumSMs)
4409 Data.first = CGM.getLangOpts().OpenMPCUDANumSMs;
4410 if (CGM.getLangOpts().OpenMPCUDABlocksPerSM)
4411 Data.second = CGM.getLangOpts().OpenMPCUDABlocksPerSM;
4412 if (Data.first && Data.second)
4413 return Data;
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004414 switch (getCudaArch(CGM)) {
4415 case CudaArch::SM_20:
4416 case CudaArch::SM_21:
4417 case CudaArch::SM_30:
4418 case CudaArch::SM_32:
4419 case CudaArch::SM_35:
4420 case CudaArch::SM_37:
4421 case CudaArch::SM_50:
4422 case CudaArch::SM_52:
4423 case CudaArch::SM_53:
4424 return {16, 16};
4425 case CudaArch::SM_60:
4426 case CudaArch::SM_61:
4427 case CudaArch::SM_62:
4428 return {56, 32};
4429 case CudaArch::SM_70:
4430 case CudaArch::SM_72:
4431 case CudaArch::SM_75:
4432 return {84, 32};
4433 case CudaArch::GFX600:
4434 case CudaArch::GFX601:
4435 case CudaArch::GFX700:
4436 case CudaArch::GFX701:
4437 case CudaArch::GFX702:
4438 case CudaArch::GFX703:
4439 case CudaArch::GFX704:
4440 case CudaArch::GFX801:
4441 case CudaArch::GFX802:
4442 case CudaArch::GFX803:
4443 case CudaArch::GFX810:
4444 case CudaArch::GFX900:
4445 case CudaArch::GFX902:
4446 case CudaArch::GFX904:
4447 case CudaArch::GFX906:
4448 case CudaArch::GFX909:
4449 case CudaArch::UNKNOWN:
4450 break;
4451 case CudaArch::LAST:
4452 llvm_unreachable("Unexpected Cuda arch.");
Alexey Bataeve4090182018-11-02 14:54:07 +00004453 }
4454 llvm_unreachable("Unexpected NVPTX target without ptx feature.");
4455}
4456
4457void CGOpenMPRuntimeNVPTX::clear() {
4458 if (!GlobalizedRecords.empty()) {
4459 ASTContext &C = CGM.getContext();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004460 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> GlobalRecs;
4461 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> SharedRecs;
Alexey Bataeve4090182018-11-02 14:54:07 +00004462 RecordDecl *StaticRD = C.buildImplicitRecord(
4463 "_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
4464 StaticRD->startDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004465 RecordDecl *SharedStaticRD = C.buildImplicitRecord(
4466 "_shared_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
4467 SharedStaticRD->startDefinition();
Alexey Bataeve4090182018-11-02 14:54:07 +00004468 for (const GlobalPtrSizeRecsTy &Records : GlobalizedRecords) {
4469 if (Records.Records.empty())
4470 continue;
4471 unsigned Size = 0;
4472 unsigned RecAlignment = 0;
4473 for (const RecordDecl *RD : Records.Records) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004474 QualType RDTy = C.getRecordType(RD);
4475 unsigned Alignment = C.getTypeAlignInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00004476 RecAlignment = std::max(RecAlignment, Alignment);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004477 unsigned RecSize = C.getTypeSizeInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00004478 Size =
4479 llvm::alignTo(llvm::alignTo(Size, Alignment) + RecSize, Alignment);
4480 }
4481 Size = llvm::alignTo(Size, RecAlignment);
4482 llvm::APInt ArySize(/*numBits=*/64, Size);
4483 QualType SubTy = C.getConstantArrayType(
4484 C.CharTy, ArySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004485 const bool UseSharedMemory = Size <= SharedMemorySize;
4486 auto *Field =
4487 FieldDecl::Create(C, UseSharedMemory ? SharedStaticRD : StaticRD,
4488 SourceLocation(), SourceLocation(), nullptr, SubTy,
4489 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
4490 /*BW=*/nullptr, /*Mutable=*/false,
4491 /*InitStyle=*/ICIS_NoInit);
Alexey Bataeve4090182018-11-02 14:54:07 +00004492 Field->setAccess(AS_public);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004493 if (UseSharedMemory) {
4494 SharedStaticRD->addDecl(Field);
4495 SharedRecs.push_back(&Records);
4496 } else {
4497 StaticRD->addDecl(Field);
4498 GlobalRecs.push_back(&Records);
4499 }
Alexey Bataeve4090182018-11-02 14:54:07 +00004500 Records.RecSize->setInitializer(llvm::ConstantInt::get(CGM.SizeTy, Size));
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004501 Records.UseSharedMemory->setInitializer(
4502 llvm::ConstantInt::get(CGM.Int16Ty, UseSharedMemory ? 1 : 0));
4503 }
4504 SharedStaticRD->completeDefinition();
4505 if (!SharedStaticRD->field_empty()) {
4506 QualType StaticTy = C.getRecordType(SharedStaticRD);
4507 llvm::Type *LLVMStaticTy = CGM.getTypes().ConvertTypeForMem(StaticTy);
4508 auto *GV = new llvm::GlobalVariable(
4509 CGM.getModule(), LLVMStaticTy,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004510 /*isConstant=*/false, llvm::GlobalValue::CommonLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004511 llvm::Constant::getNullValue(LLVMStaticTy),
4512 "_openmp_shared_static_glob_rd_$_", /*InsertBefore=*/nullptr,
4513 llvm::GlobalValue::NotThreadLocal,
4514 C.getTargetAddressSpace(LangAS::cuda_shared));
4515 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
4516 GV, CGM.VoidPtrTy);
4517 for (const GlobalPtrSizeRecsTy *Rec : SharedRecs) {
4518 Rec->Buffer->replaceAllUsesWith(Replacement);
4519 Rec->Buffer->eraseFromParent();
4520 }
Alexey Bataeve4090182018-11-02 14:54:07 +00004521 }
4522 StaticRD->completeDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004523 if (!StaticRD->field_empty()) {
4524 QualType StaticTy = C.getRecordType(StaticRD);
4525 std::pair<unsigned, unsigned> SMsBlockPerSM = getSMsBlocksPerSM(CGM);
4526 llvm::APInt Size1(32, SMsBlockPerSM.second);
4527 QualType Arr1Ty =
4528 C.getConstantArrayType(StaticTy, Size1, ArrayType::Normal,
4529 /*IndexTypeQuals=*/0);
4530 llvm::APInt Size2(32, SMsBlockPerSM.first);
4531 QualType Arr2Ty = C.getConstantArrayType(Arr1Ty, Size2, ArrayType::Normal,
4532 /*IndexTypeQuals=*/0);
4533 llvm::Type *LLVMArr2Ty = CGM.getTypes().ConvertTypeForMem(Arr2Ty);
4534 auto *GV = new llvm::GlobalVariable(
4535 CGM.getModule(), LLVMArr2Ty,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004536 /*isConstant=*/false, llvm::GlobalValue::CommonLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004537 llvm::Constant::getNullValue(LLVMArr2Ty),
4538 "_openmp_static_glob_rd_$_");
4539 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
4540 GV, CGM.VoidPtrTy);
4541 for (const GlobalPtrSizeRecsTy *Rec : GlobalRecs) {
4542 Rec->Buffer->replaceAllUsesWith(Replacement);
4543 Rec->Buffer->eraseFromParent();
4544 }
4545 }
Alexey Bataeve4090182018-11-02 14:54:07 +00004546 }
4547 CGOpenMPRuntime::clear();
4548}