blob: c8dd1a6f7b6ddd18c25639b39cd4003fac655544 [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 Bataevff23bb62018-10-11 18:30:31 +0000206 // /* globalized vars */[WarSize] align (max(decl_align,
207 // GlobalMemoryAlignment))
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000208 // /* globalized vars */ for EscapedDeclsForTeams
Alexey Bataev2adecff2018-09-21 14:22:53 +0000209 // };
210 RecordDecl *GlobalizedRD = C.buildImplicitRecord("_globalized_locals_ty");
211 GlobalizedRD->startDefinition();
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000212 llvm::SmallPtrSet<const ValueDecl *, 16> SingleEscaped(
213 EscapedDeclsForTeams.begin(), EscapedDeclsForTeams.end());
Alexey Bataev2adecff2018-09-21 14:22:53 +0000214 for (const auto &Pair : GlobalizedVars) {
215 const ValueDecl *VD = Pair.second;
216 QualType Type = VD->getType();
217 if (Type->isLValueReferenceType())
218 Type = C.getPointerType(Type.getNonReferenceType());
219 else
220 Type = Type.getNonReferenceType();
221 SourceLocation Loc = VD->getLocation();
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000222 FieldDecl *Field;
223 if (SingleEscaped.count(VD)) {
224 Field = FieldDecl::Create(
225 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
226 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
227 /*BW=*/nullptr, /*Mutable=*/false,
228 /*InitStyle=*/ICIS_NoInit);
229 Field->setAccess(AS_public);
230 if (VD->hasAttrs()) {
231 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
232 E(VD->getAttrs().end());
233 I != E; ++I)
234 Field->addAttr(*I);
235 }
236 } else {
237 llvm::APInt ArraySize(32, WarpSize);
238 Type = C.getConstantArrayType(Type, ArraySize, ArrayType::Normal, 0);
239 Field = FieldDecl::Create(
240 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
241 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
242 /*BW=*/nullptr, /*Mutable=*/false,
243 /*InitStyle=*/ICIS_NoInit);
244 Field->setAccess(AS_public);
245 llvm::APInt Align(32, std::max(C.getDeclAlign(VD).getQuantity(),
246 static_cast<CharUnits::QuantityType>(
247 GlobalMemoryAlignment)));
248 Field->addAttr(AlignedAttr::CreateImplicit(
249 C, AlignedAttr::GNU_aligned, /*IsAlignmentExpr=*/true,
250 IntegerLiteral::Create(C, Align,
251 C.getIntTypeForBitwidth(32, /*Signed=*/0),
252 SourceLocation())));
Alexey Bataev2adecff2018-09-21 14:22:53 +0000253 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000254 GlobalizedRD->addDecl(Field);
Alexey Bataev2adecff2018-09-21 14:22:53 +0000255 MappedDeclsFields.try_emplace(VD, Field);
256 }
257 GlobalizedRD->completeDefinition();
258 return GlobalizedRD;
259}
260
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000261/// Get the list of variables that can escape their declaration context.
262class CheckVarsEscapingDeclContext final
263 : public ConstStmtVisitor<CheckVarsEscapingDeclContext> {
264 CodeGenFunction &CGF;
265 llvm::SetVector<const ValueDecl *> EscapedDecls;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000266 llvm::SetVector<const ValueDecl *> EscapedVariableLengthDecls;
Alexey Bataevc99042b2018-03-15 18:10:54 +0000267 llvm::SmallPtrSet<const Decl *, 4> EscapedParameters;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000268 RecordDecl *GlobalizedRD = nullptr;
269 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000270 bool AllEscaped = false;
Alexey Bataev91433f62018-06-26 17:24:03 +0000271 bool IsForCombinedParallelRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000272
273 void markAsEscaped(const ValueDecl *VD) {
Alexey Bataev03f270c2018-03-30 18:31:07 +0000274 // Do not globalize declare target variables.
Alexey Bataev97b72212018-08-14 18:31:20 +0000275 if (!isa<VarDecl>(VD) ||
276 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataev03f270c2018-03-30 18:31:07 +0000277 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000278 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataevc99042b2018-03-15 18:10:54 +0000279 // Variables captured by value must be globalized.
280 if (auto *CSI = CGF.CapturedStmtInfo) {
Mikael Holmen9f373a32018-03-16 07:27:57 +0000281 if (const FieldDecl *FD = CSI->lookup(cast<VarDecl>(VD))) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000282 // Check if need to capture the variable that was already captured by
283 // value in the outer region.
Alexey Bataev91433f62018-06-26 17:24:03 +0000284 if (!IsForCombinedParallelRegion) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000285 if (!FD->hasAttrs())
286 return;
287 const auto *Attr = FD->getAttr<OMPCaptureKindAttr>();
288 if (!Attr)
289 return;
290 if (!isOpenMPPrivate(
291 static_cast<OpenMPClauseKind>(Attr->getCaptureKind())) ||
292 Attr->getCaptureKind() == OMPC_map)
293 return;
294 }
295 if (!FD->getType()->isReferenceType()) {
296 assert(!VD->getType()->isVariablyModifiedType() &&
297 "Parameter captured by value with variably modified type");
298 EscapedParameters.insert(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000299 } else if (!IsForCombinedParallelRegion) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000300 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000301 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000302 }
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000303 }
304 if ((!CGF.CapturedStmtInfo ||
Alexey Bataev91433f62018-06-26 17:24:03 +0000305 (IsForCombinedParallelRegion && CGF.CapturedStmtInfo)) &&
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000306 VD->getType()->isReferenceType())
307 // Do not globalize variables with reference type.
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000308 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000309 if (VD->getType()->isVariablyModifiedType())
310 EscapedVariableLengthDecls.insert(VD);
311 else
312 EscapedDecls.insert(VD);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000313 }
314
315 void VisitValueDecl(const ValueDecl *VD) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000316 if (VD->getType()->isLValueReferenceType())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000317 markAsEscaped(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000318 if (const auto *VarD = dyn_cast<VarDecl>(VD)) {
319 if (!isa<ParmVarDecl>(VarD) && VarD->hasInit()) {
320 const bool SavedAllEscaped = AllEscaped;
321 AllEscaped = VD->getType()->isLValueReferenceType();
322 Visit(VarD->getInit());
323 AllEscaped = SavedAllEscaped;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000324 }
325 }
326 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000327 void VisitOpenMPCapturedStmt(const CapturedStmt *S,
328 ArrayRef<OMPClause *> Clauses,
329 bool IsCombinedParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000330 if (!S)
331 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000332 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000333 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
334 const ValueDecl *VD = C.getCapturedVar();
Alexey Bataev91433f62018-06-26 17:24:03 +0000335 bool SavedIsForCombinedParallelRegion = IsForCombinedParallelRegion;
336 if (IsCombinedParallelRegion) {
337 // Check if the variable is privatized in the combined construct and
338 // those private copies must be shared in the inner parallel
339 // directive.
340 IsForCombinedParallelRegion = false;
341 for (const OMPClause *C : Clauses) {
342 if (!isOpenMPPrivate(C->getClauseKind()) ||
343 C->getClauseKind() == OMPC_reduction ||
344 C->getClauseKind() == OMPC_linear ||
345 C->getClauseKind() == OMPC_private)
346 continue;
347 ArrayRef<const Expr *> Vars;
348 if (const auto *PC = dyn_cast<OMPFirstprivateClause>(C))
349 Vars = PC->getVarRefs();
350 else if (const auto *PC = dyn_cast<OMPLastprivateClause>(C))
351 Vars = PC->getVarRefs();
352 else
353 llvm_unreachable("Unexpected clause.");
354 for (const auto *E : Vars) {
355 const Decl *D =
356 cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
357 if (D == VD->getCanonicalDecl()) {
358 IsForCombinedParallelRegion = true;
359 break;
360 }
361 }
362 if (IsForCombinedParallelRegion)
363 break;
364 }
365 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000366 markAsEscaped(VD);
367 if (isa<OMPCapturedExprDecl>(VD))
368 VisitValueDecl(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000369 IsForCombinedParallelRegion = SavedIsForCombinedParallelRegion;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000370 }
371 }
372 }
373
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000374 void buildRecordForGlobalizedVars(bool IsInTTDRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000375 assert(!GlobalizedRD &&
376 "Record for globalized variables is built already.");
Alexey Bataevff23bb62018-10-11 18:30:31 +0000377 ArrayRef<const ValueDecl *> EscapedDeclsForParallel, EscapedDeclsForTeams;
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000378 if (IsInTTDRegion)
Alexey Bataevff23bb62018-10-11 18:30:31 +0000379 EscapedDeclsForTeams = EscapedDecls.getArrayRef();
380 else
381 EscapedDeclsForParallel = EscapedDecls.getArrayRef();
Alexey Bataev2adecff2018-09-21 14:22:53 +0000382 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataevff23bb62018-10-11 18:30:31 +0000383 CGF.getContext(), EscapedDeclsForParallel, EscapedDeclsForTeams,
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000384 MappedDeclsFields);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000385 }
386
387public:
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000388 CheckVarsEscapingDeclContext(CodeGenFunction &CGF) : CGF(CGF) {}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000389 virtual ~CheckVarsEscapingDeclContext() = default;
390 void VisitDeclStmt(const DeclStmt *S) {
391 if (!S)
392 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000393 for (const Decl *D : S->decls())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000394 if (const auto *VD = dyn_cast_or_null<ValueDecl>(D))
395 VisitValueDecl(VD);
396 }
397 void VisitOMPExecutableDirective(const OMPExecutableDirective *D) {
398 if (!D)
399 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000400 if (!D->hasAssociatedStmt())
401 return;
402 if (const auto *S =
403 dyn_cast_or_null<CapturedStmt>(D->getAssociatedStmt())) {
404 // Do not analyze directives that do not actually require capturing,
405 // like `omp for` or `omp simd` directives.
406 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
407 getOpenMPCaptureRegions(CaptureRegions, D->getDirectiveKind());
408 if (CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown) {
409 VisitStmt(S->getCapturedStmt());
410 return;
Alexey Bataev673110d2018-05-16 13:36:30 +0000411 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000412 VisitOpenMPCapturedStmt(
413 S, D->clauses(),
414 CaptureRegions.back() == OMPD_parallel &&
415 isOpenMPDistributeDirective(D->getDirectiveKind()));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000416 }
417 }
418 void VisitCapturedStmt(const CapturedStmt *S) {
419 if (!S)
420 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000421 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000422 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
423 const ValueDecl *VD = C.getCapturedVar();
424 markAsEscaped(VD);
425 if (isa<OMPCapturedExprDecl>(VD))
426 VisitValueDecl(VD);
427 }
428 }
429 }
430 void VisitLambdaExpr(const LambdaExpr *E) {
431 if (!E)
432 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000433 for (const LambdaCapture &C : E->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000434 if (C.capturesVariable()) {
435 if (C.getCaptureKind() == LCK_ByRef) {
436 const ValueDecl *VD = C.getCapturedVar();
437 markAsEscaped(VD);
438 if (E->isInitCapture(&C) || isa<OMPCapturedExprDecl>(VD))
439 VisitValueDecl(VD);
440 }
441 }
442 }
443 }
444 void VisitBlockExpr(const BlockExpr *E) {
445 if (!E)
446 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000447 for (const BlockDecl::Capture &C : E->getBlockDecl()->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000448 if (C.isByRef()) {
449 const VarDecl *VD = C.getVariable();
450 markAsEscaped(VD);
451 if (isa<OMPCapturedExprDecl>(VD) || VD->isInitCapture())
452 VisitValueDecl(VD);
453 }
454 }
455 }
456 void VisitCallExpr(const CallExpr *E) {
457 if (!E)
458 return;
459 for (const Expr *Arg : E->arguments()) {
460 if (!Arg)
461 continue;
462 if (Arg->isLValue()) {
463 const bool SavedAllEscaped = AllEscaped;
464 AllEscaped = true;
465 Visit(Arg);
466 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000467 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000468 Visit(Arg);
Alexey Bataev9ff80832018-04-16 20:16:21 +0000469 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000470 }
471 Visit(E->getCallee());
472 }
473 void VisitDeclRefExpr(const DeclRefExpr *E) {
474 if (!E)
475 return;
476 const ValueDecl *VD = E->getDecl();
477 if (AllEscaped)
478 markAsEscaped(VD);
479 if (isa<OMPCapturedExprDecl>(VD))
480 VisitValueDecl(VD);
481 else if (const auto *VarD = dyn_cast<VarDecl>(VD))
482 if (VarD->isInitCapture())
483 VisitValueDecl(VD);
484 }
485 void VisitUnaryOperator(const UnaryOperator *E) {
486 if (!E)
487 return;
488 if (E->getOpcode() == UO_AddrOf) {
489 const bool SavedAllEscaped = AllEscaped;
490 AllEscaped = true;
491 Visit(E->getSubExpr());
492 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000493 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000494 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000495 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000496 }
497 void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
498 if (!E)
499 return;
500 if (E->getCastKind() == CK_ArrayToPointerDecay) {
501 const bool SavedAllEscaped = AllEscaped;
502 AllEscaped = true;
503 Visit(E->getSubExpr());
504 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000505 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000506 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000507 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000508 }
509 void VisitExpr(const Expr *E) {
510 if (!E)
511 return;
512 bool SavedAllEscaped = AllEscaped;
513 if (!E->isLValue())
514 AllEscaped = false;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000515 for (const Stmt *Child : E->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000516 if (Child)
517 Visit(Child);
518 AllEscaped = SavedAllEscaped;
519 }
520 void VisitStmt(const Stmt *S) {
521 if (!S)
522 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000523 for (const Stmt *Child : S->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000524 if (Child)
525 Visit(Child);
526 }
527
Alexey Bataevc99042b2018-03-15 18:10:54 +0000528 /// Returns the record that handles all the escaped local variables and used
529 /// instead of their original storage.
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000530 const RecordDecl *getGlobalizedRecord(bool IsInTTDRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000531 if (!GlobalizedRD)
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000532 buildRecordForGlobalizedVars(IsInTTDRegion);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000533 return GlobalizedRD;
534 }
535
Alexey Bataevc99042b2018-03-15 18:10:54 +0000536 /// Returns the field in the globalized record for the escaped variable.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000537 const FieldDecl *getFieldForGlobalizedVar(const ValueDecl *VD) const {
538 assert(GlobalizedRD &&
539 "Record for globalized variables must be generated already.");
540 auto I = MappedDeclsFields.find(VD);
541 if (I == MappedDeclsFields.end())
542 return nullptr;
543 return I->getSecond();
544 }
545
Alexey Bataevc99042b2018-03-15 18:10:54 +0000546 /// Returns the list of the escaped local variables/parameters.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000547 ArrayRef<const ValueDecl *> getEscapedDecls() const {
548 return EscapedDecls.getArrayRef();
549 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000550
551 /// Checks if the escaped local variable is actually a parameter passed by
552 /// value.
553 const llvm::SmallPtrSetImpl<const Decl *> &getEscapedParameters() const {
554 return EscapedParameters;
555 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000556
557 /// Returns the list of the escaped variables with the variably modified
558 /// types.
559 ArrayRef<const ValueDecl *> getEscapedVariableLengthDecls() const {
560 return EscapedVariableLengthDecls.getArrayRef();
561 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000562};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000563} // anonymous namespace
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000564
565/// Get the GPU warp size.
566static llvm::Value *getNVPTXWarpSize(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000567 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000568 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000569 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_warpsize),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000570 "nvptx_warp_size");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000571}
572
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000573/// Get the id of the current thread on the GPU.
574static llvm::Value *getNVPTXThreadID(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000575 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000576 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000577 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_tid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000578 "nvptx_tid");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000579}
580
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000581/// Get the id of the warp in the block.
582/// We assume that the warp size is 32, which is always the case
583/// on the NVPTX device, to generate more efficient code.
584static llvm::Value *getNVPTXWarpID(CodeGenFunction &CGF) {
585 CGBuilderTy &Bld = CGF.Builder;
586 return Bld.CreateAShr(getNVPTXThreadID(CGF), LaneIDBits, "nvptx_warp_id");
587}
588
589/// Get the id of the current lane in the Warp.
590/// We assume that the warp size is 32, which is always the case
591/// on the NVPTX device, to generate more efficient code.
592static llvm::Value *getNVPTXLaneID(CodeGenFunction &CGF) {
593 CGBuilderTy &Bld = CGF.Builder;
594 return Bld.CreateAnd(getNVPTXThreadID(CGF), Bld.getInt32(LaneIDMask),
595 "nvptx_lane_id");
596}
597
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000598/// Get the maximum number of threads in a block of the GPU.
599static llvm::Value *getNVPTXNumThreads(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000600 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000601 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000602 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_ntid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000603 "nvptx_num_threads");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000604}
605
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000606/// Get barrier to synchronize all threads in a block.
607static void getNVPTXCTABarrier(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000608 CGF.EmitRuntimeCall(llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000609 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_barrier0));
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000610}
611
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000612/// Get barrier #ID to synchronize selected (multiple of warp size) threads in
613/// a CTA.
614static void getNVPTXBarrier(CodeGenFunction &CGF, int ID,
615 llvm::Value *NumThreads) {
616 CGBuilderTy &Bld = CGF.Builder;
617 llvm::Value *Args[] = {Bld.getInt32(ID), NumThreads};
Alexey Bataev3c595a62017-08-14 15:01:03 +0000618 CGF.EmitRuntimeCall(llvm::Intrinsic::getDeclaration(
619 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_barrier),
620 Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000621}
622
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000623/// Synchronize all GPU threads in a block.
624static void syncCTAThreads(CodeGenFunction &CGF) { getNVPTXCTABarrier(CGF); }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000625
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000626/// Synchronize worker threads in a parallel region.
627static void syncParallelThreads(CodeGenFunction &CGF, llvm::Value *NumThreads) {
628 return getNVPTXBarrier(CGF, NB_Parallel, NumThreads);
629}
630
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000631/// Get the value of the thread_limit clause in the teams directive.
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000632/// For the 'generic' execution mode, the runtime encodes thread_limit in
633/// the launch parameters, always starting thread_limit+warpSize threads per
634/// CTA. The threads in the last warp are reserved for master execution.
635/// For the 'spmd' execution mode, all threads in a CTA are part of the team.
636static llvm::Value *getThreadLimit(CodeGenFunction &CGF,
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000637 bool IsInSPMDExecutionMode = false) {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000638 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000639 return IsInSPMDExecutionMode
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000640 ? getNVPTXNumThreads(CGF)
Alexey Bataeve290ec02018-04-06 16:03:36 +0000641 : Bld.CreateNUWSub(getNVPTXNumThreads(CGF), getNVPTXWarpSize(CGF),
642 "thread_limit");
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000643}
644
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000645/// Get the thread id of the OMP master thread.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000646/// The master thread id is the first thread (lane) of the last warp in the
647/// GPU block. Warp size is assumed to be some power of 2.
648/// Thread id is 0 indexed.
649/// E.g: If NumThreads is 33, master id is 32.
650/// If NumThreads is 64, master id is 32.
651/// If NumThreads is 1024, master id is 992.
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000652static llvm::Value *getMasterThreadID(CodeGenFunction &CGF) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000653 CGBuilderTy &Bld = CGF.Builder;
654 llvm::Value *NumThreads = getNVPTXNumThreads(CGF);
655
656 // We assume that the warp size is a power of 2.
Alexey Bataeve290ec02018-04-06 16:03:36 +0000657 llvm::Value *Mask = Bld.CreateNUWSub(getNVPTXWarpSize(CGF), Bld.getInt32(1));
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000658
Alexey Bataeve290ec02018-04-06 16:03:36 +0000659 return Bld.CreateAnd(Bld.CreateNUWSub(NumThreads, Bld.getInt32(1)),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000660 Bld.CreateNot(Mask), "master_tid");
661}
662
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000663CGOpenMPRuntimeNVPTX::WorkerFunctionState::WorkerFunctionState(
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000664 CodeGenModule &CGM, SourceLocation Loc)
Alexey Bataev9ff80832018-04-16 20:16:21 +0000665 : WorkerFn(nullptr), CGFI(CGM.getTypes().arrangeNullaryFunction()),
666 Loc(Loc) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000667 createWorkerFunction(CGM);
Vasileios Kalintirise5c09592016-03-22 10:41:20 +0000668}
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000669
670void CGOpenMPRuntimeNVPTX::WorkerFunctionState::createWorkerFunction(
671 CodeGenModule &CGM) {
672 // Create an worker function with no arguments.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000673
674 WorkerFn = llvm::Function::Create(
Alexey Bataev9ff80832018-04-16 20:16:21 +0000675 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataevaee93892018-01-08 20:09:47 +0000676 /*placeholder=*/"_worker", &CGM.getModule());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000677 CGM.SetInternalFunctionAttributes(GlobalDecl(), WorkerFn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +0000678 WorkerFn->setDoesNotRecurse();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000679}
680
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000681CGOpenMPRuntimeNVPTX::ExecutionMode
682CGOpenMPRuntimeNVPTX::getExecutionMode() const {
683 return CurrentExecutionMode;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000684}
685
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000686static CGOpenMPRuntimeNVPTX::DataSharingMode
687getDataSharingMode(CodeGenModule &CGM) {
688 return CGM.getLangOpts().OpenMPCUDAMode ? CGOpenMPRuntimeNVPTX::CUDA
689 : CGOpenMPRuntimeNVPTX::Generic;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000690}
691
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000692/// Checks if the \p Body is the \a CompoundStmt and returns its child statement
693/// iff there is only one.
694static const Stmt *getSingleCompoundChild(const Stmt *Body) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000695 if (const auto *C = dyn_cast<CompoundStmt>(Body))
696 if (C->size() == 1)
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000697 return C->body_front();
698 return Body;
699}
700
701/// Check if the parallel directive has an 'if' clause with non-constant or
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000702/// false condition. Also, check if the number of threads is strictly specified
703/// and run those directives in non-SPMD mode.
704static bool hasParallelIfNumThreadsClause(ASTContext &Ctx,
705 const OMPExecutableDirective &D) {
706 if (D.hasClausesOfKind<OMPNumThreadsClause>())
707 return true;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000708 for (const auto *C : D.getClausesOfKind<OMPIfClause>()) {
709 OpenMPDirectiveKind NameModifier = C->getNameModifier();
710 if (NameModifier != OMPD_parallel && NameModifier != OMPD_unknown)
711 continue;
712 const Expr *Cond = C->getCondition();
713 bool Result;
714 if (!Cond->EvaluateAsBooleanCondition(Result, Ctx) || !Result)
715 return true;
716 }
717 return false;
718}
719
720/// Check for inner (nested) SPMD construct, if any
721static bool hasNestedSPMDDirective(ASTContext &Ctx,
722 const OMPExecutableDirective &D) {
723 const auto *CS = D.getInnermostCapturedStmt();
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000724 const auto *Body =
725 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000726 const Stmt *ChildStmt = getSingleCompoundChild(Body);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000727
728 if (const auto *NestedDir = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
729 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000730 switch (D.getDirectiveKind()) {
731 case OMPD_target:
Alexey Bataevdf093e72018-05-11 19:45:14 +0000732 if (isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000733 !hasParallelIfNumThreadsClause(Ctx, *NestedDir))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000734 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000735 if (DKind == OMPD_teams) {
736 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
737 /*IgnoreCaptured=*/true);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000738 if (!Body)
739 return false;
740 ChildStmt = getSingleCompoundChild(Body);
741 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
742 DKind = NND->getDirectiveKind();
Alexey Bataevdf093e72018-05-11 19:45:14 +0000743 if (isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000744 !hasParallelIfNumThreadsClause(Ctx, *NND))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000745 return true;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000746 }
747 }
748 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000749 case OMPD_target_teams:
Alexey Bataevdf093e72018-05-11 19:45:14 +0000750 return isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000751 !hasParallelIfNumThreadsClause(Ctx, *NestedDir);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000752 case OMPD_target_simd:
753 case OMPD_target_parallel:
754 case OMPD_target_parallel_for:
755 case OMPD_target_parallel_for_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000756 case OMPD_target_teams_distribute:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000757 case OMPD_target_teams_distribute_simd:
758 case OMPD_target_teams_distribute_parallel_for:
759 case OMPD_target_teams_distribute_parallel_for_simd:
760 case OMPD_parallel:
761 case OMPD_for:
762 case OMPD_parallel_for:
763 case OMPD_parallel_sections:
764 case OMPD_for_simd:
765 case OMPD_parallel_for_simd:
766 case OMPD_cancel:
767 case OMPD_cancellation_point:
768 case OMPD_ordered:
769 case OMPD_threadprivate:
770 case OMPD_task:
771 case OMPD_simd:
772 case OMPD_sections:
773 case OMPD_section:
774 case OMPD_single:
775 case OMPD_master:
776 case OMPD_critical:
777 case OMPD_taskyield:
778 case OMPD_barrier:
779 case OMPD_taskwait:
780 case OMPD_taskgroup:
781 case OMPD_atomic:
782 case OMPD_flush:
783 case OMPD_teams:
784 case OMPD_target_data:
785 case OMPD_target_exit_data:
786 case OMPD_target_enter_data:
787 case OMPD_distribute:
788 case OMPD_distribute_simd:
789 case OMPD_distribute_parallel_for:
790 case OMPD_distribute_parallel_for_simd:
791 case OMPD_teams_distribute:
792 case OMPD_teams_distribute_simd:
793 case OMPD_teams_distribute_parallel_for:
794 case OMPD_teams_distribute_parallel_for_simd:
795 case OMPD_target_update:
796 case OMPD_declare_simd:
797 case OMPD_declare_target:
798 case OMPD_end_declare_target:
799 case OMPD_declare_reduction:
800 case OMPD_taskloop:
801 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000802 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000803 case OMPD_unknown:
804 llvm_unreachable("Unexpected directive.");
805 }
806 }
807
808 return false;
809}
810
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000811static bool supportsSPMDExecutionMode(ASTContext &Ctx,
812 const OMPExecutableDirective &D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000813 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
814 switch (DirectiveKind) {
815 case OMPD_target:
816 case OMPD_target_teams:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000817 return hasNestedSPMDDirective(Ctx, D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000818 case OMPD_target_parallel:
819 case OMPD_target_parallel_for:
820 case OMPD_target_parallel_for_simd:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000821 case OMPD_target_teams_distribute_parallel_for:
822 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev2adecff2018-09-21 14:22:53 +0000823 return !hasParallelIfNumThreadsClause(Ctx, D);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000824 case OMPD_target_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000825 case OMPD_target_teams_distribute:
826 case OMPD_target_teams_distribute_simd:
827 return false;
828 case OMPD_parallel:
829 case OMPD_for:
830 case OMPD_parallel_for:
831 case OMPD_parallel_sections:
832 case OMPD_for_simd:
833 case OMPD_parallel_for_simd:
834 case OMPD_cancel:
835 case OMPD_cancellation_point:
836 case OMPD_ordered:
837 case OMPD_threadprivate:
838 case OMPD_task:
839 case OMPD_simd:
840 case OMPD_sections:
841 case OMPD_section:
842 case OMPD_single:
843 case OMPD_master:
844 case OMPD_critical:
845 case OMPD_taskyield:
846 case OMPD_barrier:
847 case OMPD_taskwait:
848 case OMPD_taskgroup:
849 case OMPD_atomic:
850 case OMPD_flush:
851 case OMPD_teams:
852 case OMPD_target_data:
853 case OMPD_target_exit_data:
854 case OMPD_target_enter_data:
855 case OMPD_distribute:
856 case OMPD_distribute_simd:
857 case OMPD_distribute_parallel_for:
858 case OMPD_distribute_parallel_for_simd:
859 case OMPD_teams_distribute:
860 case OMPD_teams_distribute_simd:
861 case OMPD_teams_distribute_parallel_for:
862 case OMPD_teams_distribute_parallel_for_simd:
863 case OMPD_target_update:
864 case OMPD_declare_simd:
865 case OMPD_declare_target:
866 case OMPD_end_declare_target:
867 case OMPD_declare_reduction:
868 case OMPD_taskloop:
869 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000870 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000871 case OMPD_unknown:
872 break;
873 }
874 llvm_unreachable(
875 "Unknown programming model for OpenMP directive on NVPTX target.");
876}
877
878/// Check if the directive is loops based and has schedule clause at all or has
879/// static scheduling.
880static bool hasStaticScheduling(const OMPExecutableDirective &D) {
881 assert(isOpenMPWorksharingDirective(D.getDirectiveKind()) &&
882 isOpenMPLoopDirective(D.getDirectiveKind()) &&
883 "Expected loop-based directive.");
884 return !D.hasClausesOfKind<OMPOrderedClause>() &&
885 (!D.hasClausesOfKind<OMPScheduleClause>() ||
886 llvm::any_of(D.getClausesOfKind<OMPScheduleClause>(),
887 [](const OMPScheduleClause *C) {
888 return C->getScheduleKind() == OMPC_SCHEDULE_static;
889 }));
890}
891
892/// Check for inner (nested) lightweight runtime construct, if any
893static bool hasNestedLightweightDirective(ASTContext &Ctx,
894 const OMPExecutableDirective &D) {
895 assert(supportsSPMDExecutionMode(Ctx, D) && "Expected SPMD mode directive.");
896 const auto *CS = D.getInnermostCapturedStmt();
897 const auto *Body =
898 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
899 const Stmt *ChildStmt = getSingleCompoundChild(Body);
900
901 if (const auto *NestedDir = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
902 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
903 switch (D.getDirectiveKind()) {
904 case OMPD_target:
905 if (isOpenMPParallelDirective(DKind) &&
906 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
907 hasStaticScheduling(*NestedDir))
908 return true;
909 if (DKind == OMPD_parallel) {
910 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
911 /*IgnoreCaptured=*/true);
912 if (!Body)
913 return false;
914 ChildStmt = getSingleCompoundChild(Body);
915 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
916 DKind = NND->getDirectiveKind();
917 if (isOpenMPWorksharingDirective(DKind) &&
918 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
919 return true;
920 }
921 } else if (DKind == OMPD_teams) {
922 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
923 /*IgnoreCaptured=*/true);
924 if (!Body)
925 return false;
926 ChildStmt = getSingleCompoundChild(Body);
927 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
928 DKind = NND->getDirectiveKind();
929 if (isOpenMPParallelDirective(DKind) &&
930 isOpenMPWorksharingDirective(DKind) &&
931 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
932 return true;
933 if (DKind == OMPD_parallel) {
934 Body = NND->getInnermostCapturedStmt()->IgnoreContainers(
935 /*IgnoreCaptured=*/true);
936 if (!Body)
937 return false;
938 ChildStmt = getSingleCompoundChild(Body);
939 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
940 DKind = NND->getDirectiveKind();
941 if (isOpenMPWorksharingDirective(DKind) &&
942 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
943 return true;
944 }
945 }
946 }
947 }
948 return false;
949 case OMPD_target_teams:
950 if (isOpenMPParallelDirective(DKind) &&
951 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
952 hasStaticScheduling(*NestedDir))
953 return true;
954 if (DKind == OMPD_parallel) {
955 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
956 /*IgnoreCaptured=*/true);
957 if (!Body)
958 return false;
959 ChildStmt = getSingleCompoundChild(Body);
960 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
961 DKind = NND->getDirectiveKind();
962 if (isOpenMPWorksharingDirective(DKind) &&
963 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
964 return true;
965 }
966 }
967 return false;
968 case OMPD_target_parallel:
969 return isOpenMPWorksharingDirective(DKind) &&
970 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NestedDir);
971 case OMPD_target_teams_distribute:
972 case OMPD_target_simd:
973 case OMPD_target_parallel_for:
974 case OMPD_target_parallel_for_simd:
975 case OMPD_target_teams_distribute_simd:
976 case OMPD_target_teams_distribute_parallel_for:
977 case OMPD_target_teams_distribute_parallel_for_simd:
978 case OMPD_parallel:
979 case OMPD_for:
980 case OMPD_parallel_for:
981 case OMPD_parallel_sections:
982 case OMPD_for_simd:
983 case OMPD_parallel_for_simd:
984 case OMPD_cancel:
985 case OMPD_cancellation_point:
986 case OMPD_ordered:
987 case OMPD_threadprivate:
988 case OMPD_task:
989 case OMPD_simd:
990 case OMPD_sections:
991 case OMPD_section:
992 case OMPD_single:
993 case OMPD_master:
994 case OMPD_critical:
995 case OMPD_taskyield:
996 case OMPD_barrier:
997 case OMPD_taskwait:
998 case OMPD_taskgroup:
999 case OMPD_atomic:
1000 case OMPD_flush:
1001 case OMPD_teams:
1002 case OMPD_target_data:
1003 case OMPD_target_exit_data:
1004 case OMPD_target_enter_data:
1005 case OMPD_distribute:
1006 case OMPD_distribute_simd:
1007 case OMPD_distribute_parallel_for:
1008 case OMPD_distribute_parallel_for_simd:
1009 case OMPD_teams_distribute:
1010 case OMPD_teams_distribute_simd:
1011 case OMPD_teams_distribute_parallel_for:
1012 case OMPD_teams_distribute_parallel_for_simd:
1013 case OMPD_target_update:
1014 case OMPD_declare_simd:
1015 case OMPD_declare_target:
1016 case OMPD_end_declare_target:
1017 case OMPD_declare_reduction:
1018 case OMPD_taskloop:
1019 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001020 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001021 case OMPD_unknown:
1022 llvm_unreachable("Unexpected directive.");
1023 }
1024 }
1025
1026 return false;
1027}
1028
1029/// Checks if the construct supports lightweight runtime. It must be SPMD
1030/// construct + inner loop-based construct with static scheduling.
1031static bool supportsLightweightRuntime(ASTContext &Ctx,
1032 const OMPExecutableDirective &D) {
1033 if (!supportsSPMDExecutionMode(Ctx, D))
1034 return false;
1035 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
1036 switch (DirectiveKind) {
1037 case OMPD_target:
1038 case OMPD_target_teams:
1039 case OMPD_target_parallel:
1040 return hasNestedLightweightDirective(Ctx, D);
1041 case OMPD_target_parallel_for:
1042 case OMPD_target_parallel_for_simd:
1043 case OMPD_target_teams_distribute_parallel_for:
1044 case OMPD_target_teams_distribute_parallel_for_simd:
1045 // (Last|First)-privates must be shared in parallel region.
1046 return hasStaticScheduling(D);
1047 case OMPD_target_simd:
1048 case OMPD_target_teams_distribute:
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001049 case OMPD_target_teams_distribute_simd:
Alexey Bataevdf093e72018-05-11 19:45:14 +00001050 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001051 case OMPD_parallel:
1052 case OMPD_for:
1053 case OMPD_parallel_for:
1054 case OMPD_parallel_sections:
1055 case OMPD_for_simd:
1056 case OMPD_parallel_for_simd:
1057 case OMPD_cancel:
1058 case OMPD_cancellation_point:
1059 case OMPD_ordered:
1060 case OMPD_threadprivate:
1061 case OMPD_task:
1062 case OMPD_simd:
1063 case OMPD_sections:
1064 case OMPD_section:
1065 case OMPD_single:
1066 case OMPD_master:
1067 case OMPD_critical:
1068 case OMPD_taskyield:
1069 case OMPD_barrier:
1070 case OMPD_taskwait:
1071 case OMPD_taskgroup:
1072 case OMPD_atomic:
1073 case OMPD_flush:
1074 case OMPD_teams:
1075 case OMPD_target_data:
1076 case OMPD_target_exit_data:
1077 case OMPD_target_enter_data:
1078 case OMPD_distribute:
1079 case OMPD_distribute_simd:
1080 case OMPD_distribute_parallel_for:
1081 case OMPD_distribute_parallel_for_simd:
1082 case OMPD_teams_distribute:
1083 case OMPD_teams_distribute_simd:
1084 case OMPD_teams_distribute_parallel_for:
1085 case OMPD_teams_distribute_parallel_for_simd:
1086 case OMPD_target_update:
1087 case OMPD_declare_simd:
1088 case OMPD_declare_target:
1089 case OMPD_end_declare_target:
1090 case OMPD_declare_reduction:
1091 case OMPD_taskloop:
1092 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001093 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001094 case OMPD_unknown:
1095 break;
1096 }
1097 llvm_unreachable(
1098 "Unknown programming model for OpenMP directive on NVPTX target.");
1099}
1100
1101void CGOpenMPRuntimeNVPTX::emitNonSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001102 StringRef ParentName,
1103 llvm::Function *&OutlinedFn,
1104 llvm::Constant *&OutlinedFnID,
1105 bool IsOffloadEntry,
1106 const RegionCodeGenTy &CodeGen) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001107 ExecutionModeRAII ModeRAII(CurrentExecutionMode, /*IsSPMD=*/false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001108 EntryFunctionState EST;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001109 WorkerFunctionState WST(CGM, D.getBeginLoc());
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001110 Work.clear();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001111 WrapperFunctionsMap.clear();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001112
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001113 // Emit target region as a standalone region.
1114 class NVPTXPrePostActionTy : public PrePostActionTy {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001115 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1116 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001117
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001118 public:
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001119 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001120 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST)
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001121 : EST(EST), WST(WST) {}
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001122 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev6bc27322018-10-05 15:27:47 +00001123 auto &RT = static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
1124 RT.emitNonSPMDEntryHeader(CGF, EST, WST);
1125 // Skip target region initialization.
1126 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001127 }
1128 void Exit(CodeGenFunction &CGF) override {
Alexey Bataev6bc27322018-10-05 15:27:47 +00001129 auto &RT = static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
1130 RT.clearLocThreadIdInsertPt(CGF);
1131 RT.emitNonSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001132 }
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001133 } Action(EST, WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001134 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001135 IsInTTDRegion = true;
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001136 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1137 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001138 IsInTTDRegion = false;
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001139
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001140 // Now change the name of the worker function to correspond to this target
1141 // region's entry function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001142 WST.WorkerFn->setName(Twine(OutlinedFn->getName(), "_worker"));
Alexey Bataevaee93892018-01-08 20:09:47 +00001143
1144 // Create the worker function
1145 emitWorkerFunction(WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001146}
1147
1148// Setup NVPTX threads for master-worker OpenMP scheme.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001149void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryHeader(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001150 EntryFunctionState &EST,
1151 WorkerFunctionState &WST) {
1152 CGBuilderTy &Bld = CGF.Builder;
1153
1154 llvm::BasicBlock *WorkerBB = CGF.createBasicBlock(".worker");
1155 llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
1156 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
1157 EST.ExitBB = CGF.createBasicBlock(".exit");
1158
Alexey Bataev9ff80832018-04-16 20:16:21 +00001159 llvm::Value *IsWorker =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001160 Bld.CreateICmpULT(getNVPTXThreadID(CGF), getThreadLimit(CGF));
1161 Bld.CreateCondBr(IsWorker, WorkerBB, MasterCheckBB);
1162
1163 CGF.EmitBlock(WorkerBB);
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001164 emitCall(CGF, WST.Loc, WST.WorkerFn);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001165 CGF.EmitBranch(EST.ExitBB);
1166
1167 CGF.EmitBlock(MasterCheckBB);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001168 llvm::Value *IsMaster =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001169 Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
1170 Bld.CreateCondBr(IsMaster, MasterBB, EST.ExitBB);
1171
1172 CGF.EmitBlock(MasterBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001173 IsInTargetMasterThreadRegion = true;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001174 // SEQUENTIAL (MASTER) REGION START
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001175 // First action in sequential region:
1176 // Initialize the state of the OpenMP runtime library on the GPU.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001177 // TODO: Optimize runtime initialization and pass in correct value.
1178 llvm::Value *Args[] = {getThreadLimit(CGF),
1179 Bld.getInt16(/*RequiresOMPRuntime=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001180 CGF.EmitRuntimeCall(
1181 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_init), Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001182
1183 // For data sharing, we need to initialize the stack.
1184 CGF.EmitRuntimeCall(
1185 createNVPTXRuntimeFunction(
1186 OMPRTL_NVPTX__kmpc_data_sharing_init_stack));
1187
Alexey Bataevc99042b2018-03-15 18:10:54 +00001188 emitGenericVarsProlog(CGF, WST.Loc);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001189}
1190
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001191void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001192 EntryFunctionState &EST) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001193 IsInTargetMasterThreadRegion = false;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001194 if (!CGF.HaveInsertPoint())
1195 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001196
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001197 emitGenericVarsEpilog(CGF);
1198
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001199 if (!EST.ExitBB)
1200 EST.ExitBB = CGF.createBasicBlock(".exit");
1201
1202 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".termination.notifier");
1203 CGF.EmitBranch(TerminateBB);
1204
1205 CGF.EmitBlock(TerminateBB);
1206 // Signal termination condition.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001207 // TODO: Optimize runtime initialization and pass in correct value.
1208 llvm::Value *Args[] = {CGF.Builder.getInt16(/*IsOMPRuntimeInitialized=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001209 CGF.EmitRuntimeCall(
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001210 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_deinit), Args);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001211 // Barrier to terminate worker threads.
1212 syncCTAThreads(CGF);
1213 // Master thread jumps to exit point.
1214 CGF.EmitBranch(EST.ExitBB);
1215
1216 CGF.EmitBlock(EST.ExitBB);
1217 EST.ExitBB = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001218}
1219
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001220void CGOpenMPRuntimeNVPTX::emitSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001221 StringRef ParentName,
1222 llvm::Function *&OutlinedFn,
1223 llvm::Constant *&OutlinedFnID,
1224 bool IsOffloadEntry,
1225 const RegionCodeGenTy &CodeGen) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001226 ExecutionModeRAII ModeRAII(CurrentExecutionMode, /*IsSPMD=*/true);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001227 EntryFunctionState EST;
1228
1229 // Emit target region as a standalone region.
1230 class NVPTXPrePostActionTy : public PrePostActionTy {
1231 CGOpenMPRuntimeNVPTX &RT;
1232 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1233 const OMPExecutableDirective &D;
1234
1235 public:
1236 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT,
1237 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
1238 const OMPExecutableDirective &D)
1239 : RT(RT), EST(EST), D(D) {}
1240 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001241 RT.emitSPMDEntryHeader(CGF, EST, D);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001242 // Skip target region initialization.
1243 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001244 }
1245 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevfd006c42018-10-05 15:08:53 +00001246 RT.clearLocThreadIdInsertPt(CGF);
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001247 RT.emitSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001248 }
1249 } Action(*this, EST, D);
1250 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001251 IsInTTDRegion = true;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001252 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1253 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001254 IsInTTDRegion = false;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001255}
1256
Alexey Bataeve79451a2018-10-01 16:20:57 +00001257static void
1258getDistributeLastprivateVars(const OMPExecutableDirective &D,
1259 llvm::SmallVectorImpl<const ValueDecl *> &Vars);
1260
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001261void CGOpenMPRuntimeNVPTX::emitSPMDEntryHeader(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001262 CodeGenFunction &CGF, EntryFunctionState &EST,
1263 const OMPExecutableDirective &D) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001264 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001265
1266 // Setup BBs in entry function.
1267 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute");
1268 EST.ExitBB = CGF.createBasicBlock(".exit");
1269
1270 // Initialize the OMP state in the runtime; called by all active threads.
Alexey Bataev80a9a612018-08-30 14:45:24 +00001271 bool RequiresFullRuntime = CGM.getLangOpts().OpenMPCUDAForceFullRuntime ||
1272 !supportsLightweightRuntime(CGF.getContext(), D);
Alexey Bataeve79451a2018-10-01 16:20:57 +00001273 // Check if we have inner distribute + lastprivate|reduction clauses.
1274 bool RequiresDatasharing = RequiresFullRuntime;
1275 if (!RequiresDatasharing) {
1276 const OMPExecutableDirective *TD = &D;
1277 if (!isOpenMPTeamsDirective(TD->getDirectiveKind()) &&
1278 !isOpenMPParallelDirective(TD->getDirectiveKind())) {
1279 const Stmt *S = getSingleCompoundChild(
1280 TD->getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
1281 /*IgnoreCaptured=*/true));
1282 TD = cast<OMPExecutableDirective>(S);
1283 }
1284 if (!isOpenMPDistributeDirective(TD->getDirectiveKind()) &&
1285 !isOpenMPParallelDirective(TD->getDirectiveKind())) {
1286 const Stmt *S = getSingleCompoundChild(
1287 TD->getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
1288 /*IgnoreCaptured=*/true));
1289 TD = cast<OMPExecutableDirective>(S);
1290 }
1291 if (isOpenMPDistributeDirective(TD->getDirectiveKind()))
1292 RequiresDatasharing = TD->hasClausesOfKind<OMPLastprivateClause>() ||
1293 TD->hasClausesOfKind<OMPReductionClause>();
1294 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001295 llvm::Value *Args[] = {
1296 getThreadLimit(CGF, /*IsInSPMDExecutionMode=*/true),
1297 /*RequiresOMPRuntime=*/
1298 Bld.getInt16(RequiresFullRuntime ? 1 : 0),
Alexey Bataeve79451a2018-10-01 16:20:57 +00001299 /*RequiresDataSharing=*/Bld.getInt16(RequiresDatasharing ? 1 : 0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001300 CGF.EmitRuntimeCall(
1301 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_init), Args);
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001302
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001303 if (RequiresFullRuntime) {
1304 // For data sharing, we need to initialize the stack.
1305 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1306 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd));
1307 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001308
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001309 CGF.EmitBranch(ExecuteBB);
1310
1311 CGF.EmitBlock(ExecuteBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001312
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001313 IsInTargetMasterThreadRegion = true;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001314}
1315
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001316void CGOpenMPRuntimeNVPTX::emitSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001317 EntryFunctionState &EST) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001318 IsInTargetMasterThreadRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001319 if (!CGF.HaveInsertPoint())
1320 return;
1321
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001322 if (!EST.ExitBB)
1323 EST.ExitBB = CGF.createBasicBlock(".exit");
1324
1325 llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit");
1326 CGF.EmitBranch(OMPDeInitBB);
1327
1328 CGF.EmitBlock(OMPDeInitBB);
1329 // DeInitialize the OMP state in the runtime; called by all active threads.
1330 CGF.EmitRuntimeCall(
1331 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_deinit), None);
1332 CGF.EmitBranch(EST.ExitBB);
1333
1334 CGF.EmitBlock(EST.ExitBB);
1335 EST.ExitBB = nullptr;
1336}
1337
1338// Create a unique global variable to indicate the execution mode of this target
1339// region. The execution mode is either 'generic', or 'spmd' depending on the
1340// target directive. This variable is picked up by the offload library to setup
1341// the device appropriately before kernel launch. If the execution mode is
1342// 'generic', the runtime reserves one warp for the master, otherwise, all
1343// warps participate in parallel work.
1344static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001345 bool Mode) {
1346 auto *GVMode =
1347 new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
1348 llvm::GlobalValue::WeakAnyLinkage,
1349 llvm::ConstantInt::get(CGM.Int8Ty, Mode ? 0 : 1),
1350 Twine(Name, "_exec_mode"));
Alexey Bataev9ff80832018-04-16 20:16:21 +00001351 CGM.addCompilerUsedGlobal(GVMode);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001352}
1353
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001354void CGOpenMPRuntimeNVPTX::emitWorkerFunction(WorkerFunctionState &WST) {
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +00001355 ASTContext &Ctx = CGM.getContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001356
1357 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001358 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, WST.CGFI, {},
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001359 WST.Loc, WST.Loc);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001360 emitWorkerLoop(CGF, WST);
1361 CGF.FinishFunction();
1362}
1363
1364void CGOpenMPRuntimeNVPTX::emitWorkerLoop(CodeGenFunction &CGF,
1365 WorkerFunctionState &WST) {
1366 //
1367 // The workers enter this loop and wait for parallel work from the master.
1368 // When the master encounters a parallel region it sets up the work + variable
1369 // arguments, and wakes up the workers. The workers first check to see if
1370 // they are required for the parallel region, i.e., within the # of requested
1371 // parallel threads. The activated workers load the variable arguments and
1372 // execute the parallel work.
1373 //
1374
1375 CGBuilderTy &Bld = CGF.Builder;
1376
1377 llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work");
1378 llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers");
1379 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel");
1380 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel");
1381 llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel");
1382 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1383
1384 CGF.EmitBranch(AwaitBB);
1385
1386 // Workers wait for work from master.
1387 CGF.EmitBlock(AwaitBB);
1388 // Wait for parallel work
1389 syncCTAThreads(CGF);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001390
1391 Address WorkFn =
1392 CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn");
1393 Address ExecStatus =
1394 CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status");
1395 CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0));
1396 CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy));
1397
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001398 // TODO: Optimize runtime initialization and pass in correct value.
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001399 llvm::Value *Args[] = {WorkFn.getPointer(),
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001400 /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001401 llvm::Value *Ret = CGF.EmitRuntimeCall(
1402 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args);
1403 Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001404
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001405 // On termination condition (workid == 0), exit loop.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001406 llvm::Value *WorkID = Bld.CreateLoad(WorkFn);
1407 llvm::Value *ShouldTerminate = Bld.CreateIsNull(WorkID, "should_terminate");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001408 Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB);
1409
1410 // Activate requested workers.
1411 CGF.EmitBlock(SelectWorkersBB);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001412 llvm::Value *IsActive =
1413 Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active");
1414 Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001415
1416 // Signal start of parallel region.
1417 CGF.EmitBlock(ExecuteBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001418
1419 // Process work items: outlined parallel functions.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001420 for (llvm::Function *W : Work) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001421 // Try to match this outlined function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001422 llvm::Value *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001423
1424 llvm::Value *WorkFnMatch =
1425 Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match");
1426
1427 llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn");
1428 llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next");
1429 Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB);
1430
1431 // Execute this outlined function.
1432 CGF.EmitBlock(ExecuteFNBB);
1433
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001434 // Insert call to work function via shared wrapper. The shared
1435 // wrapper takes two arguments:
1436 // - the parallelism level;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001437 // - the thread ID;
1438 emitCall(CGF, WST.Loc, W,
1439 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001440
1441 // Go to end of parallel region.
1442 CGF.EmitBranch(TerminateBB);
1443
1444 CGF.EmitBlock(CheckNextBB);
1445 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001446 // Default case: call to outlined function through pointer if the target
1447 // region makes a declare target call that may contain an orphaned parallel
1448 // directive.
1449 auto *ParallelFnTy =
1450 llvm::FunctionType::get(CGM.VoidTy, {CGM.Int16Ty, CGM.Int32Ty},
1451 /*isVarArg=*/false)
1452 ->getPointerTo();
1453 llvm::Value *WorkFnCast = Bld.CreateBitCast(WorkID, ParallelFnTy);
1454 // Insert call to work function via shared wrapper. The shared
1455 // wrapper takes two arguments:
1456 // - the parallelism level;
1457 // - the thread ID;
1458 emitCall(CGF, WST.Loc, WorkFnCast,
1459 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
1460 // Go to end of parallel region.
1461 CGF.EmitBranch(TerminateBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001462
1463 // Signal end of parallel region.
1464 CGF.EmitBlock(TerminateBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001465 CGF.EmitRuntimeCall(
1466 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_end_parallel),
1467 llvm::None);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001468 CGF.EmitBranch(BarrierBB);
1469
1470 // All active and inactive workers wait at a barrier after parallel region.
1471 CGF.EmitBlock(BarrierBB);
1472 // Barrier after parallel region.
1473 syncCTAThreads(CGF);
1474 CGF.EmitBranch(AwaitBB);
1475
1476 // Exit target region.
1477 CGF.EmitBlock(ExitBB);
1478}
1479
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001480/// Returns specified OpenMP runtime function for the current OpenMP
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001481/// implementation. Specialized for the NVPTX device.
1482/// \param Function OpenMP runtime function.
1483/// \return Specified function.
1484llvm::Constant *
1485CGOpenMPRuntimeNVPTX::createNVPTXRuntimeFunction(unsigned Function) {
1486 llvm::Constant *RTLFn = nullptr;
1487 switch (static_cast<OpenMPRTLFunctionNVPTX>(Function)) {
1488 case OMPRTL_NVPTX__kmpc_kernel_init: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001489 // Build void __kmpc_kernel_init(kmp_int32 thread_limit, int16_t
1490 // RequiresOMPRuntime);
1491 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001492 auto *FnTy =
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001493 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1494 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_init");
1495 break;
1496 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001497 case OMPRTL_NVPTX__kmpc_kernel_deinit: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001498 // Build void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
1499 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001500 auto *FnTy =
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001501 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001502 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_deinit");
1503 break;
1504 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001505 case OMPRTL_NVPTX__kmpc_spmd_kernel_init: {
1506 // Build void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001507 // int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001508 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001509 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001510 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1511 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_init");
1512 break;
1513 }
1514 case OMPRTL_NVPTX__kmpc_spmd_kernel_deinit: {
1515 // Build void __kmpc_spmd_kernel_deinit();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001516 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001517 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1518 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_deinit");
1519 break;
1520 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001521 case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: {
1522 /// Build void __kmpc_kernel_prepare_parallel(
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001523 /// void *outlined_function, int16_t IsOMPRuntimeInitialized);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001524 llvm::Type *TypeParams[] = {CGM.Int8PtrTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001525 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001526 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1527 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_prepare_parallel");
1528 break;
1529 }
1530 case OMPRTL_NVPTX__kmpc_kernel_parallel: {
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001531 /// Build bool __kmpc_kernel_parallel(void **outlined_function,
1532 /// int16_t IsOMPRuntimeInitialized);
1533 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy, CGM.Int16Ty};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001534 llvm::Type *RetTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001535 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001536 llvm::FunctionType::get(RetTy, TypeParams, /*isVarArg*/ false);
1537 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_parallel");
1538 break;
1539 }
1540 case OMPRTL_NVPTX__kmpc_kernel_end_parallel: {
1541 /// Build void __kmpc_kernel_end_parallel();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001542 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001543 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1544 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_end_parallel");
1545 break;
1546 }
1547 case OMPRTL_NVPTX__kmpc_serialized_parallel: {
1548 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1549 // global_tid);
1550 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001551 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001552 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1553 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1554 break;
1555 }
1556 case OMPRTL_NVPTX__kmpc_end_serialized_parallel: {
1557 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1558 // global_tid);
1559 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001560 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001561 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1562 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1563 break;
1564 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001565 case OMPRTL_NVPTX__kmpc_shuffle_int32: {
1566 // Build int32_t __kmpc_shuffle_int32(int32_t element,
1567 // int16_t lane_offset, int16_t warp_size);
1568 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001569 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001570 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1571 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int32");
1572 break;
1573 }
1574 case OMPRTL_NVPTX__kmpc_shuffle_int64: {
1575 // Build int64_t __kmpc_shuffle_int64(int64_t element,
1576 // int16_t lane_offset, int16_t warp_size);
1577 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001578 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001579 llvm::FunctionType::get(CGM.Int64Ty, TypeParams, /*isVarArg*/ false);
1580 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int64");
1581 break;
1582 }
1583 case OMPRTL_NVPTX__kmpc_parallel_reduce_nowait: {
1584 // Build int32_t kmpc_nvptx_parallel_reduce_nowait(kmp_int32 global_tid,
1585 // kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
1586 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1587 // lane_offset, int16_t Algorithm Version),
1588 // void (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
1589 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1590 CGM.Int16Ty, CGM.Int16Ty};
1591 auto *ShuffleReduceFnTy =
1592 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1593 /*isVarArg=*/false);
1594 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1595 auto *InterWarpCopyFnTy =
1596 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1597 /*isVarArg=*/false);
1598 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1599 CGM.Int32Ty,
1600 CGM.SizeTy,
1601 CGM.VoidPtrTy,
1602 ShuffleReduceFnTy->getPointerTo(),
1603 InterWarpCopyFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001604 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001605 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1606 RTLFn = CGM.CreateRuntimeFunction(
1607 FnTy, /*Name=*/"__kmpc_nvptx_parallel_reduce_nowait");
1608 break;
1609 }
Alexey Bataevfac26cf2018-05-02 20:03:27 +00001610 case OMPRTL_NVPTX__kmpc_simd_reduce_nowait: {
1611 // Build int32_t kmpc_nvptx_simd_reduce_nowait(kmp_int32 global_tid,
1612 // kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
1613 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1614 // lane_offset, int16_t Algorithm Version),
1615 // void (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
1616 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1617 CGM.Int16Ty, CGM.Int16Ty};
1618 auto *ShuffleReduceFnTy =
1619 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1620 /*isVarArg=*/false);
1621 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1622 auto *InterWarpCopyFnTy =
1623 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1624 /*isVarArg=*/false);
1625 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1626 CGM.Int32Ty,
1627 CGM.SizeTy,
1628 CGM.VoidPtrTy,
1629 ShuffleReduceFnTy->getPointerTo(),
1630 InterWarpCopyFnTy->getPointerTo()};
1631 auto *FnTy =
1632 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1633 RTLFn = CGM.CreateRuntimeFunction(
1634 FnTy, /*Name=*/"__kmpc_nvptx_simd_reduce_nowait");
1635 break;
1636 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001637 case OMPRTL_NVPTX__kmpc_teams_reduce_nowait: {
1638 // Build int32_t __kmpc_nvptx_teams_reduce_nowait(int32_t global_tid,
1639 // int32_t num_vars, size_t reduce_size, void *reduce_data,
1640 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1641 // lane_offset, int16_t shortCircuit),
1642 // void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num),
1643 // void (*kmp_CopyToScratchpadFctPtr)(void *reduce_data, void * scratchpad,
1644 // int32_t index, int32_t width),
1645 // void (*kmp_LoadReduceFctPtr)(void *reduce_data, void * scratchpad,
1646 // int32_t index, int32_t width, int32_t reduce))
1647 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1648 CGM.Int16Ty, CGM.Int16Ty};
1649 auto *ShuffleReduceFnTy =
1650 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1651 /*isVarArg=*/false);
1652 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1653 auto *InterWarpCopyFnTy =
1654 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1655 /*isVarArg=*/false);
1656 llvm::Type *CopyToScratchpadTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy,
1657 CGM.Int32Ty, CGM.Int32Ty};
1658 auto *CopyToScratchpadFnTy =
1659 llvm::FunctionType::get(CGM.VoidTy, CopyToScratchpadTypeParams,
1660 /*isVarArg=*/false);
1661 llvm::Type *LoadReduceTypeParams[] = {
1662 CGM.VoidPtrTy, CGM.VoidPtrTy, CGM.Int32Ty, CGM.Int32Ty, CGM.Int32Ty};
1663 auto *LoadReduceFnTy =
1664 llvm::FunctionType::get(CGM.VoidTy, LoadReduceTypeParams,
1665 /*isVarArg=*/false);
1666 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1667 CGM.Int32Ty,
1668 CGM.SizeTy,
1669 CGM.VoidPtrTy,
1670 ShuffleReduceFnTy->getPointerTo(),
1671 InterWarpCopyFnTy->getPointerTo(),
1672 CopyToScratchpadFnTy->getPointerTo(),
1673 LoadReduceFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001674 auto *FnTy =
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001675 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1676 RTLFn = CGM.CreateRuntimeFunction(
1677 FnTy, /*Name=*/"__kmpc_nvptx_teams_reduce_nowait");
1678 break;
1679 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001680 case OMPRTL_NVPTX__kmpc_end_reduce_nowait: {
1681 // Build __kmpc_end_reduce_nowait(kmp_int32 global_tid);
1682 llvm::Type *TypeParams[] = {CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001683 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001684 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1685 RTLFn = CGM.CreateRuntimeFunction(
1686 FnTy, /*Name=*/"__kmpc_nvptx_end_reduce_nowait");
1687 break;
1688 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001689 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack: {
1690 /// Build void __kmpc_data_sharing_init_stack();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001691 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001692 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1693 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack");
1694 break;
1695 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001696 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd: {
1697 /// Build void __kmpc_data_sharing_init_stack_spmd();
1698 auto *FnTy =
1699 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001700 RTLFn =
1701 CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack_spmd");
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001702 break;
1703 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001704 case OMPRTL_NVPTX__kmpc_data_sharing_push_stack: {
1705 // Build void *__kmpc_data_sharing_push_stack(size_t size,
1706 // int16_t UseSharedMemory);
1707 llvm::Type *TypeParams[] = {CGM.SizeTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001708 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001709 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1710 RTLFn = CGM.CreateRuntimeFunction(
1711 FnTy, /*Name=*/"__kmpc_data_sharing_push_stack");
1712 break;
1713 }
1714 case OMPRTL_NVPTX__kmpc_data_sharing_pop_stack: {
1715 // Build void __kmpc_data_sharing_pop_stack(void *a);
1716 llvm::Type *TypeParams[] = {CGM.VoidPtrTy};
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,
1720 /*Name=*/"__kmpc_data_sharing_pop_stack");
1721 break;
1722 }
1723 case OMPRTL_NVPTX__kmpc_begin_sharing_variables: {
1724 /// Build void __kmpc_begin_sharing_variables(void ***args,
1725 /// size_t n_args);
1726 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo(), CGM.SizeTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001727 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001728 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1729 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_begin_sharing_variables");
1730 break;
1731 }
1732 case OMPRTL_NVPTX__kmpc_end_sharing_variables: {
1733 /// Build void __kmpc_end_sharing_variables();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001734 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001735 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1736 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_sharing_variables");
1737 break;
1738 }
1739 case OMPRTL_NVPTX__kmpc_get_shared_variables: {
1740 /// Build void __kmpc_get_shared_variables(void ***GlobalArgs);
1741 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001742 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001743 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1744 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_shared_variables");
1745 break;
1746 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001747 case OMPRTL_NVPTX__kmpc_parallel_level: {
1748 // Build uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32 global_tid);
1749 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1750 auto *FnTy =
1751 llvm::FunctionType::get(CGM.Int16Ty, TypeParams, /*isVarArg*/ false);
1752 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_parallel_level");
1753 break;
1754 }
Alexey Bataev673110d2018-05-16 13:36:30 +00001755 case OMPRTL_NVPTX__kmpc_is_spmd_exec_mode: {
1756 // Build int8_t __kmpc_is_spmd_exec_mode();
1757 auto *FnTy = llvm::FunctionType::get(CGM.Int8Ty, /*isVarArg=*/false);
1758 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_is_spmd_exec_mode");
1759 break;
1760 }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001761 }
1762 return RTLFn;
1763}
1764
1765void CGOpenMPRuntimeNVPTX::createOffloadEntry(llvm::Constant *ID,
1766 llvm::Constant *Addr,
Alexey Bataev03f270c2018-03-30 18:31:07 +00001767 uint64_t Size, int32_t,
1768 llvm::GlobalValue::LinkageTypes) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001769 // TODO: Add support for global variables on the device after declare target
1770 // support.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001771 if (!isa<llvm::Function>(Addr))
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001772 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +00001773 llvm::Module &M = CGM.getModule();
1774 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001775
1776 // Get "nvvm.annotations" metadata node
Alexey Bataev9ff80832018-04-16 20:16:21 +00001777 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001778
1779 llvm::Metadata *MDVals[] = {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001780 llvm::ConstantAsMetadata::get(Addr), llvm::MDString::get(Ctx, "kernel"),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001781 llvm::ConstantAsMetadata::get(
1782 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))};
1783 // Append metadata to nvvm.annotations
1784 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
1785}
1786
1787void CGOpenMPRuntimeNVPTX::emitTargetOutlinedFunction(
1788 const OMPExecutableDirective &D, StringRef ParentName,
1789 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001790 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001791 if (!IsOffloadEntry) // Nothing to do.
1792 return;
1793
1794 assert(!ParentName.empty() && "Invalid target region parent name!");
1795
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001796 bool Mode = supportsSPMDExecutionMode(CGM.getContext(), D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001797 if (Mode)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001798 emitSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001799 CodeGen);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001800 else
1801 emitNonSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1802 CodeGen);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001803
1804 setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001805}
1806
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001807CGOpenMPRuntimeNVPTX::CGOpenMPRuntimeNVPTX(CodeGenModule &CGM)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001808 : CGOpenMPRuntime(CGM, "_", "$") {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001809 if (!CGM.getLangOpts().OpenMPIsDevice)
1810 llvm_unreachable("OpenMP NVPTX can only handle device code.");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001811}
Carlo Bertollic6872252016-04-04 15:55:02 +00001812
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001813void CGOpenMPRuntimeNVPTX::emitProcBindClause(CodeGenFunction &CGF,
1814 OpenMPProcBindClauseKind ProcBind,
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 Jacob2cd6eea2017-01-25 16:55:10 +00001818 return;
1819
1820 CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc);
1821}
1822
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001823void CGOpenMPRuntimeNVPTX::emitNumThreadsClause(CodeGenFunction &CGF,
1824 llvm::Value *NumThreads,
1825 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001826 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001827 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001828 return;
1829
1830 CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc);
1831}
1832
Carlo Bertollic6872252016-04-04 15:55:02 +00001833void CGOpenMPRuntimeNVPTX::emitNumTeamsClause(CodeGenFunction &CGF,
1834 const Expr *NumTeams,
1835 const Expr *ThreadLimit,
1836 SourceLocation Loc) {}
1837
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001838llvm::Value *CGOpenMPRuntimeNVPTX::emitParallelOutlinedFunction(
1839 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1840 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00001841 // Emit target region as a standalone region.
1842 class NVPTXPrePostActionTy : public PrePostActionTy {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001843 bool &IsInParallelRegion;
1844 bool PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001845
1846 public:
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001847 NVPTXPrePostActionTy(bool &IsInParallelRegion)
1848 : IsInParallelRegion(IsInParallelRegion) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00001849 void Enter(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001850 PrevIsInParallelRegion = IsInParallelRegion;
1851 IsInParallelRegion = true;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001852 }
1853 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001854 IsInParallelRegion = PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001855 }
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001856 } Action(IsInParallelRegion);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001857 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001858 bool PrevIsInTTDRegion = IsInTTDRegion;
1859 IsInTTDRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001860 bool PrevIsInTargetMasterThreadRegion = IsInTargetMasterThreadRegion;
1861 IsInTargetMasterThreadRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001862 auto *OutlinedFun =
1863 cast<llvm::Function>(CGOpenMPRuntime::emitParallelOutlinedFunction(
1864 D, ThreadIDVar, InnermostKind, CodeGen));
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001865 IsInTargetMasterThreadRegion = PrevIsInTargetMasterThreadRegion;
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001866 IsInTTDRegion = PrevIsInTTDRegion;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001867 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD &&
1868 !IsInParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001869 llvm::Function *WrapperFun =
1870 createParallelDataSharingWrapper(OutlinedFun, D);
1871 WrapperFunctionsMap[OutlinedFun] = WrapperFun;
1872 }
1873
1874 return OutlinedFun;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001875}
1876
Alexey Bataev2adecff2018-09-21 14:22:53 +00001877/// Get list of lastprivate variables from the teams distribute ... or
1878/// teams {distribute ...} directives.
1879static void
1880getDistributeLastprivateVars(const OMPExecutableDirective &D,
1881 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
1882 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
1883 "expected teams directive.");
1884 const OMPExecutableDirective *Dir = &D;
1885 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
1886 if (const Stmt *S = getSingleCompoundChild(
1887 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
1888 /*IgnoreCaptured=*/true))) {
1889 Dir = dyn_cast<OMPExecutableDirective>(S);
1890 if (Dir && !isOpenMPDistributeDirective(Dir->getDirectiveKind()))
1891 Dir = nullptr;
1892 }
1893 }
1894 if (!Dir)
1895 return;
Alexey Bataev9ea3c382018-10-09 14:49:00 +00001896 for (const auto *C : Dir->getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00001897 for (const Expr *E : C->getVarRefs()) {
1898 const auto *DE = cast<DeclRefExpr>(E->IgnoreParens());
1899 Vars.push_back(cast<ValueDecl>(DE->getDecl()->getCanonicalDecl()));
1900 }
1901 }
1902}
1903
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001904llvm::Value *CGOpenMPRuntimeNVPTX::emitTeamsOutlinedFunction(
Carlo Bertollic6872252016-04-04 15:55:02 +00001905 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1906 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001907 SourceLocation Loc = D.getBeginLoc();
Carlo Bertollic6872252016-04-04 15:55:02 +00001908
Alexey Bataev2adecff2018-09-21 14:22:53 +00001909 const RecordDecl *GlobalizedRD = nullptr;
1910 llvm::SmallVector<const ValueDecl *, 4> LastPrivates;
1911 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
1912 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
1913 getDistributeLastprivateVars(D, LastPrivates);
1914 if (!LastPrivates.empty())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00001915 GlobalizedRD = ::buildRecordForGlobalizedVars(
1916 CGM.getContext(), llvm::None, LastPrivates, MappedDeclsFields);
Alexey Bataev2adecff2018-09-21 14:22:53 +00001917 }
1918
Alexey Bataevc99042b2018-03-15 18:10:54 +00001919 // Emit target region as a standalone region.
1920 class NVPTXPrePostActionTy : public PrePostActionTy {
1921 SourceLocation &Loc;
Alexey Bataev2adecff2018-09-21 14:22:53 +00001922 const RecordDecl *GlobalizedRD;
1923 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
1924 &MappedDeclsFields;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001925
1926 public:
Alexey Bataev2adecff2018-09-21 14:22:53 +00001927 NVPTXPrePostActionTy(
1928 SourceLocation &Loc, const RecordDecl *GlobalizedRD,
1929 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
1930 &MappedDeclsFields)
1931 : Loc(Loc), GlobalizedRD(GlobalizedRD),
1932 MappedDeclsFields(MappedDeclsFields) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00001933 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev2adecff2018-09-21 14:22:53 +00001934 auto &Rt =
1935 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
1936 if (GlobalizedRD) {
1937 auto I = Rt.FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
1938 I->getSecond().GlobalRecord = GlobalizedRD;
1939 I->getSecond().MappedParams =
1940 llvm::make_unique<CodeGenFunction::OMPMapVars>();
1941 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
1942 for (const auto &Pair : MappedDeclsFields) {
1943 assert(Pair.getFirst()->isCanonicalDecl() &&
1944 "Expected canonical declaration");
Alexey Bataev9ea3c382018-10-09 14:49:00 +00001945 Data.insert(std::make_pair(Pair.getFirst(),
1946 MappedVarData(Pair.getSecond(),
1947 /*IsOnePerTeam=*/true)));
Alexey Bataev2adecff2018-09-21 14:22:53 +00001948 }
1949 }
1950 Rt.emitGenericVarsProlog(CGF, Loc);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001951 }
1952 void Exit(CodeGenFunction &CGF) override {
1953 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
1954 .emitGenericVarsEpilog(CGF);
1955 }
Alexey Bataev2adecff2018-09-21 14:22:53 +00001956 } Action(Loc, GlobalizedRD, MappedDeclsFields);
1957 CodeGen.setAction(Action);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001958 llvm::Value *OutlinedFunVal = CGOpenMPRuntime::emitTeamsOutlinedFunction(
1959 D, ThreadIDVar, InnermostKind, CodeGen);
1960 llvm::Function *OutlinedFun = cast<llvm::Function>(OutlinedFunVal);
1961 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001962 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001963 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
Carlo Bertollic6872252016-04-04 15:55:02 +00001964
1965 return OutlinedFun;
1966}
1967
Alexey Bataevc99042b2018-03-15 18:10:54 +00001968void CGOpenMPRuntimeNVPTX::emitGenericVarsProlog(CodeGenFunction &CGF,
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00001969 SourceLocation Loc,
1970 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00001971 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
1972 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001973 return;
1974
Alexey Bataevc99042b2018-03-15 18:10:54 +00001975 CGBuilderTy &Bld = CGF.Builder;
1976
1977 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
1978 if (I == FunctionGlobalizedDecls.end())
1979 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001980 if (const RecordDecl *GlobalizedVarsRecord = I->getSecond().GlobalRecord) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00001981 QualType GlobalRecTy = CGM.getContext().getRecordType(GlobalizedVarsRecord);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00001982 QualType SecGlobalRecTy;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001983
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001984 // Recover pointer to this function's global record. The runtime will
1985 // handle the specifics of the allocation of the memory.
1986 // Use actual memory size of the record including the padding
1987 // for alignment purposes.
1988 unsigned Alignment =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00001989 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001990 unsigned GlobalRecordSize =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00001991 CGM.getContext().getTypeSizeInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001992 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001993
Alexey Bataev9ea3c382018-10-09 14:49:00 +00001994 llvm::PointerType *GlobalRecPtrTy =
1995 CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo();
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001996 llvm::Value *GlobalRecCastAddr;
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00001997 llvm::Value *IsTTD = nullptr;
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00001998 if (WithSPMDCheck ||
1999 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002000 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2001 llvm::BasicBlock *SPMDBB = CGF.createBasicBlock(".spmd");
2002 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002003 if (I->getSecond().SecondaryGlobalRecord.hasValue()) {
2004 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2005 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2006 llvm::Value *PL = CGF.EmitRuntimeCall(
2007 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2008 {RTLoc, ThreadID});
2009 IsTTD = Bld.CreateIsNull(PL);
2010 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002011 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2012 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
2013 Bld.CreateCondBr(IsSPMD, SPMDBB, NonSPMDBB);
2014 // There is no need to emit line number for unconditional branch.
2015 (void)ApplyDebugLocation::CreateEmpty(CGF);
2016 CGF.EmitBlock(SPMDBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002017 Address RecPtr = Address(llvm::ConstantPointerNull::get(GlobalRecPtrTy),
2018 CharUnits::fromQuantity(Alignment));
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002019 CGF.EmitBranch(ExitBB);
2020 // There is no need to emit line number for unconditional branch.
2021 (void)ApplyDebugLocation::CreateEmpty(CGF);
2022 CGF.EmitBlock(NonSPMDBB);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002023 llvm::Value *Size = llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize);
2024 if (const RecordDecl *SecGlobalizedVarsRecord =
2025 I->getSecond().SecondaryGlobalRecord.getValueOr(nullptr)) {
2026 SecGlobalRecTy =
2027 CGM.getContext().getRecordType(SecGlobalizedVarsRecord);
2028
2029 // Recover pointer to this function's global record. The runtime will
2030 // handle the specifics of the allocation of the memory.
2031 // Use actual memory size of the record including the padding
2032 // for alignment purposes.
2033 unsigned Alignment =
2034 CGM.getContext().getTypeAlignInChars(SecGlobalRecTy).getQuantity();
2035 unsigned GlobalRecordSize =
2036 CGM.getContext().getTypeSizeInChars(SecGlobalRecTy).getQuantity();
2037 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
2038 Size = Bld.CreateSelect(
2039 IsTTD, llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize), Size);
2040 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002041 // TODO: allow the usage of shared memory to be controlled by
2042 // the user, for now, default to global.
2043 llvm::Value *GlobalRecordSizeArg[] = {
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002044 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002045 llvm::Value *GlobalRecValue =
2046 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2047 OMPRTL_NVPTX__kmpc_data_sharing_push_stack),
2048 GlobalRecordSizeArg);
2049 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002050 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002051 CGF.EmitBlock(ExitBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002052 auto *Phi = Bld.CreatePHI(GlobalRecPtrTy,
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002053 /*NumReservedValues=*/2, "_select_stack");
2054 Phi->addIncoming(RecPtr.getPointer(), SPMDBB);
2055 Phi->addIncoming(GlobalRecCastAddr, NonSPMDBB);
2056 GlobalRecCastAddr = Phi;
2057 I->getSecond().GlobalRecordAddr = Phi;
2058 I->getSecond().IsInSPMDModeFlag = IsSPMD;
2059 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002060 // TODO: allow the usage of shared memory to be controlled by
2061 // the user, for now, default to global.
2062 llvm::Value *GlobalRecordSizeArg[] = {
2063 llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize),
2064 CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
2065 llvm::Value *GlobalRecValue =
2066 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2067 OMPRTL_NVPTX__kmpc_data_sharing_push_stack),
2068 GlobalRecordSizeArg);
2069 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002070 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002071 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2072 I->getSecond().IsInSPMDModeFlag = nullptr;
2073 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002074 LValue Base =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002075 CGF.MakeNaturalAlignPointeeAddrLValue(GlobalRecCastAddr, GlobalRecTy);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002076
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002077 // Emit the "global alloca" which is a GEP from the global declaration
2078 // record using the pointer returned by the runtime.
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002079 LValue SecBase;
2080 decltype(I->getSecond().LocalVarData)::const_iterator SecIt;
2081 if (IsTTD) {
2082 SecIt = I->getSecond().SecondaryLocalVarData->begin();
2083 llvm::PointerType *SecGlobalRecPtrTy =
2084 CGF.ConvertTypeForMem(SecGlobalRecTy)->getPointerTo();
2085 SecBase = CGF.MakeNaturalAlignPointeeAddrLValue(
2086 Bld.CreatePointerBitCastOrAddrSpaceCast(
2087 I->getSecond().GlobalRecordAddr, SecGlobalRecPtrTy),
2088 SecGlobalRecTy);
2089 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002090 for (auto &Rec : I->getSecond().LocalVarData) {
2091 bool EscapedParam = I->getSecond().EscapedParameters.count(Rec.first);
2092 llvm::Value *ParValue;
2093 if (EscapedParam) {
2094 const auto *VD = cast<VarDecl>(Rec.first);
2095 LValue ParLVal =
2096 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
2097 ParValue = CGF.EmitLoadOfScalar(ParLVal, Loc);
2098 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002099 LValue VarAddr = CGF.EmitLValueForField(Base, Rec.second.FD);
2100 // Emit VarAddr basing on lane-id if required.
2101 QualType VarTy;
2102 if (Rec.second.IsOnePerTeam) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002103 VarTy = Rec.second.FD->getType();
2104 } else {
2105 llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(
2106 VarAddr.getAddress().getPointer(),
2107 {Bld.getInt32(0), getNVPTXLaneID(CGF)});
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002108 VarTy =
2109 Rec.second.FD->getType()->castAsArrayTypeUnsafe()->getElementType();
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002110 VarAddr = CGF.MakeAddrLValue(
2111 Address(Ptr, CGM.getContext().getDeclAlign(Rec.first)), VarTy,
2112 AlignmentSource::Decl);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002113 }
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002114 Rec.second.PrivateAddr = VarAddr.getAddress();
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002115 if (WithSPMDCheck ||
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002116 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002117 assert(I->getSecond().IsInSPMDModeFlag &&
2118 "Expected unknown execution mode or required SPMD check.");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002119 if (IsTTD) {
2120 assert(SecIt->second.IsOnePerTeam &&
2121 "Secondary glob data must be one per team.");
2122 LValue SecVarAddr = CGF.EmitLValueForField(SecBase, SecIt->second.FD);
2123 VarAddr.setAddress(
2124 Address(Bld.CreateSelect(IsTTD, SecVarAddr.getPointer(),
2125 VarAddr.getPointer()),
2126 VarAddr.getAlignment()));
2127 Rec.second.PrivateAddr = VarAddr.getAddress();
2128 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002129 Address GlobalPtr = Rec.second.PrivateAddr;
2130 Address LocalAddr = CGF.CreateMemTemp(VarTy, Rec.second.FD->getName());
2131 Rec.second.PrivateAddr = Address(
2132 Bld.CreateSelect(I->getSecond().IsInSPMDModeFlag,
2133 LocalAddr.getPointer(), GlobalPtr.getPointer()),
2134 LocalAddr.getAlignment());
2135 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002136 if (EscapedParam) {
2137 const auto *VD = cast<VarDecl>(Rec.first);
2138 CGF.EmitStoreOfScalar(ParValue, VarAddr);
2139 I->getSecond().MappedParams->setVarAddr(CGF, VD, VarAddr.getAddress());
2140 }
Alexey Bataev93a38d62018-10-16 00:09:06 +00002141 if (IsTTD)
2142 ++SecIt;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002143 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002144 }
2145 for (const ValueDecl *VD : I->getSecond().EscapedVariableLengthDecls) {
2146 // Recover pointer to this function's global record. The runtime will
2147 // handle the specifics of the allocation of the memory.
2148 // Use actual memory size of the record including the padding
2149 // for alignment purposes.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002150 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002151 llvm::Value *Size = CGF.getTypeSize(VD->getType());
2152 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2153 Size = Bld.CreateNUWAdd(
2154 Size, llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity() - 1));
2155 llvm::Value *AlignVal =
2156 llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity());
2157 Size = Bld.CreateUDiv(Size, AlignVal);
2158 Size = Bld.CreateNUWMul(Size, AlignVal);
2159 // TODO: allow the usage of shared memory to be controlled by
2160 // the user, for now, default to global.
2161 llvm::Value *GlobalRecordSizeArg[] = {
2162 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
2163 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2164 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_push_stack),
2165 GlobalRecordSizeArg);
2166 llvm::Value *GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2167 GlobalRecValue, CGF.ConvertTypeForMem(VD->getType())->getPointerTo());
2168 LValue Base = CGF.MakeAddrLValue(GlobalRecCastAddr, VD->getType(),
2169 CGM.getContext().getDeclAlign(VD),
2170 AlignmentSource::Decl);
2171 I->getSecond().MappedParams->setVarAddr(CGF, cast<VarDecl>(VD),
2172 Base.getAddress());
2173 I->getSecond().EscapedVariableLengthDeclsAddrs.emplace_back(GlobalRecValue);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002174 }
2175 I->getSecond().MappedParams->apply(CGF);
2176}
2177
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002178void CGOpenMPRuntimeNVPTX::emitGenericVarsEpilog(CodeGenFunction &CGF,
2179 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002180 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2181 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002182 return;
2183
Alexey Bataevc99042b2018-03-15 18:10:54 +00002184 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002185 if (I != FunctionGlobalizedDecls.end()) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00002186 I->getSecond().MappedParams->restore(CGF);
2187 if (!CGF.HaveInsertPoint())
2188 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002189 for (llvm::Value *Addr :
2190 llvm::reverse(I->getSecond().EscapedVariableLengthDeclsAddrs)) {
2191 CGF.EmitRuntimeCall(
2192 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2193 Addr);
2194 }
2195 if (I->getSecond().GlobalRecordAddr) {
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002196 if (WithSPMDCheck ||
2197 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002198 CGBuilderTy &Bld = CGF.Builder;
2199 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2200 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
2201 Bld.CreateCondBr(I->getSecond().IsInSPMDModeFlag, ExitBB, NonSPMDBB);
2202 // There is no need to emit line number for unconditional branch.
2203 (void)ApplyDebugLocation::CreateEmpty(CGF);
2204 CGF.EmitBlock(NonSPMDBB);
2205 CGF.EmitRuntimeCall(
2206 createNVPTXRuntimeFunction(
2207 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2208 CGF.EmitCastToVoidPtr(I->getSecond().GlobalRecordAddr));
2209 CGF.EmitBlock(ExitBB);
2210 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002211 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2212 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2213 I->getSecond().GlobalRecordAddr);
2214 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002215 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00002216 }
2217}
2218
Carlo Bertollic6872252016-04-04 15:55:02 +00002219void CGOpenMPRuntimeNVPTX::emitTeamsCall(CodeGenFunction &CGF,
2220 const OMPExecutableDirective &D,
2221 SourceLocation Loc,
2222 llvm::Value *OutlinedFn,
2223 ArrayRef<llvm::Value *> CapturedVars) {
2224 if (!CGF.HaveInsertPoint())
2225 return;
2226
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002227 Address ZeroAddr = CGF.CreateMemTemp(
2228 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2229 /*Name*/ ".zero.addr");
Carlo Bertollic6872252016-04-04 15:55:02 +00002230 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2231 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002232 OutlinedFnArgs.push_back(emitThreadIDAddress(CGF, Loc).getPointer());
Carlo Bertollic6872252016-04-04 15:55:02 +00002233 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2234 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002235 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Carlo Bertollic6872252016-04-04 15:55:02 +00002236}
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002237
2238void CGOpenMPRuntimeNVPTX::emitParallelCall(
2239 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2240 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2241 if (!CGF.HaveInsertPoint())
2242 return;
2243
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002244 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002245 emitSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002246 else
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002247 emitNonSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002248}
2249
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002250void CGOpenMPRuntimeNVPTX::emitNonSPMDParallelCall(
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002251 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2252 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2253 llvm::Function *Fn = cast<llvm::Function>(OutlinedFn);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002254
2255 // Force inline this outlined function at its call site.
2256 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
2257
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002258 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2259 /*DestWidth=*/32, /*Signed=*/1),
2260 ".zero.addr");
2261 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002262 // ThreadId for serialized parallels is 0.
2263 Address ThreadIDAddr = ZeroAddr;
2264 auto &&CodeGen = [this, Fn, CapturedVars, Loc, ZeroAddr, &ThreadIDAddr](
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002265 CodeGenFunction &CGF, PrePostActionTy &Action) {
2266 Action.Enter(CGF);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002267
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002268 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2269 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2270 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2271 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2272 emitOutlinedFunctionCall(CGF, Loc, Fn, OutlinedFnArgs);
2273 };
2274 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2275 PrePostActionTy &) {
2276
2277 RegionCodeGenTy RCG(CodeGen);
2278 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2279 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2280 llvm::Value *Args[] = {RTLoc, ThreadID};
2281
2282 NVPTXActionTy Action(
2283 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2284 Args,
2285 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2286 Args);
2287 RCG.setAction(Action);
2288 RCG(CGF);
2289 };
2290
2291 auto &&L0ParallelGen = [this, CapturedVars, Fn](CodeGenFunction &CGF,
2292 PrePostActionTy &Action) {
2293 CGBuilderTy &Bld = CGF.Builder;
2294 llvm::Function *WFn = WrapperFunctionsMap[Fn];
2295 assert(WFn && "Wrapper function does not exist!");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002296 llvm::Value *ID = Bld.CreateBitOrPointerCast(WFn, CGM.Int8PtrTy);
2297
2298 // Prepare for parallel region. Indicate the outlined function.
2299 llvm::Value *Args[] = {ID, /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002300 CGF.EmitRuntimeCall(
2301 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_prepare_parallel),
2302 Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002303
2304 // Create a private scope that will globalize the arguments
2305 // passed from the outside of the target region.
2306 CodeGenFunction::OMPPrivateScope PrivateArgScope(CGF);
2307
2308 // There's somehting to share.
2309 if (!CapturedVars.empty()) {
2310 // Prepare for parallel region. Indicate the outlined function.
2311 Address SharedArgs =
2312 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "shared_arg_refs");
2313 llvm::Value *SharedArgsPtr = SharedArgs.getPointer();
2314
2315 llvm::Value *DataSharingArgs[] = {
2316 SharedArgsPtr,
2317 llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size())};
2318 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2319 OMPRTL_NVPTX__kmpc_begin_sharing_variables),
2320 DataSharingArgs);
2321
2322 // Store variable address in a list of references to pass to workers.
2323 unsigned Idx = 0;
2324 ASTContext &Ctx = CGF.getContext();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002325 Address SharedArgListAddress = CGF.EmitLoadOfPointer(
2326 SharedArgs, Ctx.getPointerType(Ctx.getPointerType(Ctx.VoidPtrTy))
2327 .castAs<PointerType>());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002328 for (llvm::Value *V : CapturedVars) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002329 Address Dst = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
2330 CGF.getPointerSize());
2331 llvm::Value *PtrV;
Alexey Bataev17314212018-03-20 15:41:05 +00002332 if (V->getType()->isIntegerTy())
2333 PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
2334 else
2335 PtrV = Bld.CreatePointerBitCastOrAddrSpaceCast(V, CGF.VoidPtrTy);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002336 CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
2337 Ctx.getPointerType(Ctx.VoidPtrTy));
Alexey Bataevc99042b2018-03-15 18:10:54 +00002338 ++Idx;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002339 }
2340 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002341
2342 // Activate workers. This barrier is used by the master to signal
2343 // work for the workers.
2344 syncCTAThreads(CGF);
2345
2346 // OpenMP [2.5, Parallel Construct, p.49]
2347 // There is an implied barrier at the end of a parallel region. After the
2348 // end of a parallel region, only the master thread of the team resumes
2349 // execution of the enclosing task region.
2350 //
2351 // The master waits at this barrier until all workers are done.
2352 syncCTAThreads(CGF);
2353
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002354 if (!CapturedVars.empty())
2355 CGF.EmitRuntimeCall(
2356 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_sharing_variables));
2357
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002358 // Remember for post-processing in worker loop.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002359 Work.emplace_back(WFn);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002360 };
2361
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002362 auto &&LNParallelGen = [this, Loc, &SeqGen, &L0ParallelGen](
2363 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002364 if (IsInParallelRegion) {
2365 SeqGen(CGF, Action);
2366 } else if (IsInTargetMasterThreadRegion) {
2367 L0ParallelGen(CGF, Action);
2368 } else {
2369 // Check for master and then parallelism:
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002370 // if (__kmpc_is_spmd_exec_mode() || __kmpc_parallel_level(loc, gtid)) {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002371 // Serialized execution.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002372 // } else {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002373 // Worker call.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002374 // }
2375 CGBuilderTy &Bld = CGF.Builder;
2376 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002377 llvm::BasicBlock *SeqBB = CGF.createBasicBlock(".sequential");
2378 llvm::BasicBlock *ParallelCheckBB = CGF.createBasicBlock(".parcheck");
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002379 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
Alexey Bataev673110d2018-05-16 13:36:30 +00002380 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2381 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002382 Bld.CreateCondBr(IsSPMD, SeqBB, ParallelCheckBB);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002383 // There is no need to emit line number for unconditional branch.
2384 (void)ApplyDebugLocation::CreateEmpty(CGF);
2385 CGF.EmitBlock(ParallelCheckBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002386 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2387 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2388 llvm::Value *PL = CGF.EmitRuntimeCall(
2389 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2390 {RTLoc, ThreadID});
2391 llvm::Value *Res = Bld.CreateIsNotNull(PL);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002392 Bld.CreateCondBr(Res, SeqBB, MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002393 CGF.EmitBlock(SeqBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002394 SeqGen(CGF, Action);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002395 CGF.EmitBranch(ExitBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002396 // There is no need to emit line number for unconditional branch.
2397 (void)ApplyDebugLocation::CreateEmpty(CGF);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002398 CGF.EmitBlock(MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002399 L0ParallelGen(CGF, Action);
2400 CGF.EmitBranch(ExitBB);
2401 // There is no need to emit line number for unconditional branch.
2402 (void)ApplyDebugLocation::CreateEmpty(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002403 // Emit the continuation block for code after the if.
2404 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2405 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002406 };
2407
Alexey Bataev9ff80832018-04-16 20:16:21 +00002408 if (IfCond) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002409 emitOMPIfClause(CGF, IfCond, LNParallelGen, SeqGen);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002410 } else {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002411 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002412 RegionCodeGenTy ThenRCG(LNParallelGen);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002413 ThenRCG(CGF);
2414 }
2415}
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002416
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002417void CGOpenMPRuntimeNVPTX::emitSPMDParallelCall(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002418 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2419 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2420 // Just call the outlined function to execute the parallel region.
2421 // OutlinedFn(&GTid, &zero, CapturedStruct);
2422 //
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002423 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Carlo Bertolli79712092018-02-28 20:48:35 +00002424
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002425 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2426 /*DestWidth=*/32, /*Signed=*/1),
2427 ".zero.addr");
Carlo Bertolli79712092018-02-28 20:48:35 +00002428 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002429 // ThreadId for serialized parallels is 0.
2430 Address ThreadIDAddr = ZeroAddr;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002431 auto &&CodeGen = [this, OutlinedFn, CapturedVars, Loc, ZeroAddr,
Alexey Bataev8521ff62018-07-25 20:03:01 +00002432 &ThreadIDAddr](CodeGenFunction &CGF,
2433 PrePostActionTy &Action) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002434 Action.Enter(CGF);
2435
2436 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2437 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2438 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2439 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2440 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2441 };
2442 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2443 PrePostActionTy &) {
2444
2445 RegionCodeGenTy RCG(CodeGen);
2446 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2447 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2448 llvm::Value *Args[] = {RTLoc, ThreadID};
2449
2450 NVPTXActionTy Action(
2451 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2452 Args,
2453 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2454 Args);
2455 RCG.setAction(Action);
2456 RCG(CGF);
2457 };
2458
2459 if (IsInTargetMasterThreadRegion) {
Alexey Bataev8521ff62018-07-25 20:03:01 +00002460 // In the worker need to use the real thread id.
2461 ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002462 RegionCodeGenTy RCG(CodeGen);
2463 RCG(CGF);
2464 } else {
2465 // If we are not in the target region, it is definitely L2 parallelism or
2466 // more, because for SPMD mode we always has L1 parallel level, sowe don't
2467 // need to check for orphaned directives.
2468 RegionCodeGenTy RCG(SeqGen);
2469 RCG(CGF);
2470 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002471}
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002472
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002473void CGOpenMPRuntimeNVPTX::emitCriticalRegion(
2474 CodeGenFunction &CGF, StringRef CriticalName,
2475 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
2476 const Expr *Hint) {
2477 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
2478 llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
2479 llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
2480 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
2481 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
2482
2483 // Fetch team-local id of the thread.
2484 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
2485
2486 // Get the width of the team.
2487 llvm::Value *TeamWidth = getNVPTXNumThreads(CGF);
2488
2489 // Initialize the counter variable for the loop.
2490 QualType Int32Ty =
2491 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
2492 Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
2493 LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
2494 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
2495 /*isInit=*/true);
2496
2497 // Block checks if loop counter exceeds upper bound.
2498 CGF.EmitBlock(LoopBB);
2499 llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2500 llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
2501 CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
2502
2503 // Block tests which single thread should execute region, and which threads
2504 // should go straight to synchronisation point.
2505 CGF.EmitBlock(TestBB);
2506 CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2507 llvm::Value *CmpThreadToCounter =
2508 CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
2509 CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
2510
2511 // Block emits the body of the critical region.
2512 CGF.EmitBlock(BodyBB);
2513
2514 // Output the critical statement.
2515 CriticalOpGen(CGF);
2516
2517 // After the body surrounded by the critical region, the single executing
2518 // thread will jump to the synchronisation point.
2519 // Block waits for all threads in current team to finish then increments the
2520 // counter variable and returns to the loop.
2521 CGF.EmitBlock(SyncBB);
2522 getNVPTXCTABarrier(CGF);
2523
2524 llvm::Value *IncCounterVal =
2525 CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
2526 CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
2527 CGF.EmitBranch(LoopBB);
2528
2529 // Block that is reached when all threads in the team complete the region.
2530 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2531}
2532
Alexey Bataevb2575932018-01-04 20:18:55 +00002533/// Cast value to the specified type.
Alexey Bataeva453f362018-03-19 17:53:56 +00002534static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
2535 QualType ValTy, QualType CastTy,
2536 SourceLocation Loc) {
2537 assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
2538 "Cast type must sized.");
2539 assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
2540 "Val type must sized.");
2541 llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
2542 if (ValTy == CastTy)
Alexey Bataevb2575932018-01-04 20:18:55 +00002543 return Val;
Alexey Bataeva453f362018-03-19 17:53:56 +00002544 if (CGF.getContext().getTypeSizeInChars(ValTy) ==
2545 CGF.getContext().getTypeSizeInChars(CastTy))
2546 return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
2547 if (CastTy->isIntegerType() && ValTy->isIntegerType())
2548 return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
2549 CastTy->hasSignedIntegerRepresentation());
2550 Address CastItem = CGF.CreateMemTemp(CastTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002551 Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2552 CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
Alexey Bataeva453f362018-03-19 17:53:56 +00002553 CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy);
2554 return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc);
Alexey Bataevb2575932018-01-04 20:18:55 +00002555}
2556
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002557/// This function creates calls to one of two shuffle functions to copy
2558/// variables between lanes in a warp.
2559static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002560 llvm::Value *Elem,
Alexey Bataeva453f362018-03-19 17:53:56 +00002561 QualType ElemType,
2562 llvm::Value *Offset,
2563 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002564 CodeGenModule &CGM = CGF.CGM;
2565 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002566 CGOpenMPRuntimeNVPTX &RT =
2567 *(static_cast<CGOpenMPRuntimeNVPTX *>(&CGM.getOpenMPRuntime()));
2568
Alexey Bataeva453f362018-03-19 17:53:56 +00002569 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2570 assert(Size.getQuantity() <= 8 &&
2571 "Unsupported bitwidth in shuffle instruction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002572
Alexey Bataeva453f362018-03-19 17:53:56 +00002573 OpenMPRTLFunctionNVPTX ShuffleFn = Size.getQuantity() <= 4
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002574 ? OMPRTL_NVPTX__kmpc_shuffle_int32
2575 : OMPRTL_NVPTX__kmpc_shuffle_int64;
2576
2577 // Cast all types to 32- or 64-bit values before calling shuffle routines.
Alexey Bataeva453f362018-03-19 17:53:56 +00002578 QualType CastTy = CGF.getContext().getIntTypeForBitwidth(
2579 Size.getQuantity() <= 4 ? 32 : 64, /*Signed=*/1);
2580 llvm::Value *ElemCast = castValueToType(CGF, Elem, ElemType, CastTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002581 llvm::Value *WarpSize =
Alexey Bataevb2575932018-01-04 20:18:55 +00002582 Bld.CreateIntCast(getNVPTXWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002583
Alexey Bataev9ff80832018-04-16 20:16:21 +00002584 llvm::Value *ShuffledVal = CGF.EmitRuntimeCall(
2585 RT.createNVPTXRuntimeFunction(ShuffleFn), {ElemCast, Offset, WarpSize});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002586
Alexey Bataeva453f362018-03-19 17:53:56 +00002587 return castValueToType(CGF, ShuffledVal, CastTy, ElemType, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002588}
2589
Alexey Bataev12c62902018-06-22 19:10:38 +00002590static void shuffleAndStore(CodeGenFunction &CGF, Address SrcAddr,
2591 Address DestAddr, QualType ElemType,
2592 llvm::Value *Offset, SourceLocation Loc) {
2593 CGBuilderTy &Bld = CGF.Builder;
2594
2595 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2596 // Create the loop over the big sized data.
2597 // ptr = (void*)Elem;
2598 // ptrEnd = (void*) Elem + 1;
2599 // Step = 8;
2600 // while (ptr + Step < ptrEnd)
2601 // shuffle((int64_t)*ptr);
2602 // Step = 4;
2603 // while (ptr + Step < ptrEnd)
2604 // shuffle((int32_t)*ptr);
2605 // ...
2606 Address ElemPtr = DestAddr;
2607 Address Ptr = SrcAddr;
2608 Address PtrEnd = Bld.CreatePointerBitCastOrAddrSpaceCast(
2609 Bld.CreateConstGEP(SrcAddr, 1, Size), CGF.VoidPtrTy);
2610 for (int IntSize = 8; IntSize >= 1; IntSize /= 2) {
2611 if (Size < CharUnits::fromQuantity(IntSize))
2612 continue;
2613 QualType IntType = CGF.getContext().getIntTypeForBitwidth(
2614 CGF.getContext().toBits(CharUnits::fromQuantity(IntSize)),
2615 /*Signed=*/1);
2616 llvm::Type *IntTy = CGF.ConvertTypeForMem(IntType);
2617 Ptr = Bld.CreatePointerBitCastOrAddrSpaceCast(Ptr, IntTy->getPointerTo());
2618 ElemPtr =
2619 Bld.CreatePointerBitCastOrAddrSpaceCast(ElemPtr, IntTy->getPointerTo());
2620 if (Size.getQuantity() / IntSize > 1) {
2621 llvm::BasicBlock *PreCondBB = CGF.createBasicBlock(".shuffle.pre_cond");
2622 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".shuffle.then");
2623 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".shuffle.exit");
2624 llvm::BasicBlock *CurrentBB = Bld.GetInsertBlock();
2625 CGF.EmitBlock(PreCondBB);
2626 llvm::PHINode *PhiSrc =
2627 Bld.CreatePHI(Ptr.getType(), /*NumReservedValues=*/2);
2628 PhiSrc->addIncoming(Ptr.getPointer(), CurrentBB);
2629 llvm::PHINode *PhiDest =
2630 Bld.CreatePHI(ElemPtr.getType(), /*NumReservedValues=*/2);
2631 PhiDest->addIncoming(ElemPtr.getPointer(), CurrentBB);
2632 Ptr = Address(PhiSrc, Ptr.getAlignment());
2633 ElemPtr = Address(PhiDest, ElemPtr.getAlignment());
2634 llvm::Value *PtrDiff = Bld.CreatePtrDiff(
2635 PtrEnd.getPointer(), Bld.CreatePointerBitCastOrAddrSpaceCast(
2636 Ptr.getPointer(), CGF.VoidPtrTy));
2637 Bld.CreateCondBr(Bld.CreateICmpSGT(PtrDiff, Bld.getInt64(IntSize - 1)),
2638 ThenBB, ExitBB);
2639 CGF.EmitBlock(ThenBB);
2640 llvm::Value *Res = createRuntimeShuffleFunction(
2641 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2642 IntType, Offset, Loc);
2643 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
2644 Ptr = Bld.CreateConstGEP(Ptr, 1, CharUnits::fromQuantity(IntSize));
2645 ElemPtr =
2646 Bld.CreateConstGEP(ElemPtr, 1, CharUnits::fromQuantity(IntSize));
2647 PhiSrc->addIncoming(Ptr.getPointer(), ThenBB);
2648 PhiDest->addIncoming(ElemPtr.getPointer(), ThenBB);
2649 CGF.EmitBranch(PreCondBB);
2650 CGF.EmitBlock(ExitBB);
2651 } else {
2652 llvm::Value *Res = createRuntimeShuffleFunction(
2653 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2654 IntType, Offset, Loc);
2655 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
2656 Ptr = Bld.CreateConstGEP(Ptr, 1, CharUnits::fromQuantity(IntSize));
2657 ElemPtr =
2658 Bld.CreateConstGEP(ElemPtr, 1, CharUnits::fromQuantity(IntSize));
2659 }
2660 Size = Size % IntSize;
2661 }
2662}
2663
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002664namespace {
2665enum CopyAction : unsigned {
2666 // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
2667 // the warp using shuffle instructions.
2668 RemoteLaneToThread,
2669 // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
2670 ThreadCopy,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002671 // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
2672 ThreadToScratchpad,
2673 // ScratchpadToThread: Copy from a scratchpad array in global memory
2674 // containing team-reduced data to a thread's stack.
2675 ScratchpadToThread,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002676};
2677} // namespace
2678
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002679struct CopyOptionsTy {
2680 llvm::Value *RemoteLaneOffset;
2681 llvm::Value *ScratchpadIndex;
2682 llvm::Value *ScratchpadWidth;
2683};
2684
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002685/// Emit instructions to copy a Reduce list, which contains partially
2686/// aggregated values, in the specified direction.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002687static void emitReductionListCopy(
2688 CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
2689 ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
2690 CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002691
Alexey Bataev9ff80832018-04-16 20:16:21 +00002692 CodeGenModule &CGM = CGF.CGM;
2693 ASTContext &C = CGM.getContext();
2694 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002695
Alexey Bataev9ff80832018-04-16 20:16:21 +00002696 llvm::Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
2697 llvm::Value *ScratchpadIndex = CopyOptions.ScratchpadIndex;
2698 llvm::Value *ScratchpadWidth = CopyOptions.ScratchpadWidth;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002699
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002700 // Iterates, element-by-element, through the source Reduce list and
2701 // make a copy.
2702 unsigned Idx = 0;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002703 unsigned Size = Privates.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00002704 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002705 Address SrcElementAddr = Address::invalid();
2706 Address DestElementAddr = Address::invalid();
2707 Address DestElementPtrAddr = Address::invalid();
2708 // Should we shuffle in an element from a remote lane?
2709 bool ShuffleInElement = false;
2710 // Set to true to update the pointer in the dest Reduce list to a
2711 // newly created element.
2712 bool UpdateDestListPtr = false;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002713 // Increment the src or dest pointer to the scratchpad, for each
2714 // new element.
2715 bool IncrScratchpadSrc = false;
2716 bool IncrScratchpadDest = false;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002717
2718 switch (Action) {
2719 case RemoteLaneToThread: {
2720 // Step 1.1: Get the address for the src element in the Reduce list.
2721 Address SrcElementPtrAddr =
2722 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002723 SrcElementAddr = CGF.EmitLoadOfPointer(
2724 SrcElementPtrAddr,
2725 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002726
2727 // Step 1.2: Create a temporary to store the element in the destination
2728 // Reduce list.
2729 DestElementPtrAddr =
2730 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
2731 DestElementAddr =
2732 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2733 ShuffleInElement = true;
2734 UpdateDestListPtr = true;
2735 break;
2736 }
2737 case ThreadCopy: {
2738 // Step 1.1: Get the address for the src element in the Reduce list.
2739 Address SrcElementPtrAddr =
2740 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002741 SrcElementAddr = CGF.EmitLoadOfPointer(
2742 SrcElementPtrAddr,
2743 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002744
2745 // Step 1.2: Get the address for dest element. The destination
2746 // element has already been created on the thread's stack.
2747 DestElementPtrAddr =
2748 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002749 DestElementAddr = CGF.EmitLoadOfPointer(
2750 DestElementPtrAddr,
2751 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002752 break;
2753 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002754 case ThreadToScratchpad: {
2755 // Step 1.1: Get the address for the src element in the Reduce list.
2756 Address SrcElementPtrAddr =
2757 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002758 SrcElementAddr = CGF.EmitLoadOfPointer(
2759 SrcElementPtrAddr,
2760 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002761
2762 // Step 1.2: Get the address for dest element:
2763 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00002764 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00002765 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002766 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002767 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002768 Bld.CreateNUWAdd(DestBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002769 ScratchPadElemAbsolutePtrVal =
2770 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002771 DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
2772 C.getTypeAlignInChars(Private->getType()));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002773 IncrScratchpadDest = true;
2774 break;
2775 }
2776 case ScratchpadToThread: {
2777 // Step 1.1: Get the address for the src element in the scratchpad.
2778 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00002779 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00002780 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002781 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002782 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002783 Bld.CreateNUWAdd(SrcBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002784 ScratchPadElemAbsolutePtrVal =
2785 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
2786 SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
2787 C.getTypeAlignInChars(Private->getType()));
2788 IncrScratchpadSrc = true;
2789
2790 // Step 1.2: Create a temporary to store the element in the destination
2791 // Reduce list.
2792 DestElementPtrAddr =
2793 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
2794 DestElementAddr =
2795 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2796 UpdateDestListPtr = true;
2797 break;
2798 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002799 }
2800
2801 // Regardless of src and dest of copy, we emit the load of src
2802 // element as this is required in all directions
2803 SrcElementAddr = Bld.CreateElementBitCast(
2804 SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
Alexey Bataev12c62902018-06-22 19:10:38 +00002805 DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
2806 SrcElementAddr.getElementType());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002807
2808 // Now that all active lanes have read the element in the
2809 // Reduce list, shuffle over the value from the remote lane.
Alexey Bataeva453f362018-03-19 17:53:56 +00002810 if (ShuffleInElement) {
Alexey Bataev12c62902018-06-22 19:10:38 +00002811 shuffleAndStore(CGF, SrcElementAddr, DestElementAddr, Private->getType(),
2812 RemoteLaneOffset, Private->getExprLoc());
2813 } else {
2814 if (Private->getType()->isScalarType()) {
2815 llvm::Value *Elem =
2816 CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false,
2817 Private->getType(), Private->getExprLoc());
2818 // Store the source element value to the dest element address.
2819 CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false,
2820 Private->getType());
2821 } else {
2822 CGF.EmitAggregateCopy(
2823 CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
2824 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
2825 Private->getType(), AggValueSlot::DoesNotOverlap);
2826 }
Alexey Bataeva453f362018-03-19 17:53:56 +00002827 }
Alexey Bataevb2575932018-01-04 20:18:55 +00002828
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002829 // Step 3.1: Modify reference in dest Reduce list as needed.
2830 // Modifying the reference in Reduce list to point to the newly
2831 // created element. The element is live in the current function
2832 // scope and that of functions it invokes (i.e., reduce_function).
2833 // RemoteReduceData[i] = (void*)&RemoteElem
2834 if (UpdateDestListPtr) {
2835 CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
2836 DestElementAddr.getPointer(), CGF.VoidPtrTy),
2837 DestElementPtrAddr, /*Volatile=*/false,
2838 C.VoidPtrTy);
2839 }
2840
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002841 // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
2842 // address of the next element in scratchpad memory, unless we're currently
2843 // processing the last one. Memory alignment is also taken care of here.
2844 if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
2845 llvm::Value *ScratchpadBasePtr =
2846 IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
Alexey Bataeve290ec02018-04-06 16:03:36 +00002847 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
2848 ScratchpadBasePtr = Bld.CreateNUWAdd(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002849 ScratchpadBasePtr,
Alexey Bataeve290ec02018-04-06 16:03:36 +00002850 Bld.CreateNUWMul(ScratchpadWidth, ElementSizeInChars));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002851
2852 // Take care of global memory alignment for performance
Alexey Bataeve290ec02018-04-06 16:03:36 +00002853 ScratchpadBasePtr = Bld.CreateNUWSub(
2854 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
2855 ScratchpadBasePtr = Bld.CreateUDiv(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002856 ScratchpadBasePtr,
2857 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
Alexey Bataeve290ec02018-04-06 16:03:36 +00002858 ScratchpadBasePtr = Bld.CreateNUWAdd(
2859 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
2860 ScratchpadBasePtr = Bld.CreateNUWMul(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002861 ScratchpadBasePtr,
2862 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
2863
2864 if (IncrScratchpadDest)
2865 DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
2866 else /* IncrScratchpadSrc = true */
2867 SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
2868 }
2869
Alexey Bataev9ff80832018-04-16 20:16:21 +00002870 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002871 }
2872}
2873
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002874/// This function emits a helper that loads data from the scratchpad array
2875/// and (optionally) reduces it with the input operand.
2876///
2877/// load_and_reduce(local, scratchpad, index, width, should_reduce)
2878/// reduce_data remote;
2879/// for elem in remote:
2880/// remote.elem = Scratchpad[elem_id][index]
2881/// if (should_reduce)
2882/// local = local @ remote
2883/// else
2884/// local = remote
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002885static llvm::Value *emitReduceScratchpadFunction(
2886 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
2887 QualType ReductionArrayTy, llvm::Value *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002888 ASTContext &C = CGM.getContext();
2889 QualType Int32Ty = C.getIntTypeForBitwidth(32, /*Signed=*/1);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002890
2891 // Destination of the copy.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002892 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2893 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002894 // Base address of the scratchpad array, with each element storing a
2895 // Reduce list per team.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002896 ImplicitParamDecl ScratchPadArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2897 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002898 // A source index into the scratchpad array.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002899 ImplicitParamDecl IndexArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
2900 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002901 // Row width of an element in the scratchpad array, typically
2902 // the number of teams.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002903 ImplicitParamDecl WidthArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
2904 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002905 // If should_reduce == 1, then it's load AND reduce,
2906 // If should_reduce == 0 (or otherwise), then it only loads (+ copy).
2907 // The latter case is used for initialization.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002908 ImplicitParamDecl ShouldReduceArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2909 Int32Ty, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002910
2911 FunctionArgList Args;
2912 Args.push_back(&ReduceListArg);
2913 Args.push_back(&ScratchPadArg);
2914 Args.push_back(&IndexArg);
2915 Args.push_back(&WidthArg);
2916 Args.push_back(&ShouldReduceArg);
2917
Alexey Bataev9ff80832018-04-16 20:16:21 +00002918 const CGFunctionInfo &CGFI =
2919 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002920 auto *Fn = llvm::Function::Create(
2921 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2922 "_omp_reduction_load_and_reduce", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002923 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002924 Fn->setDoesNotRecurse();
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002925 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002926 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002927
Alexey Bataev9ff80832018-04-16 20:16:21 +00002928 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002929
2930 // Get local Reduce list pointer.
2931 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2932 Address ReduceListAddr(
2933 Bld.CreatePointerBitCastOrAddrSpaceCast(
2934 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002935 C.VoidPtrTy, Loc),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002936 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
2937 CGF.getPointerAlign());
2938
2939 Address AddrScratchPadArg = CGF.GetAddrOfLocalVar(&ScratchPadArg);
2940 llvm::Value *ScratchPadBase = CGF.EmitLoadOfScalar(
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002941 AddrScratchPadArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002942
2943 Address AddrIndexArg = CGF.GetAddrOfLocalVar(&IndexArg);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002944 llvm::Value *IndexVal = Bld.CreateIntCast(
2945 CGF.EmitLoadOfScalar(AddrIndexArg, /*Volatile=*/false, Int32Ty, Loc),
2946 CGM.SizeTy, /*isSigned=*/true);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002947
2948 Address AddrWidthArg = CGF.GetAddrOfLocalVar(&WidthArg);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002949 llvm::Value *WidthVal = Bld.CreateIntCast(
2950 CGF.EmitLoadOfScalar(AddrWidthArg, /*Volatile=*/false, Int32Ty, Loc),
2951 CGM.SizeTy, /*isSigned=*/true);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002952
2953 Address AddrShouldReduceArg = CGF.GetAddrOfLocalVar(&ShouldReduceArg);
2954 llvm::Value *ShouldReduceVal = CGF.EmitLoadOfScalar(
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002955 AddrShouldReduceArg, /*Volatile=*/false, Int32Ty, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002956
2957 // The absolute ptr address to the base addr of the next element to copy.
2958 llvm::Value *CumulativeElemBasePtr =
2959 Bld.CreatePtrToInt(ScratchPadBase, CGM.SizeTy);
2960 Address SrcDataAddr(CumulativeElemBasePtr, CGF.getPointerAlign());
2961
2962 // Create a Remote Reduce list to store the elements read from the
2963 // scratchpad array.
2964 Address RemoteReduceList =
2965 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_red_list");
2966
2967 // Assemble remote Reduce list from scratchpad array.
2968 emitReductionListCopy(ScratchpadToThread, CGF, ReductionArrayTy, Privates,
2969 SrcDataAddr, RemoteReduceList,
2970 {/*RemoteLaneOffset=*/nullptr,
2971 /*ScratchpadIndex=*/IndexVal,
2972 /*ScratchpadWidth=*/WidthVal});
2973
2974 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
2975 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
2976 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
2977
Alexey Bataev9ff80832018-04-16 20:16:21 +00002978 llvm::Value *CondReduce = Bld.CreateIsNotNull(ShouldReduceVal);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002979 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
2980
2981 CGF.EmitBlock(ThenBB);
2982 // We should reduce with the local Reduce list.
2983 // reduce_function(LocalReduceList, RemoteReduceList)
2984 llvm::Value *LocalDataPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2985 ReduceListAddr.getPointer(), CGF.VoidPtrTy);
2986 llvm::Value *RemoteDataPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2987 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002988 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
2989 CGF, Loc, ReduceFn, {LocalDataPtr, RemoteDataPtr});
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002990 Bld.CreateBr(MergeBB);
2991
2992 CGF.EmitBlock(ElseBB);
2993 // No reduction; just copy:
2994 // Local Reduce list = Remote Reduce list.
2995 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
2996 RemoteReduceList, ReduceListAddr);
2997 Bld.CreateBr(MergeBB);
2998
2999 CGF.EmitBlock(MergeBB);
3000
3001 CGF.FinishFunction();
3002 return Fn;
3003}
3004
3005/// This function emits a helper that stores reduced data from the team
3006/// master to a scratchpad array in global memory.
3007///
3008/// for elem in Reduce List:
3009/// scratchpad[elem_id][index] = elem
3010///
Benjamin Kramer674d5792017-05-26 20:08:24 +00003011static llvm::Value *emitCopyToScratchpad(CodeGenModule &CGM,
3012 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003013 QualType ReductionArrayTy,
3014 SourceLocation Loc) {
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003015
Alexey Bataev9ff80832018-04-16 20:16:21 +00003016 ASTContext &C = CGM.getContext();
3017 QualType Int32Ty = C.getIntTypeForBitwidth(32, /*Signed=*/1);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003018
3019 // Source of the copy.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003020 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3021 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003022 // Base address of the scratchpad array, with each element storing a
3023 // Reduce list per team.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003024 ImplicitParamDecl ScratchPadArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3025 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003026 // A destination index into the scratchpad array, typically the team
3027 // identifier.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003028 ImplicitParamDecl IndexArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
3029 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003030 // Row width of an element in the scratchpad array, typically
3031 // the number of teams.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003032 ImplicitParamDecl WidthArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
3033 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003034
3035 FunctionArgList Args;
3036 Args.push_back(&ReduceListArg);
3037 Args.push_back(&ScratchPadArg);
3038 Args.push_back(&IndexArg);
3039 Args.push_back(&WidthArg);
3040
Alexey Bataev9ff80832018-04-16 20:16:21 +00003041 const CGFunctionInfo &CGFI =
3042 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003043 auto *Fn = llvm::Function::Create(
3044 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3045 "_omp_reduction_copy_to_scratchpad", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003046 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003047 Fn->setDoesNotRecurse();
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003048 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003049 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003050
Alexey Bataev9ff80832018-04-16 20:16:21 +00003051 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003052
3053 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3054 Address SrcDataAddr(
3055 Bld.CreatePointerBitCastOrAddrSpaceCast(
3056 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003057 C.VoidPtrTy, Loc),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003058 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3059 CGF.getPointerAlign());
3060
3061 Address AddrScratchPadArg = CGF.GetAddrOfLocalVar(&ScratchPadArg);
3062 llvm::Value *ScratchPadBase = CGF.EmitLoadOfScalar(
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003063 AddrScratchPadArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003064
3065 Address AddrIndexArg = CGF.GetAddrOfLocalVar(&IndexArg);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003066 llvm::Value *IndexVal = Bld.CreateIntCast(
3067 CGF.EmitLoadOfScalar(AddrIndexArg, /*Volatile=*/false, Int32Ty, Loc),
3068 CGF.SizeTy, /*isSigned=*/true);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003069
3070 Address AddrWidthArg = CGF.GetAddrOfLocalVar(&WidthArg);
3071 llvm::Value *WidthVal =
3072 Bld.CreateIntCast(CGF.EmitLoadOfScalar(AddrWidthArg, /*Volatile=*/false,
3073 Int32Ty, SourceLocation()),
3074 CGF.SizeTy, /*isSigned=*/true);
3075
3076 // The absolute ptr address to the base addr of the next element to copy.
3077 llvm::Value *CumulativeElemBasePtr =
3078 Bld.CreatePtrToInt(ScratchPadBase, CGM.SizeTy);
3079 Address DestDataAddr(CumulativeElemBasePtr, CGF.getPointerAlign());
3080
3081 emitReductionListCopy(ThreadToScratchpad, CGF, ReductionArrayTy, Privates,
3082 SrcDataAddr, DestDataAddr,
3083 {/*RemoteLaneOffset=*/nullptr,
3084 /*ScratchpadIndex=*/IndexVal,
3085 /*ScratchpadWidth=*/WidthVal});
3086
3087 CGF.FinishFunction();
3088 return Fn;
3089}
3090
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003091/// This function emits a helper that gathers Reduce lists from the first
3092/// lane of every active warp to lanes in the first warp.
3093///
3094/// void inter_warp_copy_func(void* reduce_data, num_warps)
3095/// shared smem[warp_size];
3096/// For all data entries D in reduce_data:
3097/// If (I am the first lane in each warp)
3098/// Copy my local D to smem[warp_id]
3099/// sync
3100/// if (I am the first warp)
3101/// Copy smem[thread_id] to my local D
3102/// sync
3103static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
3104 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003105 QualType ReductionArrayTy,
3106 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003107 ASTContext &C = CGM.getContext();
3108 llvm::Module &M = CGM.getModule();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003109
3110 // ReduceList: thread local Reduce list.
3111 // At the stage of the computation when this function is called, partially
3112 // aggregated values reside in the first lane of every active warp.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003113 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3114 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003115 // NumWarps: number of warps active in the parallel region. This could
3116 // be smaller than 32 (max warps in a CTA) for partial block reduction.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003117 ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00003118 C.getIntTypeForBitwidth(32, /* Signed */ true),
3119 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003120 FunctionArgList Args;
3121 Args.push_back(&ReduceListArg);
3122 Args.push_back(&NumWarpsArg);
3123
Alexey Bataev9ff80832018-04-16 20:16:21 +00003124 const CGFunctionInfo &CGFI =
3125 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003126 auto *Fn = llvm::Function::Create(
3127 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3128 "_omp_reduction_inter_warp_copy_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003129 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003130 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003131 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003132 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003133
Alexey Bataev9ff80832018-04-16 20:16:21 +00003134 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003135
3136 // This array is used as a medium to transfer, one reduce element at a time,
3137 // the data from the first lane of every warp to lanes in the first warp
3138 // in order to perform the final step of a reduction in a parallel region
3139 // (reduction across warps). The array is placed in NVPTX __shared__ memory
3140 // for reduced latency, as well as to have a distinct copy for concurrently
3141 // executing target regions. The array is declared with common linkage so
3142 // as to be shared across compilation units.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003143 StringRef TransferMediumName =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003144 "__openmp_nvptx_data_transfer_temporary_storage";
3145 llvm::GlobalVariable *TransferMedium =
3146 M.getGlobalVariable(TransferMediumName);
3147 if (!TransferMedium) {
3148 auto *Ty = llvm::ArrayType::get(CGM.Int64Ty, WarpSize);
3149 unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
3150 TransferMedium = new llvm::GlobalVariable(
3151 M, Ty,
3152 /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage,
3153 llvm::Constant::getNullValue(Ty), TransferMediumName,
3154 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3155 SharedAddressSpace);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003156 CGM.addCompilerUsedGlobal(TransferMedium);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003157 }
3158
3159 // Get the CUDA thread id of the current OpenMP thread on the GPU.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003160 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003161 // nvptx_lane_id = nvptx_id % warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003162 llvm::Value *LaneID = getNVPTXLaneID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003163 // nvptx_warp_id = nvptx_id / warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003164 llvm::Value *WarpID = getNVPTXWarpID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003165
3166 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3167 Address LocalReduceList(
3168 Bld.CreatePointerBitCastOrAddrSpaceCast(
3169 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3170 C.VoidPtrTy, SourceLocation()),
3171 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3172 CGF.getPointerAlign());
3173
3174 unsigned Idx = 0;
Alexey Bataev9ff80832018-04-16 20:16:21 +00003175 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003176 //
3177 // Warp master copies reduce element to transfer medium in __shared__
3178 // memory.
3179 //
3180 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3181 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3182 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
3183
3184 // if (lane_id == 0)
Alexey Bataev9ff80832018-04-16 20:16:21 +00003185 llvm::Value *IsWarpMaster = Bld.CreateIsNull(LaneID, "warp_master");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003186 Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
3187 CGF.EmitBlock(ThenBB);
3188
3189 // Reduce element = LocalReduceList[i]
3190 Address ElemPtrPtrAddr =
3191 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
3192 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3193 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3194 // elemptr = (type[i]*)(elemptrptr)
3195 Address ElemPtr =
3196 Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
3197 ElemPtr = Bld.CreateElementBitCast(
3198 ElemPtr, CGF.ConvertTypeForMem(Private->getType()));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003199
3200 // Get pointer to location in transfer medium.
3201 // MediumPtr = &medium[warp_id]
3202 llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
3203 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
3204 Address MediumPtr(MediumPtrVal, C.getTypeAlignInChars(Private->getType()));
3205 // Casting to actual data type.
3206 // MediumPtr = (type[i]*)MediumPtrAddr;
3207 MediumPtr = Bld.CreateElementBitCast(
3208 MediumPtr, CGF.ConvertTypeForMem(Private->getType()));
3209
Alexey Bataev12c62902018-06-22 19:10:38 +00003210 // elem = *elemptr
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003211 //*MediumPtr = elem
Alexey Bataev12c62902018-06-22 19:10:38 +00003212 if (Private->getType()->isScalarType()) {
3213 llvm::Value *Elem = CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false,
3214 Private->getType(), Loc);
3215 // Store the source element value to the dest element address.
3216 CGF.EmitStoreOfScalar(Elem, MediumPtr, /*Volatile=*/false,
3217 Private->getType());
3218 } else {
3219 CGF.EmitAggregateCopy(CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3220 CGF.MakeAddrLValue(MediumPtr, Private->getType()),
3221 Private->getType(), AggValueSlot::DoesNotOverlap);
3222 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003223
3224 Bld.CreateBr(MergeBB);
3225
3226 CGF.EmitBlock(ElseBB);
3227 Bld.CreateBr(MergeBB);
3228
3229 CGF.EmitBlock(MergeBB);
3230
3231 Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
3232 llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
3233 AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, SourceLocation());
3234
Alexey Bataev9ff80832018-04-16 20:16:21 +00003235 llvm::Value *NumActiveThreads = Bld.CreateNSWMul(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003236 NumWarpsVal, getNVPTXWarpSize(CGF), "num_active_threads");
3237 // named_barrier_sync(ParallelBarrierID, num_active_threads)
3238 syncParallelThreads(CGF, NumActiveThreads);
3239
3240 //
3241 // Warp 0 copies reduce element from transfer medium.
3242 //
3243 llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
3244 llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
3245 llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
3246
3247 // Up to 32 threads in warp 0 are active.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003248 llvm::Value *IsActiveThread =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003249 Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
3250 Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
3251
3252 CGF.EmitBlock(W0ThenBB);
3253
3254 // SrcMediumPtr = &medium[tid]
3255 llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
3256 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
3257 Address SrcMediumPtr(SrcMediumPtrVal,
3258 C.getTypeAlignInChars(Private->getType()));
3259 // SrcMediumVal = *SrcMediumPtr;
3260 SrcMediumPtr = Bld.CreateElementBitCast(
3261 SrcMediumPtr, CGF.ConvertTypeForMem(Private->getType()));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003262
3263 // TargetElemPtr = (type[i]*)(SrcDataAddr[i])
3264 Address TargetElemPtrPtr =
3265 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
3266 llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
3267 TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3268 Address TargetElemPtr =
3269 Address(TargetElemPtrVal, C.getTypeAlignInChars(Private->getType()));
3270 TargetElemPtr = Bld.CreateElementBitCast(
3271 TargetElemPtr, CGF.ConvertTypeForMem(Private->getType()));
3272
3273 // *TargetElemPtr = SrcMediumVal;
Alexey Bataev12c62902018-06-22 19:10:38 +00003274 if (Private->getType()->isScalarType()) {
3275 llvm::Value *SrcMediumValue = CGF.EmitLoadOfScalar(
3276 SrcMediumPtr, /*Volatile=*/false, Private->getType(), Loc);
3277 CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
3278 Private->getType());
3279 } else {
3280 CGF.EmitAggregateCopy(
3281 CGF.MakeAddrLValue(SrcMediumPtr, Private->getType()),
3282 CGF.MakeAddrLValue(TargetElemPtr, Private->getType()),
3283 Private->getType(), AggValueSlot::DoesNotOverlap);
3284 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003285 Bld.CreateBr(W0MergeBB);
3286
3287 CGF.EmitBlock(W0ElseBB);
3288 Bld.CreateBr(W0MergeBB);
3289
3290 CGF.EmitBlock(W0MergeBB);
3291
3292 // While warp 0 copies values from transfer medium, all other warps must
3293 // wait.
3294 syncParallelThreads(CGF, NumActiveThreads);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003295 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003296 }
3297
3298 CGF.FinishFunction();
3299 return Fn;
3300}
3301
3302/// Emit a helper that reduces data across two OpenMP threads (lanes)
3303/// in the same warp. It uses shuffle instructions to copy over data from
3304/// a remote lane's stack. The reduction algorithm performed is specified
3305/// by the fourth parameter.
3306///
3307/// Algorithm Versions.
3308/// Full Warp Reduce (argument value 0):
3309/// This algorithm assumes that all 32 lanes are active and gathers
3310/// data from these 32 lanes, producing a single resultant value.
3311/// Contiguous Partial Warp Reduce (argument value 1):
3312/// This algorithm assumes that only a *contiguous* subset of lanes
3313/// are active. This happens for the last warp in a parallel region
3314/// when the user specified num_threads is not an integer multiple of
3315/// 32. This contiguous subset always starts with the zeroth lane.
3316/// Partial Warp Reduce (argument value 2):
3317/// This algorithm gathers data from any number of lanes at any position.
3318/// All reduced values are stored in the lowest possible lane. The set
3319/// of problems every algorithm addresses is a super set of those
3320/// addressable by algorithms with a lower version number. Overhead
3321/// increases as algorithm version increases.
3322///
3323/// Terminology
3324/// Reduce element:
3325/// Reduce element refers to the individual data field with primitive
3326/// data types to be combined and reduced across threads.
3327/// Reduce list:
3328/// Reduce list refers to a collection of local, thread-private
3329/// reduce elements.
3330/// Remote Reduce list:
3331/// Remote Reduce list refers to a collection of remote (relative to
3332/// the current thread) reduce elements.
3333///
3334/// We distinguish between three states of threads that are important to
3335/// the implementation of this function.
3336/// Alive threads:
3337/// Threads in a warp executing the SIMT instruction, as distinguished from
3338/// threads that are inactive due to divergent control flow.
3339/// Active threads:
3340/// The minimal set of threads that has to be alive upon entry to this
3341/// function. The computation is correct iff active threads are alive.
3342/// Some threads are alive but they are not active because they do not
3343/// contribute to the computation in any useful manner. Turning them off
3344/// may introduce control flow overheads without any tangible benefits.
3345/// Effective threads:
3346/// In order to comply with the argument requirements of the shuffle
3347/// function, we must keep all lanes holding data alive. But at most
3348/// half of them perform value aggregation; we refer to this half of
3349/// threads as effective. The other half is simply handing off their
3350/// data.
3351///
3352/// Procedure
3353/// Value shuffle:
3354/// In this step active threads transfer data from higher lane positions
3355/// in the warp to lower lane positions, creating Remote Reduce list.
3356/// Value aggregation:
3357/// In this step, effective threads combine their thread local Reduce list
3358/// with Remote Reduce list and store the result in the thread local
3359/// Reduce list.
3360/// Value copy:
3361/// In this step, we deal with the assumption made by algorithm 2
3362/// (i.e. contiguity assumption). When we have an odd number of lanes
3363/// active, say 2k+1, only k threads will be effective and therefore k
3364/// new values will be produced. However, the Reduce list owned by the
3365/// (2k+1)th thread is ignored in the value aggregation. Therefore
3366/// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
3367/// that the contiguity assumption still holds.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003368static llvm::Value *emitShuffleAndReduceFunction(
3369 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3370 QualType ReductionArrayTy, llvm::Value *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003371 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003372
3373 // Thread local Reduce list used to host the values of data to be reduced.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003374 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3375 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003376 // Current lane id; could be logical.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003377 ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
3378 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003379 // Offset of the remote source lane relative to the current lane.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003380 ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3381 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003382 // Algorithm version. This is expected to be known at compile time.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003383 ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3384 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003385 FunctionArgList Args;
3386 Args.push_back(&ReduceListArg);
3387 Args.push_back(&LaneIDArg);
3388 Args.push_back(&RemoteLaneOffsetArg);
3389 Args.push_back(&AlgoVerArg);
3390
Alexey Bataev9ff80832018-04-16 20:16:21 +00003391 const CGFunctionInfo &CGFI =
3392 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003393 auto *Fn = llvm::Function::Create(
3394 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3395 "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003396 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003397 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003398 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003399 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003400
Alexey Bataev9ff80832018-04-16 20:16:21 +00003401 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003402
3403 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3404 Address LocalReduceList(
3405 Bld.CreatePointerBitCastOrAddrSpaceCast(
3406 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3407 C.VoidPtrTy, SourceLocation()),
3408 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3409 CGF.getPointerAlign());
3410
3411 Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
3412 llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
3413 AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3414
3415 Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
3416 llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
3417 AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3418
3419 Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
3420 llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
3421 AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3422
3423 // Create a local thread-private variable to host the Reduce list
3424 // from a remote lane.
3425 Address RemoteReduceList =
3426 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
3427
3428 // This loop iterates through the list of reduce elements and copies,
3429 // element by element, from a remote lane in the warp to RemoteReduceList,
3430 // hosted on the thread's stack.
3431 emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
3432 LocalReduceList, RemoteReduceList,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003433 {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
3434 /*ScratchpadIndex=*/nullptr,
3435 /*ScratchpadWidth=*/nullptr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003436
3437 // The actions to be performed on the Remote Reduce list is dependent
3438 // on the algorithm version.
3439 //
3440 // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
3441 // LaneId % 2 == 0 && Offset > 0):
3442 // do the reduction value aggregation
3443 //
3444 // The thread local variable Reduce list is mutated in place to host the
3445 // reduced data, which is the aggregated value produced from local and
3446 // remote lanes.
3447 //
3448 // Note that AlgoVer is expected to be a constant integer known at compile
3449 // time.
3450 // When AlgoVer==0, the first conjunction evaluates to true, making
3451 // the entire predicate true during compile time.
3452 // When AlgoVer==1, the second conjunction has only the second part to be
3453 // evaluated during runtime. Other conjunctions evaluates to false
3454 // during compile time.
3455 // When AlgoVer==2, the third conjunction has only the second part to be
3456 // evaluated during runtime. Other conjunctions evaluates to false
3457 // during compile time.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003458 llvm::Value *CondAlgo0 = Bld.CreateIsNull(AlgoVerArgVal);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003459
Alexey Bataev9ff80832018-04-16 20:16:21 +00003460 llvm::Value *Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
3461 llvm::Value *CondAlgo1 = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003462 Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
3463
Alexey Bataev9ff80832018-04-16 20:16:21 +00003464 llvm::Value *Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
3465 llvm::Value *CondAlgo2 = Bld.CreateAnd(
3466 Algo2, Bld.CreateIsNull(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1))));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003467 CondAlgo2 = Bld.CreateAnd(
3468 CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
3469
Alexey Bataev9ff80832018-04-16 20:16:21 +00003470 llvm::Value *CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003471 CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
3472
3473 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3474 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3475 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
3476 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
3477
3478 CGF.EmitBlock(ThenBB);
3479 // reduce_function(LocalReduceList, RemoteReduceList)
3480 llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3481 LocalReduceList.getPointer(), CGF.VoidPtrTy);
3482 llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3483 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003484 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3485 CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003486 Bld.CreateBr(MergeBB);
3487
3488 CGF.EmitBlock(ElseBB);
3489 Bld.CreateBr(MergeBB);
3490
3491 CGF.EmitBlock(MergeBB);
3492
3493 // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
3494 // Reduce list.
3495 Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
Alexey Bataev9ff80832018-04-16 20:16:21 +00003496 llvm::Value *CondCopy = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003497 Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
3498
3499 llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
3500 llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
3501 llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
3502 Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
3503
3504 CGF.EmitBlock(CpyThenBB);
3505 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
3506 RemoteReduceList, LocalReduceList);
3507 Bld.CreateBr(CpyMergeBB);
3508
3509 CGF.EmitBlock(CpyElseBB);
3510 Bld.CreateBr(CpyMergeBB);
3511
3512 CGF.EmitBlock(CpyMergeBB);
3513
3514 CGF.FinishFunction();
3515 return Fn;
3516}
3517
3518///
3519/// Design of OpenMP reductions on the GPU
3520///
3521/// Consider a typical OpenMP program with one or more reduction
3522/// clauses:
3523///
3524/// float foo;
3525/// double bar;
3526/// #pragma omp target teams distribute parallel for \
3527/// reduction(+:foo) reduction(*:bar)
3528/// for (int i = 0; i < N; i++) {
3529/// foo += A[i]; bar *= B[i];
3530/// }
3531///
3532/// where 'foo' and 'bar' are reduced across all OpenMP threads in
3533/// all teams. In our OpenMP implementation on the NVPTX device an
3534/// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
3535/// within a team are mapped to CUDA threads within a threadblock.
3536/// Our goal is to efficiently aggregate values across all OpenMP
3537/// threads such that:
3538///
3539/// - the compiler and runtime are logically concise, and
3540/// - the reduction is performed efficiently in a hierarchical
3541/// manner as follows: within OpenMP threads in the same warp,
3542/// across warps in a threadblock, and finally across teams on
3543/// the NVPTX device.
3544///
3545/// Introduction to Decoupling
3546///
3547/// We would like to decouple the compiler and the runtime so that the
3548/// latter is ignorant of the reduction variables (number, data types)
3549/// and the reduction operators. This allows a simpler interface
3550/// and implementation while still attaining good performance.
3551///
3552/// Pseudocode for the aforementioned OpenMP program generated by the
3553/// compiler is as follows:
3554///
3555/// 1. Create private copies of reduction variables on each OpenMP
3556/// thread: 'foo_private', 'bar_private'
3557/// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
3558/// to it and writes the result in 'foo_private' and 'bar_private'
3559/// respectively.
3560/// 3. Call the OpenMP runtime on the GPU to reduce within a team
3561/// and store the result on the team master:
3562///
3563/// __kmpc_nvptx_parallel_reduce_nowait(...,
3564/// reduceData, shuffleReduceFn, interWarpCpyFn)
3565///
3566/// where:
3567/// struct ReduceData {
3568/// double *foo;
3569/// double *bar;
3570/// } reduceData
3571/// reduceData.foo = &foo_private
3572/// reduceData.bar = &bar_private
3573///
3574/// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
3575/// auxiliary functions generated by the compiler that operate on
3576/// variables of type 'ReduceData'. They aid the runtime perform
3577/// algorithmic steps in a data agnostic manner.
3578///
3579/// 'shuffleReduceFn' is a pointer to a function that reduces data
3580/// of type 'ReduceData' across two OpenMP threads (lanes) in the
3581/// same warp. It takes the following arguments as input:
3582///
3583/// a. variable of type 'ReduceData' on the calling lane,
3584/// b. its lane_id,
3585/// c. an offset relative to the current lane_id to generate a
3586/// remote_lane_id. The remote lane contains the second
3587/// variable of type 'ReduceData' that is to be reduced.
3588/// d. an algorithm version parameter determining which reduction
3589/// algorithm to use.
3590///
3591/// 'shuffleReduceFn' retrieves data from the remote lane using
3592/// efficient GPU shuffle intrinsics and reduces, using the
3593/// algorithm specified by the 4th parameter, the two operands
3594/// element-wise. The result is written to the first operand.
3595///
3596/// Different reduction algorithms are implemented in different
3597/// runtime functions, all calling 'shuffleReduceFn' to perform
3598/// the essential reduction step. Therefore, based on the 4th
3599/// parameter, this function behaves slightly differently to
3600/// cooperate with the runtime to ensure correctness under
3601/// different circumstances.
3602///
3603/// 'InterWarpCpyFn' is a pointer to a function that transfers
3604/// reduced variables across warps. It tunnels, through CUDA
3605/// shared memory, the thread-private data of type 'ReduceData'
3606/// from lane 0 of each warp to a lane in the first warp.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003607/// 4. Call the OpenMP runtime on the GPU to reduce across teams.
3608/// The last team writes the global reduced value to memory.
3609///
3610/// ret = __kmpc_nvptx_teams_reduce_nowait(...,
3611/// reduceData, shuffleReduceFn, interWarpCpyFn,
3612/// scratchpadCopyFn, loadAndReduceFn)
3613///
3614/// 'scratchpadCopyFn' is a helper that stores reduced
3615/// data from the team master to a scratchpad array in
3616/// global memory.
3617///
3618/// 'loadAndReduceFn' is a helper that loads data from
3619/// the scratchpad array and reduces it with the input
3620/// operand.
3621///
3622/// These compiler generated functions hide address
3623/// calculation and alignment information from the runtime.
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003624/// 5. if ret == 1:
3625/// The team master of the last team stores the reduced
3626/// result to the globals in memory.
3627/// foo += reduceData.foo; bar *= reduceData.bar
3628///
3629///
3630/// Warp Reduction Algorithms
3631///
3632/// On the warp level, we have three algorithms implemented in the
3633/// OpenMP runtime depending on the number of active lanes:
3634///
3635/// Full Warp Reduction
3636///
3637/// The reduce algorithm within a warp where all lanes are active
3638/// is implemented in the runtime as follows:
3639///
3640/// full_warp_reduce(void *reduce_data,
3641/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3642/// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
3643/// ShuffleReduceFn(reduce_data, 0, offset, 0);
3644/// }
3645///
3646/// The algorithm completes in log(2, WARPSIZE) steps.
3647///
3648/// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
3649/// not used therefore we save instructions by not retrieving lane_id
3650/// from the corresponding special registers. The 4th parameter, which
3651/// represents the version of the algorithm being used, is set to 0 to
3652/// signify full warp reduction.
3653///
3654/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3655///
3656/// #reduce_elem refers to an element in the local lane's data structure
3657/// #remote_elem is retrieved from a remote lane
3658/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3659/// reduce_elem = reduce_elem REDUCE_OP remote_elem;
3660///
3661/// Contiguous Partial Warp Reduction
3662///
3663/// This reduce algorithm is used within a warp where only the first
3664/// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
3665/// number of OpenMP threads in a parallel region is not a multiple of
3666/// WARPSIZE. The algorithm is implemented in the runtime as follows:
3667///
3668/// void
3669/// contiguous_partial_reduce(void *reduce_data,
3670/// kmp_ShuffleReductFctPtr ShuffleReduceFn,
3671/// int size, int lane_id) {
3672/// int curr_size;
3673/// int offset;
3674/// curr_size = size;
3675/// mask = curr_size/2;
3676/// while (offset>0) {
3677/// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
3678/// curr_size = (curr_size+1)/2;
3679/// offset = curr_size/2;
3680/// }
3681/// }
3682///
3683/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3684///
3685/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3686/// if (lane_id < offset)
3687/// reduce_elem = reduce_elem REDUCE_OP remote_elem
3688/// else
3689/// reduce_elem = remote_elem
3690///
3691/// This algorithm assumes that the data to be reduced are located in a
3692/// contiguous subset of lanes starting from the first. When there is
3693/// an odd number of active lanes, the data in the last lane is not
3694/// aggregated with any other lane's dat but is instead copied over.
3695///
3696/// Dispersed Partial Warp Reduction
3697///
3698/// This algorithm is used within a warp when any discontiguous subset of
3699/// lanes are active. It is used to implement the reduction operation
3700/// across lanes in an OpenMP simd region or in a nested parallel region.
3701///
3702/// void
3703/// dispersed_partial_reduce(void *reduce_data,
3704/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3705/// int size, remote_id;
3706/// int logical_lane_id = number_of_active_lanes_before_me() * 2;
3707/// do {
3708/// remote_id = next_active_lane_id_right_after_me();
3709/// # the above function returns 0 of no active lane
3710/// # is present right after the current lane.
3711/// size = number_of_active_lanes_in_this_warp();
3712/// logical_lane_id /= 2;
3713/// ShuffleReduceFn(reduce_data, logical_lane_id,
3714/// remote_id-1-threadIdx.x, 2);
3715/// } while (logical_lane_id % 2 == 0 && size > 1);
3716/// }
3717///
3718/// There is no assumption made about the initial state of the reduction.
3719/// Any number of lanes (>=1) could be active at any position. The reduction
3720/// result is returned in the first active lane.
3721///
3722/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3723///
3724/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3725/// if (lane_id % 2 == 0 && offset > 0)
3726/// reduce_elem = reduce_elem REDUCE_OP remote_elem
3727/// else
3728/// reduce_elem = remote_elem
3729///
3730///
3731/// Intra-Team Reduction
3732///
3733/// This function, as implemented in the runtime call
3734/// '__kmpc_nvptx_parallel_reduce_nowait', aggregates data across OpenMP
3735/// threads in a team. It first reduces within a warp using the
3736/// aforementioned algorithms. We then proceed to gather all such
3737/// reduced values at the first warp.
3738///
3739/// The runtime makes use of the function 'InterWarpCpyFn', which copies
3740/// data from each of the "warp master" (zeroth lane of each warp, where
3741/// warp-reduced data is held) to the zeroth warp. This step reduces (in
3742/// a mathematical sense) the problem of reduction across warp masters in
3743/// a block to the problem of warp reduction.
3744///
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003745///
3746/// Inter-Team Reduction
3747///
3748/// Once a team has reduced its data to a single value, it is stored in
3749/// a global scratchpad array. Since each team has a distinct slot, this
3750/// can be done without locking.
3751///
3752/// The last team to write to the scratchpad array proceeds to reduce the
3753/// scratchpad array. One or more workers in the last team use the helper
3754/// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
3755/// the k'th worker reduces every k'th element.
3756///
3757/// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait' to
3758/// reduce across workers and compute a globally reduced value.
3759///
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003760void CGOpenMPRuntimeNVPTX::emitReduction(
3761 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
3762 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
3763 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
3764 if (!CGF.HaveInsertPoint())
3765 return;
3766
3767 bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003768 bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
Alexey Bataevfac26cf2018-05-02 20:03:27 +00003769 bool SimdReduction = isOpenMPSimdDirective(Options.ReductionKind);
3770 assert((TeamsReduction || ParallelReduction || SimdReduction) &&
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003771 "Invalid reduction selection in emitReduction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003772
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00003773 if (Options.SimpleReduction) {
3774 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
3775 ReductionOps, Options);
3776 return;
3777 }
3778
Alexey Bataev9ff80832018-04-16 20:16:21 +00003779 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003780
3781 // 1. Build a list of reduction variables.
3782 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3783 auto Size = RHSExprs.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00003784 for (const Expr *E : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003785 if (E->getType()->isVariablyModifiedType())
3786 // Reserve place for array size.
3787 ++Size;
3788 }
3789 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
3790 QualType ReductionArrayTy =
3791 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3792 /*IndexTypeQuals=*/0);
3793 Address ReductionList =
3794 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3795 auto IPriv = Privates.begin();
3796 unsigned Idx = 0;
3797 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
3798 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3799 CGF.getPointerSize());
3800 CGF.Builder.CreateStore(
3801 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3802 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
3803 Elem);
3804 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3805 // Store array size.
3806 ++Idx;
3807 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3808 CGF.getPointerSize());
3809 llvm::Value *Size = CGF.Builder.CreateIntCast(
3810 CGF.getVLASize(
3811 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
Sander de Smalen891af03a2018-02-03 13:55:59 +00003812 .NumElts,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003813 CGF.SizeTy, /*isSigned=*/false);
3814 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3815 Elem);
3816 }
3817 }
3818
3819 // 2. Emit reduce_func().
Alexey Bataev9ff80832018-04-16 20:16:21 +00003820 llvm::Value *ReductionFn = emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003821 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
3822 Privates, LHSExprs, RHSExprs, ReductionOps);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003823
3824 // 4. Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
3825 // RedList, shuffle_reduce_func, interwarp_copy_func);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003826 llvm::Value *ThreadId = getThreadID(CGF, Loc);
3827 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
3828 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003829 ReductionList.getPointer(), CGF.VoidPtrTy);
3830
Alexey Bataev9ff80832018-04-16 20:16:21 +00003831 llvm::Value *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003832 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003833 llvm::Value *InterWarpCopyFn =
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003834 emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003835
Alexey Bataevfac26cf2018-05-02 20:03:27 +00003836 llvm::Value *Args[] = {ThreadId,
3837 CGF.Builder.getInt32(RHSExprs.size()),
3838 ReductionArrayTySize,
3839 RL,
3840 ShuffleAndReduceFn,
3841 InterWarpCopyFn};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003842
Alexey Bataevfac26cf2018-05-02 20:03:27 +00003843 llvm::Value *Res = nullptr;
3844 if (ParallelReduction)
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003845 Res = CGF.EmitRuntimeCall(
3846 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_reduce_nowait),
3847 Args);
Alexey Bataevfac26cf2018-05-02 20:03:27 +00003848 else if (SimdReduction)
3849 Res = CGF.EmitRuntimeCall(
3850 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_simd_reduce_nowait),
3851 Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003852
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003853 if (TeamsReduction) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003854 llvm::Value *ScratchPadCopyFn =
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003855 emitCopyToScratchpad(CGM, Privates, ReductionArrayTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003856 llvm::Value *LoadAndReduceFn = emitReduceScratchpadFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003857 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003858
3859 llvm::Value *Args[] = {ThreadId,
3860 CGF.Builder.getInt32(RHSExprs.size()),
3861 ReductionArrayTySize,
3862 RL,
3863 ShuffleAndReduceFn,
3864 InterWarpCopyFn,
3865 ScratchPadCopyFn,
3866 LoadAndReduceFn};
3867 Res = CGF.EmitRuntimeCall(
3868 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_teams_reduce_nowait),
3869 Args);
3870 }
3871
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003872 // 5. Build switch(res)
Alexey Bataev9ff80832018-04-16 20:16:21 +00003873 llvm::BasicBlock *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
3874 llvm::SwitchInst *SwInst =
3875 CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003876
3877 // 6. Build case 1: where we have reduced values in the master
3878 // thread in each team.
3879 // __kmpc_end_reduce{_nowait}(<gtid>);
3880 // break;
Alexey Bataev9ff80832018-04-16 20:16:21 +00003881 llvm::BasicBlock *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003882 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
3883 CGF.EmitBlock(Case1BB);
3884
3885 // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
3886 llvm::Value *EndArgs[] = {ThreadId};
Alexey Bataev9ff80832018-04-16 20:16:21 +00003887 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003888 this](CodeGenFunction &CGF, PrePostActionTy &Action) {
3889 auto IPriv = Privates.begin();
3890 auto ILHS = LHSExprs.begin();
3891 auto IRHS = RHSExprs.begin();
Alexey Bataev9ff80832018-04-16 20:16:21 +00003892 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003893 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
3894 cast<DeclRefExpr>(*IRHS));
3895 ++IPriv;
3896 ++ILHS;
3897 ++IRHS;
3898 }
3899 };
3900 RegionCodeGenTy RCG(CodeGen);
3901 NVPTXActionTy Action(
3902 nullptr, llvm::None,
3903 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_reduce_nowait),
3904 EndArgs);
3905 RCG.setAction(Action);
3906 RCG(CGF);
3907 CGF.EmitBranch(DefaultBB);
3908 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
3909}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003910
3911const VarDecl *
3912CGOpenMPRuntimeNVPTX::translateParameter(const FieldDecl *FD,
3913 const VarDecl *NativeParam) const {
3914 if (!NativeParam->getType()->isReferenceType())
3915 return NativeParam;
3916 QualType ArgType = NativeParam->getType();
3917 QualifierCollector QC;
3918 const Type *NonQualTy = QC.strip(ArgType);
3919 QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
3920 if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
3921 if (Attr->getCaptureKind() == OMPC_map) {
3922 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
3923 LangAS::opencl_global);
3924 }
3925 }
3926 ArgType = CGM.getContext().getPointerType(PointeeTy);
3927 QC.addRestrict();
3928 enum { NVPTX_local_addr = 5 };
Alexander Richardson6d989432017-10-15 18:48:14 +00003929 QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003930 ArgType = QC.apply(CGM.getContext(), ArgType);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003931 if (isa<ImplicitParamDecl>(NativeParam))
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003932 return ImplicitParamDecl::Create(
3933 CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
3934 NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003935 return ParmVarDecl::Create(
3936 CGM.getContext(),
3937 const_cast<DeclContext *>(NativeParam->getDeclContext()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003938 NativeParam->getBeginLoc(), NativeParam->getLocation(),
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003939 NativeParam->getIdentifier(), ArgType,
3940 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003941}
3942
3943Address
3944CGOpenMPRuntimeNVPTX::getParameterAddress(CodeGenFunction &CGF,
3945 const VarDecl *NativeParam,
3946 const VarDecl *TargetParam) const {
3947 assert(NativeParam != TargetParam &&
3948 NativeParam->getType()->isReferenceType() &&
3949 "Native arg must not be the same as target arg.");
3950 Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
3951 QualType NativeParamType = NativeParam->getType();
3952 QualifierCollector QC;
3953 const Type *NonQualTy = QC.strip(NativeParamType);
3954 QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
3955 unsigned NativePointeeAddrSpace =
Alexander Richardson6d989432017-10-15 18:48:14 +00003956 CGF.getContext().getTargetAddressSpace(NativePointeeTy);
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00003957 QualType TargetTy = TargetParam->getType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003958 llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00003959 LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003960 // First cast to generic.
3961 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3962 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
3963 /*AddrSpace=*/0));
3964 // Cast from generic to native address space.
3965 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3966 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
3967 NativePointeeAddrSpace));
3968 Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
3969 CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00003970 NativeParamType);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003971 return NativeParamAddr;
3972}
3973
3974void CGOpenMPRuntimeNVPTX::emitOutlinedFunctionCall(
Alexey Bataev3c595a62017-08-14 15:01:03 +00003975 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003976 ArrayRef<llvm::Value *> Args) const {
3977 SmallVector<llvm::Value *, 4> TargetArgs;
Alexey Bataev07ed94a2017-08-15 14:34:04 +00003978 TargetArgs.reserve(Args.size());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003979 auto *FnType =
3980 cast<llvm::FunctionType>(OutlinedFn->getType()->getPointerElementType());
3981 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
Alexey Bataev07ed94a2017-08-15 14:34:04 +00003982 if (FnType->isVarArg() && FnType->getNumParams() <= I) {
3983 TargetArgs.append(std::next(Args.begin(), I), Args.end());
3984 break;
3985 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003986 llvm::Type *TargetType = FnType->getParamType(I);
3987 llvm::Value *NativeArg = Args[I];
3988 if (!TargetType->isPointerTy()) {
3989 TargetArgs.emplace_back(NativeArg);
3990 continue;
3991 }
3992 llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataevc99042b2018-03-15 18:10:54 +00003993 NativeArg,
3994 NativeArg->getType()->getPointerElementType()->getPointerTo());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003995 TargetArgs.emplace_back(
3996 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
3997 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00003998 CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003999}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004000
4001/// Emit function which wraps the outline parallel region
4002/// and controls the arguments which are passed to this function.
4003/// The wrapper ensures that the outlined function is called
4004/// with the correct arguments when data is shared.
4005llvm::Function *CGOpenMPRuntimeNVPTX::createParallelDataSharingWrapper(
4006 llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
4007 ASTContext &Ctx = CGM.getContext();
4008 const auto &CS = *D.getCapturedStmt(OMPD_parallel);
4009
4010 // Create a function that takes as argument the source thread.
4011 FunctionArgList WrapperArgs;
4012 QualType Int16QTy =
4013 Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
4014 QualType Int32QTy =
4015 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004016 ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004017 /*Id=*/nullptr, Int16QTy,
4018 ImplicitParamDecl::Other);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004019 ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004020 /*Id=*/nullptr, Int32QTy,
4021 ImplicitParamDecl::Other);
4022 WrapperArgs.emplace_back(&ParallelLevelArg);
4023 WrapperArgs.emplace_back(&WrapperArg);
4024
Alexey Bataev9ff80832018-04-16 20:16:21 +00004025 const CGFunctionInfo &CGFI =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004026 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
4027
4028 auto *Fn = llvm::Function::Create(
4029 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataev9ff80832018-04-16 20:16:21 +00004030 Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004031 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004032 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004033 Fn->setDoesNotRecurse();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004034
4035 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
4036 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004037 D.getBeginLoc(), D.getBeginLoc());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004038
4039 const auto *RD = CS.getCapturedRecordDecl();
4040 auto CurField = RD->field_begin();
4041
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004042 Address ZeroAddr = CGF.CreateMemTemp(
4043 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
4044 /*Name*/ ".zero.addr");
4045 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004046 // Get the array of arguments.
4047 SmallVector<llvm::Value *, 8> Args;
4048
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004049 Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).getPointer());
4050 Args.emplace_back(ZeroAddr.getPointer());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004051
4052 CGBuilderTy &Bld = CGF.Builder;
4053 auto CI = CS.capture_begin();
4054
4055 // Use global memory for data sharing.
4056 // Handle passing of global args to workers.
4057 Address GlobalArgs =
4058 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
4059 llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
4060 llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
4061 CGF.EmitRuntimeCall(
4062 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_get_shared_variables),
4063 DataSharingArgs);
4064
4065 // Retrieve the shared variables from the list of references returned
4066 // by the runtime. Pass the variables to the outlined function.
Alexey Bataev17314212018-03-20 15:41:05 +00004067 Address SharedArgListAddress = Address::invalid();
4068 if (CS.capture_size() > 0 ||
4069 isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4070 SharedArgListAddress = CGF.EmitLoadOfPointer(
4071 GlobalArgs, CGF.getContext()
4072 .getPointerType(CGF.getContext().getPointerType(
4073 CGF.getContext().VoidPtrTy))
4074 .castAs<PointerType>());
4075 }
4076 unsigned Idx = 0;
4077 if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4078 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
4079 CGF.getPointerSize());
4080 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4081 Src, CGF.SizeTy->getPointerTo());
4082 llvm::Value *LB = CGF.EmitLoadOfScalar(
4083 TypedAddress,
4084 /*Volatile=*/false,
4085 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4086 cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
4087 Args.emplace_back(LB);
4088 ++Idx;
4089 Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
4090 CGF.getPointerSize());
4091 TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4092 Src, CGF.SizeTy->getPointerTo());
4093 llvm::Value *UB = CGF.EmitLoadOfScalar(
4094 TypedAddress,
4095 /*Volatile=*/false,
4096 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4097 cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
4098 Args.emplace_back(UB);
4099 ++Idx;
4100 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004101 if (CS.capture_size() > 0) {
4102 ASTContext &CGFContext = CGF.getContext();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004103 for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
4104 QualType ElemTy = CurField->getType();
Alexey Bataev17314212018-03-20 15:41:05 +00004105 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx,
4106 CGF.getPointerSize());
4107 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004108 Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)));
4109 llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
4110 /*Volatile=*/false,
4111 CGFContext.getPointerType(ElemTy),
4112 CI->getLocation());
Alexey Bataev2091ca62018-04-23 17:33:41 +00004113 if (CI->capturesVariableByCopy() &&
4114 !CI->getCapturedVar()->getType()->isAnyPointerType()) {
Alexey Bataev17314212018-03-20 15:41:05 +00004115 Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
4116 CI->getLocation());
4117 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004118 Args.emplace_back(Arg);
4119 }
4120 }
4121
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004122 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedParallelFn, Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004123 CGF.FinishFunction();
4124 return Fn;
4125}
4126
4127void CGOpenMPRuntimeNVPTX::emitFunctionProlog(CodeGenFunction &CGF,
4128 const Decl *D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004129 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4130 return;
4131
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004132 assert(D && "Expected function or captured|block decl.");
4133 assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
4134 "Function is registered already.");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004135 const Stmt *Body = nullptr;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004136 bool NeedToDelayGlobalization = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004137 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4138 Body = FD->getBody();
4139 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
4140 Body = BD->getBody();
4141 } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
4142 Body = CD->getBody();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004143 NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
Alexey Bataev2adecff2018-09-21 14:22:53 +00004144 if (NeedToDelayGlobalization &&
4145 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
4146 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004147 }
4148 if (!Body)
4149 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004150 CheckVarsEscapingDeclContext VarChecker(CGF);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004151 VarChecker.Visit(Body);
Alexey Bataevff23bb62018-10-11 18:30:31 +00004152 const RecordDecl *GlobalizedVarsRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004153 VarChecker.getGlobalizedRecord(IsInTTDRegion);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004154 ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
4155 VarChecker.getEscapedVariableLengthDecls();
4156 if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004157 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004158 auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
4159 I->getSecond().MappedParams =
4160 llvm::make_unique<CodeGenFunction::OMPMapVars>();
4161 I->getSecond().GlobalRecord = GlobalizedVarsRecord;
4162 I->getSecond().EscapedParameters.insert(
4163 VarChecker.getEscapedParameters().begin(),
4164 VarChecker.getEscapedParameters().end());
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004165 I->getSecond().EscapedVariableLengthDecls.append(
4166 EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004167 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004168 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004169 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004170 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004171 Data.insert(std::make_pair(VD, MappedVarData(FD, IsInTTDRegion)));
Alexey Bataevc99042b2018-03-15 18:10:54 +00004172 }
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004173 if (!IsInTTDRegion && !NeedToDelayGlobalization && !IsInParallelRegion) {
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004174 CheckVarsEscapingDeclContext VarChecker(CGF);
4175 VarChecker.Visit(Body);
4176 I->getSecond().SecondaryGlobalRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004177 VarChecker.getGlobalizedRecord(/*IsInTTDRegion=*/true);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004178 I->getSecond().SecondaryLocalVarData.emplace();
4179 DeclToAddrMapTy &Data = I->getSecond().SecondaryLocalVarData.getValue();
4180 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
4181 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
4182 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004183 Data.insert(
4184 std::make_pair(VD, MappedVarData(FD, /*IsInTTDRegion=*/true)));
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004185 }
4186 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00004187 if (!NeedToDelayGlobalization) {
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004188 emitGenericVarsProlog(CGF, D->getBeginLoc(), /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004189 struct GlobalizationScope final : EHScopeStack::Cleanup {
4190 GlobalizationScope() = default;
4191
4192 void Emit(CodeGenFunction &CGF, Flags flags) override {
4193 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004194 .emitGenericVarsEpilog(CGF, /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004195 }
4196 };
4197 CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004198 }
4199}
4200
4201Address CGOpenMPRuntimeNVPTX::getAddressOfLocalVariable(CodeGenFunction &CGF,
4202 const VarDecl *VD) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004203 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4204 return Address::invalid();
4205
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004206 VD = VD->getCanonicalDecl();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004207 auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
4208 if (I == FunctionGlobalizedDecls.end())
4209 return Address::invalid();
Alexey Bataevc99042b2018-03-15 18:10:54 +00004210 auto VDI = I->getSecond().LocalVarData.find(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004211 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004212 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004213 if (VD->hasAttrs()) {
4214 for (specific_attr_iterator<OMPReferencedVarAttr> IT(VD->attr_begin()),
4215 E(VD->attr_end());
4216 IT != E; ++IT) {
4217 auto VDI = I->getSecond().LocalVarData.find(
4218 cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
4219 ->getCanonicalDecl());
4220 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004221 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004222 }
4223 }
4224 return Address::invalid();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004225}
4226
4227void CGOpenMPRuntimeNVPTX::functionFinished(CodeGenFunction &CGF) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004228 FunctionGlobalizedDecls.erase(CGF.CurFn);
4229 CGOpenMPRuntime::functionFinished(CGF);
4230}
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004231
4232void CGOpenMPRuntimeNVPTX::getDefaultDistScheduleAndChunk(
4233 CodeGenFunction &CGF, const OMPLoopDirective &S,
4234 OpenMPDistScheduleClauseKind &ScheduleKind,
4235 llvm::Value *&Chunk) const {
4236 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
4237 ScheduleKind = OMPC_DIST_SCHEDULE_static;
4238 Chunk = CGF.EmitScalarConversion(getNVPTXNumThreads(CGF),
4239 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4240 S.getIterationVariable()->getType(), S.getBeginLoc());
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004241 return;
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004242 }
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004243 CGOpenMPRuntime::getDefaultDistScheduleAndChunk(
4244 CGF, S, ScheduleKind, Chunk);
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004245}
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004246
4247void CGOpenMPRuntimeNVPTX::getDefaultScheduleAndChunk(
4248 CodeGenFunction &CGF, const OMPLoopDirective &S,
4249 OpenMPScheduleClauseKind &ScheduleKind,
4250 llvm::Value *&Chunk) const {
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004251 ScheduleKind = OMPC_SCHEDULE_static;
4252 Chunk = CGF.Builder.getIntN(CGF.getContext().getTypeSize(
4253 S.getIterationVariable()->getType()), 1);
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004254}