blob: 04de395662226c50e8ead1228e66e63c88ea5089 [file] [log] [blame]
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001//===---- CGOpenMPRuntimeNVPTX.cpp - Interface to OpenMP NVPTX Runtimes ---===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides a class for OpenMP runtime code generation specialized to NVPTX
11// targets.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CGOpenMPRuntimeNVPTX.h"
Carlo Bertollic6872252016-04-04 15:55:02 +000016#include "CodeGenFunction.h"
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000017#include "clang/AST/DeclOpenMP.h"
Carlo Bertollic6872252016-04-04 15:55:02 +000018#include "clang/AST/StmtOpenMP.h"
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000019#include "clang/AST/StmtVisitor.h"
20#include "llvm/ADT/SmallPtrSet.h"
Samuel Antao45bfe4c2016-02-08 15:59:20 +000021
22using namespace clang;
23using namespace CodeGen;
24
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +000025namespace {
26enum OpenMPRTLFunctionNVPTX {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000027 /// Call to void __kmpc_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +000028 /// int16_t RequiresOMPRuntime);
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +000029 OMPRTL_NVPTX__kmpc_kernel_init,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000030 /// Call to void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +000031 OMPRTL_NVPTX__kmpc_kernel_deinit,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000032 /// Call to void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +000033 /// int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +000034 OMPRTL_NVPTX__kmpc_spmd_kernel_init,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000035 /// Call to void __kmpc_spmd_kernel_deinit();
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +000036 OMPRTL_NVPTX__kmpc_spmd_kernel_deinit,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000037 /// Call to void __kmpc_kernel_prepare_parallel(void
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +000038 /// *outlined_function, int16_t
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +000039 /// IsOMPRuntimeInitialized);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000040 OMPRTL_NVPTX__kmpc_kernel_prepare_parallel,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000041 /// Call to bool __kmpc_kernel_parallel(void **outlined_function,
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +000042 /// int16_t IsOMPRuntimeInitialized);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000043 OMPRTL_NVPTX__kmpc_kernel_parallel,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000044 /// Call to void __kmpc_kernel_end_parallel();
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000045 OMPRTL_NVPTX__kmpc_kernel_end_parallel,
46 /// Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
47 /// global_tid);
48 OMPRTL_NVPTX__kmpc_serialized_parallel,
49 /// Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
50 /// global_tid);
51 OMPRTL_NVPTX__kmpc_end_serialized_parallel,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000052 /// Call to int32_t __kmpc_shuffle_int32(int32_t element,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000053 /// int16_t lane_offset, int16_t warp_size);
54 OMPRTL_NVPTX__kmpc_shuffle_int32,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000055 /// Call to int64_t __kmpc_shuffle_int64(int64_t element,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000056 /// int16_t lane_offset, int16_t warp_size);
57 OMPRTL_NVPTX__kmpc_shuffle_int64,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000058 /// Call to __kmpc_nvptx_parallel_reduce_nowait(kmp_int32
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000059 /// global_tid, kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
60 /// void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
61 /// lane_offset, int16_t shortCircuit),
62 /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num));
63 OMPRTL_NVPTX__kmpc_parallel_reduce_nowait,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000064 /// Call to __kmpc_nvptx_simd_reduce_nowait(kmp_int32
Alexey Bataevfac26cf2018-05-02 20:03:27 +000065 /// global_tid, kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
66 /// void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
67 /// lane_offset, int16_t shortCircuit),
68 /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num));
69 OMPRTL_NVPTX__kmpc_simd_reduce_nowait,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000070 /// Call to __kmpc_nvptx_teams_reduce_nowait(int32_t global_tid,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +000071 /// int32_t num_vars, size_t reduce_size, void *reduce_data,
72 /// void (*kmp_ShuffleReductFctPtr)(void *rhs, int16_t lane_id, int16_t
73 /// lane_offset, int16_t shortCircuit),
74 /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num),
75 /// void (*kmp_CopyToScratchpadFctPtr)(void *reduce_data, void * scratchpad,
76 /// int32_t index, int32_t width),
77 /// void (*kmp_LoadReduceFctPtr)(void *reduce_data, void * scratchpad, int32_t
78 /// index, int32_t width, int32_t reduce))
79 OMPRTL_NVPTX__kmpc_teams_reduce_nowait,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000080 /// Call to __kmpc_nvptx_end_reduce_nowait(int32_t global_tid);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000081 OMPRTL_NVPTX__kmpc_end_reduce_nowait,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000082 /// Call to void __kmpc_data_sharing_init_stack();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000083 OMPRTL_NVPTX__kmpc_data_sharing_init_stack,
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +000084 /// Call to void __kmpc_data_sharing_init_stack_spmd();
85 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000086 /// Call to void* __kmpc_data_sharing_push_stack(size_t size,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000087 /// int16_t UseSharedMemory);
88 OMPRTL_NVPTX__kmpc_data_sharing_push_stack,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000089 /// Call to void __kmpc_data_sharing_pop_stack(void *a);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000090 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000091 /// Call to void __kmpc_begin_sharing_variables(void ***args,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000092 /// size_t n_args);
93 OMPRTL_NVPTX__kmpc_begin_sharing_variables,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000094 /// Call to void __kmpc_end_sharing_variables();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000095 OMPRTL_NVPTX__kmpc_end_sharing_variables,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000096 /// Call to void __kmpc_get_shared_variables(void ***GlobalArgs)
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000097 OMPRTL_NVPTX__kmpc_get_shared_variables,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +000098 /// Call to uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32
99 /// global_tid);
100 OMPRTL_NVPTX__kmpc_parallel_level,
Alexey Bataev673110d2018-05-16 13:36:30 +0000101 /// Call to int8_t __kmpc_is_spmd_exec_mode();
102 OMPRTL_NVPTX__kmpc_is_spmd_exec_mode,
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000103};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000104
105/// Pre(post)-action for different OpenMP constructs specialized for NVPTX.
106class NVPTXActionTy final : public PrePostActionTy {
Alexey Bataev9ff80832018-04-16 20:16:21 +0000107 llvm::Value *EnterCallee = nullptr;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000108 ArrayRef<llvm::Value *> EnterArgs;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000109 llvm::Value *ExitCallee = nullptr;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000110 ArrayRef<llvm::Value *> ExitArgs;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000111 bool Conditional = false;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000112 llvm::BasicBlock *ContBlock = nullptr;
113
114public:
115 NVPTXActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
116 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
117 bool Conditional = false)
118 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
119 ExitArgs(ExitArgs), Conditional(Conditional) {}
120 void Enter(CodeGenFunction &CGF) override {
121 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
122 if (Conditional) {
123 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
124 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
125 ContBlock = CGF.createBasicBlock("omp_if.end");
126 // Generate the branch (If-stmt)
127 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
128 CGF.EmitBlock(ThenBlock);
129 }
130 }
131 void Done(CodeGenFunction &CGF) {
132 // Emit the rest of blocks/branches
133 CGF.EmitBranch(ContBlock);
134 CGF.EmitBlock(ContBlock, true);
135 }
136 void Exit(CodeGenFunction &CGF) override {
137 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
138 }
139};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000140
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000141/// A class to track the execution mode when codegening directives within
142/// a target region. The appropriate mode (SPMD|NON-SPMD) is set on entry
143/// to the target region and used by containing directives such as 'parallel'
144/// to emit optimized code.
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000145class ExecutionModeRAII {
146private:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000147 CGOpenMPRuntimeNVPTX::ExecutionMode SavedMode;
148 CGOpenMPRuntimeNVPTX::ExecutionMode &Mode;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000149
150public:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000151 ExecutionModeRAII(CGOpenMPRuntimeNVPTX::ExecutionMode &Mode, bool IsSPMD)
152 : Mode(Mode) {
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000153 SavedMode = Mode;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000154 Mode = IsSPMD ? CGOpenMPRuntimeNVPTX::EM_SPMD
155 : CGOpenMPRuntimeNVPTX::EM_NonSPMD;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000156 }
157 ~ExecutionModeRAII() { Mode = SavedMode; }
158};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000159
160/// GPU Configuration: This information can be derived from cuda registers,
161/// however, providing compile time constants helps generate more efficient
162/// code. For all practical purposes this is fine because the configuration
163/// is the same for all known NVPTX architectures.
164enum MachineConfiguration : unsigned {
165 WarpSize = 32,
166 /// Number of bits required to represent a lane identifier, which is
167 /// computed as log_2(WarpSize).
168 LaneIDBits = 5,
169 LaneIDMask = WarpSize - 1,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +0000170
171 /// Global memory alignment for performance.
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000172 GlobalMemoryAlignment = 128,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000173};
174
175enum NamedBarrier : unsigned {
176 /// Synchronize on this barrier #ID using a named barrier primitive.
177 /// Only the subset of active threads in a parallel region arrive at the
178 /// barrier.
179 NB_Parallel = 1,
180};
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000181
Alexey Bataev2adecff2018-09-21 14:22:53 +0000182typedef std::pair<CharUnits /*Align*/, const ValueDecl *> VarsDataTy;
183static bool stable_sort_comparator(const VarsDataTy P1, const VarsDataTy P2) {
184 return P1.first > P2.first;
185}
186
187static RecordDecl *buildRecordForGlobalizedVars(
188 ASTContext &C, ArrayRef<const ValueDecl *> EscapedDecls,
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000189 ArrayRef<const ValueDecl *> EscapedDeclsForTeams,
Alexey Bataev2adecff2018-09-21 14:22:53 +0000190 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
191 &MappedDeclsFields) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000192 if (EscapedDecls.empty() && EscapedDeclsForTeams.empty())
Alexey Bataev2adecff2018-09-21 14:22:53 +0000193 return nullptr;
194 SmallVector<VarsDataTy, 4> GlobalizedVars;
195 for (const ValueDecl *D : EscapedDecls)
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000196 GlobalizedVars.emplace_back(
197 CharUnits::fromQuantity(std::max(
198 C.getDeclAlign(D).getQuantity(),
199 static_cast<CharUnits::QuantityType>(GlobalMemoryAlignment))),
200 D);
201 for (const ValueDecl *D : EscapedDeclsForTeams)
Alexey Bataev2adecff2018-09-21 14:22:53 +0000202 GlobalizedVars.emplace_back(C.getDeclAlign(D), D);
203 std::stable_sort(GlobalizedVars.begin(), GlobalizedVars.end(),
204 stable_sort_comparator);
205 // Build struct _globalized_locals_ty {
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000206 // /* globalized vars */[32] align (max(decl_align, 128))
207 // /* globalized vars */ for EscapedDeclsForTeams
Alexey Bataev2adecff2018-09-21 14:22:53 +0000208 // };
209 RecordDecl *GlobalizedRD = C.buildImplicitRecord("_globalized_locals_ty");
210 GlobalizedRD->startDefinition();
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000211 llvm::SmallPtrSet<const ValueDecl *, 16> SingleEscaped(
212 EscapedDeclsForTeams.begin(), EscapedDeclsForTeams.end());
Alexey Bataev2adecff2018-09-21 14:22:53 +0000213 for (const auto &Pair : GlobalizedVars) {
214 const ValueDecl *VD = Pair.second;
215 QualType Type = VD->getType();
216 if (Type->isLValueReferenceType())
217 Type = C.getPointerType(Type.getNonReferenceType());
218 else
219 Type = Type.getNonReferenceType();
220 SourceLocation Loc = VD->getLocation();
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000221 FieldDecl *Field;
222 if (SingleEscaped.count(VD)) {
223 Field = FieldDecl::Create(
224 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
225 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
226 /*BW=*/nullptr, /*Mutable=*/false,
227 /*InitStyle=*/ICIS_NoInit);
228 Field->setAccess(AS_public);
229 if (VD->hasAttrs()) {
230 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
231 E(VD->getAttrs().end());
232 I != E; ++I)
233 Field->addAttr(*I);
234 }
235 } else {
236 llvm::APInt ArraySize(32, WarpSize);
237 Type = C.getConstantArrayType(Type, ArraySize, ArrayType::Normal, 0);
238 Field = FieldDecl::Create(
239 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
240 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
241 /*BW=*/nullptr, /*Mutable=*/false,
242 /*InitStyle=*/ICIS_NoInit);
243 Field->setAccess(AS_public);
244 llvm::APInt Align(32, std::max(C.getDeclAlign(VD).getQuantity(),
245 static_cast<CharUnits::QuantityType>(
246 GlobalMemoryAlignment)));
247 Field->addAttr(AlignedAttr::CreateImplicit(
248 C, AlignedAttr::GNU_aligned, /*IsAlignmentExpr=*/true,
249 IntegerLiteral::Create(C, Align,
250 C.getIntTypeForBitwidth(32, /*Signed=*/0),
251 SourceLocation())));
Alexey Bataev2adecff2018-09-21 14:22:53 +0000252 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000253 GlobalizedRD->addDecl(Field);
Alexey Bataev2adecff2018-09-21 14:22:53 +0000254 MappedDeclsFields.try_emplace(VD, Field);
255 }
256 GlobalizedRD->completeDefinition();
257 return GlobalizedRD;
258}
259
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000260/// Get the list of variables that can escape their declaration context.
261class CheckVarsEscapingDeclContext final
262 : public ConstStmtVisitor<CheckVarsEscapingDeclContext> {
263 CodeGenFunction &CGF;
264 llvm::SetVector<const ValueDecl *> EscapedDecls;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000265 llvm::SetVector<const ValueDecl *> EscapedVariableLengthDecls;
Alexey Bataevc99042b2018-03-15 18:10:54 +0000266 llvm::SmallPtrSet<const Decl *, 4> EscapedParameters;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000267 RecordDecl *GlobalizedRD = nullptr;
268 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000269 bool AllEscaped = false;
Alexey Bataev91433f62018-06-26 17:24:03 +0000270 bool IsForCombinedParallelRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000271
272 void markAsEscaped(const ValueDecl *VD) {
Alexey Bataev03f270c2018-03-30 18:31:07 +0000273 // Do not globalize declare target variables.
Alexey Bataev97b72212018-08-14 18:31:20 +0000274 if (!isa<VarDecl>(VD) ||
275 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataev03f270c2018-03-30 18:31:07 +0000276 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000277 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataevc99042b2018-03-15 18:10:54 +0000278 // Variables captured by value must be globalized.
279 if (auto *CSI = CGF.CapturedStmtInfo) {
Mikael Holmen9f373a32018-03-16 07:27:57 +0000280 if (const FieldDecl *FD = CSI->lookup(cast<VarDecl>(VD))) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000281 // Check if need to capture the variable that was already captured by
282 // value in the outer region.
Alexey Bataev91433f62018-06-26 17:24:03 +0000283 if (!IsForCombinedParallelRegion) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000284 if (!FD->hasAttrs())
285 return;
286 const auto *Attr = FD->getAttr<OMPCaptureKindAttr>();
287 if (!Attr)
288 return;
289 if (!isOpenMPPrivate(
290 static_cast<OpenMPClauseKind>(Attr->getCaptureKind())) ||
291 Attr->getCaptureKind() == OMPC_map)
292 return;
293 }
294 if (!FD->getType()->isReferenceType()) {
295 assert(!VD->getType()->isVariablyModifiedType() &&
296 "Parameter captured by value with variably modified type");
297 EscapedParameters.insert(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000298 } else if (!IsForCombinedParallelRegion) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000299 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000300 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000301 }
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000302 }
303 if ((!CGF.CapturedStmtInfo ||
Alexey Bataev91433f62018-06-26 17:24:03 +0000304 (IsForCombinedParallelRegion && CGF.CapturedStmtInfo)) &&
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000305 VD->getType()->isReferenceType())
306 // Do not globalize variables with reference type.
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000307 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000308 if (VD->getType()->isVariablyModifiedType())
309 EscapedVariableLengthDecls.insert(VD);
310 else
311 EscapedDecls.insert(VD);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000312 }
313
314 void VisitValueDecl(const ValueDecl *VD) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000315 if (VD->getType()->isLValueReferenceType())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000316 markAsEscaped(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000317 if (const auto *VarD = dyn_cast<VarDecl>(VD)) {
318 if (!isa<ParmVarDecl>(VarD) && VarD->hasInit()) {
319 const bool SavedAllEscaped = AllEscaped;
320 AllEscaped = VD->getType()->isLValueReferenceType();
321 Visit(VarD->getInit());
322 AllEscaped = SavedAllEscaped;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000323 }
324 }
325 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000326 void VisitOpenMPCapturedStmt(const CapturedStmt *S,
327 ArrayRef<OMPClause *> Clauses,
328 bool IsCombinedParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000329 if (!S)
330 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000331 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000332 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
333 const ValueDecl *VD = C.getCapturedVar();
Alexey Bataev91433f62018-06-26 17:24:03 +0000334 bool SavedIsForCombinedParallelRegion = IsForCombinedParallelRegion;
335 if (IsCombinedParallelRegion) {
336 // Check if the variable is privatized in the combined construct and
337 // those private copies must be shared in the inner parallel
338 // directive.
339 IsForCombinedParallelRegion = false;
340 for (const OMPClause *C : Clauses) {
341 if (!isOpenMPPrivate(C->getClauseKind()) ||
342 C->getClauseKind() == OMPC_reduction ||
343 C->getClauseKind() == OMPC_linear ||
344 C->getClauseKind() == OMPC_private)
345 continue;
346 ArrayRef<const Expr *> Vars;
347 if (const auto *PC = dyn_cast<OMPFirstprivateClause>(C))
348 Vars = PC->getVarRefs();
349 else if (const auto *PC = dyn_cast<OMPLastprivateClause>(C))
350 Vars = PC->getVarRefs();
351 else
352 llvm_unreachable("Unexpected clause.");
353 for (const auto *E : Vars) {
354 const Decl *D =
355 cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
356 if (D == VD->getCanonicalDecl()) {
357 IsForCombinedParallelRegion = true;
358 break;
359 }
360 }
361 if (IsForCombinedParallelRegion)
362 break;
363 }
364 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000365 markAsEscaped(VD);
366 if (isa<OMPCapturedExprDecl>(VD))
367 VisitValueDecl(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000368 IsForCombinedParallelRegion = SavedIsForCombinedParallelRegion;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000369 }
370 }
371 }
372
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000373 void buildRecordForGlobalizedVars() {
374 assert(!GlobalizedRD &&
375 "Record for globalized variables is built already.");
Alexey Bataev2adecff2018-09-21 14:22:53 +0000376 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000377 CGF.getContext(), EscapedDecls.getArrayRef(), llvm::None,
378 MappedDeclsFields);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000379 }
380
381public:
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000382 CheckVarsEscapingDeclContext(CodeGenFunction &CGF) : CGF(CGF) {}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000383 virtual ~CheckVarsEscapingDeclContext() = default;
384 void VisitDeclStmt(const DeclStmt *S) {
385 if (!S)
386 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000387 for (const Decl *D : S->decls())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000388 if (const auto *VD = dyn_cast_or_null<ValueDecl>(D))
389 VisitValueDecl(VD);
390 }
391 void VisitOMPExecutableDirective(const OMPExecutableDirective *D) {
392 if (!D)
393 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000394 if (!D->hasAssociatedStmt())
395 return;
396 if (const auto *S =
397 dyn_cast_or_null<CapturedStmt>(D->getAssociatedStmt())) {
398 // Do not analyze directives that do not actually require capturing,
399 // like `omp for` or `omp simd` directives.
400 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
401 getOpenMPCaptureRegions(CaptureRegions, D->getDirectiveKind());
402 if (CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown) {
403 VisitStmt(S->getCapturedStmt());
404 return;
Alexey Bataev673110d2018-05-16 13:36:30 +0000405 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000406 VisitOpenMPCapturedStmt(
407 S, D->clauses(),
408 CaptureRegions.back() == OMPD_parallel &&
409 isOpenMPDistributeDirective(D->getDirectiveKind()));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000410 }
411 }
412 void VisitCapturedStmt(const CapturedStmt *S) {
413 if (!S)
414 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000415 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000416 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
417 const ValueDecl *VD = C.getCapturedVar();
418 markAsEscaped(VD);
419 if (isa<OMPCapturedExprDecl>(VD))
420 VisitValueDecl(VD);
421 }
422 }
423 }
424 void VisitLambdaExpr(const LambdaExpr *E) {
425 if (!E)
426 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000427 for (const LambdaCapture &C : E->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000428 if (C.capturesVariable()) {
429 if (C.getCaptureKind() == LCK_ByRef) {
430 const ValueDecl *VD = C.getCapturedVar();
431 markAsEscaped(VD);
432 if (E->isInitCapture(&C) || isa<OMPCapturedExprDecl>(VD))
433 VisitValueDecl(VD);
434 }
435 }
436 }
437 }
438 void VisitBlockExpr(const BlockExpr *E) {
439 if (!E)
440 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000441 for (const BlockDecl::Capture &C : E->getBlockDecl()->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000442 if (C.isByRef()) {
443 const VarDecl *VD = C.getVariable();
444 markAsEscaped(VD);
445 if (isa<OMPCapturedExprDecl>(VD) || VD->isInitCapture())
446 VisitValueDecl(VD);
447 }
448 }
449 }
450 void VisitCallExpr(const CallExpr *E) {
451 if (!E)
452 return;
453 for (const Expr *Arg : E->arguments()) {
454 if (!Arg)
455 continue;
456 if (Arg->isLValue()) {
457 const bool SavedAllEscaped = AllEscaped;
458 AllEscaped = true;
459 Visit(Arg);
460 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000461 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000462 Visit(Arg);
Alexey Bataev9ff80832018-04-16 20:16:21 +0000463 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000464 }
465 Visit(E->getCallee());
466 }
467 void VisitDeclRefExpr(const DeclRefExpr *E) {
468 if (!E)
469 return;
470 const ValueDecl *VD = E->getDecl();
471 if (AllEscaped)
472 markAsEscaped(VD);
473 if (isa<OMPCapturedExprDecl>(VD))
474 VisitValueDecl(VD);
475 else if (const auto *VarD = dyn_cast<VarDecl>(VD))
476 if (VarD->isInitCapture())
477 VisitValueDecl(VD);
478 }
479 void VisitUnaryOperator(const UnaryOperator *E) {
480 if (!E)
481 return;
482 if (E->getOpcode() == UO_AddrOf) {
483 const bool SavedAllEscaped = AllEscaped;
484 AllEscaped = true;
485 Visit(E->getSubExpr());
486 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000487 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000488 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000489 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000490 }
491 void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
492 if (!E)
493 return;
494 if (E->getCastKind() == CK_ArrayToPointerDecay) {
495 const bool SavedAllEscaped = AllEscaped;
496 AllEscaped = true;
497 Visit(E->getSubExpr());
498 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000499 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000500 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000501 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000502 }
503 void VisitExpr(const Expr *E) {
504 if (!E)
505 return;
506 bool SavedAllEscaped = AllEscaped;
507 if (!E->isLValue())
508 AllEscaped = false;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000509 for (const Stmt *Child : E->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000510 if (Child)
511 Visit(Child);
512 AllEscaped = SavedAllEscaped;
513 }
514 void VisitStmt(const Stmt *S) {
515 if (!S)
516 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000517 for (const Stmt *Child : S->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000518 if (Child)
519 Visit(Child);
520 }
521
Alexey Bataevc99042b2018-03-15 18:10:54 +0000522 /// Returns the record that handles all the escaped local variables and used
523 /// instead of their original storage.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000524 const RecordDecl *getGlobalizedRecord() {
525 if (!GlobalizedRD)
526 buildRecordForGlobalizedVars();
527 return GlobalizedRD;
528 }
529
Alexey Bataevc99042b2018-03-15 18:10:54 +0000530 /// Returns the field in the globalized record for the escaped variable.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000531 const FieldDecl *getFieldForGlobalizedVar(const ValueDecl *VD) const {
532 assert(GlobalizedRD &&
533 "Record for globalized variables must be generated already.");
534 auto I = MappedDeclsFields.find(VD);
535 if (I == MappedDeclsFields.end())
536 return nullptr;
537 return I->getSecond();
538 }
539
Alexey Bataevc99042b2018-03-15 18:10:54 +0000540 /// Returns the list of the escaped local variables/parameters.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000541 ArrayRef<const ValueDecl *> getEscapedDecls() const {
542 return EscapedDecls.getArrayRef();
543 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000544
545 /// Checks if the escaped local variable is actually a parameter passed by
546 /// value.
547 const llvm::SmallPtrSetImpl<const Decl *> &getEscapedParameters() const {
548 return EscapedParameters;
549 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000550
551 /// Returns the list of the escaped variables with the variably modified
552 /// types.
553 ArrayRef<const ValueDecl *> getEscapedVariableLengthDecls() const {
554 return EscapedVariableLengthDecls.getArrayRef();
555 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000556};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000557} // anonymous namespace
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000558
559/// Get the GPU warp size.
560static llvm::Value *getNVPTXWarpSize(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000561 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000562 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000563 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_warpsize),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000564 "nvptx_warp_size");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000565}
566
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000567/// Get the id of the current thread on the GPU.
568static llvm::Value *getNVPTXThreadID(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000569 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000570 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000571 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_tid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000572 "nvptx_tid");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000573}
574
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000575/// Get the id of the warp in the block.
576/// We assume that the warp size is 32, which is always the case
577/// on the NVPTX device, to generate more efficient code.
578static llvm::Value *getNVPTXWarpID(CodeGenFunction &CGF) {
579 CGBuilderTy &Bld = CGF.Builder;
580 return Bld.CreateAShr(getNVPTXThreadID(CGF), LaneIDBits, "nvptx_warp_id");
581}
582
583/// Get the id of the current lane in the Warp.
584/// We assume that the warp size is 32, which is always the case
585/// on the NVPTX device, to generate more efficient code.
586static llvm::Value *getNVPTXLaneID(CodeGenFunction &CGF) {
587 CGBuilderTy &Bld = CGF.Builder;
588 return Bld.CreateAnd(getNVPTXThreadID(CGF), Bld.getInt32(LaneIDMask),
589 "nvptx_lane_id");
590}
591
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000592/// Get the maximum number of threads in a block of the GPU.
593static llvm::Value *getNVPTXNumThreads(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000594 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000595 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000596 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_ntid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000597 "nvptx_num_threads");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000598}
599
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000600/// Get barrier to synchronize all threads in a block.
601static void getNVPTXCTABarrier(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000602 CGF.EmitRuntimeCall(llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000603 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_barrier0));
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000604}
605
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000606/// Get barrier #ID to synchronize selected (multiple of warp size) threads in
607/// a CTA.
608static void getNVPTXBarrier(CodeGenFunction &CGF, int ID,
609 llvm::Value *NumThreads) {
610 CGBuilderTy &Bld = CGF.Builder;
611 llvm::Value *Args[] = {Bld.getInt32(ID), NumThreads};
Alexey Bataev3c595a62017-08-14 15:01:03 +0000612 CGF.EmitRuntimeCall(llvm::Intrinsic::getDeclaration(
613 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_barrier),
614 Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000615}
616
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000617/// Synchronize all GPU threads in a block.
618static void syncCTAThreads(CodeGenFunction &CGF) { getNVPTXCTABarrier(CGF); }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000619
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000620/// Synchronize worker threads in a parallel region.
621static void syncParallelThreads(CodeGenFunction &CGF, llvm::Value *NumThreads) {
622 return getNVPTXBarrier(CGF, NB_Parallel, NumThreads);
623}
624
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000625/// Get the value of the thread_limit clause in the teams directive.
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000626/// For the 'generic' execution mode, the runtime encodes thread_limit in
627/// the launch parameters, always starting thread_limit+warpSize threads per
628/// CTA. The threads in the last warp are reserved for master execution.
629/// For the 'spmd' execution mode, all threads in a CTA are part of the team.
630static llvm::Value *getThreadLimit(CodeGenFunction &CGF,
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000631 bool IsInSPMDExecutionMode = false) {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000632 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000633 return IsInSPMDExecutionMode
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000634 ? getNVPTXNumThreads(CGF)
Alexey Bataeve290ec02018-04-06 16:03:36 +0000635 : Bld.CreateNUWSub(getNVPTXNumThreads(CGF), getNVPTXWarpSize(CGF),
636 "thread_limit");
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000637}
638
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000639/// Get the thread id of the OMP master thread.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000640/// The master thread id is the first thread (lane) of the last warp in the
641/// GPU block. Warp size is assumed to be some power of 2.
642/// Thread id is 0 indexed.
643/// E.g: If NumThreads is 33, master id is 32.
644/// If NumThreads is 64, master id is 32.
645/// If NumThreads is 1024, master id is 992.
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000646static llvm::Value *getMasterThreadID(CodeGenFunction &CGF) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000647 CGBuilderTy &Bld = CGF.Builder;
648 llvm::Value *NumThreads = getNVPTXNumThreads(CGF);
649
650 // We assume that the warp size is a power of 2.
Alexey Bataeve290ec02018-04-06 16:03:36 +0000651 llvm::Value *Mask = Bld.CreateNUWSub(getNVPTXWarpSize(CGF), Bld.getInt32(1));
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000652
Alexey Bataeve290ec02018-04-06 16:03:36 +0000653 return Bld.CreateAnd(Bld.CreateNUWSub(NumThreads, Bld.getInt32(1)),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000654 Bld.CreateNot(Mask), "master_tid");
655}
656
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000657CGOpenMPRuntimeNVPTX::WorkerFunctionState::WorkerFunctionState(
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000658 CodeGenModule &CGM, SourceLocation Loc)
Alexey Bataev9ff80832018-04-16 20:16:21 +0000659 : WorkerFn(nullptr), CGFI(CGM.getTypes().arrangeNullaryFunction()),
660 Loc(Loc) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000661 createWorkerFunction(CGM);
Vasileios Kalintirise5c09592016-03-22 10:41:20 +0000662}
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000663
664void CGOpenMPRuntimeNVPTX::WorkerFunctionState::createWorkerFunction(
665 CodeGenModule &CGM) {
666 // Create an worker function with no arguments.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000667
668 WorkerFn = llvm::Function::Create(
Alexey Bataev9ff80832018-04-16 20:16:21 +0000669 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataevaee93892018-01-08 20:09:47 +0000670 /*placeholder=*/"_worker", &CGM.getModule());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000671 CGM.SetInternalFunctionAttributes(GlobalDecl(), WorkerFn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +0000672 WorkerFn->setDoesNotRecurse();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000673}
674
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000675CGOpenMPRuntimeNVPTX::ExecutionMode
676CGOpenMPRuntimeNVPTX::getExecutionMode() const {
677 return CurrentExecutionMode;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000678}
679
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000680static CGOpenMPRuntimeNVPTX::DataSharingMode
681getDataSharingMode(CodeGenModule &CGM) {
682 return CGM.getLangOpts().OpenMPCUDAMode ? CGOpenMPRuntimeNVPTX::CUDA
683 : CGOpenMPRuntimeNVPTX::Generic;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000684}
685
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000686/// Checks if the \p Body is the \a CompoundStmt and returns its child statement
687/// iff there is only one.
688static const Stmt *getSingleCompoundChild(const Stmt *Body) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000689 if (const auto *C = dyn_cast<CompoundStmt>(Body))
690 if (C->size() == 1)
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000691 return C->body_front();
692 return Body;
693}
694
695/// Check if the parallel directive has an 'if' clause with non-constant or
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000696/// false condition. Also, check if the number of threads is strictly specified
697/// and run those directives in non-SPMD mode.
698static bool hasParallelIfNumThreadsClause(ASTContext &Ctx,
699 const OMPExecutableDirective &D) {
700 if (D.hasClausesOfKind<OMPNumThreadsClause>())
701 return true;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000702 for (const auto *C : D.getClausesOfKind<OMPIfClause>()) {
703 OpenMPDirectiveKind NameModifier = C->getNameModifier();
704 if (NameModifier != OMPD_parallel && NameModifier != OMPD_unknown)
705 continue;
706 const Expr *Cond = C->getCondition();
707 bool Result;
708 if (!Cond->EvaluateAsBooleanCondition(Result, Ctx) || !Result)
709 return true;
710 }
711 return false;
712}
713
714/// Check for inner (nested) SPMD construct, if any
715static bool hasNestedSPMDDirective(ASTContext &Ctx,
716 const OMPExecutableDirective &D) {
717 const auto *CS = D.getInnermostCapturedStmt();
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000718 const auto *Body =
719 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000720 const Stmt *ChildStmt = getSingleCompoundChild(Body);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000721
722 if (const auto *NestedDir = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
723 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000724 switch (D.getDirectiveKind()) {
725 case OMPD_target:
Alexey Bataevdf093e72018-05-11 19:45:14 +0000726 if (isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000727 !hasParallelIfNumThreadsClause(Ctx, *NestedDir))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000728 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000729 if (DKind == OMPD_teams) {
730 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
731 /*IgnoreCaptured=*/true);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000732 if (!Body)
733 return false;
734 ChildStmt = getSingleCompoundChild(Body);
735 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
736 DKind = NND->getDirectiveKind();
Alexey Bataevdf093e72018-05-11 19:45:14 +0000737 if (isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000738 !hasParallelIfNumThreadsClause(Ctx, *NND))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000739 return true;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000740 }
741 }
742 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000743 case OMPD_target_teams:
Alexey Bataevdf093e72018-05-11 19:45:14 +0000744 return isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000745 !hasParallelIfNumThreadsClause(Ctx, *NestedDir);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000746 case OMPD_target_simd:
747 case OMPD_target_parallel:
748 case OMPD_target_parallel_for:
749 case OMPD_target_parallel_for_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000750 case OMPD_target_teams_distribute:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000751 case OMPD_target_teams_distribute_simd:
752 case OMPD_target_teams_distribute_parallel_for:
753 case OMPD_target_teams_distribute_parallel_for_simd:
754 case OMPD_parallel:
755 case OMPD_for:
756 case OMPD_parallel_for:
757 case OMPD_parallel_sections:
758 case OMPD_for_simd:
759 case OMPD_parallel_for_simd:
760 case OMPD_cancel:
761 case OMPD_cancellation_point:
762 case OMPD_ordered:
763 case OMPD_threadprivate:
764 case OMPD_task:
765 case OMPD_simd:
766 case OMPD_sections:
767 case OMPD_section:
768 case OMPD_single:
769 case OMPD_master:
770 case OMPD_critical:
771 case OMPD_taskyield:
772 case OMPD_barrier:
773 case OMPD_taskwait:
774 case OMPD_taskgroup:
775 case OMPD_atomic:
776 case OMPD_flush:
777 case OMPD_teams:
778 case OMPD_target_data:
779 case OMPD_target_exit_data:
780 case OMPD_target_enter_data:
781 case OMPD_distribute:
782 case OMPD_distribute_simd:
783 case OMPD_distribute_parallel_for:
784 case OMPD_distribute_parallel_for_simd:
785 case OMPD_teams_distribute:
786 case OMPD_teams_distribute_simd:
787 case OMPD_teams_distribute_parallel_for:
788 case OMPD_teams_distribute_parallel_for_simd:
789 case OMPD_target_update:
790 case OMPD_declare_simd:
791 case OMPD_declare_target:
792 case OMPD_end_declare_target:
793 case OMPD_declare_reduction:
794 case OMPD_taskloop:
795 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000796 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000797 case OMPD_unknown:
798 llvm_unreachable("Unexpected directive.");
799 }
800 }
801
802 return false;
803}
804
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000805static bool supportsSPMDExecutionMode(ASTContext &Ctx,
806 const OMPExecutableDirective &D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000807 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
808 switch (DirectiveKind) {
809 case OMPD_target:
810 case OMPD_target_teams:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000811 return hasNestedSPMDDirective(Ctx, D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000812 case OMPD_target_parallel:
813 case OMPD_target_parallel_for:
814 case OMPD_target_parallel_for_simd:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000815 case OMPD_target_teams_distribute_parallel_for:
816 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev2adecff2018-09-21 14:22:53 +0000817 return !hasParallelIfNumThreadsClause(Ctx, D);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000818 case OMPD_target_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000819 case OMPD_target_teams_distribute:
820 case OMPD_target_teams_distribute_simd:
821 return false;
822 case OMPD_parallel:
823 case OMPD_for:
824 case OMPD_parallel_for:
825 case OMPD_parallel_sections:
826 case OMPD_for_simd:
827 case OMPD_parallel_for_simd:
828 case OMPD_cancel:
829 case OMPD_cancellation_point:
830 case OMPD_ordered:
831 case OMPD_threadprivate:
832 case OMPD_task:
833 case OMPD_simd:
834 case OMPD_sections:
835 case OMPD_section:
836 case OMPD_single:
837 case OMPD_master:
838 case OMPD_critical:
839 case OMPD_taskyield:
840 case OMPD_barrier:
841 case OMPD_taskwait:
842 case OMPD_taskgroup:
843 case OMPD_atomic:
844 case OMPD_flush:
845 case OMPD_teams:
846 case OMPD_target_data:
847 case OMPD_target_exit_data:
848 case OMPD_target_enter_data:
849 case OMPD_distribute:
850 case OMPD_distribute_simd:
851 case OMPD_distribute_parallel_for:
852 case OMPD_distribute_parallel_for_simd:
853 case OMPD_teams_distribute:
854 case OMPD_teams_distribute_simd:
855 case OMPD_teams_distribute_parallel_for:
856 case OMPD_teams_distribute_parallel_for_simd:
857 case OMPD_target_update:
858 case OMPD_declare_simd:
859 case OMPD_declare_target:
860 case OMPD_end_declare_target:
861 case OMPD_declare_reduction:
862 case OMPD_taskloop:
863 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000864 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000865 case OMPD_unknown:
866 break;
867 }
868 llvm_unreachable(
869 "Unknown programming model for OpenMP directive on NVPTX target.");
870}
871
872/// Check if the directive is loops based and has schedule clause at all or has
873/// static scheduling.
874static bool hasStaticScheduling(const OMPExecutableDirective &D) {
875 assert(isOpenMPWorksharingDirective(D.getDirectiveKind()) &&
876 isOpenMPLoopDirective(D.getDirectiveKind()) &&
877 "Expected loop-based directive.");
878 return !D.hasClausesOfKind<OMPOrderedClause>() &&
879 (!D.hasClausesOfKind<OMPScheduleClause>() ||
880 llvm::any_of(D.getClausesOfKind<OMPScheduleClause>(),
881 [](const OMPScheduleClause *C) {
882 return C->getScheduleKind() == OMPC_SCHEDULE_static;
883 }));
884}
885
886/// Check for inner (nested) lightweight runtime construct, if any
887static bool hasNestedLightweightDirective(ASTContext &Ctx,
888 const OMPExecutableDirective &D) {
889 assert(supportsSPMDExecutionMode(Ctx, D) && "Expected SPMD mode directive.");
890 const auto *CS = D.getInnermostCapturedStmt();
891 const auto *Body =
892 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
893 const Stmt *ChildStmt = getSingleCompoundChild(Body);
894
895 if (const auto *NestedDir = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
896 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
897 switch (D.getDirectiveKind()) {
898 case OMPD_target:
899 if (isOpenMPParallelDirective(DKind) &&
900 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
901 hasStaticScheduling(*NestedDir))
902 return true;
903 if (DKind == OMPD_parallel) {
904 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
905 /*IgnoreCaptured=*/true);
906 if (!Body)
907 return false;
908 ChildStmt = getSingleCompoundChild(Body);
909 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
910 DKind = NND->getDirectiveKind();
911 if (isOpenMPWorksharingDirective(DKind) &&
912 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
913 return true;
914 }
915 } else if (DKind == OMPD_teams) {
916 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
917 /*IgnoreCaptured=*/true);
918 if (!Body)
919 return false;
920 ChildStmt = getSingleCompoundChild(Body);
921 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
922 DKind = NND->getDirectiveKind();
923 if (isOpenMPParallelDirective(DKind) &&
924 isOpenMPWorksharingDirective(DKind) &&
925 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
926 return true;
927 if (DKind == OMPD_parallel) {
928 Body = NND->getInnermostCapturedStmt()->IgnoreContainers(
929 /*IgnoreCaptured=*/true);
930 if (!Body)
931 return false;
932 ChildStmt = getSingleCompoundChild(Body);
933 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
934 DKind = NND->getDirectiveKind();
935 if (isOpenMPWorksharingDirective(DKind) &&
936 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
937 return true;
938 }
939 }
940 }
941 }
942 return false;
943 case OMPD_target_teams:
944 if (isOpenMPParallelDirective(DKind) &&
945 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
946 hasStaticScheduling(*NestedDir))
947 return true;
948 if (DKind == OMPD_parallel) {
949 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
950 /*IgnoreCaptured=*/true);
951 if (!Body)
952 return false;
953 ChildStmt = getSingleCompoundChild(Body);
954 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
955 DKind = NND->getDirectiveKind();
956 if (isOpenMPWorksharingDirective(DKind) &&
957 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
958 return true;
959 }
960 }
961 return false;
962 case OMPD_target_parallel:
963 return isOpenMPWorksharingDirective(DKind) &&
964 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NestedDir);
965 case OMPD_target_teams_distribute:
966 case OMPD_target_simd:
967 case OMPD_target_parallel_for:
968 case OMPD_target_parallel_for_simd:
969 case OMPD_target_teams_distribute_simd:
970 case OMPD_target_teams_distribute_parallel_for:
971 case OMPD_target_teams_distribute_parallel_for_simd:
972 case OMPD_parallel:
973 case OMPD_for:
974 case OMPD_parallel_for:
975 case OMPD_parallel_sections:
976 case OMPD_for_simd:
977 case OMPD_parallel_for_simd:
978 case OMPD_cancel:
979 case OMPD_cancellation_point:
980 case OMPD_ordered:
981 case OMPD_threadprivate:
982 case OMPD_task:
983 case OMPD_simd:
984 case OMPD_sections:
985 case OMPD_section:
986 case OMPD_single:
987 case OMPD_master:
988 case OMPD_critical:
989 case OMPD_taskyield:
990 case OMPD_barrier:
991 case OMPD_taskwait:
992 case OMPD_taskgroup:
993 case OMPD_atomic:
994 case OMPD_flush:
995 case OMPD_teams:
996 case OMPD_target_data:
997 case OMPD_target_exit_data:
998 case OMPD_target_enter_data:
999 case OMPD_distribute:
1000 case OMPD_distribute_simd:
1001 case OMPD_distribute_parallel_for:
1002 case OMPD_distribute_parallel_for_simd:
1003 case OMPD_teams_distribute:
1004 case OMPD_teams_distribute_simd:
1005 case OMPD_teams_distribute_parallel_for:
1006 case OMPD_teams_distribute_parallel_for_simd:
1007 case OMPD_target_update:
1008 case OMPD_declare_simd:
1009 case OMPD_declare_target:
1010 case OMPD_end_declare_target:
1011 case OMPD_declare_reduction:
1012 case OMPD_taskloop:
1013 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001014 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001015 case OMPD_unknown:
1016 llvm_unreachable("Unexpected directive.");
1017 }
1018 }
1019
1020 return false;
1021}
1022
1023/// Checks if the construct supports lightweight runtime. It must be SPMD
1024/// construct + inner loop-based construct with static scheduling.
1025static bool supportsLightweightRuntime(ASTContext &Ctx,
1026 const OMPExecutableDirective &D) {
1027 if (!supportsSPMDExecutionMode(Ctx, D))
1028 return false;
1029 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
1030 switch (DirectiveKind) {
1031 case OMPD_target:
1032 case OMPD_target_teams:
1033 case OMPD_target_parallel:
1034 return hasNestedLightweightDirective(Ctx, D);
1035 case OMPD_target_parallel_for:
1036 case OMPD_target_parallel_for_simd:
1037 case OMPD_target_teams_distribute_parallel_for:
1038 case OMPD_target_teams_distribute_parallel_for_simd:
1039 // (Last|First)-privates must be shared in parallel region.
1040 return hasStaticScheduling(D);
1041 case OMPD_target_simd:
1042 case OMPD_target_teams_distribute:
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001043 case OMPD_target_teams_distribute_simd:
Alexey Bataevdf093e72018-05-11 19:45:14 +00001044 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001045 case OMPD_parallel:
1046 case OMPD_for:
1047 case OMPD_parallel_for:
1048 case OMPD_parallel_sections:
1049 case OMPD_for_simd:
1050 case OMPD_parallel_for_simd:
1051 case OMPD_cancel:
1052 case OMPD_cancellation_point:
1053 case OMPD_ordered:
1054 case OMPD_threadprivate:
1055 case OMPD_task:
1056 case OMPD_simd:
1057 case OMPD_sections:
1058 case OMPD_section:
1059 case OMPD_single:
1060 case OMPD_master:
1061 case OMPD_critical:
1062 case OMPD_taskyield:
1063 case OMPD_barrier:
1064 case OMPD_taskwait:
1065 case OMPD_taskgroup:
1066 case OMPD_atomic:
1067 case OMPD_flush:
1068 case OMPD_teams:
1069 case OMPD_target_data:
1070 case OMPD_target_exit_data:
1071 case OMPD_target_enter_data:
1072 case OMPD_distribute:
1073 case OMPD_distribute_simd:
1074 case OMPD_distribute_parallel_for:
1075 case OMPD_distribute_parallel_for_simd:
1076 case OMPD_teams_distribute:
1077 case OMPD_teams_distribute_simd:
1078 case OMPD_teams_distribute_parallel_for:
1079 case OMPD_teams_distribute_parallel_for_simd:
1080 case OMPD_target_update:
1081 case OMPD_declare_simd:
1082 case OMPD_declare_target:
1083 case OMPD_end_declare_target:
1084 case OMPD_declare_reduction:
1085 case OMPD_taskloop:
1086 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001087 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001088 case OMPD_unknown:
1089 break;
1090 }
1091 llvm_unreachable(
1092 "Unknown programming model for OpenMP directive on NVPTX target.");
1093}
1094
1095void CGOpenMPRuntimeNVPTX::emitNonSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001096 StringRef ParentName,
1097 llvm::Function *&OutlinedFn,
1098 llvm::Constant *&OutlinedFnID,
1099 bool IsOffloadEntry,
1100 const RegionCodeGenTy &CodeGen) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001101 ExecutionModeRAII ModeRAII(CurrentExecutionMode, /*IsSPMD=*/false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001102 EntryFunctionState EST;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001103 WorkerFunctionState WST(CGM, D.getBeginLoc());
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001104 Work.clear();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001105 WrapperFunctionsMap.clear();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001106
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001107 // Emit target region as a standalone region.
1108 class NVPTXPrePostActionTy : public PrePostActionTy {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001109 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1110 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001111
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001112 public:
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001113 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001114 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST)
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001115 : EST(EST), WST(WST) {}
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001116 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev6bc27322018-10-05 15:27:47 +00001117 auto &RT = static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
1118 RT.emitNonSPMDEntryHeader(CGF, EST, WST);
1119 // Skip target region initialization.
1120 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001121 }
1122 void Exit(CodeGenFunction &CGF) override {
Alexey Bataev6bc27322018-10-05 15:27:47 +00001123 auto &RT = static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
1124 RT.clearLocThreadIdInsertPt(CGF);
1125 RT.emitNonSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001126 }
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001127 } Action(EST, WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001128 CodeGen.setAction(Action);
1129 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1130 IsOffloadEntry, CodeGen);
1131
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001132 // Now change the name of the worker function to correspond to this target
1133 // region's entry function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001134 WST.WorkerFn->setName(Twine(OutlinedFn->getName(), "_worker"));
Alexey Bataevaee93892018-01-08 20:09:47 +00001135
1136 // Create the worker function
1137 emitWorkerFunction(WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001138}
1139
1140// Setup NVPTX threads for master-worker OpenMP scheme.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001141void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryHeader(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001142 EntryFunctionState &EST,
1143 WorkerFunctionState &WST) {
1144 CGBuilderTy &Bld = CGF.Builder;
1145
1146 llvm::BasicBlock *WorkerBB = CGF.createBasicBlock(".worker");
1147 llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
1148 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
1149 EST.ExitBB = CGF.createBasicBlock(".exit");
1150
Alexey Bataev9ff80832018-04-16 20:16:21 +00001151 llvm::Value *IsWorker =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001152 Bld.CreateICmpULT(getNVPTXThreadID(CGF), getThreadLimit(CGF));
1153 Bld.CreateCondBr(IsWorker, WorkerBB, MasterCheckBB);
1154
1155 CGF.EmitBlock(WorkerBB);
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001156 emitCall(CGF, WST.Loc, WST.WorkerFn);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001157 CGF.EmitBranch(EST.ExitBB);
1158
1159 CGF.EmitBlock(MasterCheckBB);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001160 llvm::Value *IsMaster =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001161 Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
1162 Bld.CreateCondBr(IsMaster, MasterBB, EST.ExitBB);
1163
1164 CGF.EmitBlock(MasterBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001165 IsInTargetMasterThreadRegion = true;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001166 // SEQUENTIAL (MASTER) REGION START
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001167 // First action in sequential region:
1168 // Initialize the state of the OpenMP runtime library on the GPU.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001169 // TODO: Optimize runtime initialization and pass in correct value.
1170 llvm::Value *Args[] = {getThreadLimit(CGF),
1171 Bld.getInt16(/*RequiresOMPRuntime=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001172 CGF.EmitRuntimeCall(
1173 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_init), Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001174
1175 // For data sharing, we need to initialize the stack.
1176 CGF.EmitRuntimeCall(
1177 createNVPTXRuntimeFunction(
1178 OMPRTL_NVPTX__kmpc_data_sharing_init_stack));
1179
Alexey Bataevc99042b2018-03-15 18:10:54 +00001180 emitGenericVarsProlog(CGF, WST.Loc);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001181}
1182
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001183void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001184 EntryFunctionState &EST) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001185 IsInTargetMasterThreadRegion = false;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001186 if (!CGF.HaveInsertPoint())
1187 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001188
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001189 emitGenericVarsEpilog(CGF);
1190
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001191 if (!EST.ExitBB)
1192 EST.ExitBB = CGF.createBasicBlock(".exit");
1193
1194 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".termination.notifier");
1195 CGF.EmitBranch(TerminateBB);
1196
1197 CGF.EmitBlock(TerminateBB);
1198 // Signal termination condition.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001199 // TODO: Optimize runtime initialization and pass in correct value.
1200 llvm::Value *Args[] = {CGF.Builder.getInt16(/*IsOMPRuntimeInitialized=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001201 CGF.EmitRuntimeCall(
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001202 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_deinit), Args);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001203 // Barrier to terminate worker threads.
1204 syncCTAThreads(CGF);
1205 // Master thread jumps to exit point.
1206 CGF.EmitBranch(EST.ExitBB);
1207
1208 CGF.EmitBlock(EST.ExitBB);
1209 EST.ExitBB = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001210}
1211
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001212void CGOpenMPRuntimeNVPTX::emitSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001213 StringRef ParentName,
1214 llvm::Function *&OutlinedFn,
1215 llvm::Constant *&OutlinedFnID,
1216 bool IsOffloadEntry,
1217 const RegionCodeGenTy &CodeGen) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001218 ExecutionModeRAII ModeRAII(CurrentExecutionMode, /*IsSPMD=*/true);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001219 EntryFunctionState EST;
1220
1221 // Emit target region as a standalone region.
1222 class NVPTXPrePostActionTy : public PrePostActionTy {
1223 CGOpenMPRuntimeNVPTX &RT;
1224 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1225 const OMPExecutableDirective &D;
1226
1227 public:
1228 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT,
1229 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
1230 const OMPExecutableDirective &D)
1231 : RT(RT), EST(EST), D(D) {}
1232 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001233 RT.emitSPMDEntryHeader(CGF, EST, D);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001234 // Skip target region initialization.
1235 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001236 }
1237 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevfd006c42018-10-05 15:08:53 +00001238 RT.clearLocThreadIdInsertPt(CGF);
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001239 RT.emitSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001240 }
1241 } Action(*this, EST, D);
1242 CodeGen.setAction(Action);
1243 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1244 IsOffloadEntry, CodeGen);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001245}
1246
Alexey Bataeve79451a2018-10-01 16:20:57 +00001247static void
1248getDistributeLastprivateVars(const OMPExecutableDirective &D,
1249 llvm::SmallVectorImpl<const ValueDecl *> &Vars);
1250
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001251void CGOpenMPRuntimeNVPTX::emitSPMDEntryHeader(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001252 CodeGenFunction &CGF, EntryFunctionState &EST,
1253 const OMPExecutableDirective &D) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001254 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001255
1256 // Setup BBs in entry function.
1257 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute");
1258 EST.ExitBB = CGF.createBasicBlock(".exit");
1259
1260 // Initialize the OMP state in the runtime; called by all active threads.
Alexey Bataev80a9a612018-08-30 14:45:24 +00001261 bool RequiresFullRuntime = CGM.getLangOpts().OpenMPCUDAForceFullRuntime ||
1262 !supportsLightweightRuntime(CGF.getContext(), D);
Alexey Bataeve79451a2018-10-01 16:20:57 +00001263 // Check if we have inner distribute + lastprivate|reduction clauses.
1264 bool RequiresDatasharing = RequiresFullRuntime;
1265 if (!RequiresDatasharing) {
1266 const OMPExecutableDirective *TD = &D;
1267 if (!isOpenMPTeamsDirective(TD->getDirectiveKind()) &&
1268 !isOpenMPParallelDirective(TD->getDirectiveKind())) {
1269 const Stmt *S = getSingleCompoundChild(
1270 TD->getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
1271 /*IgnoreCaptured=*/true));
1272 TD = cast<OMPExecutableDirective>(S);
1273 }
1274 if (!isOpenMPDistributeDirective(TD->getDirectiveKind()) &&
1275 !isOpenMPParallelDirective(TD->getDirectiveKind())) {
1276 const Stmt *S = getSingleCompoundChild(
1277 TD->getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
1278 /*IgnoreCaptured=*/true));
1279 TD = cast<OMPExecutableDirective>(S);
1280 }
1281 if (isOpenMPDistributeDirective(TD->getDirectiveKind()))
1282 RequiresDatasharing = TD->hasClausesOfKind<OMPLastprivateClause>() ||
1283 TD->hasClausesOfKind<OMPReductionClause>();
1284 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001285 llvm::Value *Args[] = {
1286 getThreadLimit(CGF, /*IsInSPMDExecutionMode=*/true),
1287 /*RequiresOMPRuntime=*/
1288 Bld.getInt16(RequiresFullRuntime ? 1 : 0),
Alexey Bataeve79451a2018-10-01 16:20:57 +00001289 /*RequiresDataSharing=*/Bld.getInt16(RequiresDatasharing ? 1 : 0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001290 CGF.EmitRuntimeCall(
1291 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_init), Args);
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001292
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001293 if (RequiresFullRuntime) {
1294 // For data sharing, we need to initialize the stack.
1295 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1296 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd));
1297 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001298
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001299 CGF.EmitBranch(ExecuteBB);
1300
1301 CGF.EmitBlock(ExecuteBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001302
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001303 IsInTargetMasterThreadRegion = true;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001304}
1305
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001306void CGOpenMPRuntimeNVPTX::emitSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001307 EntryFunctionState &EST) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001308 IsInTargetMasterThreadRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001309 if (!CGF.HaveInsertPoint())
1310 return;
1311
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001312 if (!EST.ExitBB)
1313 EST.ExitBB = CGF.createBasicBlock(".exit");
1314
1315 llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit");
1316 CGF.EmitBranch(OMPDeInitBB);
1317
1318 CGF.EmitBlock(OMPDeInitBB);
1319 // DeInitialize the OMP state in the runtime; called by all active threads.
1320 CGF.EmitRuntimeCall(
1321 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_deinit), None);
1322 CGF.EmitBranch(EST.ExitBB);
1323
1324 CGF.EmitBlock(EST.ExitBB);
1325 EST.ExitBB = nullptr;
1326}
1327
1328// Create a unique global variable to indicate the execution mode of this target
1329// region. The execution mode is either 'generic', or 'spmd' depending on the
1330// target directive. This variable is picked up by the offload library to setup
1331// the device appropriately before kernel launch. If the execution mode is
1332// 'generic', the runtime reserves one warp for the master, otherwise, all
1333// warps participate in parallel work.
1334static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001335 bool Mode) {
1336 auto *GVMode =
1337 new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
1338 llvm::GlobalValue::WeakAnyLinkage,
1339 llvm::ConstantInt::get(CGM.Int8Ty, Mode ? 0 : 1),
1340 Twine(Name, "_exec_mode"));
Alexey Bataev9ff80832018-04-16 20:16:21 +00001341 CGM.addCompilerUsedGlobal(GVMode);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001342}
1343
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001344void CGOpenMPRuntimeNVPTX::emitWorkerFunction(WorkerFunctionState &WST) {
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +00001345 ASTContext &Ctx = CGM.getContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001346
1347 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001348 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, WST.CGFI, {},
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001349 WST.Loc, WST.Loc);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001350 emitWorkerLoop(CGF, WST);
1351 CGF.FinishFunction();
1352}
1353
1354void CGOpenMPRuntimeNVPTX::emitWorkerLoop(CodeGenFunction &CGF,
1355 WorkerFunctionState &WST) {
1356 //
1357 // The workers enter this loop and wait for parallel work from the master.
1358 // When the master encounters a parallel region it sets up the work + variable
1359 // arguments, and wakes up the workers. The workers first check to see if
1360 // they are required for the parallel region, i.e., within the # of requested
1361 // parallel threads. The activated workers load the variable arguments and
1362 // execute the parallel work.
1363 //
1364
1365 CGBuilderTy &Bld = CGF.Builder;
1366
1367 llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work");
1368 llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers");
1369 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel");
1370 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel");
1371 llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel");
1372 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1373
1374 CGF.EmitBranch(AwaitBB);
1375
1376 // Workers wait for work from master.
1377 CGF.EmitBlock(AwaitBB);
1378 // Wait for parallel work
1379 syncCTAThreads(CGF);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001380
1381 Address WorkFn =
1382 CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn");
1383 Address ExecStatus =
1384 CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status");
1385 CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0));
1386 CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy));
1387
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001388 // TODO: Optimize runtime initialization and pass in correct value.
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001389 llvm::Value *Args[] = {WorkFn.getPointer(),
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001390 /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001391 llvm::Value *Ret = CGF.EmitRuntimeCall(
1392 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args);
1393 Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001394
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001395 // On termination condition (workid == 0), exit loop.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001396 llvm::Value *WorkID = Bld.CreateLoad(WorkFn);
1397 llvm::Value *ShouldTerminate = Bld.CreateIsNull(WorkID, "should_terminate");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001398 Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB);
1399
1400 // Activate requested workers.
1401 CGF.EmitBlock(SelectWorkersBB);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001402 llvm::Value *IsActive =
1403 Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active");
1404 Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001405
1406 // Signal start of parallel region.
1407 CGF.EmitBlock(ExecuteBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001408
1409 // Process work items: outlined parallel functions.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001410 for (llvm::Function *W : Work) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001411 // Try to match this outlined function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001412 llvm::Value *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001413
1414 llvm::Value *WorkFnMatch =
1415 Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match");
1416
1417 llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn");
1418 llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next");
1419 Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB);
1420
1421 // Execute this outlined function.
1422 CGF.EmitBlock(ExecuteFNBB);
1423
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001424 // Insert call to work function via shared wrapper. The shared
1425 // wrapper takes two arguments:
1426 // - the parallelism level;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001427 // - the thread ID;
1428 emitCall(CGF, WST.Loc, W,
1429 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001430
1431 // Go to end of parallel region.
1432 CGF.EmitBranch(TerminateBB);
1433
1434 CGF.EmitBlock(CheckNextBB);
1435 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001436 // Default case: call to outlined function through pointer if the target
1437 // region makes a declare target call that may contain an orphaned parallel
1438 // directive.
1439 auto *ParallelFnTy =
1440 llvm::FunctionType::get(CGM.VoidTy, {CGM.Int16Ty, CGM.Int32Ty},
1441 /*isVarArg=*/false)
1442 ->getPointerTo();
1443 llvm::Value *WorkFnCast = Bld.CreateBitCast(WorkID, ParallelFnTy);
1444 // Insert call to work function via shared wrapper. The shared
1445 // wrapper takes two arguments:
1446 // - the parallelism level;
1447 // - the thread ID;
1448 emitCall(CGF, WST.Loc, WorkFnCast,
1449 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
1450 // Go to end of parallel region.
1451 CGF.EmitBranch(TerminateBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001452
1453 // Signal end of parallel region.
1454 CGF.EmitBlock(TerminateBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001455 CGF.EmitRuntimeCall(
1456 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_end_parallel),
1457 llvm::None);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001458 CGF.EmitBranch(BarrierBB);
1459
1460 // All active and inactive workers wait at a barrier after parallel region.
1461 CGF.EmitBlock(BarrierBB);
1462 // Barrier after parallel region.
1463 syncCTAThreads(CGF);
1464 CGF.EmitBranch(AwaitBB);
1465
1466 // Exit target region.
1467 CGF.EmitBlock(ExitBB);
1468}
1469
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001470/// Returns specified OpenMP runtime function for the current OpenMP
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001471/// implementation. Specialized for the NVPTX device.
1472/// \param Function OpenMP runtime function.
1473/// \return Specified function.
1474llvm::Constant *
1475CGOpenMPRuntimeNVPTX::createNVPTXRuntimeFunction(unsigned Function) {
1476 llvm::Constant *RTLFn = nullptr;
1477 switch (static_cast<OpenMPRTLFunctionNVPTX>(Function)) {
1478 case OMPRTL_NVPTX__kmpc_kernel_init: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001479 // Build void __kmpc_kernel_init(kmp_int32 thread_limit, int16_t
1480 // RequiresOMPRuntime);
1481 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001482 auto *FnTy =
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001483 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1484 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_init");
1485 break;
1486 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001487 case OMPRTL_NVPTX__kmpc_kernel_deinit: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001488 // Build void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
1489 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001490 auto *FnTy =
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001491 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001492 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_deinit");
1493 break;
1494 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001495 case OMPRTL_NVPTX__kmpc_spmd_kernel_init: {
1496 // Build void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001497 // int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001498 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001499 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001500 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1501 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_init");
1502 break;
1503 }
1504 case OMPRTL_NVPTX__kmpc_spmd_kernel_deinit: {
1505 // Build void __kmpc_spmd_kernel_deinit();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001506 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001507 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1508 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_deinit");
1509 break;
1510 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001511 case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: {
1512 /// Build void __kmpc_kernel_prepare_parallel(
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001513 /// void *outlined_function, int16_t IsOMPRuntimeInitialized);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001514 llvm::Type *TypeParams[] = {CGM.Int8PtrTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001515 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001516 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1517 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_prepare_parallel");
1518 break;
1519 }
1520 case OMPRTL_NVPTX__kmpc_kernel_parallel: {
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001521 /// Build bool __kmpc_kernel_parallel(void **outlined_function,
1522 /// int16_t IsOMPRuntimeInitialized);
1523 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy, CGM.Int16Ty};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001524 llvm::Type *RetTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001525 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001526 llvm::FunctionType::get(RetTy, TypeParams, /*isVarArg*/ false);
1527 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_parallel");
1528 break;
1529 }
1530 case OMPRTL_NVPTX__kmpc_kernel_end_parallel: {
1531 /// Build void __kmpc_kernel_end_parallel();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001532 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001533 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1534 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_end_parallel");
1535 break;
1536 }
1537 case OMPRTL_NVPTX__kmpc_serialized_parallel: {
1538 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1539 // global_tid);
1540 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001541 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001542 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1543 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1544 break;
1545 }
1546 case OMPRTL_NVPTX__kmpc_end_serialized_parallel: {
1547 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1548 // global_tid);
1549 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001550 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001551 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1552 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1553 break;
1554 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001555 case OMPRTL_NVPTX__kmpc_shuffle_int32: {
1556 // Build int32_t __kmpc_shuffle_int32(int32_t element,
1557 // int16_t lane_offset, int16_t warp_size);
1558 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001559 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001560 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1561 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int32");
1562 break;
1563 }
1564 case OMPRTL_NVPTX__kmpc_shuffle_int64: {
1565 // Build int64_t __kmpc_shuffle_int64(int64_t element,
1566 // int16_t lane_offset, int16_t warp_size);
1567 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001568 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001569 llvm::FunctionType::get(CGM.Int64Ty, TypeParams, /*isVarArg*/ false);
1570 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int64");
1571 break;
1572 }
1573 case OMPRTL_NVPTX__kmpc_parallel_reduce_nowait: {
1574 // Build int32_t kmpc_nvptx_parallel_reduce_nowait(kmp_int32 global_tid,
1575 // kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
1576 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1577 // lane_offset, int16_t Algorithm Version),
1578 // void (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
1579 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1580 CGM.Int16Ty, CGM.Int16Ty};
1581 auto *ShuffleReduceFnTy =
1582 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1583 /*isVarArg=*/false);
1584 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1585 auto *InterWarpCopyFnTy =
1586 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1587 /*isVarArg=*/false);
1588 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1589 CGM.Int32Ty,
1590 CGM.SizeTy,
1591 CGM.VoidPtrTy,
1592 ShuffleReduceFnTy->getPointerTo(),
1593 InterWarpCopyFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001594 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001595 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1596 RTLFn = CGM.CreateRuntimeFunction(
1597 FnTy, /*Name=*/"__kmpc_nvptx_parallel_reduce_nowait");
1598 break;
1599 }
Alexey Bataevfac26cf2018-05-02 20:03:27 +00001600 case OMPRTL_NVPTX__kmpc_simd_reduce_nowait: {
1601 // Build int32_t kmpc_nvptx_simd_reduce_nowait(kmp_int32 global_tid,
1602 // kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
1603 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1604 // lane_offset, int16_t Algorithm Version),
1605 // void (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
1606 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1607 CGM.Int16Ty, CGM.Int16Ty};
1608 auto *ShuffleReduceFnTy =
1609 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1610 /*isVarArg=*/false);
1611 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1612 auto *InterWarpCopyFnTy =
1613 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1614 /*isVarArg=*/false);
1615 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1616 CGM.Int32Ty,
1617 CGM.SizeTy,
1618 CGM.VoidPtrTy,
1619 ShuffleReduceFnTy->getPointerTo(),
1620 InterWarpCopyFnTy->getPointerTo()};
1621 auto *FnTy =
1622 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1623 RTLFn = CGM.CreateRuntimeFunction(
1624 FnTy, /*Name=*/"__kmpc_nvptx_simd_reduce_nowait");
1625 break;
1626 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001627 case OMPRTL_NVPTX__kmpc_teams_reduce_nowait: {
1628 // Build int32_t __kmpc_nvptx_teams_reduce_nowait(int32_t global_tid,
1629 // int32_t num_vars, size_t reduce_size, void *reduce_data,
1630 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1631 // lane_offset, int16_t shortCircuit),
1632 // void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num),
1633 // void (*kmp_CopyToScratchpadFctPtr)(void *reduce_data, void * scratchpad,
1634 // int32_t index, int32_t width),
1635 // void (*kmp_LoadReduceFctPtr)(void *reduce_data, void * scratchpad,
1636 // int32_t index, int32_t width, int32_t reduce))
1637 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1638 CGM.Int16Ty, CGM.Int16Ty};
1639 auto *ShuffleReduceFnTy =
1640 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1641 /*isVarArg=*/false);
1642 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1643 auto *InterWarpCopyFnTy =
1644 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1645 /*isVarArg=*/false);
1646 llvm::Type *CopyToScratchpadTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy,
1647 CGM.Int32Ty, CGM.Int32Ty};
1648 auto *CopyToScratchpadFnTy =
1649 llvm::FunctionType::get(CGM.VoidTy, CopyToScratchpadTypeParams,
1650 /*isVarArg=*/false);
1651 llvm::Type *LoadReduceTypeParams[] = {
1652 CGM.VoidPtrTy, CGM.VoidPtrTy, CGM.Int32Ty, CGM.Int32Ty, CGM.Int32Ty};
1653 auto *LoadReduceFnTy =
1654 llvm::FunctionType::get(CGM.VoidTy, LoadReduceTypeParams,
1655 /*isVarArg=*/false);
1656 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1657 CGM.Int32Ty,
1658 CGM.SizeTy,
1659 CGM.VoidPtrTy,
1660 ShuffleReduceFnTy->getPointerTo(),
1661 InterWarpCopyFnTy->getPointerTo(),
1662 CopyToScratchpadFnTy->getPointerTo(),
1663 LoadReduceFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001664 auto *FnTy =
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001665 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1666 RTLFn = CGM.CreateRuntimeFunction(
1667 FnTy, /*Name=*/"__kmpc_nvptx_teams_reduce_nowait");
1668 break;
1669 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001670 case OMPRTL_NVPTX__kmpc_end_reduce_nowait: {
1671 // Build __kmpc_end_reduce_nowait(kmp_int32 global_tid);
1672 llvm::Type *TypeParams[] = {CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001673 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001674 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1675 RTLFn = CGM.CreateRuntimeFunction(
1676 FnTy, /*Name=*/"__kmpc_nvptx_end_reduce_nowait");
1677 break;
1678 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001679 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack: {
1680 /// Build void __kmpc_data_sharing_init_stack();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001681 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001682 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1683 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack");
1684 break;
1685 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001686 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd: {
1687 /// Build void __kmpc_data_sharing_init_stack_spmd();
1688 auto *FnTy =
1689 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001690 RTLFn =
1691 CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack_spmd");
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001692 break;
1693 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001694 case OMPRTL_NVPTX__kmpc_data_sharing_push_stack: {
1695 // Build void *__kmpc_data_sharing_push_stack(size_t size,
1696 // int16_t UseSharedMemory);
1697 llvm::Type *TypeParams[] = {CGM.SizeTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001698 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001699 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1700 RTLFn = CGM.CreateRuntimeFunction(
1701 FnTy, /*Name=*/"__kmpc_data_sharing_push_stack");
1702 break;
1703 }
1704 case OMPRTL_NVPTX__kmpc_data_sharing_pop_stack: {
1705 // Build void __kmpc_data_sharing_pop_stack(void *a);
1706 llvm::Type *TypeParams[] = {CGM.VoidPtrTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001707 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001708 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1709 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1710 /*Name=*/"__kmpc_data_sharing_pop_stack");
1711 break;
1712 }
1713 case OMPRTL_NVPTX__kmpc_begin_sharing_variables: {
1714 /// Build void __kmpc_begin_sharing_variables(void ***args,
1715 /// size_t n_args);
1716 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo(), CGM.SizeTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001717 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001718 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1719 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_begin_sharing_variables");
1720 break;
1721 }
1722 case OMPRTL_NVPTX__kmpc_end_sharing_variables: {
1723 /// Build void __kmpc_end_sharing_variables();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001724 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001725 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1726 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_sharing_variables");
1727 break;
1728 }
1729 case OMPRTL_NVPTX__kmpc_get_shared_variables: {
1730 /// Build void __kmpc_get_shared_variables(void ***GlobalArgs);
1731 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001732 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001733 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1734 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_shared_variables");
1735 break;
1736 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001737 case OMPRTL_NVPTX__kmpc_parallel_level: {
1738 // Build uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32 global_tid);
1739 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1740 auto *FnTy =
1741 llvm::FunctionType::get(CGM.Int16Ty, TypeParams, /*isVarArg*/ false);
1742 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_parallel_level");
1743 break;
1744 }
Alexey Bataev673110d2018-05-16 13:36:30 +00001745 case OMPRTL_NVPTX__kmpc_is_spmd_exec_mode: {
1746 // Build int8_t __kmpc_is_spmd_exec_mode();
1747 auto *FnTy = llvm::FunctionType::get(CGM.Int8Ty, /*isVarArg=*/false);
1748 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_is_spmd_exec_mode");
1749 break;
1750 }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001751 }
1752 return RTLFn;
1753}
1754
1755void CGOpenMPRuntimeNVPTX::createOffloadEntry(llvm::Constant *ID,
1756 llvm::Constant *Addr,
Alexey Bataev03f270c2018-03-30 18:31:07 +00001757 uint64_t Size, int32_t,
1758 llvm::GlobalValue::LinkageTypes) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001759 // TODO: Add support for global variables on the device after declare target
1760 // support.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001761 if (!isa<llvm::Function>(Addr))
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001762 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +00001763 llvm::Module &M = CGM.getModule();
1764 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001765
1766 // Get "nvvm.annotations" metadata node
Alexey Bataev9ff80832018-04-16 20:16:21 +00001767 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001768
1769 llvm::Metadata *MDVals[] = {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001770 llvm::ConstantAsMetadata::get(Addr), llvm::MDString::get(Ctx, "kernel"),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001771 llvm::ConstantAsMetadata::get(
1772 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))};
1773 // Append metadata to nvvm.annotations
1774 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
1775}
1776
1777void CGOpenMPRuntimeNVPTX::emitTargetOutlinedFunction(
1778 const OMPExecutableDirective &D, StringRef ParentName,
1779 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001780 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001781 if (!IsOffloadEntry) // Nothing to do.
1782 return;
1783
1784 assert(!ParentName.empty() && "Invalid target region parent name!");
1785
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001786 bool Mode = supportsSPMDExecutionMode(CGM.getContext(), D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001787 if (Mode)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001788 emitSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001789 CodeGen);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001790 else
1791 emitNonSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1792 CodeGen);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001793
1794 setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001795}
1796
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001797CGOpenMPRuntimeNVPTX::CGOpenMPRuntimeNVPTX(CodeGenModule &CGM)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001798 : CGOpenMPRuntime(CGM, "_", "$") {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001799 if (!CGM.getLangOpts().OpenMPIsDevice)
1800 llvm_unreachable("OpenMP NVPTX can only handle device code.");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001801}
Carlo Bertollic6872252016-04-04 15:55:02 +00001802
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001803void CGOpenMPRuntimeNVPTX::emitProcBindClause(CodeGenFunction &CGF,
1804 OpenMPProcBindClauseKind ProcBind,
1805 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001806 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001807 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001808 return;
1809
1810 CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc);
1811}
1812
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001813void CGOpenMPRuntimeNVPTX::emitNumThreadsClause(CodeGenFunction &CGF,
1814 llvm::Value *NumThreads,
1815 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001816 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001817 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001818 return;
1819
1820 CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc);
1821}
1822
Carlo Bertollic6872252016-04-04 15:55:02 +00001823void CGOpenMPRuntimeNVPTX::emitNumTeamsClause(CodeGenFunction &CGF,
1824 const Expr *NumTeams,
1825 const Expr *ThreadLimit,
1826 SourceLocation Loc) {}
1827
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001828llvm::Value *CGOpenMPRuntimeNVPTX::emitParallelOutlinedFunction(
1829 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1830 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00001831 // Emit target region as a standalone region.
1832 class NVPTXPrePostActionTy : public PrePostActionTy {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001833 bool &IsInParallelRegion;
1834 bool PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001835
1836 public:
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001837 NVPTXPrePostActionTy(bool &IsInParallelRegion)
1838 : IsInParallelRegion(IsInParallelRegion) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00001839 void Enter(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001840 PrevIsInParallelRegion = IsInParallelRegion;
1841 IsInParallelRegion = true;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001842 }
1843 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001844 IsInParallelRegion = PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001845 }
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001846 } Action(IsInParallelRegion);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001847 CodeGen.setAction(Action);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001848 bool PrevIsInTargetMasterThreadRegion = IsInTargetMasterThreadRegion;
1849 IsInTargetMasterThreadRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001850 auto *OutlinedFun =
1851 cast<llvm::Function>(CGOpenMPRuntime::emitParallelOutlinedFunction(
1852 D, ThreadIDVar, InnermostKind, CodeGen));
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001853 IsInTargetMasterThreadRegion = PrevIsInTargetMasterThreadRegion;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001854 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD &&
1855 !IsInParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001856 llvm::Function *WrapperFun =
1857 createParallelDataSharingWrapper(OutlinedFun, D);
1858 WrapperFunctionsMap[OutlinedFun] = WrapperFun;
1859 }
1860
1861 return OutlinedFun;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001862}
1863
Alexey Bataev2adecff2018-09-21 14:22:53 +00001864/// Get list of lastprivate variables from the teams distribute ... or
1865/// teams {distribute ...} directives.
1866static void
1867getDistributeLastprivateVars(const OMPExecutableDirective &D,
1868 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
1869 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
1870 "expected teams directive.");
1871 const OMPExecutableDirective *Dir = &D;
1872 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
1873 if (const Stmt *S = getSingleCompoundChild(
1874 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
1875 /*IgnoreCaptured=*/true))) {
1876 Dir = dyn_cast<OMPExecutableDirective>(S);
1877 if (Dir && !isOpenMPDistributeDirective(Dir->getDirectiveKind()))
1878 Dir = nullptr;
1879 }
1880 }
1881 if (!Dir)
1882 return;
Alexey Bataev9ea3c382018-10-09 14:49:00 +00001883 for (const auto *C : Dir->getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00001884 for (const Expr *E : C->getVarRefs()) {
1885 const auto *DE = cast<DeclRefExpr>(E->IgnoreParens());
1886 Vars.push_back(cast<ValueDecl>(DE->getDecl()->getCanonicalDecl()));
1887 }
1888 }
1889}
1890
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001891llvm::Value *CGOpenMPRuntimeNVPTX::emitTeamsOutlinedFunction(
Carlo Bertollic6872252016-04-04 15:55:02 +00001892 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1893 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001894 SourceLocation Loc = D.getBeginLoc();
Carlo Bertollic6872252016-04-04 15:55:02 +00001895
Alexey Bataev2adecff2018-09-21 14:22:53 +00001896 const RecordDecl *GlobalizedRD = nullptr;
1897 llvm::SmallVector<const ValueDecl *, 4> LastPrivates;
1898 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
1899 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
1900 getDistributeLastprivateVars(D, LastPrivates);
1901 if (!LastPrivates.empty())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00001902 GlobalizedRD = ::buildRecordForGlobalizedVars(
1903 CGM.getContext(), llvm::None, LastPrivates, MappedDeclsFields);
Alexey Bataev2adecff2018-09-21 14:22:53 +00001904 }
1905
Alexey Bataevc99042b2018-03-15 18:10:54 +00001906 // Emit target region as a standalone region.
1907 class NVPTXPrePostActionTy : public PrePostActionTy {
1908 SourceLocation &Loc;
Alexey Bataev2adecff2018-09-21 14:22:53 +00001909 const RecordDecl *GlobalizedRD;
1910 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
1911 &MappedDeclsFields;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001912
1913 public:
Alexey Bataev2adecff2018-09-21 14:22:53 +00001914 NVPTXPrePostActionTy(
1915 SourceLocation &Loc, const RecordDecl *GlobalizedRD,
1916 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
1917 &MappedDeclsFields)
1918 : Loc(Loc), GlobalizedRD(GlobalizedRD),
1919 MappedDeclsFields(MappedDeclsFields) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00001920 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev2adecff2018-09-21 14:22:53 +00001921 auto &Rt =
1922 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
1923 if (GlobalizedRD) {
1924 auto I = Rt.FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
1925 I->getSecond().GlobalRecord = GlobalizedRD;
1926 I->getSecond().MappedParams =
1927 llvm::make_unique<CodeGenFunction::OMPMapVars>();
1928 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
1929 for (const auto &Pair : MappedDeclsFields) {
1930 assert(Pair.getFirst()->isCanonicalDecl() &&
1931 "Expected canonical declaration");
Alexey Bataev9ea3c382018-10-09 14:49:00 +00001932 Data.insert(std::make_pair(Pair.getFirst(),
1933 MappedVarData(Pair.getSecond(),
1934 /*IsOnePerTeam=*/true)));
Alexey Bataev2adecff2018-09-21 14:22:53 +00001935 }
1936 }
1937 Rt.emitGenericVarsProlog(CGF, Loc);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001938 }
1939 void Exit(CodeGenFunction &CGF) override {
1940 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
1941 .emitGenericVarsEpilog(CGF);
1942 }
Alexey Bataev2adecff2018-09-21 14:22:53 +00001943 } Action(Loc, GlobalizedRD, MappedDeclsFields);
1944 CodeGen.setAction(Action);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001945 llvm::Value *OutlinedFunVal = CGOpenMPRuntime::emitTeamsOutlinedFunction(
1946 D, ThreadIDVar, InnermostKind, CodeGen);
1947 llvm::Function *OutlinedFun = cast<llvm::Function>(OutlinedFunVal);
1948 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001949 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001950 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
Carlo Bertollic6872252016-04-04 15:55:02 +00001951
1952 return OutlinedFun;
1953}
1954
Alexey Bataevc99042b2018-03-15 18:10:54 +00001955void CGOpenMPRuntimeNVPTX::emitGenericVarsProlog(CodeGenFunction &CGF,
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00001956 SourceLocation Loc,
1957 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00001958 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
1959 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001960 return;
1961
Alexey Bataevc99042b2018-03-15 18:10:54 +00001962 CGBuilderTy &Bld = CGF.Builder;
1963
1964 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
1965 if (I == FunctionGlobalizedDecls.end())
1966 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001967 if (const RecordDecl *GlobalizedVarsRecord = I->getSecond().GlobalRecord) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00001968 QualType GlobalRecTy = CGM.getContext().getRecordType(GlobalizedVarsRecord);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001969
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001970 // Recover pointer to this function's global record. The runtime will
1971 // handle the specifics of the allocation of the memory.
1972 // Use actual memory size of the record including the padding
1973 // for alignment purposes.
1974 unsigned Alignment =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00001975 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001976 unsigned GlobalRecordSize =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00001977 CGM.getContext().getTypeSizeInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001978 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001979
Alexey Bataev9ea3c382018-10-09 14:49:00 +00001980 llvm::PointerType *GlobalRecPtrTy =
1981 CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo();
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001982 llvm::Value *GlobalRecCastAddr;
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00001983 if (WithSPMDCheck ||
1984 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001985 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1986 llvm::BasicBlock *SPMDBB = CGF.createBasicBlock(".spmd");
1987 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
1988 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
1989 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
1990 Bld.CreateCondBr(IsSPMD, SPMDBB, NonSPMDBB);
1991 // There is no need to emit line number for unconditional branch.
1992 (void)ApplyDebugLocation::CreateEmpty(CGF);
1993 CGF.EmitBlock(SPMDBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00001994 Address RecPtr = Address(llvm::ConstantPointerNull::get(GlobalRecPtrTy),
1995 CharUnits::fromQuantity(Alignment));
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001996 CGF.EmitBranch(ExitBB);
1997 // There is no need to emit line number for unconditional branch.
1998 (void)ApplyDebugLocation::CreateEmpty(CGF);
1999 CGF.EmitBlock(NonSPMDBB);
2000 // TODO: allow the usage of shared memory to be controlled by
2001 // the user, for now, default to global.
2002 llvm::Value *GlobalRecordSizeArg[] = {
2003 llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize),
2004 CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
2005 llvm::Value *GlobalRecValue =
2006 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2007 OMPRTL_NVPTX__kmpc_data_sharing_push_stack),
2008 GlobalRecordSizeArg);
2009 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002010 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002011 CGF.EmitBlock(ExitBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002012 auto *Phi = Bld.CreatePHI(GlobalRecPtrTy,
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002013 /*NumReservedValues=*/2, "_select_stack");
2014 Phi->addIncoming(RecPtr.getPointer(), SPMDBB);
2015 Phi->addIncoming(GlobalRecCastAddr, NonSPMDBB);
2016 GlobalRecCastAddr = Phi;
2017 I->getSecond().GlobalRecordAddr = Phi;
2018 I->getSecond().IsInSPMDModeFlag = IsSPMD;
2019 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002020 // TODO: allow the usage of shared memory to be controlled by
2021 // the user, for now, default to global.
2022 llvm::Value *GlobalRecordSizeArg[] = {
2023 llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize),
2024 CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
2025 llvm::Value *GlobalRecValue =
2026 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2027 OMPRTL_NVPTX__kmpc_data_sharing_push_stack),
2028 GlobalRecordSizeArg);
2029 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002030 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002031 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2032 I->getSecond().IsInSPMDModeFlag = nullptr;
2033 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002034 LValue Base =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002035 CGF.MakeNaturalAlignPointeeAddrLValue(GlobalRecCastAddr, GlobalRecTy);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002036
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002037 // Emit the "global alloca" which is a GEP from the global declaration
2038 // record using the pointer returned by the runtime.
2039 for (auto &Rec : I->getSecond().LocalVarData) {
2040 bool EscapedParam = I->getSecond().EscapedParameters.count(Rec.first);
2041 llvm::Value *ParValue;
2042 if (EscapedParam) {
2043 const auto *VD = cast<VarDecl>(Rec.first);
2044 LValue ParLVal =
2045 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
2046 ParValue = CGF.EmitLoadOfScalar(ParLVal, Loc);
2047 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002048 LValue VarAddr = CGF.EmitLValueForField(Base, Rec.second.FD);
2049 // Emit VarAddr basing on lane-id if required.
2050 QualType VarTy;
2051 if (Rec.second.IsOnePerTeam) {
2052 Rec.second.PrivateAddr = VarAddr.getAddress();
2053 VarTy = Rec.second.FD->getType();
2054 } else {
2055 llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(
2056 VarAddr.getAddress().getPointer(),
2057 {Bld.getInt32(0), getNVPTXLaneID(CGF)});
2058 Rec.second.PrivateAddr =
2059 Address(Ptr, CGM.getContext().getDeclAlign(Rec.first));
2060 VarTy =
2061 Rec.second.FD->getType()->castAsArrayTypeUnsafe()->getElementType();
2062 VarAddr = CGF.MakeAddrLValue(Rec.second.PrivateAddr, VarTy,
2063 AlignmentSource::Decl);
2064 }
2065 if (WithSPMDCheck ||
2066 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown) {
2067 assert(I->getSecond().IsInSPMDModeFlag &&
2068 "Expected unknown execution mode or required SPMD check.");
2069 Address GlobalPtr = Rec.second.PrivateAddr;
2070 Address LocalAddr = CGF.CreateMemTemp(VarTy, Rec.second.FD->getName());
2071 Rec.second.PrivateAddr = Address(
2072 Bld.CreateSelect(I->getSecond().IsInSPMDModeFlag,
2073 LocalAddr.getPointer(), GlobalPtr.getPointer()),
2074 LocalAddr.getAlignment());
2075 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002076 if (EscapedParam) {
2077 const auto *VD = cast<VarDecl>(Rec.first);
2078 CGF.EmitStoreOfScalar(ParValue, VarAddr);
2079 I->getSecond().MappedParams->setVarAddr(CGF, VD, VarAddr.getAddress());
2080 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00002081 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002082 }
2083 for (const ValueDecl *VD : I->getSecond().EscapedVariableLengthDecls) {
2084 // Recover pointer to this function's global record. The runtime will
2085 // handle the specifics of the allocation of the memory.
2086 // Use actual memory size of the record including the padding
2087 // for alignment purposes.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002088 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002089 llvm::Value *Size = CGF.getTypeSize(VD->getType());
2090 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2091 Size = Bld.CreateNUWAdd(
2092 Size, llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity() - 1));
2093 llvm::Value *AlignVal =
2094 llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity());
2095 Size = Bld.CreateUDiv(Size, AlignVal);
2096 Size = Bld.CreateNUWMul(Size, AlignVal);
2097 // TODO: allow the usage of shared memory to be controlled by
2098 // the user, for now, default to global.
2099 llvm::Value *GlobalRecordSizeArg[] = {
2100 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
2101 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2102 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_push_stack),
2103 GlobalRecordSizeArg);
2104 llvm::Value *GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2105 GlobalRecValue, CGF.ConvertTypeForMem(VD->getType())->getPointerTo());
2106 LValue Base = CGF.MakeAddrLValue(GlobalRecCastAddr, VD->getType(),
2107 CGM.getContext().getDeclAlign(VD),
2108 AlignmentSource::Decl);
2109 I->getSecond().MappedParams->setVarAddr(CGF, cast<VarDecl>(VD),
2110 Base.getAddress());
2111 I->getSecond().EscapedVariableLengthDeclsAddrs.emplace_back(GlobalRecValue);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002112 }
2113 I->getSecond().MappedParams->apply(CGF);
2114}
2115
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002116void CGOpenMPRuntimeNVPTX::emitGenericVarsEpilog(CodeGenFunction &CGF,
2117 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002118 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2119 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002120 return;
2121
Alexey Bataevc99042b2018-03-15 18:10:54 +00002122 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002123 if (I != FunctionGlobalizedDecls.end()) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00002124 I->getSecond().MappedParams->restore(CGF);
2125 if (!CGF.HaveInsertPoint())
2126 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002127 for (llvm::Value *Addr :
2128 llvm::reverse(I->getSecond().EscapedVariableLengthDeclsAddrs)) {
2129 CGF.EmitRuntimeCall(
2130 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2131 Addr);
2132 }
2133 if (I->getSecond().GlobalRecordAddr) {
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002134 if (WithSPMDCheck ||
2135 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002136 CGBuilderTy &Bld = CGF.Builder;
2137 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2138 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
2139 Bld.CreateCondBr(I->getSecond().IsInSPMDModeFlag, ExitBB, NonSPMDBB);
2140 // There is no need to emit line number for unconditional branch.
2141 (void)ApplyDebugLocation::CreateEmpty(CGF);
2142 CGF.EmitBlock(NonSPMDBB);
2143 CGF.EmitRuntimeCall(
2144 createNVPTXRuntimeFunction(
2145 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2146 CGF.EmitCastToVoidPtr(I->getSecond().GlobalRecordAddr));
2147 CGF.EmitBlock(ExitBB);
2148 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002149 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2150 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2151 I->getSecond().GlobalRecordAddr);
2152 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002153 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00002154 }
2155}
2156
Carlo Bertollic6872252016-04-04 15:55:02 +00002157void CGOpenMPRuntimeNVPTX::emitTeamsCall(CodeGenFunction &CGF,
2158 const OMPExecutableDirective &D,
2159 SourceLocation Loc,
2160 llvm::Value *OutlinedFn,
2161 ArrayRef<llvm::Value *> CapturedVars) {
2162 if (!CGF.HaveInsertPoint())
2163 return;
2164
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002165 Address ZeroAddr = CGF.CreateMemTemp(
2166 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2167 /*Name*/ ".zero.addr");
Carlo Bertollic6872252016-04-04 15:55:02 +00002168 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2169 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002170 OutlinedFnArgs.push_back(emitThreadIDAddress(CGF, Loc).getPointer());
Carlo Bertollic6872252016-04-04 15:55:02 +00002171 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2172 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002173 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Carlo Bertollic6872252016-04-04 15:55:02 +00002174}
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002175
2176void CGOpenMPRuntimeNVPTX::emitParallelCall(
2177 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2178 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2179 if (!CGF.HaveInsertPoint())
2180 return;
2181
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002182 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002183 emitSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002184 else
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002185 emitNonSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002186}
2187
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002188void CGOpenMPRuntimeNVPTX::emitNonSPMDParallelCall(
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002189 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2190 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2191 llvm::Function *Fn = cast<llvm::Function>(OutlinedFn);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002192
2193 // Force inline this outlined function at its call site.
2194 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
2195
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002196 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2197 /*DestWidth=*/32, /*Signed=*/1),
2198 ".zero.addr");
2199 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002200 // ThreadId for serialized parallels is 0.
2201 Address ThreadIDAddr = ZeroAddr;
2202 auto &&CodeGen = [this, Fn, CapturedVars, Loc, ZeroAddr, &ThreadIDAddr](
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002203 CodeGenFunction &CGF, PrePostActionTy &Action) {
2204 Action.Enter(CGF);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002205
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002206 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2207 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2208 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2209 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2210 emitOutlinedFunctionCall(CGF, Loc, Fn, OutlinedFnArgs);
2211 };
2212 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2213 PrePostActionTy &) {
2214
2215 RegionCodeGenTy RCG(CodeGen);
2216 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2217 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2218 llvm::Value *Args[] = {RTLoc, ThreadID};
2219
2220 NVPTXActionTy Action(
2221 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2222 Args,
2223 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2224 Args);
2225 RCG.setAction(Action);
2226 RCG(CGF);
2227 };
2228
2229 auto &&L0ParallelGen = [this, CapturedVars, Fn](CodeGenFunction &CGF,
2230 PrePostActionTy &Action) {
2231 CGBuilderTy &Bld = CGF.Builder;
2232 llvm::Function *WFn = WrapperFunctionsMap[Fn];
2233 assert(WFn && "Wrapper function does not exist!");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002234 llvm::Value *ID = Bld.CreateBitOrPointerCast(WFn, CGM.Int8PtrTy);
2235
2236 // Prepare for parallel region. Indicate the outlined function.
2237 llvm::Value *Args[] = {ID, /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002238 CGF.EmitRuntimeCall(
2239 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_prepare_parallel),
2240 Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002241
2242 // Create a private scope that will globalize the arguments
2243 // passed from the outside of the target region.
2244 CodeGenFunction::OMPPrivateScope PrivateArgScope(CGF);
2245
2246 // There's somehting to share.
2247 if (!CapturedVars.empty()) {
2248 // Prepare for parallel region. Indicate the outlined function.
2249 Address SharedArgs =
2250 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "shared_arg_refs");
2251 llvm::Value *SharedArgsPtr = SharedArgs.getPointer();
2252
2253 llvm::Value *DataSharingArgs[] = {
2254 SharedArgsPtr,
2255 llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size())};
2256 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2257 OMPRTL_NVPTX__kmpc_begin_sharing_variables),
2258 DataSharingArgs);
2259
2260 // Store variable address in a list of references to pass to workers.
2261 unsigned Idx = 0;
2262 ASTContext &Ctx = CGF.getContext();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002263 Address SharedArgListAddress = CGF.EmitLoadOfPointer(
2264 SharedArgs, Ctx.getPointerType(Ctx.getPointerType(Ctx.VoidPtrTy))
2265 .castAs<PointerType>());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002266 for (llvm::Value *V : CapturedVars) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002267 Address Dst = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
2268 CGF.getPointerSize());
2269 llvm::Value *PtrV;
Alexey Bataev17314212018-03-20 15:41:05 +00002270 if (V->getType()->isIntegerTy())
2271 PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
2272 else
2273 PtrV = Bld.CreatePointerBitCastOrAddrSpaceCast(V, CGF.VoidPtrTy);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002274 CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
2275 Ctx.getPointerType(Ctx.VoidPtrTy));
Alexey Bataevc99042b2018-03-15 18:10:54 +00002276 ++Idx;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002277 }
2278 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002279
2280 // Activate workers. This barrier is used by the master to signal
2281 // work for the workers.
2282 syncCTAThreads(CGF);
2283
2284 // OpenMP [2.5, Parallel Construct, p.49]
2285 // There is an implied barrier at the end of a parallel region. After the
2286 // end of a parallel region, only the master thread of the team resumes
2287 // execution of the enclosing task region.
2288 //
2289 // The master waits at this barrier until all workers are done.
2290 syncCTAThreads(CGF);
2291
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002292 if (!CapturedVars.empty())
2293 CGF.EmitRuntimeCall(
2294 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_sharing_variables));
2295
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002296 // Remember for post-processing in worker loop.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002297 Work.emplace_back(WFn);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002298 };
2299
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002300 auto &&LNParallelGen = [this, Loc, &SeqGen, &L0ParallelGen](
2301 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002302 if (IsInParallelRegion) {
2303 SeqGen(CGF, Action);
2304 } else if (IsInTargetMasterThreadRegion) {
2305 L0ParallelGen(CGF, Action);
2306 } else {
2307 // Check for master and then parallelism:
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002308 // if (__kmpc_is_spmd_exec_mode() || __kmpc_parallel_level(loc, gtid)) {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002309 // Serialized execution.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002310 // } else {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002311 // Worker call.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002312 // }
2313 CGBuilderTy &Bld = CGF.Builder;
2314 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002315 llvm::BasicBlock *SeqBB = CGF.createBasicBlock(".sequential");
2316 llvm::BasicBlock *ParallelCheckBB = CGF.createBasicBlock(".parcheck");
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002317 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
Alexey Bataev673110d2018-05-16 13:36:30 +00002318 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2319 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002320 Bld.CreateCondBr(IsSPMD, SeqBB, ParallelCheckBB);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002321 // There is no need to emit line number for unconditional branch.
2322 (void)ApplyDebugLocation::CreateEmpty(CGF);
2323 CGF.EmitBlock(ParallelCheckBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002324 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2325 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2326 llvm::Value *PL = CGF.EmitRuntimeCall(
2327 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2328 {RTLoc, ThreadID});
2329 llvm::Value *Res = Bld.CreateIsNotNull(PL);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002330 Bld.CreateCondBr(Res, SeqBB, MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002331 CGF.EmitBlock(SeqBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002332 SeqGen(CGF, Action);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002333 CGF.EmitBranch(ExitBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002334 // There is no need to emit line number for unconditional branch.
2335 (void)ApplyDebugLocation::CreateEmpty(CGF);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002336 CGF.EmitBlock(MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002337 L0ParallelGen(CGF, Action);
2338 CGF.EmitBranch(ExitBB);
2339 // There is no need to emit line number for unconditional branch.
2340 (void)ApplyDebugLocation::CreateEmpty(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002341 // Emit the continuation block for code after the if.
2342 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2343 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002344 };
2345
Alexey Bataev9ff80832018-04-16 20:16:21 +00002346 if (IfCond) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002347 emitOMPIfClause(CGF, IfCond, LNParallelGen, SeqGen);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002348 } else {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002349 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002350 RegionCodeGenTy ThenRCG(LNParallelGen);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002351 ThenRCG(CGF);
2352 }
2353}
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002354
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002355void CGOpenMPRuntimeNVPTX::emitSPMDParallelCall(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002356 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2357 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2358 // Just call the outlined function to execute the parallel region.
2359 // OutlinedFn(&GTid, &zero, CapturedStruct);
2360 //
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002361 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Carlo Bertolli79712092018-02-28 20:48:35 +00002362
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002363 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2364 /*DestWidth=*/32, /*Signed=*/1),
2365 ".zero.addr");
Carlo Bertolli79712092018-02-28 20:48:35 +00002366 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002367 // ThreadId for serialized parallels is 0.
2368 Address ThreadIDAddr = ZeroAddr;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002369 auto &&CodeGen = [this, OutlinedFn, CapturedVars, Loc, ZeroAddr,
Alexey Bataev8521ff62018-07-25 20:03:01 +00002370 &ThreadIDAddr](CodeGenFunction &CGF,
2371 PrePostActionTy &Action) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002372 Action.Enter(CGF);
2373
2374 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2375 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2376 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2377 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2378 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2379 };
2380 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2381 PrePostActionTy &) {
2382
2383 RegionCodeGenTy RCG(CodeGen);
2384 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2385 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2386 llvm::Value *Args[] = {RTLoc, ThreadID};
2387
2388 NVPTXActionTy Action(
2389 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2390 Args,
2391 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2392 Args);
2393 RCG.setAction(Action);
2394 RCG(CGF);
2395 };
2396
2397 if (IsInTargetMasterThreadRegion) {
Alexey Bataev8521ff62018-07-25 20:03:01 +00002398 // In the worker need to use the real thread id.
2399 ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002400 RegionCodeGenTy RCG(CodeGen);
2401 RCG(CGF);
2402 } else {
2403 // If we are not in the target region, it is definitely L2 parallelism or
2404 // more, because for SPMD mode we always has L1 parallel level, sowe don't
2405 // need to check for orphaned directives.
2406 RegionCodeGenTy RCG(SeqGen);
2407 RCG(CGF);
2408 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002409}
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002410
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002411void CGOpenMPRuntimeNVPTX::emitCriticalRegion(
2412 CodeGenFunction &CGF, StringRef CriticalName,
2413 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
2414 const Expr *Hint) {
2415 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
2416 llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
2417 llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
2418 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
2419 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
2420
2421 // Fetch team-local id of the thread.
2422 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
2423
2424 // Get the width of the team.
2425 llvm::Value *TeamWidth = getNVPTXNumThreads(CGF);
2426
2427 // Initialize the counter variable for the loop.
2428 QualType Int32Ty =
2429 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
2430 Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
2431 LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
2432 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
2433 /*isInit=*/true);
2434
2435 // Block checks if loop counter exceeds upper bound.
2436 CGF.EmitBlock(LoopBB);
2437 llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2438 llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
2439 CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
2440
2441 // Block tests which single thread should execute region, and which threads
2442 // should go straight to synchronisation point.
2443 CGF.EmitBlock(TestBB);
2444 CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2445 llvm::Value *CmpThreadToCounter =
2446 CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
2447 CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
2448
2449 // Block emits the body of the critical region.
2450 CGF.EmitBlock(BodyBB);
2451
2452 // Output the critical statement.
2453 CriticalOpGen(CGF);
2454
2455 // After the body surrounded by the critical region, the single executing
2456 // thread will jump to the synchronisation point.
2457 // Block waits for all threads in current team to finish then increments the
2458 // counter variable and returns to the loop.
2459 CGF.EmitBlock(SyncBB);
2460 getNVPTXCTABarrier(CGF);
2461
2462 llvm::Value *IncCounterVal =
2463 CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
2464 CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
2465 CGF.EmitBranch(LoopBB);
2466
2467 // Block that is reached when all threads in the team complete the region.
2468 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2469}
2470
Alexey Bataevb2575932018-01-04 20:18:55 +00002471/// Cast value to the specified type.
Alexey Bataeva453f362018-03-19 17:53:56 +00002472static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
2473 QualType ValTy, QualType CastTy,
2474 SourceLocation Loc) {
2475 assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
2476 "Cast type must sized.");
2477 assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
2478 "Val type must sized.");
2479 llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
2480 if (ValTy == CastTy)
Alexey Bataevb2575932018-01-04 20:18:55 +00002481 return Val;
Alexey Bataeva453f362018-03-19 17:53:56 +00002482 if (CGF.getContext().getTypeSizeInChars(ValTy) ==
2483 CGF.getContext().getTypeSizeInChars(CastTy))
2484 return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
2485 if (CastTy->isIntegerType() && ValTy->isIntegerType())
2486 return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
2487 CastTy->hasSignedIntegerRepresentation());
2488 Address CastItem = CGF.CreateMemTemp(CastTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002489 Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2490 CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
Alexey Bataeva453f362018-03-19 17:53:56 +00002491 CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy);
2492 return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc);
Alexey Bataevb2575932018-01-04 20:18:55 +00002493}
2494
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002495/// This function creates calls to one of two shuffle functions to copy
2496/// variables between lanes in a warp.
2497static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002498 llvm::Value *Elem,
Alexey Bataeva453f362018-03-19 17:53:56 +00002499 QualType ElemType,
2500 llvm::Value *Offset,
2501 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002502 CodeGenModule &CGM = CGF.CGM;
2503 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002504 CGOpenMPRuntimeNVPTX &RT =
2505 *(static_cast<CGOpenMPRuntimeNVPTX *>(&CGM.getOpenMPRuntime()));
2506
Alexey Bataeva453f362018-03-19 17:53:56 +00002507 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2508 assert(Size.getQuantity() <= 8 &&
2509 "Unsupported bitwidth in shuffle instruction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002510
Alexey Bataeva453f362018-03-19 17:53:56 +00002511 OpenMPRTLFunctionNVPTX ShuffleFn = Size.getQuantity() <= 4
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002512 ? OMPRTL_NVPTX__kmpc_shuffle_int32
2513 : OMPRTL_NVPTX__kmpc_shuffle_int64;
2514
2515 // Cast all types to 32- or 64-bit values before calling shuffle routines.
Alexey Bataeva453f362018-03-19 17:53:56 +00002516 QualType CastTy = CGF.getContext().getIntTypeForBitwidth(
2517 Size.getQuantity() <= 4 ? 32 : 64, /*Signed=*/1);
2518 llvm::Value *ElemCast = castValueToType(CGF, Elem, ElemType, CastTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002519 llvm::Value *WarpSize =
Alexey Bataevb2575932018-01-04 20:18:55 +00002520 Bld.CreateIntCast(getNVPTXWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002521
Alexey Bataev9ff80832018-04-16 20:16:21 +00002522 llvm::Value *ShuffledVal = CGF.EmitRuntimeCall(
2523 RT.createNVPTXRuntimeFunction(ShuffleFn), {ElemCast, Offset, WarpSize});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002524
Alexey Bataeva453f362018-03-19 17:53:56 +00002525 return castValueToType(CGF, ShuffledVal, CastTy, ElemType, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002526}
2527
Alexey Bataev12c62902018-06-22 19:10:38 +00002528static void shuffleAndStore(CodeGenFunction &CGF, Address SrcAddr,
2529 Address DestAddr, QualType ElemType,
2530 llvm::Value *Offset, SourceLocation Loc) {
2531 CGBuilderTy &Bld = CGF.Builder;
2532
2533 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2534 // Create the loop over the big sized data.
2535 // ptr = (void*)Elem;
2536 // ptrEnd = (void*) Elem + 1;
2537 // Step = 8;
2538 // while (ptr + Step < ptrEnd)
2539 // shuffle((int64_t)*ptr);
2540 // Step = 4;
2541 // while (ptr + Step < ptrEnd)
2542 // shuffle((int32_t)*ptr);
2543 // ...
2544 Address ElemPtr = DestAddr;
2545 Address Ptr = SrcAddr;
2546 Address PtrEnd = Bld.CreatePointerBitCastOrAddrSpaceCast(
2547 Bld.CreateConstGEP(SrcAddr, 1, Size), CGF.VoidPtrTy);
2548 for (int IntSize = 8; IntSize >= 1; IntSize /= 2) {
2549 if (Size < CharUnits::fromQuantity(IntSize))
2550 continue;
2551 QualType IntType = CGF.getContext().getIntTypeForBitwidth(
2552 CGF.getContext().toBits(CharUnits::fromQuantity(IntSize)),
2553 /*Signed=*/1);
2554 llvm::Type *IntTy = CGF.ConvertTypeForMem(IntType);
2555 Ptr = Bld.CreatePointerBitCastOrAddrSpaceCast(Ptr, IntTy->getPointerTo());
2556 ElemPtr =
2557 Bld.CreatePointerBitCastOrAddrSpaceCast(ElemPtr, IntTy->getPointerTo());
2558 if (Size.getQuantity() / IntSize > 1) {
2559 llvm::BasicBlock *PreCondBB = CGF.createBasicBlock(".shuffle.pre_cond");
2560 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".shuffle.then");
2561 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".shuffle.exit");
2562 llvm::BasicBlock *CurrentBB = Bld.GetInsertBlock();
2563 CGF.EmitBlock(PreCondBB);
2564 llvm::PHINode *PhiSrc =
2565 Bld.CreatePHI(Ptr.getType(), /*NumReservedValues=*/2);
2566 PhiSrc->addIncoming(Ptr.getPointer(), CurrentBB);
2567 llvm::PHINode *PhiDest =
2568 Bld.CreatePHI(ElemPtr.getType(), /*NumReservedValues=*/2);
2569 PhiDest->addIncoming(ElemPtr.getPointer(), CurrentBB);
2570 Ptr = Address(PhiSrc, Ptr.getAlignment());
2571 ElemPtr = Address(PhiDest, ElemPtr.getAlignment());
2572 llvm::Value *PtrDiff = Bld.CreatePtrDiff(
2573 PtrEnd.getPointer(), Bld.CreatePointerBitCastOrAddrSpaceCast(
2574 Ptr.getPointer(), CGF.VoidPtrTy));
2575 Bld.CreateCondBr(Bld.CreateICmpSGT(PtrDiff, Bld.getInt64(IntSize - 1)),
2576 ThenBB, ExitBB);
2577 CGF.EmitBlock(ThenBB);
2578 llvm::Value *Res = createRuntimeShuffleFunction(
2579 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2580 IntType, Offset, Loc);
2581 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
2582 Ptr = Bld.CreateConstGEP(Ptr, 1, CharUnits::fromQuantity(IntSize));
2583 ElemPtr =
2584 Bld.CreateConstGEP(ElemPtr, 1, CharUnits::fromQuantity(IntSize));
2585 PhiSrc->addIncoming(Ptr.getPointer(), ThenBB);
2586 PhiDest->addIncoming(ElemPtr.getPointer(), ThenBB);
2587 CGF.EmitBranch(PreCondBB);
2588 CGF.EmitBlock(ExitBB);
2589 } else {
2590 llvm::Value *Res = createRuntimeShuffleFunction(
2591 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2592 IntType, Offset, Loc);
2593 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
2594 Ptr = Bld.CreateConstGEP(Ptr, 1, CharUnits::fromQuantity(IntSize));
2595 ElemPtr =
2596 Bld.CreateConstGEP(ElemPtr, 1, CharUnits::fromQuantity(IntSize));
2597 }
2598 Size = Size % IntSize;
2599 }
2600}
2601
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002602namespace {
2603enum CopyAction : unsigned {
2604 // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
2605 // the warp using shuffle instructions.
2606 RemoteLaneToThread,
2607 // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
2608 ThreadCopy,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002609 // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
2610 ThreadToScratchpad,
2611 // ScratchpadToThread: Copy from a scratchpad array in global memory
2612 // containing team-reduced data to a thread's stack.
2613 ScratchpadToThread,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002614};
2615} // namespace
2616
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002617struct CopyOptionsTy {
2618 llvm::Value *RemoteLaneOffset;
2619 llvm::Value *ScratchpadIndex;
2620 llvm::Value *ScratchpadWidth;
2621};
2622
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002623/// Emit instructions to copy a Reduce list, which contains partially
2624/// aggregated values, in the specified direction.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002625static void emitReductionListCopy(
2626 CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
2627 ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
2628 CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002629
Alexey Bataev9ff80832018-04-16 20:16:21 +00002630 CodeGenModule &CGM = CGF.CGM;
2631 ASTContext &C = CGM.getContext();
2632 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002633
Alexey Bataev9ff80832018-04-16 20:16:21 +00002634 llvm::Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
2635 llvm::Value *ScratchpadIndex = CopyOptions.ScratchpadIndex;
2636 llvm::Value *ScratchpadWidth = CopyOptions.ScratchpadWidth;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002637
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002638 // Iterates, element-by-element, through the source Reduce list and
2639 // make a copy.
2640 unsigned Idx = 0;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002641 unsigned Size = Privates.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00002642 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002643 Address SrcElementAddr = Address::invalid();
2644 Address DestElementAddr = Address::invalid();
2645 Address DestElementPtrAddr = Address::invalid();
2646 // Should we shuffle in an element from a remote lane?
2647 bool ShuffleInElement = false;
2648 // Set to true to update the pointer in the dest Reduce list to a
2649 // newly created element.
2650 bool UpdateDestListPtr = false;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002651 // Increment the src or dest pointer to the scratchpad, for each
2652 // new element.
2653 bool IncrScratchpadSrc = false;
2654 bool IncrScratchpadDest = false;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002655
2656 switch (Action) {
2657 case RemoteLaneToThread: {
2658 // Step 1.1: Get the address for the src element in the Reduce list.
2659 Address SrcElementPtrAddr =
2660 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002661 SrcElementAddr = CGF.EmitLoadOfPointer(
2662 SrcElementPtrAddr,
2663 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002664
2665 // Step 1.2: Create a temporary to store the element in the destination
2666 // Reduce list.
2667 DestElementPtrAddr =
2668 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
2669 DestElementAddr =
2670 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2671 ShuffleInElement = true;
2672 UpdateDestListPtr = true;
2673 break;
2674 }
2675 case ThreadCopy: {
2676 // Step 1.1: Get the address for the src element in the Reduce list.
2677 Address SrcElementPtrAddr =
2678 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002679 SrcElementAddr = CGF.EmitLoadOfPointer(
2680 SrcElementPtrAddr,
2681 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002682
2683 // Step 1.2: Get the address for dest element. The destination
2684 // element has already been created on the thread's stack.
2685 DestElementPtrAddr =
2686 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002687 DestElementAddr = CGF.EmitLoadOfPointer(
2688 DestElementPtrAddr,
2689 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002690 break;
2691 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002692 case ThreadToScratchpad: {
2693 // Step 1.1: Get the address for the src element in the Reduce list.
2694 Address SrcElementPtrAddr =
2695 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002696 SrcElementAddr = CGF.EmitLoadOfPointer(
2697 SrcElementPtrAddr,
2698 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002699
2700 // Step 1.2: Get the address for dest element:
2701 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00002702 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00002703 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002704 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002705 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002706 Bld.CreateNUWAdd(DestBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002707 ScratchPadElemAbsolutePtrVal =
2708 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002709 DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
2710 C.getTypeAlignInChars(Private->getType()));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002711 IncrScratchpadDest = true;
2712 break;
2713 }
2714 case ScratchpadToThread: {
2715 // Step 1.1: Get the address for the src element in the scratchpad.
2716 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00002717 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00002718 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002719 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002720 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002721 Bld.CreateNUWAdd(SrcBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002722 ScratchPadElemAbsolutePtrVal =
2723 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
2724 SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
2725 C.getTypeAlignInChars(Private->getType()));
2726 IncrScratchpadSrc = true;
2727
2728 // Step 1.2: Create a temporary to store the element in the destination
2729 // Reduce list.
2730 DestElementPtrAddr =
2731 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
2732 DestElementAddr =
2733 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2734 UpdateDestListPtr = true;
2735 break;
2736 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002737 }
2738
2739 // Regardless of src and dest of copy, we emit the load of src
2740 // element as this is required in all directions
2741 SrcElementAddr = Bld.CreateElementBitCast(
2742 SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
Alexey Bataev12c62902018-06-22 19:10:38 +00002743 DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
2744 SrcElementAddr.getElementType());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002745
2746 // Now that all active lanes have read the element in the
2747 // Reduce list, shuffle over the value from the remote lane.
Alexey Bataeva453f362018-03-19 17:53:56 +00002748 if (ShuffleInElement) {
Alexey Bataev12c62902018-06-22 19:10:38 +00002749 shuffleAndStore(CGF, SrcElementAddr, DestElementAddr, Private->getType(),
2750 RemoteLaneOffset, Private->getExprLoc());
2751 } else {
2752 if (Private->getType()->isScalarType()) {
2753 llvm::Value *Elem =
2754 CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false,
2755 Private->getType(), Private->getExprLoc());
2756 // Store the source element value to the dest element address.
2757 CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false,
2758 Private->getType());
2759 } else {
2760 CGF.EmitAggregateCopy(
2761 CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
2762 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
2763 Private->getType(), AggValueSlot::DoesNotOverlap);
2764 }
Alexey Bataeva453f362018-03-19 17:53:56 +00002765 }
Alexey Bataevb2575932018-01-04 20:18:55 +00002766
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002767 // Step 3.1: Modify reference in dest Reduce list as needed.
2768 // Modifying the reference in Reduce list to point to the newly
2769 // created element. The element is live in the current function
2770 // scope and that of functions it invokes (i.e., reduce_function).
2771 // RemoteReduceData[i] = (void*)&RemoteElem
2772 if (UpdateDestListPtr) {
2773 CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
2774 DestElementAddr.getPointer(), CGF.VoidPtrTy),
2775 DestElementPtrAddr, /*Volatile=*/false,
2776 C.VoidPtrTy);
2777 }
2778
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002779 // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
2780 // address of the next element in scratchpad memory, unless we're currently
2781 // processing the last one. Memory alignment is also taken care of here.
2782 if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
2783 llvm::Value *ScratchpadBasePtr =
2784 IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
Alexey Bataeve290ec02018-04-06 16:03:36 +00002785 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
2786 ScratchpadBasePtr = Bld.CreateNUWAdd(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002787 ScratchpadBasePtr,
Alexey Bataeve290ec02018-04-06 16:03:36 +00002788 Bld.CreateNUWMul(ScratchpadWidth, ElementSizeInChars));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002789
2790 // Take care of global memory alignment for performance
Alexey Bataeve290ec02018-04-06 16:03:36 +00002791 ScratchpadBasePtr = Bld.CreateNUWSub(
2792 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
2793 ScratchpadBasePtr = Bld.CreateUDiv(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002794 ScratchpadBasePtr,
2795 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
Alexey Bataeve290ec02018-04-06 16:03:36 +00002796 ScratchpadBasePtr = Bld.CreateNUWAdd(
2797 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
2798 ScratchpadBasePtr = Bld.CreateNUWMul(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002799 ScratchpadBasePtr,
2800 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
2801
2802 if (IncrScratchpadDest)
2803 DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
2804 else /* IncrScratchpadSrc = true */
2805 SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
2806 }
2807
Alexey Bataev9ff80832018-04-16 20:16:21 +00002808 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002809 }
2810}
2811
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002812/// This function emits a helper that loads data from the scratchpad array
2813/// and (optionally) reduces it with the input operand.
2814///
2815/// load_and_reduce(local, scratchpad, index, width, should_reduce)
2816/// reduce_data remote;
2817/// for elem in remote:
2818/// remote.elem = Scratchpad[elem_id][index]
2819/// if (should_reduce)
2820/// local = local @ remote
2821/// else
2822/// local = remote
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002823static llvm::Value *emitReduceScratchpadFunction(
2824 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
2825 QualType ReductionArrayTy, llvm::Value *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002826 ASTContext &C = CGM.getContext();
2827 QualType Int32Ty = C.getIntTypeForBitwidth(32, /*Signed=*/1);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002828
2829 // Destination of the copy.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002830 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2831 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002832 // Base address of the scratchpad array, with each element storing a
2833 // Reduce list per team.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002834 ImplicitParamDecl ScratchPadArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2835 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002836 // A source index into the scratchpad array.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002837 ImplicitParamDecl IndexArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
2838 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002839 // Row width of an element in the scratchpad array, typically
2840 // the number of teams.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002841 ImplicitParamDecl WidthArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
2842 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002843 // If should_reduce == 1, then it's load AND reduce,
2844 // If should_reduce == 0 (or otherwise), then it only loads (+ copy).
2845 // The latter case is used for initialization.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002846 ImplicitParamDecl ShouldReduceArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2847 Int32Ty, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002848
2849 FunctionArgList Args;
2850 Args.push_back(&ReduceListArg);
2851 Args.push_back(&ScratchPadArg);
2852 Args.push_back(&IndexArg);
2853 Args.push_back(&WidthArg);
2854 Args.push_back(&ShouldReduceArg);
2855
Alexey Bataev9ff80832018-04-16 20:16:21 +00002856 const CGFunctionInfo &CGFI =
2857 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002858 auto *Fn = llvm::Function::Create(
2859 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2860 "_omp_reduction_load_and_reduce", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002861 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002862 Fn->setDoesNotRecurse();
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002863 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002864 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002865
Alexey Bataev9ff80832018-04-16 20:16:21 +00002866 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002867
2868 // Get local Reduce list pointer.
2869 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2870 Address ReduceListAddr(
2871 Bld.CreatePointerBitCastOrAddrSpaceCast(
2872 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002873 C.VoidPtrTy, Loc),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002874 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
2875 CGF.getPointerAlign());
2876
2877 Address AddrScratchPadArg = CGF.GetAddrOfLocalVar(&ScratchPadArg);
2878 llvm::Value *ScratchPadBase = CGF.EmitLoadOfScalar(
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002879 AddrScratchPadArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002880
2881 Address AddrIndexArg = CGF.GetAddrOfLocalVar(&IndexArg);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002882 llvm::Value *IndexVal = Bld.CreateIntCast(
2883 CGF.EmitLoadOfScalar(AddrIndexArg, /*Volatile=*/false, Int32Ty, Loc),
2884 CGM.SizeTy, /*isSigned=*/true);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002885
2886 Address AddrWidthArg = CGF.GetAddrOfLocalVar(&WidthArg);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002887 llvm::Value *WidthVal = Bld.CreateIntCast(
2888 CGF.EmitLoadOfScalar(AddrWidthArg, /*Volatile=*/false, Int32Ty, Loc),
2889 CGM.SizeTy, /*isSigned=*/true);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002890
2891 Address AddrShouldReduceArg = CGF.GetAddrOfLocalVar(&ShouldReduceArg);
2892 llvm::Value *ShouldReduceVal = CGF.EmitLoadOfScalar(
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002893 AddrShouldReduceArg, /*Volatile=*/false, Int32Ty, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002894
2895 // The absolute ptr address to the base addr of the next element to copy.
2896 llvm::Value *CumulativeElemBasePtr =
2897 Bld.CreatePtrToInt(ScratchPadBase, CGM.SizeTy);
2898 Address SrcDataAddr(CumulativeElemBasePtr, CGF.getPointerAlign());
2899
2900 // Create a Remote Reduce list to store the elements read from the
2901 // scratchpad array.
2902 Address RemoteReduceList =
2903 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_red_list");
2904
2905 // Assemble remote Reduce list from scratchpad array.
2906 emitReductionListCopy(ScratchpadToThread, CGF, ReductionArrayTy, Privates,
2907 SrcDataAddr, RemoteReduceList,
2908 {/*RemoteLaneOffset=*/nullptr,
2909 /*ScratchpadIndex=*/IndexVal,
2910 /*ScratchpadWidth=*/WidthVal});
2911
2912 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
2913 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
2914 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
2915
Alexey Bataev9ff80832018-04-16 20:16:21 +00002916 llvm::Value *CondReduce = Bld.CreateIsNotNull(ShouldReduceVal);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002917 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
2918
2919 CGF.EmitBlock(ThenBB);
2920 // We should reduce with the local Reduce list.
2921 // reduce_function(LocalReduceList, RemoteReduceList)
2922 llvm::Value *LocalDataPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2923 ReduceListAddr.getPointer(), CGF.VoidPtrTy);
2924 llvm::Value *RemoteDataPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2925 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002926 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
2927 CGF, Loc, ReduceFn, {LocalDataPtr, RemoteDataPtr});
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002928 Bld.CreateBr(MergeBB);
2929
2930 CGF.EmitBlock(ElseBB);
2931 // No reduction; just copy:
2932 // Local Reduce list = Remote Reduce list.
2933 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
2934 RemoteReduceList, ReduceListAddr);
2935 Bld.CreateBr(MergeBB);
2936
2937 CGF.EmitBlock(MergeBB);
2938
2939 CGF.FinishFunction();
2940 return Fn;
2941}
2942
2943/// This function emits a helper that stores reduced data from the team
2944/// master to a scratchpad array in global memory.
2945///
2946/// for elem in Reduce List:
2947/// scratchpad[elem_id][index] = elem
2948///
Benjamin Kramer674d5792017-05-26 20:08:24 +00002949static llvm::Value *emitCopyToScratchpad(CodeGenModule &CGM,
2950 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002951 QualType ReductionArrayTy,
2952 SourceLocation Loc) {
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002953
Alexey Bataev9ff80832018-04-16 20:16:21 +00002954 ASTContext &C = CGM.getContext();
2955 QualType Int32Ty = C.getIntTypeForBitwidth(32, /*Signed=*/1);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002956
2957 // Source of the copy.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002958 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2959 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002960 // Base address of the scratchpad array, with each element storing a
2961 // Reduce list per team.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002962 ImplicitParamDecl ScratchPadArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2963 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002964 // A destination index into the scratchpad array, typically the team
2965 // identifier.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002966 ImplicitParamDecl IndexArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
2967 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002968 // Row width of an element in the scratchpad array, typically
2969 // the number of teams.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002970 ImplicitParamDecl WidthArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
2971 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002972
2973 FunctionArgList Args;
2974 Args.push_back(&ReduceListArg);
2975 Args.push_back(&ScratchPadArg);
2976 Args.push_back(&IndexArg);
2977 Args.push_back(&WidthArg);
2978
Alexey Bataev9ff80832018-04-16 20:16:21 +00002979 const CGFunctionInfo &CGFI =
2980 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002981 auto *Fn = llvm::Function::Create(
2982 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2983 "_omp_reduction_copy_to_scratchpad", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002984 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002985 Fn->setDoesNotRecurse();
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002986 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002987 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002988
Alexey Bataev9ff80832018-04-16 20:16:21 +00002989 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002990
2991 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2992 Address SrcDataAddr(
2993 Bld.CreatePointerBitCastOrAddrSpaceCast(
2994 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002995 C.VoidPtrTy, Loc),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002996 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
2997 CGF.getPointerAlign());
2998
2999 Address AddrScratchPadArg = CGF.GetAddrOfLocalVar(&ScratchPadArg);
3000 llvm::Value *ScratchPadBase = CGF.EmitLoadOfScalar(
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003001 AddrScratchPadArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003002
3003 Address AddrIndexArg = CGF.GetAddrOfLocalVar(&IndexArg);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003004 llvm::Value *IndexVal = Bld.CreateIntCast(
3005 CGF.EmitLoadOfScalar(AddrIndexArg, /*Volatile=*/false, Int32Ty, Loc),
3006 CGF.SizeTy, /*isSigned=*/true);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003007
3008 Address AddrWidthArg = CGF.GetAddrOfLocalVar(&WidthArg);
3009 llvm::Value *WidthVal =
3010 Bld.CreateIntCast(CGF.EmitLoadOfScalar(AddrWidthArg, /*Volatile=*/false,
3011 Int32Ty, SourceLocation()),
3012 CGF.SizeTy, /*isSigned=*/true);
3013
3014 // The absolute ptr address to the base addr of the next element to copy.
3015 llvm::Value *CumulativeElemBasePtr =
3016 Bld.CreatePtrToInt(ScratchPadBase, CGM.SizeTy);
3017 Address DestDataAddr(CumulativeElemBasePtr, CGF.getPointerAlign());
3018
3019 emitReductionListCopy(ThreadToScratchpad, CGF, ReductionArrayTy, Privates,
3020 SrcDataAddr, DestDataAddr,
3021 {/*RemoteLaneOffset=*/nullptr,
3022 /*ScratchpadIndex=*/IndexVal,
3023 /*ScratchpadWidth=*/WidthVal});
3024
3025 CGF.FinishFunction();
3026 return Fn;
3027}
3028
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003029/// This function emits a helper that gathers Reduce lists from the first
3030/// lane of every active warp to lanes in the first warp.
3031///
3032/// void inter_warp_copy_func(void* reduce_data, num_warps)
3033/// shared smem[warp_size];
3034/// For all data entries D in reduce_data:
3035/// If (I am the first lane in each warp)
3036/// Copy my local D to smem[warp_id]
3037/// sync
3038/// if (I am the first warp)
3039/// Copy smem[thread_id] to my local D
3040/// sync
3041static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
3042 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003043 QualType ReductionArrayTy,
3044 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003045 ASTContext &C = CGM.getContext();
3046 llvm::Module &M = CGM.getModule();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003047
3048 // ReduceList: thread local Reduce list.
3049 // At the stage of the computation when this function is called, partially
3050 // aggregated values reside in the first lane of every active warp.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003051 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3052 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003053 // NumWarps: number of warps active in the parallel region. This could
3054 // be smaller than 32 (max warps in a CTA) for partial block reduction.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003055 ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00003056 C.getIntTypeForBitwidth(32, /* Signed */ true),
3057 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003058 FunctionArgList Args;
3059 Args.push_back(&ReduceListArg);
3060 Args.push_back(&NumWarpsArg);
3061
Alexey Bataev9ff80832018-04-16 20:16:21 +00003062 const CGFunctionInfo &CGFI =
3063 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003064 auto *Fn = llvm::Function::Create(
3065 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3066 "_omp_reduction_inter_warp_copy_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003067 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003068 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003069 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003070 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003071
Alexey Bataev9ff80832018-04-16 20:16:21 +00003072 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003073
3074 // This array is used as a medium to transfer, one reduce element at a time,
3075 // the data from the first lane of every warp to lanes in the first warp
3076 // in order to perform the final step of a reduction in a parallel region
3077 // (reduction across warps). The array is placed in NVPTX __shared__ memory
3078 // for reduced latency, as well as to have a distinct copy for concurrently
3079 // executing target regions. The array is declared with common linkage so
3080 // as to be shared across compilation units.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003081 StringRef TransferMediumName =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003082 "__openmp_nvptx_data_transfer_temporary_storage";
3083 llvm::GlobalVariable *TransferMedium =
3084 M.getGlobalVariable(TransferMediumName);
3085 if (!TransferMedium) {
3086 auto *Ty = llvm::ArrayType::get(CGM.Int64Ty, WarpSize);
3087 unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
3088 TransferMedium = new llvm::GlobalVariable(
3089 M, Ty,
3090 /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage,
3091 llvm::Constant::getNullValue(Ty), TransferMediumName,
3092 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3093 SharedAddressSpace);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003094 CGM.addCompilerUsedGlobal(TransferMedium);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003095 }
3096
3097 // Get the CUDA thread id of the current OpenMP thread on the GPU.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003098 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003099 // nvptx_lane_id = nvptx_id % warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003100 llvm::Value *LaneID = getNVPTXLaneID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003101 // nvptx_warp_id = nvptx_id / warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003102 llvm::Value *WarpID = getNVPTXWarpID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003103
3104 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3105 Address LocalReduceList(
3106 Bld.CreatePointerBitCastOrAddrSpaceCast(
3107 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3108 C.VoidPtrTy, SourceLocation()),
3109 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3110 CGF.getPointerAlign());
3111
3112 unsigned Idx = 0;
Alexey Bataev9ff80832018-04-16 20:16:21 +00003113 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003114 //
3115 // Warp master copies reduce element to transfer medium in __shared__
3116 // memory.
3117 //
3118 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3119 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3120 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
3121
3122 // if (lane_id == 0)
Alexey Bataev9ff80832018-04-16 20:16:21 +00003123 llvm::Value *IsWarpMaster = Bld.CreateIsNull(LaneID, "warp_master");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003124 Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
3125 CGF.EmitBlock(ThenBB);
3126
3127 // Reduce element = LocalReduceList[i]
3128 Address ElemPtrPtrAddr =
3129 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
3130 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3131 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3132 // elemptr = (type[i]*)(elemptrptr)
3133 Address ElemPtr =
3134 Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
3135 ElemPtr = Bld.CreateElementBitCast(
3136 ElemPtr, CGF.ConvertTypeForMem(Private->getType()));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003137
3138 // Get pointer to location in transfer medium.
3139 // MediumPtr = &medium[warp_id]
3140 llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
3141 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
3142 Address MediumPtr(MediumPtrVal, C.getTypeAlignInChars(Private->getType()));
3143 // Casting to actual data type.
3144 // MediumPtr = (type[i]*)MediumPtrAddr;
3145 MediumPtr = Bld.CreateElementBitCast(
3146 MediumPtr, CGF.ConvertTypeForMem(Private->getType()));
3147
Alexey Bataev12c62902018-06-22 19:10:38 +00003148 // elem = *elemptr
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003149 //*MediumPtr = elem
Alexey Bataev12c62902018-06-22 19:10:38 +00003150 if (Private->getType()->isScalarType()) {
3151 llvm::Value *Elem = CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false,
3152 Private->getType(), Loc);
3153 // Store the source element value to the dest element address.
3154 CGF.EmitStoreOfScalar(Elem, MediumPtr, /*Volatile=*/false,
3155 Private->getType());
3156 } else {
3157 CGF.EmitAggregateCopy(CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3158 CGF.MakeAddrLValue(MediumPtr, Private->getType()),
3159 Private->getType(), AggValueSlot::DoesNotOverlap);
3160 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003161
3162 Bld.CreateBr(MergeBB);
3163
3164 CGF.EmitBlock(ElseBB);
3165 Bld.CreateBr(MergeBB);
3166
3167 CGF.EmitBlock(MergeBB);
3168
3169 Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
3170 llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
3171 AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, SourceLocation());
3172
Alexey Bataev9ff80832018-04-16 20:16:21 +00003173 llvm::Value *NumActiveThreads = Bld.CreateNSWMul(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003174 NumWarpsVal, getNVPTXWarpSize(CGF), "num_active_threads");
3175 // named_barrier_sync(ParallelBarrierID, num_active_threads)
3176 syncParallelThreads(CGF, NumActiveThreads);
3177
3178 //
3179 // Warp 0 copies reduce element from transfer medium.
3180 //
3181 llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
3182 llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
3183 llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
3184
3185 // Up to 32 threads in warp 0 are active.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003186 llvm::Value *IsActiveThread =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003187 Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
3188 Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
3189
3190 CGF.EmitBlock(W0ThenBB);
3191
3192 // SrcMediumPtr = &medium[tid]
3193 llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
3194 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
3195 Address SrcMediumPtr(SrcMediumPtrVal,
3196 C.getTypeAlignInChars(Private->getType()));
3197 // SrcMediumVal = *SrcMediumPtr;
3198 SrcMediumPtr = Bld.CreateElementBitCast(
3199 SrcMediumPtr, CGF.ConvertTypeForMem(Private->getType()));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003200
3201 // TargetElemPtr = (type[i]*)(SrcDataAddr[i])
3202 Address TargetElemPtrPtr =
3203 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
3204 llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
3205 TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3206 Address TargetElemPtr =
3207 Address(TargetElemPtrVal, C.getTypeAlignInChars(Private->getType()));
3208 TargetElemPtr = Bld.CreateElementBitCast(
3209 TargetElemPtr, CGF.ConvertTypeForMem(Private->getType()));
3210
3211 // *TargetElemPtr = SrcMediumVal;
Alexey Bataev12c62902018-06-22 19:10:38 +00003212 if (Private->getType()->isScalarType()) {
3213 llvm::Value *SrcMediumValue = CGF.EmitLoadOfScalar(
3214 SrcMediumPtr, /*Volatile=*/false, Private->getType(), Loc);
3215 CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
3216 Private->getType());
3217 } else {
3218 CGF.EmitAggregateCopy(
3219 CGF.MakeAddrLValue(SrcMediumPtr, Private->getType()),
3220 CGF.MakeAddrLValue(TargetElemPtr, Private->getType()),
3221 Private->getType(), AggValueSlot::DoesNotOverlap);
3222 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003223 Bld.CreateBr(W0MergeBB);
3224
3225 CGF.EmitBlock(W0ElseBB);
3226 Bld.CreateBr(W0MergeBB);
3227
3228 CGF.EmitBlock(W0MergeBB);
3229
3230 // While warp 0 copies values from transfer medium, all other warps must
3231 // wait.
3232 syncParallelThreads(CGF, NumActiveThreads);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003233 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003234 }
3235
3236 CGF.FinishFunction();
3237 return Fn;
3238}
3239
3240/// Emit a helper that reduces data across two OpenMP threads (lanes)
3241/// in the same warp. It uses shuffle instructions to copy over data from
3242/// a remote lane's stack. The reduction algorithm performed is specified
3243/// by the fourth parameter.
3244///
3245/// Algorithm Versions.
3246/// Full Warp Reduce (argument value 0):
3247/// This algorithm assumes that all 32 lanes are active and gathers
3248/// data from these 32 lanes, producing a single resultant value.
3249/// Contiguous Partial Warp Reduce (argument value 1):
3250/// This algorithm assumes that only a *contiguous* subset of lanes
3251/// are active. This happens for the last warp in a parallel region
3252/// when the user specified num_threads is not an integer multiple of
3253/// 32. This contiguous subset always starts with the zeroth lane.
3254/// Partial Warp Reduce (argument value 2):
3255/// This algorithm gathers data from any number of lanes at any position.
3256/// All reduced values are stored in the lowest possible lane. The set
3257/// of problems every algorithm addresses is a super set of those
3258/// addressable by algorithms with a lower version number. Overhead
3259/// increases as algorithm version increases.
3260///
3261/// Terminology
3262/// Reduce element:
3263/// Reduce element refers to the individual data field with primitive
3264/// data types to be combined and reduced across threads.
3265/// Reduce list:
3266/// Reduce list refers to a collection of local, thread-private
3267/// reduce elements.
3268/// Remote Reduce list:
3269/// Remote Reduce list refers to a collection of remote (relative to
3270/// the current thread) reduce elements.
3271///
3272/// We distinguish between three states of threads that are important to
3273/// the implementation of this function.
3274/// Alive threads:
3275/// Threads in a warp executing the SIMT instruction, as distinguished from
3276/// threads that are inactive due to divergent control flow.
3277/// Active threads:
3278/// The minimal set of threads that has to be alive upon entry to this
3279/// function. The computation is correct iff active threads are alive.
3280/// Some threads are alive but they are not active because they do not
3281/// contribute to the computation in any useful manner. Turning them off
3282/// may introduce control flow overheads without any tangible benefits.
3283/// Effective threads:
3284/// In order to comply with the argument requirements of the shuffle
3285/// function, we must keep all lanes holding data alive. But at most
3286/// half of them perform value aggregation; we refer to this half of
3287/// threads as effective. The other half is simply handing off their
3288/// data.
3289///
3290/// Procedure
3291/// Value shuffle:
3292/// In this step active threads transfer data from higher lane positions
3293/// in the warp to lower lane positions, creating Remote Reduce list.
3294/// Value aggregation:
3295/// In this step, effective threads combine their thread local Reduce list
3296/// with Remote Reduce list and store the result in the thread local
3297/// Reduce list.
3298/// Value copy:
3299/// In this step, we deal with the assumption made by algorithm 2
3300/// (i.e. contiguity assumption). When we have an odd number of lanes
3301/// active, say 2k+1, only k threads will be effective and therefore k
3302/// new values will be produced. However, the Reduce list owned by the
3303/// (2k+1)th thread is ignored in the value aggregation. Therefore
3304/// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
3305/// that the contiguity assumption still holds.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003306static llvm::Value *emitShuffleAndReduceFunction(
3307 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3308 QualType ReductionArrayTy, llvm::Value *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003309 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003310
3311 // Thread local Reduce list used to host the values of data to be reduced.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003312 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3313 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003314 // Current lane id; could be logical.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003315 ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
3316 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003317 // Offset of the remote source lane relative to the current lane.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003318 ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3319 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003320 // Algorithm version. This is expected to be known at compile time.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003321 ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3322 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003323 FunctionArgList Args;
3324 Args.push_back(&ReduceListArg);
3325 Args.push_back(&LaneIDArg);
3326 Args.push_back(&RemoteLaneOffsetArg);
3327 Args.push_back(&AlgoVerArg);
3328
Alexey Bataev9ff80832018-04-16 20:16:21 +00003329 const CGFunctionInfo &CGFI =
3330 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003331 auto *Fn = llvm::Function::Create(
3332 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3333 "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003334 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003335 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003336 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003337 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003338
Alexey Bataev9ff80832018-04-16 20:16:21 +00003339 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003340
3341 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3342 Address LocalReduceList(
3343 Bld.CreatePointerBitCastOrAddrSpaceCast(
3344 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3345 C.VoidPtrTy, SourceLocation()),
3346 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3347 CGF.getPointerAlign());
3348
3349 Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
3350 llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
3351 AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3352
3353 Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
3354 llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
3355 AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3356
3357 Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
3358 llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
3359 AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3360
3361 // Create a local thread-private variable to host the Reduce list
3362 // from a remote lane.
3363 Address RemoteReduceList =
3364 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
3365
3366 // This loop iterates through the list of reduce elements and copies,
3367 // element by element, from a remote lane in the warp to RemoteReduceList,
3368 // hosted on the thread's stack.
3369 emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
3370 LocalReduceList, RemoteReduceList,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003371 {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
3372 /*ScratchpadIndex=*/nullptr,
3373 /*ScratchpadWidth=*/nullptr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003374
3375 // The actions to be performed on the Remote Reduce list is dependent
3376 // on the algorithm version.
3377 //
3378 // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
3379 // LaneId % 2 == 0 && Offset > 0):
3380 // do the reduction value aggregation
3381 //
3382 // The thread local variable Reduce list is mutated in place to host the
3383 // reduced data, which is the aggregated value produced from local and
3384 // remote lanes.
3385 //
3386 // Note that AlgoVer is expected to be a constant integer known at compile
3387 // time.
3388 // When AlgoVer==0, the first conjunction evaluates to true, making
3389 // the entire predicate true during compile time.
3390 // When AlgoVer==1, the second conjunction has only the second part to be
3391 // evaluated during runtime. Other conjunctions evaluates to false
3392 // during compile time.
3393 // When AlgoVer==2, the third conjunction has only the second part to be
3394 // evaluated during runtime. Other conjunctions evaluates to false
3395 // during compile time.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003396 llvm::Value *CondAlgo0 = Bld.CreateIsNull(AlgoVerArgVal);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003397
Alexey Bataev9ff80832018-04-16 20:16:21 +00003398 llvm::Value *Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
3399 llvm::Value *CondAlgo1 = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003400 Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
3401
Alexey Bataev9ff80832018-04-16 20:16:21 +00003402 llvm::Value *Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
3403 llvm::Value *CondAlgo2 = Bld.CreateAnd(
3404 Algo2, Bld.CreateIsNull(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1))));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003405 CondAlgo2 = Bld.CreateAnd(
3406 CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
3407
Alexey Bataev9ff80832018-04-16 20:16:21 +00003408 llvm::Value *CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003409 CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
3410
3411 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3412 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3413 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
3414 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
3415
3416 CGF.EmitBlock(ThenBB);
3417 // reduce_function(LocalReduceList, RemoteReduceList)
3418 llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3419 LocalReduceList.getPointer(), CGF.VoidPtrTy);
3420 llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3421 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003422 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3423 CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003424 Bld.CreateBr(MergeBB);
3425
3426 CGF.EmitBlock(ElseBB);
3427 Bld.CreateBr(MergeBB);
3428
3429 CGF.EmitBlock(MergeBB);
3430
3431 // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
3432 // Reduce list.
3433 Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
Alexey Bataev9ff80832018-04-16 20:16:21 +00003434 llvm::Value *CondCopy = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003435 Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
3436
3437 llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
3438 llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
3439 llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
3440 Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
3441
3442 CGF.EmitBlock(CpyThenBB);
3443 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
3444 RemoteReduceList, LocalReduceList);
3445 Bld.CreateBr(CpyMergeBB);
3446
3447 CGF.EmitBlock(CpyElseBB);
3448 Bld.CreateBr(CpyMergeBB);
3449
3450 CGF.EmitBlock(CpyMergeBB);
3451
3452 CGF.FinishFunction();
3453 return Fn;
3454}
3455
3456///
3457/// Design of OpenMP reductions on the GPU
3458///
3459/// Consider a typical OpenMP program with one or more reduction
3460/// clauses:
3461///
3462/// float foo;
3463/// double bar;
3464/// #pragma omp target teams distribute parallel for \
3465/// reduction(+:foo) reduction(*:bar)
3466/// for (int i = 0; i < N; i++) {
3467/// foo += A[i]; bar *= B[i];
3468/// }
3469///
3470/// where 'foo' and 'bar' are reduced across all OpenMP threads in
3471/// all teams. In our OpenMP implementation on the NVPTX device an
3472/// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
3473/// within a team are mapped to CUDA threads within a threadblock.
3474/// Our goal is to efficiently aggregate values across all OpenMP
3475/// threads such that:
3476///
3477/// - the compiler and runtime are logically concise, and
3478/// - the reduction is performed efficiently in a hierarchical
3479/// manner as follows: within OpenMP threads in the same warp,
3480/// across warps in a threadblock, and finally across teams on
3481/// the NVPTX device.
3482///
3483/// Introduction to Decoupling
3484///
3485/// We would like to decouple the compiler and the runtime so that the
3486/// latter is ignorant of the reduction variables (number, data types)
3487/// and the reduction operators. This allows a simpler interface
3488/// and implementation while still attaining good performance.
3489///
3490/// Pseudocode for the aforementioned OpenMP program generated by the
3491/// compiler is as follows:
3492///
3493/// 1. Create private copies of reduction variables on each OpenMP
3494/// thread: 'foo_private', 'bar_private'
3495/// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
3496/// to it and writes the result in 'foo_private' and 'bar_private'
3497/// respectively.
3498/// 3. Call the OpenMP runtime on the GPU to reduce within a team
3499/// and store the result on the team master:
3500///
3501/// __kmpc_nvptx_parallel_reduce_nowait(...,
3502/// reduceData, shuffleReduceFn, interWarpCpyFn)
3503///
3504/// where:
3505/// struct ReduceData {
3506/// double *foo;
3507/// double *bar;
3508/// } reduceData
3509/// reduceData.foo = &foo_private
3510/// reduceData.bar = &bar_private
3511///
3512/// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
3513/// auxiliary functions generated by the compiler that operate on
3514/// variables of type 'ReduceData'. They aid the runtime perform
3515/// algorithmic steps in a data agnostic manner.
3516///
3517/// 'shuffleReduceFn' is a pointer to a function that reduces data
3518/// of type 'ReduceData' across two OpenMP threads (lanes) in the
3519/// same warp. It takes the following arguments as input:
3520///
3521/// a. variable of type 'ReduceData' on the calling lane,
3522/// b. its lane_id,
3523/// c. an offset relative to the current lane_id to generate a
3524/// remote_lane_id. The remote lane contains the second
3525/// variable of type 'ReduceData' that is to be reduced.
3526/// d. an algorithm version parameter determining which reduction
3527/// algorithm to use.
3528///
3529/// 'shuffleReduceFn' retrieves data from the remote lane using
3530/// efficient GPU shuffle intrinsics and reduces, using the
3531/// algorithm specified by the 4th parameter, the two operands
3532/// element-wise. The result is written to the first operand.
3533///
3534/// Different reduction algorithms are implemented in different
3535/// runtime functions, all calling 'shuffleReduceFn' to perform
3536/// the essential reduction step. Therefore, based on the 4th
3537/// parameter, this function behaves slightly differently to
3538/// cooperate with the runtime to ensure correctness under
3539/// different circumstances.
3540///
3541/// 'InterWarpCpyFn' is a pointer to a function that transfers
3542/// reduced variables across warps. It tunnels, through CUDA
3543/// shared memory, the thread-private data of type 'ReduceData'
3544/// from lane 0 of each warp to a lane in the first warp.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003545/// 4. Call the OpenMP runtime on the GPU to reduce across teams.
3546/// The last team writes the global reduced value to memory.
3547///
3548/// ret = __kmpc_nvptx_teams_reduce_nowait(...,
3549/// reduceData, shuffleReduceFn, interWarpCpyFn,
3550/// scratchpadCopyFn, loadAndReduceFn)
3551///
3552/// 'scratchpadCopyFn' is a helper that stores reduced
3553/// data from the team master to a scratchpad array in
3554/// global memory.
3555///
3556/// 'loadAndReduceFn' is a helper that loads data from
3557/// the scratchpad array and reduces it with the input
3558/// operand.
3559///
3560/// These compiler generated functions hide address
3561/// calculation and alignment information from the runtime.
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003562/// 5. if ret == 1:
3563/// The team master of the last team stores the reduced
3564/// result to the globals in memory.
3565/// foo += reduceData.foo; bar *= reduceData.bar
3566///
3567///
3568/// Warp Reduction Algorithms
3569///
3570/// On the warp level, we have three algorithms implemented in the
3571/// OpenMP runtime depending on the number of active lanes:
3572///
3573/// Full Warp Reduction
3574///
3575/// The reduce algorithm within a warp where all lanes are active
3576/// is implemented in the runtime as follows:
3577///
3578/// full_warp_reduce(void *reduce_data,
3579/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3580/// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
3581/// ShuffleReduceFn(reduce_data, 0, offset, 0);
3582/// }
3583///
3584/// The algorithm completes in log(2, WARPSIZE) steps.
3585///
3586/// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
3587/// not used therefore we save instructions by not retrieving lane_id
3588/// from the corresponding special registers. The 4th parameter, which
3589/// represents the version of the algorithm being used, is set to 0 to
3590/// signify full warp reduction.
3591///
3592/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3593///
3594/// #reduce_elem refers to an element in the local lane's data structure
3595/// #remote_elem is retrieved from a remote lane
3596/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3597/// reduce_elem = reduce_elem REDUCE_OP remote_elem;
3598///
3599/// Contiguous Partial Warp Reduction
3600///
3601/// This reduce algorithm is used within a warp where only the first
3602/// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
3603/// number of OpenMP threads in a parallel region is not a multiple of
3604/// WARPSIZE. The algorithm is implemented in the runtime as follows:
3605///
3606/// void
3607/// contiguous_partial_reduce(void *reduce_data,
3608/// kmp_ShuffleReductFctPtr ShuffleReduceFn,
3609/// int size, int lane_id) {
3610/// int curr_size;
3611/// int offset;
3612/// curr_size = size;
3613/// mask = curr_size/2;
3614/// while (offset>0) {
3615/// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
3616/// curr_size = (curr_size+1)/2;
3617/// offset = curr_size/2;
3618/// }
3619/// }
3620///
3621/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3622///
3623/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3624/// if (lane_id < offset)
3625/// reduce_elem = reduce_elem REDUCE_OP remote_elem
3626/// else
3627/// reduce_elem = remote_elem
3628///
3629/// This algorithm assumes that the data to be reduced are located in a
3630/// contiguous subset of lanes starting from the first. When there is
3631/// an odd number of active lanes, the data in the last lane is not
3632/// aggregated with any other lane's dat but is instead copied over.
3633///
3634/// Dispersed Partial Warp Reduction
3635///
3636/// This algorithm is used within a warp when any discontiguous subset of
3637/// lanes are active. It is used to implement the reduction operation
3638/// across lanes in an OpenMP simd region or in a nested parallel region.
3639///
3640/// void
3641/// dispersed_partial_reduce(void *reduce_data,
3642/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3643/// int size, remote_id;
3644/// int logical_lane_id = number_of_active_lanes_before_me() * 2;
3645/// do {
3646/// remote_id = next_active_lane_id_right_after_me();
3647/// # the above function returns 0 of no active lane
3648/// # is present right after the current lane.
3649/// size = number_of_active_lanes_in_this_warp();
3650/// logical_lane_id /= 2;
3651/// ShuffleReduceFn(reduce_data, logical_lane_id,
3652/// remote_id-1-threadIdx.x, 2);
3653/// } while (logical_lane_id % 2 == 0 && size > 1);
3654/// }
3655///
3656/// There is no assumption made about the initial state of the reduction.
3657/// Any number of lanes (>=1) could be active at any position. The reduction
3658/// result is returned in the first active lane.
3659///
3660/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3661///
3662/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3663/// if (lane_id % 2 == 0 && offset > 0)
3664/// reduce_elem = reduce_elem REDUCE_OP remote_elem
3665/// else
3666/// reduce_elem = remote_elem
3667///
3668///
3669/// Intra-Team Reduction
3670///
3671/// This function, as implemented in the runtime call
3672/// '__kmpc_nvptx_parallel_reduce_nowait', aggregates data across OpenMP
3673/// threads in a team. It first reduces within a warp using the
3674/// aforementioned algorithms. We then proceed to gather all such
3675/// reduced values at the first warp.
3676///
3677/// The runtime makes use of the function 'InterWarpCpyFn', which copies
3678/// data from each of the "warp master" (zeroth lane of each warp, where
3679/// warp-reduced data is held) to the zeroth warp. This step reduces (in
3680/// a mathematical sense) the problem of reduction across warp masters in
3681/// a block to the problem of warp reduction.
3682///
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003683///
3684/// Inter-Team Reduction
3685///
3686/// Once a team has reduced its data to a single value, it is stored in
3687/// a global scratchpad array. Since each team has a distinct slot, this
3688/// can be done without locking.
3689///
3690/// The last team to write to the scratchpad array proceeds to reduce the
3691/// scratchpad array. One or more workers in the last team use the helper
3692/// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
3693/// the k'th worker reduces every k'th element.
3694///
3695/// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait' to
3696/// reduce across workers and compute a globally reduced value.
3697///
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003698void CGOpenMPRuntimeNVPTX::emitReduction(
3699 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
3700 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
3701 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
3702 if (!CGF.HaveInsertPoint())
3703 return;
3704
3705 bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003706 bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
Alexey Bataevfac26cf2018-05-02 20:03:27 +00003707 bool SimdReduction = isOpenMPSimdDirective(Options.ReductionKind);
3708 assert((TeamsReduction || ParallelReduction || SimdReduction) &&
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003709 "Invalid reduction selection in emitReduction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003710
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00003711 if (Options.SimpleReduction) {
3712 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
3713 ReductionOps, Options);
3714 return;
3715 }
3716
Alexey Bataev9ff80832018-04-16 20:16:21 +00003717 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003718
3719 // 1. Build a list of reduction variables.
3720 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3721 auto Size = RHSExprs.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00003722 for (const Expr *E : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003723 if (E->getType()->isVariablyModifiedType())
3724 // Reserve place for array size.
3725 ++Size;
3726 }
3727 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
3728 QualType ReductionArrayTy =
3729 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3730 /*IndexTypeQuals=*/0);
3731 Address ReductionList =
3732 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3733 auto IPriv = Privates.begin();
3734 unsigned Idx = 0;
3735 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
3736 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3737 CGF.getPointerSize());
3738 CGF.Builder.CreateStore(
3739 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3740 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
3741 Elem);
3742 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3743 // Store array size.
3744 ++Idx;
3745 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3746 CGF.getPointerSize());
3747 llvm::Value *Size = CGF.Builder.CreateIntCast(
3748 CGF.getVLASize(
3749 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
Sander de Smalen891af03a2018-02-03 13:55:59 +00003750 .NumElts,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003751 CGF.SizeTy, /*isSigned=*/false);
3752 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3753 Elem);
3754 }
3755 }
3756
3757 // 2. Emit reduce_func().
Alexey Bataev9ff80832018-04-16 20:16:21 +00003758 llvm::Value *ReductionFn = emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003759 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
3760 Privates, LHSExprs, RHSExprs, ReductionOps);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003761
3762 // 4. Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
3763 // RedList, shuffle_reduce_func, interwarp_copy_func);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003764 llvm::Value *ThreadId = getThreadID(CGF, Loc);
3765 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
3766 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003767 ReductionList.getPointer(), CGF.VoidPtrTy);
3768
Alexey Bataev9ff80832018-04-16 20:16:21 +00003769 llvm::Value *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003770 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003771 llvm::Value *InterWarpCopyFn =
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003772 emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003773
Alexey Bataevfac26cf2018-05-02 20:03:27 +00003774 llvm::Value *Args[] = {ThreadId,
3775 CGF.Builder.getInt32(RHSExprs.size()),
3776 ReductionArrayTySize,
3777 RL,
3778 ShuffleAndReduceFn,
3779 InterWarpCopyFn};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003780
Alexey Bataevfac26cf2018-05-02 20:03:27 +00003781 llvm::Value *Res = nullptr;
3782 if (ParallelReduction)
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003783 Res = CGF.EmitRuntimeCall(
3784 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_reduce_nowait),
3785 Args);
Alexey Bataevfac26cf2018-05-02 20:03:27 +00003786 else if (SimdReduction)
3787 Res = CGF.EmitRuntimeCall(
3788 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_simd_reduce_nowait),
3789 Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003790
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003791 if (TeamsReduction) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003792 llvm::Value *ScratchPadCopyFn =
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003793 emitCopyToScratchpad(CGM, Privates, ReductionArrayTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003794 llvm::Value *LoadAndReduceFn = emitReduceScratchpadFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003795 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003796
3797 llvm::Value *Args[] = {ThreadId,
3798 CGF.Builder.getInt32(RHSExprs.size()),
3799 ReductionArrayTySize,
3800 RL,
3801 ShuffleAndReduceFn,
3802 InterWarpCopyFn,
3803 ScratchPadCopyFn,
3804 LoadAndReduceFn};
3805 Res = CGF.EmitRuntimeCall(
3806 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_teams_reduce_nowait),
3807 Args);
3808 }
3809
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003810 // 5. Build switch(res)
Alexey Bataev9ff80832018-04-16 20:16:21 +00003811 llvm::BasicBlock *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
3812 llvm::SwitchInst *SwInst =
3813 CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003814
3815 // 6. Build case 1: where we have reduced values in the master
3816 // thread in each team.
3817 // __kmpc_end_reduce{_nowait}(<gtid>);
3818 // break;
Alexey Bataev9ff80832018-04-16 20:16:21 +00003819 llvm::BasicBlock *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003820 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
3821 CGF.EmitBlock(Case1BB);
3822
3823 // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
3824 llvm::Value *EndArgs[] = {ThreadId};
Alexey Bataev9ff80832018-04-16 20:16:21 +00003825 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003826 this](CodeGenFunction &CGF, PrePostActionTy &Action) {
3827 auto IPriv = Privates.begin();
3828 auto ILHS = LHSExprs.begin();
3829 auto IRHS = RHSExprs.begin();
Alexey Bataev9ff80832018-04-16 20:16:21 +00003830 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003831 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
3832 cast<DeclRefExpr>(*IRHS));
3833 ++IPriv;
3834 ++ILHS;
3835 ++IRHS;
3836 }
3837 };
3838 RegionCodeGenTy RCG(CodeGen);
3839 NVPTXActionTy Action(
3840 nullptr, llvm::None,
3841 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_reduce_nowait),
3842 EndArgs);
3843 RCG.setAction(Action);
3844 RCG(CGF);
3845 CGF.EmitBranch(DefaultBB);
3846 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
3847}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003848
3849const VarDecl *
3850CGOpenMPRuntimeNVPTX::translateParameter(const FieldDecl *FD,
3851 const VarDecl *NativeParam) const {
3852 if (!NativeParam->getType()->isReferenceType())
3853 return NativeParam;
3854 QualType ArgType = NativeParam->getType();
3855 QualifierCollector QC;
3856 const Type *NonQualTy = QC.strip(ArgType);
3857 QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
3858 if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
3859 if (Attr->getCaptureKind() == OMPC_map) {
3860 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
3861 LangAS::opencl_global);
3862 }
3863 }
3864 ArgType = CGM.getContext().getPointerType(PointeeTy);
3865 QC.addRestrict();
3866 enum { NVPTX_local_addr = 5 };
Alexander Richardson6d989432017-10-15 18:48:14 +00003867 QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003868 ArgType = QC.apply(CGM.getContext(), ArgType);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003869 if (isa<ImplicitParamDecl>(NativeParam))
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003870 return ImplicitParamDecl::Create(
3871 CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
3872 NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003873 return ParmVarDecl::Create(
3874 CGM.getContext(),
3875 const_cast<DeclContext *>(NativeParam->getDeclContext()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003876 NativeParam->getBeginLoc(), NativeParam->getLocation(),
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003877 NativeParam->getIdentifier(), ArgType,
3878 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003879}
3880
3881Address
3882CGOpenMPRuntimeNVPTX::getParameterAddress(CodeGenFunction &CGF,
3883 const VarDecl *NativeParam,
3884 const VarDecl *TargetParam) const {
3885 assert(NativeParam != TargetParam &&
3886 NativeParam->getType()->isReferenceType() &&
3887 "Native arg must not be the same as target arg.");
3888 Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
3889 QualType NativeParamType = NativeParam->getType();
3890 QualifierCollector QC;
3891 const Type *NonQualTy = QC.strip(NativeParamType);
3892 QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
3893 unsigned NativePointeeAddrSpace =
Alexander Richardson6d989432017-10-15 18:48:14 +00003894 CGF.getContext().getTargetAddressSpace(NativePointeeTy);
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00003895 QualType TargetTy = TargetParam->getType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003896 llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00003897 LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003898 // First cast to generic.
3899 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3900 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
3901 /*AddrSpace=*/0));
3902 // Cast from generic to native address space.
3903 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3904 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
3905 NativePointeeAddrSpace));
3906 Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
3907 CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00003908 NativeParamType);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003909 return NativeParamAddr;
3910}
3911
3912void CGOpenMPRuntimeNVPTX::emitOutlinedFunctionCall(
Alexey Bataev3c595a62017-08-14 15:01:03 +00003913 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003914 ArrayRef<llvm::Value *> Args) const {
3915 SmallVector<llvm::Value *, 4> TargetArgs;
Alexey Bataev07ed94a2017-08-15 14:34:04 +00003916 TargetArgs.reserve(Args.size());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003917 auto *FnType =
3918 cast<llvm::FunctionType>(OutlinedFn->getType()->getPointerElementType());
3919 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
Alexey Bataev07ed94a2017-08-15 14:34:04 +00003920 if (FnType->isVarArg() && FnType->getNumParams() <= I) {
3921 TargetArgs.append(std::next(Args.begin(), I), Args.end());
3922 break;
3923 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003924 llvm::Type *TargetType = FnType->getParamType(I);
3925 llvm::Value *NativeArg = Args[I];
3926 if (!TargetType->isPointerTy()) {
3927 TargetArgs.emplace_back(NativeArg);
3928 continue;
3929 }
3930 llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataevc99042b2018-03-15 18:10:54 +00003931 NativeArg,
3932 NativeArg->getType()->getPointerElementType()->getPointerTo());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003933 TargetArgs.emplace_back(
3934 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
3935 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00003936 CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003937}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003938
3939/// Emit function which wraps the outline parallel region
3940/// and controls the arguments which are passed to this function.
3941/// The wrapper ensures that the outlined function is called
3942/// with the correct arguments when data is shared.
3943llvm::Function *CGOpenMPRuntimeNVPTX::createParallelDataSharingWrapper(
3944 llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
3945 ASTContext &Ctx = CGM.getContext();
3946 const auto &CS = *D.getCapturedStmt(OMPD_parallel);
3947
3948 // Create a function that takes as argument the source thread.
3949 FunctionArgList WrapperArgs;
3950 QualType Int16QTy =
3951 Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
3952 QualType Int32QTy =
3953 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003954 ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003955 /*Id=*/nullptr, Int16QTy,
3956 ImplicitParamDecl::Other);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003957 ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003958 /*Id=*/nullptr, Int32QTy,
3959 ImplicitParamDecl::Other);
3960 WrapperArgs.emplace_back(&ParallelLevelArg);
3961 WrapperArgs.emplace_back(&WrapperArg);
3962
Alexey Bataev9ff80832018-04-16 20:16:21 +00003963 const CGFunctionInfo &CGFI =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003964 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
3965
3966 auto *Fn = llvm::Function::Create(
3967 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataev9ff80832018-04-16 20:16:21 +00003968 Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
Alexey Bataevc99042b2018-03-15 18:10:54 +00003969 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003970 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003971 Fn->setDoesNotRecurse();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003972
3973 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3974 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003975 D.getBeginLoc(), D.getBeginLoc());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003976
3977 const auto *RD = CS.getCapturedRecordDecl();
3978 auto CurField = RD->field_begin();
3979
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00003980 Address ZeroAddr = CGF.CreateMemTemp(
3981 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
3982 /*Name*/ ".zero.addr");
3983 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003984 // Get the array of arguments.
3985 SmallVector<llvm::Value *, 8> Args;
3986
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00003987 Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).getPointer());
3988 Args.emplace_back(ZeroAddr.getPointer());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003989
3990 CGBuilderTy &Bld = CGF.Builder;
3991 auto CI = CS.capture_begin();
3992
3993 // Use global memory for data sharing.
3994 // Handle passing of global args to workers.
3995 Address GlobalArgs =
3996 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
3997 llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
3998 llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
3999 CGF.EmitRuntimeCall(
4000 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_get_shared_variables),
4001 DataSharingArgs);
4002
4003 // Retrieve the shared variables from the list of references returned
4004 // by the runtime. Pass the variables to the outlined function.
Alexey Bataev17314212018-03-20 15:41:05 +00004005 Address SharedArgListAddress = Address::invalid();
4006 if (CS.capture_size() > 0 ||
4007 isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4008 SharedArgListAddress = CGF.EmitLoadOfPointer(
4009 GlobalArgs, CGF.getContext()
4010 .getPointerType(CGF.getContext().getPointerType(
4011 CGF.getContext().VoidPtrTy))
4012 .castAs<PointerType>());
4013 }
4014 unsigned Idx = 0;
4015 if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4016 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
4017 CGF.getPointerSize());
4018 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4019 Src, CGF.SizeTy->getPointerTo());
4020 llvm::Value *LB = CGF.EmitLoadOfScalar(
4021 TypedAddress,
4022 /*Volatile=*/false,
4023 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4024 cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
4025 Args.emplace_back(LB);
4026 ++Idx;
4027 Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
4028 CGF.getPointerSize());
4029 TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4030 Src, CGF.SizeTy->getPointerTo());
4031 llvm::Value *UB = CGF.EmitLoadOfScalar(
4032 TypedAddress,
4033 /*Volatile=*/false,
4034 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4035 cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
4036 Args.emplace_back(UB);
4037 ++Idx;
4038 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004039 if (CS.capture_size() > 0) {
4040 ASTContext &CGFContext = CGF.getContext();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004041 for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
4042 QualType ElemTy = CurField->getType();
Alexey Bataev17314212018-03-20 15:41:05 +00004043 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx,
4044 CGF.getPointerSize());
4045 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004046 Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)));
4047 llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
4048 /*Volatile=*/false,
4049 CGFContext.getPointerType(ElemTy),
4050 CI->getLocation());
Alexey Bataev2091ca62018-04-23 17:33:41 +00004051 if (CI->capturesVariableByCopy() &&
4052 !CI->getCapturedVar()->getType()->isAnyPointerType()) {
Alexey Bataev17314212018-03-20 15:41:05 +00004053 Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
4054 CI->getLocation());
4055 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004056 Args.emplace_back(Arg);
4057 }
4058 }
4059
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004060 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedParallelFn, Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004061 CGF.FinishFunction();
4062 return Fn;
4063}
4064
4065void CGOpenMPRuntimeNVPTX::emitFunctionProlog(CodeGenFunction &CGF,
4066 const Decl *D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004067 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4068 return;
4069
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004070 assert(D && "Expected function or captured|block decl.");
4071 assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
4072 "Function is registered already.");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004073 const Stmt *Body = nullptr;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004074 bool NeedToDelayGlobalization = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004075 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4076 Body = FD->getBody();
4077 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
4078 Body = BD->getBody();
4079 } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
4080 Body = CD->getBody();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004081 NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
Alexey Bataev2adecff2018-09-21 14:22:53 +00004082 if (NeedToDelayGlobalization &&
4083 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
4084 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004085 }
4086 if (!Body)
4087 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004088 CheckVarsEscapingDeclContext VarChecker(CGF);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004089 VarChecker.Visit(Body);
4090 const RecordDecl *GlobalizedVarsRecord = VarChecker.getGlobalizedRecord();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004091 ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
4092 VarChecker.getEscapedVariableLengthDecls();
4093 if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004094 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004095 auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
4096 I->getSecond().MappedParams =
4097 llvm::make_unique<CodeGenFunction::OMPMapVars>();
4098 I->getSecond().GlobalRecord = GlobalizedVarsRecord;
4099 I->getSecond().EscapedParameters.insert(
4100 VarChecker.getEscapedParameters().begin(),
4101 VarChecker.getEscapedParameters().end());
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004102 I->getSecond().EscapedVariableLengthDecls.append(
4103 EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004104 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004105 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004106 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004107 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004108 Data.insert(std::make_pair(VD, MappedVarData(FD)));
Alexey Bataevc99042b2018-03-15 18:10:54 +00004109 }
4110 if (!NeedToDelayGlobalization) {
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004111 emitGenericVarsProlog(CGF, D->getBeginLoc(), /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004112 struct GlobalizationScope final : EHScopeStack::Cleanup {
4113 GlobalizationScope() = default;
4114
4115 void Emit(CodeGenFunction &CGF, Flags flags) override {
4116 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004117 .emitGenericVarsEpilog(CGF, /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004118 }
4119 };
4120 CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004121 }
4122}
4123
4124Address CGOpenMPRuntimeNVPTX::getAddressOfLocalVariable(CodeGenFunction &CGF,
4125 const VarDecl *VD) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004126 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4127 return Address::invalid();
4128
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004129 VD = VD->getCanonicalDecl();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004130 auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
4131 if (I == FunctionGlobalizedDecls.end())
4132 return Address::invalid();
Alexey Bataevc99042b2018-03-15 18:10:54 +00004133 auto VDI = I->getSecond().LocalVarData.find(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004134 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004135 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004136 if (VD->hasAttrs()) {
4137 for (specific_attr_iterator<OMPReferencedVarAttr> IT(VD->attr_begin()),
4138 E(VD->attr_end());
4139 IT != E; ++IT) {
4140 auto VDI = I->getSecond().LocalVarData.find(
4141 cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
4142 ->getCanonicalDecl());
4143 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004144 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004145 }
4146 }
4147 return Address::invalid();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004148}
4149
4150void CGOpenMPRuntimeNVPTX::functionFinished(CodeGenFunction &CGF) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004151 FunctionGlobalizedDecls.erase(CGF.CurFn);
4152 CGOpenMPRuntime::functionFinished(CGF);
4153}
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004154
4155void CGOpenMPRuntimeNVPTX::getDefaultDistScheduleAndChunk(
4156 CodeGenFunction &CGF, const OMPLoopDirective &S,
4157 OpenMPDistScheduleClauseKind &ScheduleKind,
4158 llvm::Value *&Chunk) const {
4159 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
4160 ScheduleKind = OMPC_DIST_SCHEDULE_static;
4161 Chunk = CGF.EmitScalarConversion(getNVPTXNumThreads(CGF),
4162 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4163 S.getIterationVariable()->getType(), S.getBeginLoc());
4164 }
4165}
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004166
4167void CGOpenMPRuntimeNVPTX::getDefaultScheduleAndChunk(
4168 CodeGenFunction &CGF, const OMPLoopDirective &S,
4169 OpenMPScheduleClauseKind &ScheduleKind,
4170 llvm::Value *&Chunk) const {
4171 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
4172 ScheduleKind = OMPC_SCHEDULE_static;
4173 Chunk = CGF.Builder.getIntN(CGF.getContext().getTypeSize(
4174 S.getIterationVariable()->getType()), 1);
4175 }
4176}