blob: 1f5bfee41bd90e3aff6999ebe5616c19a55662d5 [file] [log] [blame]
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001//===---- CGOpenMPRuntimeNVPTX.cpp - Interface to OpenMP NVPTX Runtimes ---===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides a class for OpenMP runtime code generation specialized to NVPTX
11// targets.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CGOpenMPRuntimeNVPTX.h"
Carlo Bertollic6872252016-04-04 15:55:02 +000016#include "CodeGenFunction.h"
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000017#include "clang/AST/DeclOpenMP.h"
Carlo Bertollic6872252016-04-04 15:55:02 +000018#include "clang/AST/StmtOpenMP.h"
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000019#include "clang/AST/StmtVisitor.h"
20#include "llvm/ADT/SmallPtrSet.h"
Samuel Antao45bfe4c2016-02-08 15:59:20 +000021
22using namespace clang;
23using namespace CodeGen;
24
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +000025namespace {
26enum OpenMPRTLFunctionNVPTX {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000027 /// Call to void __kmpc_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +000028 /// int16_t RequiresOMPRuntime);
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +000029 OMPRTL_NVPTX__kmpc_kernel_init,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000030 /// Call to void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +000031 OMPRTL_NVPTX__kmpc_kernel_deinit,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000032 /// Call to void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +000033 /// int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +000034 OMPRTL_NVPTX__kmpc_spmd_kernel_init,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000035 /// Call to void __kmpc_spmd_kernel_deinit();
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +000036 OMPRTL_NVPTX__kmpc_spmd_kernel_deinit,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000037 /// Call to void __kmpc_kernel_prepare_parallel(void
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +000038 /// *outlined_function, int16_t
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +000039 /// IsOMPRuntimeInitialized);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000040 OMPRTL_NVPTX__kmpc_kernel_prepare_parallel,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000041 /// Call to bool __kmpc_kernel_parallel(void **outlined_function,
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +000042 /// int16_t IsOMPRuntimeInitialized);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000043 OMPRTL_NVPTX__kmpc_kernel_parallel,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000044 /// Call to void __kmpc_kernel_end_parallel();
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000045 OMPRTL_NVPTX__kmpc_kernel_end_parallel,
46 /// Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
47 /// global_tid);
48 OMPRTL_NVPTX__kmpc_serialized_parallel,
49 /// Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
50 /// global_tid);
51 OMPRTL_NVPTX__kmpc_end_serialized_parallel,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000052 /// Call to int32_t __kmpc_shuffle_int32(int32_t element,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000053 /// int16_t lane_offset, int16_t warp_size);
54 OMPRTL_NVPTX__kmpc_shuffle_int32,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000055 /// Call to int64_t __kmpc_shuffle_int64(int64_t element,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000056 /// int16_t lane_offset, int16_t warp_size);
57 OMPRTL_NVPTX__kmpc_shuffle_int64,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000058 /// Call to __kmpc_nvptx_parallel_reduce_nowait(kmp_int32
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000059 /// global_tid, kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
60 /// void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
61 /// lane_offset, int16_t shortCircuit),
62 /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num));
63 OMPRTL_NVPTX__kmpc_parallel_reduce_nowait,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000064 /// Call to __kmpc_nvptx_simd_reduce_nowait(kmp_int32
Alexey Bataevfac26cf2018-05-02 20:03:27 +000065 /// global_tid, kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
66 /// void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
67 /// lane_offset, int16_t shortCircuit),
68 /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num));
69 OMPRTL_NVPTX__kmpc_simd_reduce_nowait,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000070 /// Call to __kmpc_nvptx_teams_reduce_nowait(int32_t global_tid,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +000071 /// int32_t num_vars, size_t reduce_size, void *reduce_data,
72 /// void (*kmp_ShuffleReductFctPtr)(void *rhs, int16_t lane_id, int16_t
73 /// lane_offset, int16_t shortCircuit),
74 /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num),
75 /// void (*kmp_CopyToScratchpadFctPtr)(void *reduce_data, void * scratchpad,
76 /// int32_t index, int32_t width),
77 /// void (*kmp_LoadReduceFctPtr)(void *reduce_data, void * scratchpad, int32_t
78 /// index, int32_t width, int32_t reduce))
79 OMPRTL_NVPTX__kmpc_teams_reduce_nowait,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000080 /// Call to __kmpc_nvptx_end_reduce_nowait(int32_t global_tid);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000081 OMPRTL_NVPTX__kmpc_end_reduce_nowait,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000082 /// Call to void __kmpc_data_sharing_init_stack();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000083 OMPRTL_NVPTX__kmpc_data_sharing_init_stack,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000084 /// Call to void* __kmpc_data_sharing_push_stack(size_t size,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000085 /// int16_t UseSharedMemory);
86 OMPRTL_NVPTX__kmpc_data_sharing_push_stack,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000087 /// Call to void __kmpc_data_sharing_pop_stack(void *a);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000088 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000089 /// Call to void __kmpc_begin_sharing_variables(void ***args,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000090 /// size_t n_args);
91 OMPRTL_NVPTX__kmpc_begin_sharing_variables,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000092 /// Call to void __kmpc_end_sharing_variables();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000093 OMPRTL_NVPTX__kmpc_end_sharing_variables,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000094 /// Call to void __kmpc_get_shared_variables(void ***GlobalArgs)
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000095 OMPRTL_NVPTX__kmpc_get_shared_variables,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +000096 /// Call to uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32
97 /// global_tid);
98 OMPRTL_NVPTX__kmpc_parallel_level,
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +000099};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000100
101/// Pre(post)-action for different OpenMP constructs specialized for NVPTX.
102class NVPTXActionTy final : public PrePostActionTy {
Alexey Bataev9ff80832018-04-16 20:16:21 +0000103 llvm::Value *EnterCallee = nullptr;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000104 ArrayRef<llvm::Value *> EnterArgs;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000105 llvm::Value *ExitCallee = nullptr;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000106 ArrayRef<llvm::Value *> ExitArgs;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000107 bool Conditional = false;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000108 llvm::BasicBlock *ContBlock = nullptr;
109
110public:
111 NVPTXActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
112 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
113 bool Conditional = false)
114 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
115 ExitArgs(ExitArgs), Conditional(Conditional) {}
116 void Enter(CodeGenFunction &CGF) override {
117 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
118 if (Conditional) {
119 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
120 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
121 ContBlock = CGF.createBasicBlock("omp_if.end");
122 // Generate the branch (If-stmt)
123 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
124 CGF.EmitBlock(ThenBlock);
125 }
126 }
127 void Done(CodeGenFunction &CGF) {
128 // Emit the rest of blocks/branches
129 CGF.EmitBranch(ContBlock);
130 CGF.EmitBlock(ContBlock, true);
131 }
132 void Exit(CodeGenFunction &CGF) override {
133 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
134 }
135};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000136
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000137/// A class to track the execution mode when codegening directives within
138/// a target region. The appropriate mode (SPMD|NON-SPMD) is set on entry
139/// to the target region and used by containing directives such as 'parallel'
140/// to emit optimized code.
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000141class ExecutionModeRAII {
142private:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000143 CGOpenMPRuntimeNVPTX::ExecutionMode SavedMode;
144 CGOpenMPRuntimeNVPTX::ExecutionMode &Mode;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000145
146public:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000147 ExecutionModeRAII(CGOpenMPRuntimeNVPTX::ExecutionMode &Mode, bool IsSPMD)
148 : Mode(Mode) {
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000149 SavedMode = Mode;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000150 Mode = IsSPMD ? CGOpenMPRuntimeNVPTX::EM_SPMD
151 : CGOpenMPRuntimeNVPTX::EM_NonSPMD;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000152 }
153 ~ExecutionModeRAII() { Mode = SavedMode; }
154};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000155
156/// GPU Configuration: This information can be derived from cuda registers,
157/// however, providing compile time constants helps generate more efficient
158/// code. For all practical purposes this is fine because the configuration
159/// is the same for all known NVPTX architectures.
160enum MachineConfiguration : unsigned {
161 WarpSize = 32,
162 /// Number of bits required to represent a lane identifier, which is
163 /// computed as log_2(WarpSize).
164 LaneIDBits = 5,
165 LaneIDMask = WarpSize - 1,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +0000166
167 /// Global memory alignment for performance.
168 GlobalMemoryAlignment = 256,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000169};
170
171enum NamedBarrier : unsigned {
172 /// Synchronize on this barrier #ID using a named barrier primitive.
173 /// Only the subset of active threads in a parallel region arrive at the
174 /// barrier.
175 NB_Parallel = 1,
176};
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000177
178/// Get the list of variables that can escape their declaration context.
179class CheckVarsEscapingDeclContext final
180 : public ConstStmtVisitor<CheckVarsEscapingDeclContext> {
181 CodeGenFunction &CGF;
182 llvm::SetVector<const ValueDecl *> EscapedDecls;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000183 llvm::SetVector<const ValueDecl *> EscapedVariableLengthDecls;
Alexey Bataevc99042b2018-03-15 18:10:54 +0000184 llvm::SmallPtrSet<const Decl *, 4> EscapedParameters;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000185 bool AllEscaped = false;
186 RecordDecl *GlobalizedRD = nullptr;
187 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
188
Alexey Bataev03f270c2018-03-30 18:31:07 +0000189 static llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy>
190 isDeclareTargetDeclaration(const ValueDecl *VD) {
Alexey Bataev9ff80832018-04-16 20:16:21 +0000191 for (const Decl *D : VD->redecls()) {
Alexey Bataev03f270c2018-03-30 18:31:07 +0000192 if (!D->hasAttrs())
193 continue;
194 if (const auto *Attr = D->getAttr<OMPDeclareTargetDeclAttr>())
195 return Attr->getMapType();
196 }
197 return llvm::None;
198 }
199
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000200 void markAsEscaped(const ValueDecl *VD) {
Alexey Bataev03f270c2018-03-30 18:31:07 +0000201 // Do not globalize declare target variables.
202 if (isDeclareTargetDeclaration(VD))
203 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000204 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataevc99042b2018-03-15 18:10:54 +0000205 // Variables captured by value must be globalized.
206 if (auto *CSI = CGF.CapturedStmtInfo) {
Mikael Holmen9f373a32018-03-16 07:27:57 +0000207 if (const FieldDecl *FD = CSI->lookup(cast<VarDecl>(VD))) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000208 if (!FD->hasAttrs())
209 return;
210 const auto *Attr = FD->getAttr<OMPCaptureKindAttr>();
211 if (!Attr)
212 return;
213 if (!isOpenMPPrivate(
214 static_cast<OpenMPClauseKind>(Attr->getCaptureKind())) ||
215 Attr->getCaptureKind() == OMPC_map)
216 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +0000217 if (FD->getType()->isReferenceType())
218 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000219 assert(!VD->getType()->isVariablyModifiedType() &&
220 "Parameter captured by value with variably modified type");
Alexey Bataevc99042b2018-03-15 18:10:54 +0000221 EscapedParameters.insert(VD);
222 }
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000223 } else if (VD->getType()->isAnyPointerType() ||
224 VD->getType()->isReferenceType())
225 // Do not globalize variables with reference or pointer type.
226 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000227 if (VD->getType()->isVariablyModifiedType())
228 EscapedVariableLengthDecls.insert(VD);
229 else
230 EscapedDecls.insert(VD);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000231 }
232
233 void VisitValueDecl(const ValueDecl *VD) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000234 if (VD->getType()->isLValueReferenceType())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000235 markAsEscaped(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000236 if (const auto *VarD = dyn_cast<VarDecl>(VD)) {
237 if (!isa<ParmVarDecl>(VarD) && VarD->hasInit()) {
238 const bool SavedAllEscaped = AllEscaped;
239 AllEscaped = VD->getType()->isLValueReferenceType();
240 Visit(VarD->getInit());
241 AllEscaped = SavedAllEscaped;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000242 }
243 }
244 }
245 void VisitOpenMPCapturedStmt(const CapturedStmt *S) {
246 if (!S)
247 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000248 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000249 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
250 const ValueDecl *VD = C.getCapturedVar();
251 markAsEscaped(VD);
252 if (isa<OMPCapturedExprDecl>(VD))
253 VisitValueDecl(VD);
254 }
255 }
256 }
257
258 typedef std::pair<CharUnits /*Align*/, const ValueDecl *> VarsDataTy;
259 static bool stable_sort_comparator(const VarsDataTy P1, const VarsDataTy P2) {
260 return P1.first > P2.first;
261 }
262
263 void buildRecordForGlobalizedVars() {
264 assert(!GlobalizedRD &&
265 "Record for globalized variables is built already.");
266 if (EscapedDecls.empty())
267 return;
268 ASTContext &C = CGF.getContext();
269 SmallVector<VarsDataTy, 4> GlobalizedVars;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000270 for (const ValueDecl *D : EscapedDecls)
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000271 GlobalizedVars.emplace_back(C.getDeclAlign(D), D);
272 std::stable_sort(GlobalizedVars.begin(), GlobalizedVars.end(),
273 stable_sort_comparator);
274 // Build struct _globalized_locals_ty {
275 // /* globalized vars */
276 // };
277 GlobalizedRD = C.buildImplicitRecord("_globalized_locals_ty");
278 GlobalizedRD->startDefinition();
279 for (const auto &Pair : GlobalizedVars) {
280 const ValueDecl *VD = Pair.second;
281 QualType Type = VD->getType();
282 if (Type->isLValueReferenceType())
283 Type = C.getPointerType(Type.getNonReferenceType());
284 else
285 Type = Type.getNonReferenceType();
286 SourceLocation Loc = VD->getLocation();
287 auto *Field = FieldDecl::Create(
288 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
289 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
290 /*BW=*/nullptr, /*Mutable=*/false,
291 /*InitStyle=*/ICIS_NoInit);
292 Field->setAccess(AS_public);
293 GlobalizedRD->addDecl(Field);
294 if (VD->hasAttrs()) {
295 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
296 E(VD->getAttrs().end());
297 I != E; ++I)
298 Field->addAttr(*I);
299 }
300 MappedDeclsFields.try_emplace(VD, Field);
301 }
302 GlobalizedRD->completeDefinition();
303 }
304
305public:
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000306 CheckVarsEscapingDeclContext(CodeGenFunction &CGF) : CGF(CGF) {}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000307 virtual ~CheckVarsEscapingDeclContext() = default;
308 void VisitDeclStmt(const DeclStmt *S) {
309 if (!S)
310 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000311 for (const Decl *D : S->decls())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000312 if (const auto *VD = dyn_cast_or_null<ValueDecl>(D))
313 VisitValueDecl(VD);
314 }
315 void VisitOMPExecutableDirective(const OMPExecutableDirective *D) {
316 if (!D)
317 return;
318 if (D->hasAssociatedStmt()) {
319 if (const auto *S =
320 dyn_cast_or_null<CapturedStmt>(D->getAssociatedStmt()))
321 VisitOpenMPCapturedStmt(S);
322 }
323 }
324 void VisitCapturedStmt(const CapturedStmt *S) {
325 if (!S)
326 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000327 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000328 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
329 const ValueDecl *VD = C.getCapturedVar();
330 markAsEscaped(VD);
331 if (isa<OMPCapturedExprDecl>(VD))
332 VisitValueDecl(VD);
333 }
334 }
335 }
336 void VisitLambdaExpr(const LambdaExpr *E) {
337 if (!E)
338 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000339 for (const LambdaCapture &C : E->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000340 if (C.capturesVariable()) {
341 if (C.getCaptureKind() == LCK_ByRef) {
342 const ValueDecl *VD = C.getCapturedVar();
343 markAsEscaped(VD);
344 if (E->isInitCapture(&C) || isa<OMPCapturedExprDecl>(VD))
345 VisitValueDecl(VD);
346 }
347 }
348 }
349 }
350 void VisitBlockExpr(const BlockExpr *E) {
351 if (!E)
352 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000353 for (const BlockDecl::Capture &C : E->getBlockDecl()->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000354 if (C.isByRef()) {
355 const VarDecl *VD = C.getVariable();
356 markAsEscaped(VD);
357 if (isa<OMPCapturedExprDecl>(VD) || VD->isInitCapture())
358 VisitValueDecl(VD);
359 }
360 }
361 }
362 void VisitCallExpr(const CallExpr *E) {
363 if (!E)
364 return;
365 for (const Expr *Arg : E->arguments()) {
366 if (!Arg)
367 continue;
368 if (Arg->isLValue()) {
369 const bool SavedAllEscaped = AllEscaped;
370 AllEscaped = true;
371 Visit(Arg);
372 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000373 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000374 Visit(Arg);
Alexey Bataev9ff80832018-04-16 20:16:21 +0000375 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000376 }
377 Visit(E->getCallee());
378 }
379 void VisitDeclRefExpr(const DeclRefExpr *E) {
380 if (!E)
381 return;
382 const ValueDecl *VD = E->getDecl();
383 if (AllEscaped)
384 markAsEscaped(VD);
385 if (isa<OMPCapturedExprDecl>(VD))
386 VisitValueDecl(VD);
387 else if (const auto *VarD = dyn_cast<VarDecl>(VD))
388 if (VarD->isInitCapture())
389 VisitValueDecl(VD);
390 }
391 void VisitUnaryOperator(const UnaryOperator *E) {
392 if (!E)
393 return;
394 if (E->getOpcode() == UO_AddrOf) {
395 const bool SavedAllEscaped = AllEscaped;
396 AllEscaped = true;
397 Visit(E->getSubExpr());
398 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000399 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000400 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000401 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000402 }
403 void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
404 if (!E)
405 return;
406 if (E->getCastKind() == CK_ArrayToPointerDecay) {
407 const bool SavedAllEscaped = AllEscaped;
408 AllEscaped = true;
409 Visit(E->getSubExpr());
410 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000411 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000412 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000413 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000414 }
415 void VisitExpr(const Expr *E) {
416 if (!E)
417 return;
418 bool SavedAllEscaped = AllEscaped;
419 if (!E->isLValue())
420 AllEscaped = false;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000421 for (const Stmt *Child : E->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000422 if (Child)
423 Visit(Child);
424 AllEscaped = SavedAllEscaped;
425 }
426 void VisitStmt(const Stmt *S) {
427 if (!S)
428 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000429 for (const Stmt *Child : S->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000430 if (Child)
431 Visit(Child);
432 }
433
Alexey Bataevc99042b2018-03-15 18:10:54 +0000434 /// Returns the record that handles all the escaped local variables and used
435 /// instead of their original storage.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000436 const RecordDecl *getGlobalizedRecord() {
437 if (!GlobalizedRD)
438 buildRecordForGlobalizedVars();
439 return GlobalizedRD;
440 }
441
Alexey Bataevc99042b2018-03-15 18:10:54 +0000442 /// Returns the field in the globalized record for the escaped variable.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000443 const FieldDecl *getFieldForGlobalizedVar(const ValueDecl *VD) const {
444 assert(GlobalizedRD &&
445 "Record for globalized variables must be generated already.");
446 auto I = MappedDeclsFields.find(VD);
447 if (I == MappedDeclsFields.end())
448 return nullptr;
449 return I->getSecond();
450 }
451
Alexey Bataevc99042b2018-03-15 18:10:54 +0000452 /// Returns the list of the escaped local variables/parameters.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000453 ArrayRef<const ValueDecl *> getEscapedDecls() const {
454 return EscapedDecls.getArrayRef();
455 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000456
457 /// Checks if the escaped local variable is actually a parameter passed by
458 /// value.
459 const llvm::SmallPtrSetImpl<const Decl *> &getEscapedParameters() const {
460 return EscapedParameters;
461 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000462
463 /// Returns the list of the escaped variables with the variably modified
464 /// types.
465 ArrayRef<const ValueDecl *> getEscapedVariableLengthDecls() const {
466 return EscapedVariableLengthDecls.getArrayRef();
467 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000468};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000469} // anonymous namespace
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000470
471/// Get the GPU warp size.
472static llvm::Value *getNVPTXWarpSize(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000473 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000474 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000475 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_warpsize),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000476 "nvptx_warp_size");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000477}
478
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000479/// Get the id of the current thread on the GPU.
480static llvm::Value *getNVPTXThreadID(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000481 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000482 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000483 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_tid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000484 "nvptx_tid");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000485}
486
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000487/// Get the id of the warp in the block.
488/// We assume that the warp size is 32, which is always the case
489/// on the NVPTX device, to generate more efficient code.
490static llvm::Value *getNVPTXWarpID(CodeGenFunction &CGF) {
491 CGBuilderTy &Bld = CGF.Builder;
492 return Bld.CreateAShr(getNVPTXThreadID(CGF), LaneIDBits, "nvptx_warp_id");
493}
494
495/// Get the id of the current lane in the Warp.
496/// We assume that the warp size is 32, which is always the case
497/// on the NVPTX device, to generate more efficient code.
498static llvm::Value *getNVPTXLaneID(CodeGenFunction &CGF) {
499 CGBuilderTy &Bld = CGF.Builder;
500 return Bld.CreateAnd(getNVPTXThreadID(CGF), Bld.getInt32(LaneIDMask),
501 "nvptx_lane_id");
502}
503
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000504/// Get the maximum number of threads in a block of the GPU.
505static llvm::Value *getNVPTXNumThreads(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000506 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000507 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000508 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_ntid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000509 "nvptx_num_threads");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000510}
511
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000512/// Get barrier to synchronize all threads in a block.
513static void getNVPTXCTABarrier(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000514 CGF.EmitRuntimeCall(llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000515 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_barrier0));
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000516}
517
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000518/// Get barrier #ID to synchronize selected (multiple of warp size) threads in
519/// a CTA.
520static void getNVPTXBarrier(CodeGenFunction &CGF, int ID,
521 llvm::Value *NumThreads) {
522 CGBuilderTy &Bld = CGF.Builder;
523 llvm::Value *Args[] = {Bld.getInt32(ID), NumThreads};
Alexey Bataev3c595a62017-08-14 15:01:03 +0000524 CGF.EmitRuntimeCall(llvm::Intrinsic::getDeclaration(
525 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_barrier),
526 Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000527}
528
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000529/// Synchronize all GPU threads in a block.
530static void syncCTAThreads(CodeGenFunction &CGF) { getNVPTXCTABarrier(CGF); }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000531
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000532/// Synchronize worker threads in a parallel region.
533static void syncParallelThreads(CodeGenFunction &CGF, llvm::Value *NumThreads) {
534 return getNVPTXBarrier(CGF, NB_Parallel, NumThreads);
535}
536
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000537/// Get the value of the thread_limit clause in the teams directive.
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000538/// For the 'generic' execution mode, the runtime encodes thread_limit in
539/// the launch parameters, always starting thread_limit+warpSize threads per
540/// CTA. The threads in the last warp are reserved for master execution.
541/// For the 'spmd' execution mode, all threads in a CTA are part of the team.
542static llvm::Value *getThreadLimit(CodeGenFunction &CGF,
543 bool IsInSpmdExecutionMode = false) {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000544 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000545 return IsInSpmdExecutionMode
546 ? getNVPTXNumThreads(CGF)
Alexey Bataeve290ec02018-04-06 16:03:36 +0000547 : Bld.CreateNUWSub(getNVPTXNumThreads(CGF), getNVPTXWarpSize(CGF),
548 "thread_limit");
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000549}
550
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000551/// Get the thread id of the OMP master thread.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000552/// The master thread id is the first thread (lane) of the last warp in the
553/// GPU block. Warp size is assumed to be some power of 2.
554/// Thread id is 0 indexed.
555/// E.g: If NumThreads is 33, master id is 32.
556/// If NumThreads is 64, master id is 32.
557/// If NumThreads is 1024, master id is 992.
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000558static llvm::Value *getMasterThreadID(CodeGenFunction &CGF) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000559 CGBuilderTy &Bld = CGF.Builder;
560 llvm::Value *NumThreads = getNVPTXNumThreads(CGF);
561
562 // We assume that the warp size is a power of 2.
Alexey Bataeve290ec02018-04-06 16:03:36 +0000563 llvm::Value *Mask = Bld.CreateNUWSub(getNVPTXWarpSize(CGF), Bld.getInt32(1));
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000564
Alexey Bataeve290ec02018-04-06 16:03:36 +0000565 return Bld.CreateAnd(Bld.CreateNUWSub(NumThreads, Bld.getInt32(1)),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000566 Bld.CreateNot(Mask), "master_tid");
567}
568
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000569CGOpenMPRuntimeNVPTX::WorkerFunctionState::WorkerFunctionState(
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000570 CodeGenModule &CGM, SourceLocation Loc)
Alexey Bataev9ff80832018-04-16 20:16:21 +0000571 : WorkerFn(nullptr), CGFI(CGM.getTypes().arrangeNullaryFunction()),
572 Loc(Loc) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000573 createWorkerFunction(CGM);
Vasileios Kalintirise5c09592016-03-22 10:41:20 +0000574}
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000575
576void CGOpenMPRuntimeNVPTX::WorkerFunctionState::createWorkerFunction(
577 CodeGenModule &CGM) {
578 // Create an worker function with no arguments.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000579
580 WorkerFn = llvm::Function::Create(
Alexey Bataev9ff80832018-04-16 20:16:21 +0000581 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataevaee93892018-01-08 20:09:47 +0000582 /*placeholder=*/"_worker", &CGM.getModule());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000583 CGM.SetInternalFunctionAttributes(GlobalDecl(), WorkerFn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +0000584 WorkerFn->setDoesNotRecurse();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000585}
586
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000587CGOpenMPRuntimeNVPTX::ExecutionMode
588CGOpenMPRuntimeNVPTX::getExecutionMode() const {
589 return CurrentExecutionMode;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000590}
591
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000592static CGOpenMPRuntimeNVPTX::DataSharingMode
593getDataSharingMode(CodeGenModule &CGM) {
594 return CGM.getLangOpts().OpenMPCUDAMode ? CGOpenMPRuntimeNVPTX::CUDA
595 : CGOpenMPRuntimeNVPTX::Generic;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000596}
597
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000598/// Checks if the \p Body is the \a CompoundStmt and returns its child statement
599/// iff there is only one.
600static const Stmt *getSingleCompoundChild(const Stmt *Body) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000601 if (const auto *C = dyn_cast<CompoundStmt>(Body))
602 if (C->size() == 1)
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000603 return C->body_front();
604 return Body;
605}
606
607/// Check if the parallel directive has an 'if' clause with non-constant or
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000608/// false condition. Also, check if the number of threads is strictly specified
609/// and run those directives in non-SPMD mode.
610static bool hasParallelIfNumThreadsClause(ASTContext &Ctx,
611 const OMPExecutableDirective &D) {
612 if (D.hasClausesOfKind<OMPNumThreadsClause>())
613 return true;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000614 for (const auto *C : D.getClausesOfKind<OMPIfClause>()) {
615 OpenMPDirectiveKind NameModifier = C->getNameModifier();
616 if (NameModifier != OMPD_parallel && NameModifier != OMPD_unknown)
617 continue;
618 const Expr *Cond = C->getCondition();
619 bool Result;
620 if (!Cond->EvaluateAsBooleanCondition(Result, Ctx) || !Result)
621 return true;
622 }
623 return false;
624}
625
626/// Check for inner (nested) SPMD construct, if any
627static bool hasNestedSPMDDirective(ASTContext &Ctx,
628 const OMPExecutableDirective &D) {
629 const auto *CS = D.getInnermostCapturedStmt();
630 const auto *Body = CS->getCapturedStmt()->IgnoreContainers();
631 const Stmt *ChildStmt = getSingleCompoundChild(Body);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000632
633 if (const auto *NestedDir = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
634 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000635 switch (D.getDirectiveKind()) {
636 case OMPD_target:
Alexey Bataevdf093e72018-05-11 19:45:14 +0000637 if (isOpenMPParallelDirective(DKind) &&
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000638 !hasParallelIfNumThreadsClause(Ctx, *NestedDir))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000639 return true;
640 if (DKind == OMPD_teams || DKind == OMPD_teams_distribute) {
641 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers();
642 if (!Body)
643 return false;
644 ChildStmt = getSingleCompoundChild(Body);
645 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
646 DKind = NND->getDirectiveKind();
Alexey Bataevdf093e72018-05-11 19:45:14 +0000647 if (isOpenMPParallelDirective(DKind) &&
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000648 !hasParallelIfNumThreadsClause(Ctx, *NND))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000649 return true;
650 if (DKind == OMPD_distribute) {
651 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers();
652 if (!Body)
653 return false;
654 ChildStmt = getSingleCompoundChild(Body);
655 if (!ChildStmt)
656 return false;
657 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
658 DKind = NND->getDirectiveKind();
Alexey Bataevdf093e72018-05-11 19:45:14 +0000659 return isOpenMPParallelDirective(DKind) &&
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000660 !hasParallelIfNumThreadsClause(Ctx, *NND);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000661 }
662 }
663 }
664 }
665 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000666 case OMPD_target_teams:
Alexey Bataevdf093e72018-05-11 19:45:14 +0000667 if (isOpenMPParallelDirective(DKind) &&
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000668 !hasParallelIfNumThreadsClause(Ctx, *NestedDir))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000669 return true;
670 if (DKind == OMPD_distribute) {
671 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers();
672 if (!Body)
673 return false;
674 ChildStmt = getSingleCompoundChild(Body);
675 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
676 DKind = NND->getDirectiveKind();
Alexey Bataevdf093e72018-05-11 19:45:14 +0000677 return isOpenMPParallelDirective(DKind) &&
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000678 !hasParallelIfNumThreadsClause(Ctx, *NND);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000679 }
680 }
681 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000682 case OMPD_target_teams_distribute:
Alexey Bataevdf093e72018-05-11 19:45:14 +0000683 return isOpenMPParallelDirective(DKind) &&
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000684 !hasParallelIfNumThreadsClause(Ctx, *NestedDir);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000685 case OMPD_target_simd:
686 case OMPD_target_parallel:
687 case OMPD_target_parallel_for:
688 case OMPD_target_parallel_for_simd:
689 case OMPD_target_teams_distribute_simd:
690 case OMPD_target_teams_distribute_parallel_for:
691 case OMPD_target_teams_distribute_parallel_for_simd:
692 case OMPD_parallel:
693 case OMPD_for:
694 case OMPD_parallel_for:
695 case OMPD_parallel_sections:
696 case OMPD_for_simd:
697 case OMPD_parallel_for_simd:
698 case OMPD_cancel:
699 case OMPD_cancellation_point:
700 case OMPD_ordered:
701 case OMPD_threadprivate:
702 case OMPD_task:
703 case OMPD_simd:
704 case OMPD_sections:
705 case OMPD_section:
706 case OMPD_single:
707 case OMPD_master:
708 case OMPD_critical:
709 case OMPD_taskyield:
710 case OMPD_barrier:
711 case OMPD_taskwait:
712 case OMPD_taskgroup:
713 case OMPD_atomic:
714 case OMPD_flush:
715 case OMPD_teams:
716 case OMPD_target_data:
717 case OMPD_target_exit_data:
718 case OMPD_target_enter_data:
719 case OMPD_distribute:
720 case OMPD_distribute_simd:
721 case OMPD_distribute_parallel_for:
722 case OMPD_distribute_parallel_for_simd:
723 case OMPD_teams_distribute:
724 case OMPD_teams_distribute_simd:
725 case OMPD_teams_distribute_parallel_for:
726 case OMPD_teams_distribute_parallel_for_simd:
727 case OMPD_target_update:
728 case OMPD_declare_simd:
729 case OMPD_declare_target:
730 case OMPD_end_declare_target:
731 case OMPD_declare_reduction:
732 case OMPD_taskloop:
733 case OMPD_taskloop_simd:
734 case OMPD_unknown:
735 llvm_unreachable("Unexpected directive.");
736 }
737 }
738
739 return false;
740}
741
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000742static bool supportsSPMDExecutionMode(ASTContext &Ctx,
743 const OMPExecutableDirective &D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000744 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
745 switch (DirectiveKind) {
746 case OMPD_target:
747 case OMPD_target_teams:
748 case OMPD_target_teams_distribute:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000749 return hasNestedSPMDDirective(Ctx, D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000750 case OMPD_target_parallel:
751 case OMPD_target_parallel_for:
752 case OMPD_target_parallel_for_simd:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000753 case OMPD_target_teams_distribute_parallel_for:
754 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000755 return !hasParallelIfNumThreadsClause(Ctx, D);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000756 case OMPD_target_simd:
757 case OMPD_target_teams_distribute_simd:
Alexey Bataevdf093e72018-05-11 19:45:14 +0000758 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000759 case OMPD_parallel:
760 case OMPD_for:
761 case OMPD_parallel_for:
762 case OMPD_parallel_sections:
763 case OMPD_for_simd:
764 case OMPD_parallel_for_simd:
765 case OMPD_cancel:
766 case OMPD_cancellation_point:
767 case OMPD_ordered:
768 case OMPD_threadprivate:
769 case OMPD_task:
770 case OMPD_simd:
771 case OMPD_sections:
772 case OMPD_section:
773 case OMPD_single:
774 case OMPD_master:
775 case OMPD_critical:
776 case OMPD_taskyield:
777 case OMPD_barrier:
778 case OMPD_taskwait:
779 case OMPD_taskgroup:
780 case OMPD_atomic:
781 case OMPD_flush:
782 case OMPD_teams:
783 case OMPD_target_data:
784 case OMPD_target_exit_data:
785 case OMPD_target_enter_data:
786 case OMPD_distribute:
787 case OMPD_distribute_simd:
788 case OMPD_distribute_parallel_for:
789 case OMPD_distribute_parallel_for_simd:
790 case OMPD_teams_distribute:
791 case OMPD_teams_distribute_simd:
792 case OMPD_teams_distribute_parallel_for:
793 case OMPD_teams_distribute_parallel_for_simd:
794 case OMPD_target_update:
795 case OMPD_declare_simd:
796 case OMPD_declare_target:
797 case OMPD_end_declare_target:
798 case OMPD_declare_reduction:
799 case OMPD_taskloop:
800 case OMPD_taskloop_simd:
801 case OMPD_unknown:
802 break;
803 }
804 llvm_unreachable(
805 "Unknown programming model for OpenMP directive on NVPTX target.");
806}
807
808void CGOpenMPRuntimeNVPTX::emitNonSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000809 StringRef ParentName,
810 llvm::Function *&OutlinedFn,
811 llvm::Constant *&OutlinedFnID,
812 bool IsOffloadEntry,
813 const RegionCodeGenTy &CodeGen) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000814 ExecutionModeRAII ModeRAII(CurrentExecutionMode, /*IsSPMD=*/false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000815 EntryFunctionState EST;
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000816 WorkerFunctionState WST(CGM, D.getLocStart());
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000817 Work.clear();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000818 WrapperFunctionsMap.clear();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000819
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000820 // Emit target region as a standalone region.
821 class NVPTXPrePostActionTy : public PrePostActionTy {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000822 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
823 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000824
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000825 public:
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000826 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000827 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST)
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000828 : EST(EST), WST(WST) {}
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000829 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000830 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000831 .emitNonSPMDEntryHeader(CGF, EST, WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000832 }
833 void Exit(CodeGenFunction &CGF) override {
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000834 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000835 .emitNonSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000836 }
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000837 } Action(EST, WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000838 CodeGen.setAction(Action);
839 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
840 IsOffloadEntry, CodeGen);
841
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000842 // Now change the name of the worker function to correspond to this target
843 // region's entry function.
Alexey Bataev9ff80832018-04-16 20:16:21 +0000844 WST.WorkerFn->setName(Twine(OutlinedFn->getName(), "_worker"));
Alexey Bataevaee93892018-01-08 20:09:47 +0000845
846 // Create the worker function
847 emitWorkerFunction(WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000848}
849
850// Setup NVPTX threads for master-worker OpenMP scheme.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000851void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryHeader(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000852 EntryFunctionState &EST,
853 WorkerFunctionState &WST) {
854 CGBuilderTy &Bld = CGF.Builder;
855
856 llvm::BasicBlock *WorkerBB = CGF.createBasicBlock(".worker");
857 llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
858 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
859 EST.ExitBB = CGF.createBasicBlock(".exit");
860
Alexey Bataev9ff80832018-04-16 20:16:21 +0000861 llvm::Value *IsWorker =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000862 Bld.CreateICmpULT(getNVPTXThreadID(CGF), getThreadLimit(CGF));
863 Bld.CreateCondBr(IsWorker, WorkerBB, MasterCheckBB);
864
865 CGF.EmitBlock(WorkerBB);
Alexey Bataevb7f3cba2018-03-19 17:04:07 +0000866 emitCall(CGF, WST.Loc, WST.WorkerFn);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000867 CGF.EmitBranch(EST.ExitBB);
868
869 CGF.EmitBlock(MasterCheckBB);
Alexey Bataev9ff80832018-04-16 20:16:21 +0000870 llvm::Value *IsMaster =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000871 Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
872 Bld.CreateCondBr(IsMaster, MasterBB, EST.ExitBB);
873
874 CGF.EmitBlock(MasterBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000875 IsInTargetMasterThreadRegion = true;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000876 // SEQUENTIAL (MASTER) REGION START
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000877 // First action in sequential region:
878 // Initialize the state of the OpenMP runtime library on the GPU.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +0000879 // TODO: Optimize runtime initialization and pass in correct value.
880 llvm::Value *Args[] = {getThreadLimit(CGF),
881 Bld.getInt16(/*RequiresOMPRuntime=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000882 CGF.EmitRuntimeCall(
883 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_init), Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000884
885 // For data sharing, we need to initialize the stack.
886 CGF.EmitRuntimeCall(
887 createNVPTXRuntimeFunction(
888 OMPRTL_NVPTX__kmpc_data_sharing_init_stack));
889
Alexey Bataevc99042b2018-03-15 18:10:54 +0000890 emitGenericVarsProlog(CGF, WST.Loc);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000891}
892
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000893void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000894 EntryFunctionState &EST) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000895 IsInTargetMasterThreadRegion = false;
Alexey Bataevc99042b2018-03-15 18:10:54 +0000896 if (!CGF.HaveInsertPoint())
897 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000898
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000899 emitGenericVarsEpilog(CGF);
900
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000901 if (!EST.ExitBB)
902 EST.ExitBB = CGF.createBasicBlock(".exit");
903
904 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".termination.notifier");
905 CGF.EmitBranch(TerminateBB);
906
907 CGF.EmitBlock(TerminateBB);
908 // Signal termination condition.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +0000909 // TODO: Optimize runtime initialization and pass in correct value.
910 llvm::Value *Args[] = {CGF.Builder.getInt16(/*IsOMPRuntimeInitialized=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000911 CGF.EmitRuntimeCall(
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +0000912 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_deinit), Args);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000913 // Barrier to terminate worker threads.
914 syncCTAThreads(CGF);
915 // Master thread jumps to exit point.
916 CGF.EmitBranch(EST.ExitBB);
917
918 CGF.EmitBlock(EST.ExitBB);
919 EST.ExitBB = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000920}
921
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000922void CGOpenMPRuntimeNVPTX::emitSpmdKernel(const OMPExecutableDirective &D,
923 StringRef ParentName,
924 llvm::Function *&OutlinedFn,
925 llvm::Constant *&OutlinedFnID,
926 bool IsOffloadEntry,
927 const RegionCodeGenTy &CodeGen) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000928 ExecutionModeRAII ModeRAII(CurrentExecutionMode, /*IsSPMD=*/true);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000929 EntryFunctionState EST;
930
931 // Emit target region as a standalone region.
932 class NVPTXPrePostActionTy : public PrePostActionTy {
933 CGOpenMPRuntimeNVPTX &RT;
934 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
935 const OMPExecutableDirective &D;
936
937 public:
938 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT,
939 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
940 const OMPExecutableDirective &D)
941 : RT(RT), EST(EST), D(D) {}
942 void Enter(CodeGenFunction &CGF) override {
943 RT.emitSpmdEntryHeader(CGF, EST, D);
944 }
945 void Exit(CodeGenFunction &CGF) override {
946 RT.emitSpmdEntryFooter(CGF, EST);
947 }
948 } Action(*this, EST, D);
949 CodeGen.setAction(Action);
950 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
951 IsOffloadEntry, CodeGen);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000952}
953
954void CGOpenMPRuntimeNVPTX::emitSpmdEntryHeader(
955 CodeGenFunction &CGF, EntryFunctionState &EST,
956 const OMPExecutableDirective &D) {
Alexey Bataev9ff80832018-04-16 20:16:21 +0000957 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000958
959 // Setup BBs in entry function.
960 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute");
961 EST.ExitBB = CGF.createBasicBlock(".exit");
962
963 // Initialize the OMP state in the runtime; called by all active threads.
964 // TODO: Set RequiresOMPRuntime and RequiresDataSharing parameters
965 // based on code analysis of the target region.
966 llvm::Value *Args[] = {getThreadLimit(CGF, /*IsInSpmdExecutionMode=*/true),
967 /*RequiresOMPRuntime=*/Bld.getInt16(1),
968 /*RequiresDataSharing=*/Bld.getInt16(1)};
969 CGF.EmitRuntimeCall(
970 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_init), Args);
971 CGF.EmitBranch(ExecuteBB);
972
973 CGF.EmitBlock(ExecuteBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000974
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000975 IsInTargetMasterThreadRegion = true;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000976}
977
978void CGOpenMPRuntimeNVPTX::emitSpmdEntryFooter(CodeGenFunction &CGF,
979 EntryFunctionState &EST) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000980 IsInTargetMasterThreadRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000981 if (!CGF.HaveInsertPoint())
982 return;
983
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000984 if (!EST.ExitBB)
985 EST.ExitBB = CGF.createBasicBlock(".exit");
986
987 llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit");
988 CGF.EmitBranch(OMPDeInitBB);
989
990 CGF.EmitBlock(OMPDeInitBB);
991 // DeInitialize the OMP state in the runtime; called by all active threads.
992 CGF.EmitRuntimeCall(
993 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_deinit), None);
994 CGF.EmitBranch(EST.ExitBB);
995
996 CGF.EmitBlock(EST.ExitBB);
997 EST.ExitBB = nullptr;
998}
999
1000// Create a unique global variable to indicate the execution mode of this target
1001// region. The execution mode is either 'generic', or 'spmd' depending on the
1002// target directive. This variable is picked up by the offload library to setup
1003// the device appropriately before kernel launch. If the execution mode is
1004// 'generic', the runtime reserves one warp for the master, otherwise, all
1005// warps participate in parallel work.
1006static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001007 bool Mode) {
1008 auto *GVMode =
1009 new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
1010 llvm::GlobalValue::WeakAnyLinkage,
1011 llvm::ConstantInt::get(CGM.Int8Ty, Mode ? 0 : 1),
1012 Twine(Name, "_exec_mode"));
Alexey Bataev9ff80832018-04-16 20:16:21 +00001013 CGM.addCompilerUsedGlobal(GVMode);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001014}
1015
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001016void CGOpenMPRuntimeNVPTX::emitWorkerFunction(WorkerFunctionState &WST) {
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +00001017 ASTContext &Ctx = CGM.getContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001018
1019 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001020 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, WST.CGFI, {},
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001021 WST.Loc, WST.Loc);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001022 emitWorkerLoop(CGF, WST);
1023 CGF.FinishFunction();
1024}
1025
1026void CGOpenMPRuntimeNVPTX::emitWorkerLoop(CodeGenFunction &CGF,
1027 WorkerFunctionState &WST) {
1028 //
1029 // The workers enter this loop and wait for parallel work from the master.
1030 // When the master encounters a parallel region it sets up the work + variable
1031 // arguments, and wakes up the workers. The workers first check to see if
1032 // they are required for the parallel region, i.e., within the # of requested
1033 // parallel threads. The activated workers load the variable arguments and
1034 // execute the parallel work.
1035 //
1036
1037 CGBuilderTy &Bld = CGF.Builder;
1038
1039 llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work");
1040 llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers");
1041 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel");
1042 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel");
1043 llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel");
1044 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1045
1046 CGF.EmitBranch(AwaitBB);
1047
1048 // Workers wait for work from master.
1049 CGF.EmitBlock(AwaitBB);
1050 // Wait for parallel work
1051 syncCTAThreads(CGF);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001052
Gheorghe-Teodor Bercea36cdfad2018-03-22 17:33:27 +00001053 // For data sharing, we need to initialize the stack for workers.
1054 CGF.EmitRuntimeCall(
1055 createNVPTXRuntimeFunction(
1056 OMPRTL_NVPTX__kmpc_data_sharing_init_stack));
1057
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001058 Address WorkFn =
1059 CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn");
1060 Address ExecStatus =
1061 CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status");
1062 CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0));
1063 CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy));
1064
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001065 // TODO: Optimize runtime initialization and pass in correct value.
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001066 llvm::Value *Args[] = {WorkFn.getPointer(),
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001067 /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001068 llvm::Value *Ret = CGF.EmitRuntimeCall(
1069 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args);
1070 Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001071
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001072 // On termination condition (workid == 0), exit loop.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001073 llvm::Value *WorkID = Bld.CreateLoad(WorkFn);
1074 llvm::Value *ShouldTerminate = Bld.CreateIsNull(WorkID, "should_terminate");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001075 Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB);
1076
1077 // Activate requested workers.
1078 CGF.EmitBlock(SelectWorkersBB);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001079 llvm::Value *IsActive =
1080 Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active");
1081 Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001082
1083 // Signal start of parallel region.
1084 CGF.EmitBlock(ExecuteBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001085
1086 // Process work items: outlined parallel functions.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001087 for (llvm::Function *W : Work) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001088 // Try to match this outlined function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001089 llvm::Value *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001090
1091 llvm::Value *WorkFnMatch =
1092 Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match");
1093
1094 llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn");
1095 llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next");
1096 Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB);
1097
1098 // Execute this outlined function.
1099 CGF.EmitBlock(ExecuteFNBB);
1100
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001101 // Insert call to work function via shared wrapper. The shared
1102 // wrapper takes two arguments:
1103 // - the parallelism level;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001104 // - the thread ID;
1105 emitCall(CGF, WST.Loc, W,
1106 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001107
1108 // Go to end of parallel region.
1109 CGF.EmitBranch(TerminateBB);
1110
1111 CGF.EmitBlock(CheckNextBB);
1112 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001113 // Default case: call to outlined function through pointer if the target
1114 // region makes a declare target call that may contain an orphaned parallel
1115 // directive.
1116 auto *ParallelFnTy =
1117 llvm::FunctionType::get(CGM.VoidTy, {CGM.Int16Ty, CGM.Int32Ty},
1118 /*isVarArg=*/false)
1119 ->getPointerTo();
1120 llvm::Value *WorkFnCast = Bld.CreateBitCast(WorkID, ParallelFnTy);
1121 // Insert call to work function via shared wrapper. The shared
1122 // wrapper takes two arguments:
1123 // - the parallelism level;
1124 // - the thread ID;
1125 emitCall(CGF, WST.Loc, WorkFnCast,
1126 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
1127 // Go to end of parallel region.
1128 CGF.EmitBranch(TerminateBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001129
1130 // Signal end of parallel region.
1131 CGF.EmitBlock(TerminateBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001132 CGF.EmitRuntimeCall(
1133 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_end_parallel),
1134 llvm::None);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001135 CGF.EmitBranch(BarrierBB);
1136
1137 // All active and inactive workers wait at a barrier after parallel region.
1138 CGF.EmitBlock(BarrierBB);
1139 // Barrier after parallel region.
1140 syncCTAThreads(CGF);
1141 CGF.EmitBranch(AwaitBB);
1142
1143 // Exit target region.
1144 CGF.EmitBlock(ExitBB);
1145}
1146
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001147/// Returns specified OpenMP runtime function for the current OpenMP
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001148/// implementation. Specialized for the NVPTX device.
1149/// \param Function OpenMP runtime function.
1150/// \return Specified function.
1151llvm::Constant *
1152CGOpenMPRuntimeNVPTX::createNVPTXRuntimeFunction(unsigned Function) {
1153 llvm::Constant *RTLFn = nullptr;
1154 switch (static_cast<OpenMPRTLFunctionNVPTX>(Function)) {
1155 case OMPRTL_NVPTX__kmpc_kernel_init: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001156 // Build void __kmpc_kernel_init(kmp_int32 thread_limit, int16_t
1157 // RequiresOMPRuntime);
1158 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001159 auto *FnTy =
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001160 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1161 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_init");
1162 break;
1163 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001164 case OMPRTL_NVPTX__kmpc_kernel_deinit: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001165 // Build void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
1166 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001167 auto *FnTy =
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001168 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001169 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_deinit");
1170 break;
1171 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001172 case OMPRTL_NVPTX__kmpc_spmd_kernel_init: {
1173 // Build void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001174 // int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001175 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001176 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001177 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1178 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_init");
1179 break;
1180 }
1181 case OMPRTL_NVPTX__kmpc_spmd_kernel_deinit: {
1182 // Build void __kmpc_spmd_kernel_deinit();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001183 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001184 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1185 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_deinit");
1186 break;
1187 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001188 case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: {
1189 /// Build void __kmpc_kernel_prepare_parallel(
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001190 /// void *outlined_function, int16_t IsOMPRuntimeInitialized);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001191 llvm::Type *TypeParams[] = {CGM.Int8PtrTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001192 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001193 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1194 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_prepare_parallel");
1195 break;
1196 }
1197 case OMPRTL_NVPTX__kmpc_kernel_parallel: {
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001198 /// Build bool __kmpc_kernel_parallel(void **outlined_function,
1199 /// int16_t IsOMPRuntimeInitialized);
1200 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy, CGM.Int16Ty};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001201 llvm::Type *RetTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001202 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001203 llvm::FunctionType::get(RetTy, TypeParams, /*isVarArg*/ false);
1204 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_parallel");
1205 break;
1206 }
1207 case OMPRTL_NVPTX__kmpc_kernel_end_parallel: {
1208 /// Build void __kmpc_kernel_end_parallel();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001209 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001210 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1211 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_end_parallel");
1212 break;
1213 }
1214 case OMPRTL_NVPTX__kmpc_serialized_parallel: {
1215 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1216 // global_tid);
1217 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001218 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001219 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1220 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1221 break;
1222 }
1223 case OMPRTL_NVPTX__kmpc_end_serialized_parallel: {
1224 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1225 // global_tid);
1226 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001227 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001228 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1229 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1230 break;
1231 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001232 case OMPRTL_NVPTX__kmpc_shuffle_int32: {
1233 // Build int32_t __kmpc_shuffle_int32(int32_t element,
1234 // int16_t lane_offset, int16_t warp_size);
1235 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001236 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001237 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1238 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int32");
1239 break;
1240 }
1241 case OMPRTL_NVPTX__kmpc_shuffle_int64: {
1242 // Build int64_t __kmpc_shuffle_int64(int64_t element,
1243 // int16_t lane_offset, int16_t warp_size);
1244 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001245 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001246 llvm::FunctionType::get(CGM.Int64Ty, TypeParams, /*isVarArg*/ false);
1247 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int64");
1248 break;
1249 }
1250 case OMPRTL_NVPTX__kmpc_parallel_reduce_nowait: {
1251 // Build int32_t kmpc_nvptx_parallel_reduce_nowait(kmp_int32 global_tid,
1252 // kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
1253 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1254 // lane_offset, int16_t Algorithm Version),
1255 // void (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
1256 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1257 CGM.Int16Ty, CGM.Int16Ty};
1258 auto *ShuffleReduceFnTy =
1259 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1260 /*isVarArg=*/false);
1261 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1262 auto *InterWarpCopyFnTy =
1263 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1264 /*isVarArg=*/false);
1265 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1266 CGM.Int32Ty,
1267 CGM.SizeTy,
1268 CGM.VoidPtrTy,
1269 ShuffleReduceFnTy->getPointerTo(),
1270 InterWarpCopyFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001271 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001272 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1273 RTLFn = CGM.CreateRuntimeFunction(
1274 FnTy, /*Name=*/"__kmpc_nvptx_parallel_reduce_nowait");
1275 break;
1276 }
Alexey Bataevfac26cf2018-05-02 20:03:27 +00001277 case OMPRTL_NVPTX__kmpc_simd_reduce_nowait: {
1278 // Build int32_t kmpc_nvptx_simd_reduce_nowait(kmp_int32 global_tid,
1279 // kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
1280 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1281 // lane_offset, int16_t Algorithm Version),
1282 // void (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
1283 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1284 CGM.Int16Ty, CGM.Int16Ty};
1285 auto *ShuffleReduceFnTy =
1286 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1287 /*isVarArg=*/false);
1288 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1289 auto *InterWarpCopyFnTy =
1290 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1291 /*isVarArg=*/false);
1292 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1293 CGM.Int32Ty,
1294 CGM.SizeTy,
1295 CGM.VoidPtrTy,
1296 ShuffleReduceFnTy->getPointerTo(),
1297 InterWarpCopyFnTy->getPointerTo()};
1298 auto *FnTy =
1299 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1300 RTLFn = CGM.CreateRuntimeFunction(
1301 FnTy, /*Name=*/"__kmpc_nvptx_simd_reduce_nowait");
1302 break;
1303 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001304 case OMPRTL_NVPTX__kmpc_teams_reduce_nowait: {
1305 // Build int32_t __kmpc_nvptx_teams_reduce_nowait(int32_t global_tid,
1306 // int32_t num_vars, size_t reduce_size, void *reduce_data,
1307 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1308 // lane_offset, int16_t shortCircuit),
1309 // void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num),
1310 // void (*kmp_CopyToScratchpadFctPtr)(void *reduce_data, void * scratchpad,
1311 // int32_t index, int32_t width),
1312 // void (*kmp_LoadReduceFctPtr)(void *reduce_data, void * scratchpad,
1313 // int32_t index, int32_t width, int32_t reduce))
1314 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1315 CGM.Int16Ty, CGM.Int16Ty};
1316 auto *ShuffleReduceFnTy =
1317 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1318 /*isVarArg=*/false);
1319 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1320 auto *InterWarpCopyFnTy =
1321 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1322 /*isVarArg=*/false);
1323 llvm::Type *CopyToScratchpadTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy,
1324 CGM.Int32Ty, CGM.Int32Ty};
1325 auto *CopyToScratchpadFnTy =
1326 llvm::FunctionType::get(CGM.VoidTy, CopyToScratchpadTypeParams,
1327 /*isVarArg=*/false);
1328 llvm::Type *LoadReduceTypeParams[] = {
1329 CGM.VoidPtrTy, CGM.VoidPtrTy, CGM.Int32Ty, CGM.Int32Ty, CGM.Int32Ty};
1330 auto *LoadReduceFnTy =
1331 llvm::FunctionType::get(CGM.VoidTy, LoadReduceTypeParams,
1332 /*isVarArg=*/false);
1333 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1334 CGM.Int32Ty,
1335 CGM.SizeTy,
1336 CGM.VoidPtrTy,
1337 ShuffleReduceFnTy->getPointerTo(),
1338 InterWarpCopyFnTy->getPointerTo(),
1339 CopyToScratchpadFnTy->getPointerTo(),
1340 LoadReduceFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001341 auto *FnTy =
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001342 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1343 RTLFn = CGM.CreateRuntimeFunction(
1344 FnTy, /*Name=*/"__kmpc_nvptx_teams_reduce_nowait");
1345 break;
1346 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001347 case OMPRTL_NVPTX__kmpc_end_reduce_nowait: {
1348 // Build __kmpc_end_reduce_nowait(kmp_int32 global_tid);
1349 llvm::Type *TypeParams[] = {CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001350 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001351 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1352 RTLFn = CGM.CreateRuntimeFunction(
1353 FnTy, /*Name=*/"__kmpc_nvptx_end_reduce_nowait");
1354 break;
1355 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001356 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack: {
1357 /// Build void __kmpc_data_sharing_init_stack();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001358 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001359 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1360 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack");
1361 break;
1362 }
1363 case OMPRTL_NVPTX__kmpc_data_sharing_push_stack: {
1364 // Build void *__kmpc_data_sharing_push_stack(size_t size,
1365 // int16_t UseSharedMemory);
1366 llvm::Type *TypeParams[] = {CGM.SizeTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001367 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001368 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1369 RTLFn = CGM.CreateRuntimeFunction(
1370 FnTy, /*Name=*/"__kmpc_data_sharing_push_stack");
1371 break;
1372 }
1373 case OMPRTL_NVPTX__kmpc_data_sharing_pop_stack: {
1374 // Build void __kmpc_data_sharing_pop_stack(void *a);
1375 llvm::Type *TypeParams[] = {CGM.VoidPtrTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001376 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001377 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1378 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1379 /*Name=*/"__kmpc_data_sharing_pop_stack");
1380 break;
1381 }
1382 case OMPRTL_NVPTX__kmpc_begin_sharing_variables: {
1383 /// Build void __kmpc_begin_sharing_variables(void ***args,
1384 /// size_t n_args);
1385 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo(), CGM.SizeTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001386 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001387 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1388 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_begin_sharing_variables");
1389 break;
1390 }
1391 case OMPRTL_NVPTX__kmpc_end_sharing_variables: {
1392 /// Build void __kmpc_end_sharing_variables();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001393 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001394 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1395 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_sharing_variables");
1396 break;
1397 }
1398 case OMPRTL_NVPTX__kmpc_get_shared_variables: {
1399 /// Build void __kmpc_get_shared_variables(void ***GlobalArgs);
1400 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001401 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001402 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1403 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_shared_variables");
1404 break;
1405 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001406 case OMPRTL_NVPTX__kmpc_parallel_level: {
1407 // Build uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32 global_tid);
1408 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1409 auto *FnTy =
1410 llvm::FunctionType::get(CGM.Int16Ty, TypeParams, /*isVarArg*/ false);
1411 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_parallel_level");
1412 break;
1413 }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001414 }
1415 return RTLFn;
1416}
1417
1418void CGOpenMPRuntimeNVPTX::createOffloadEntry(llvm::Constant *ID,
1419 llvm::Constant *Addr,
Alexey Bataev03f270c2018-03-30 18:31:07 +00001420 uint64_t Size, int32_t,
1421 llvm::GlobalValue::LinkageTypes) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001422 // TODO: Add support for global variables on the device after declare target
1423 // support.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001424 if (!isa<llvm::Function>(Addr))
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001425 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +00001426 llvm::Module &M = CGM.getModule();
1427 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001428
1429 // Get "nvvm.annotations" metadata node
Alexey Bataev9ff80832018-04-16 20:16:21 +00001430 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001431
1432 llvm::Metadata *MDVals[] = {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001433 llvm::ConstantAsMetadata::get(Addr), llvm::MDString::get(Ctx, "kernel"),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001434 llvm::ConstantAsMetadata::get(
1435 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))};
1436 // Append metadata to nvvm.annotations
1437 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
1438}
1439
1440void CGOpenMPRuntimeNVPTX::emitTargetOutlinedFunction(
1441 const OMPExecutableDirective &D, StringRef ParentName,
1442 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001443 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001444 if (!IsOffloadEntry) // Nothing to do.
1445 return;
1446
1447 assert(!ParentName.empty() && "Invalid target region parent name!");
1448
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001449 bool Mode = supportsSPMDExecutionMode(CGM.getContext(), D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001450 if (Mode)
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001451 emitSpmdKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1452 CodeGen);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001453 else
1454 emitNonSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1455 CodeGen);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001456
1457 setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001458}
1459
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001460CGOpenMPRuntimeNVPTX::CGOpenMPRuntimeNVPTX(CodeGenModule &CGM)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001461 : CGOpenMPRuntime(CGM, "_", "$") {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001462 if (!CGM.getLangOpts().OpenMPIsDevice)
1463 llvm_unreachable("OpenMP NVPTX can only handle device code.");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001464}
Carlo Bertollic6872252016-04-04 15:55:02 +00001465
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001466void CGOpenMPRuntimeNVPTX::emitProcBindClause(CodeGenFunction &CGF,
1467 OpenMPProcBindClauseKind ProcBind,
1468 SourceLocation Loc) {
1469 // Do nothing in case of Spmd mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001470 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001471 return;
1472
1473 CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc);
1474}
1475
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001476void CGOpenMPRuntimeNVPTX::emitNumThreadsClause(CodeGenFunction &CGF,
1477 llvm::Value *NumThreads,
1478 SourceLocation Loc) {
1479 // Do nothing in case of Spmd mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001480 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001481 return;
1482
1483 CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc);
1484}
1485
Carlo Bertollic6872252016-04-04 15:55:02 +00001486void CGOpenMPRuntimeNVPTX::emitNumTeamsClause(CodeGenFunction &CGF,
1487 const Expr *NumTeams,
1488 const Expr *ThreadLimit,
1489 SourceLocation Loc) {}
1490
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001491llvm::Value *CGOpenMPRuntimeNVPTX::emitParallelOutlinedFunction(
1492 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1493 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00001494 SourceLocation Loc = D.getLocStart();
1495
1496 // Emit target region as a standalone region.
1497 class NVPTXPrePostActionTy : public PrePostActionTy {
1498 SourceLocation &Loc;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001499 bool &IsInParallelRegion;
1500 bool PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001501
1502 public:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001503 NVPTXPrePostActionTy(SourceLocation &Loc, bool &IsInParallelRegion)
1504 : Loc(Loc), IsInParallelRegion(IsInParallelRegion) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00001505 void Enter(CodeGenFunction &CGF) override {
1506 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
1507 .emitGenericVarsProlog(CGF, Loc);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001508 PrevIsInParallelRegion = IsInParallelRegion;
1509 IsInParallelRegion = true;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001510 }
1511 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001512 IsInParallelRegion = PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001513 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
1514 .emitGenericVarsEpilog(CGF);
1515 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001516 } Action(Loc, IsInParallelRegion);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001517 CodeGen.setAction(Action);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001518 bool PrevIsInTargetMasterThreadRegion = IsInTargetMasterThreadRegion;
1519 IsInTargetMasterThreadRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001520 auto *OutlinedFun =
1521 cast<llvm::Function>(CGOpenMPRuntime::emitParallelOutlinedFunction(
1522 D, ThreadIDVar, InnermostKind, CodeGen));
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001523 IsInTargetMasterThreadRegion = PrevIsInTargetMasterThreadRegion;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001524 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD &&
1525 !IsInParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001526 llvm::Function *WrapperFun =
1527 createParallelDataSharingWrapper(OutlinedFun, D);
1528 WrapperFunctionsMap[OutlinedFun] = WrapperFun;
1529 }
1530
1531 return OutlinedFun;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001532}
1533
1534llvm::Value *CGOpenMPRuntimeNVPTX::emitTeamsOutlinedFunction(
Carlo Bertollic6872252016-04-04 15:55:02 +00001535 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1536 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00001537 SourceLocation Loc = D.getLocStart();
Carlo Bertollic6872252016-04-04 15:55:02 +00001538
Alexey Bataevc99042b2018-03-15 18:10:54 +00001539 // Emit target region as a standalone region.
1540 class NVPTXPrePostActionTy : public PrePostActionTy {
1541 SourceLocation &Loc;
1542
1543 public:
1544 NVPTXPrePostActionTy(SourceLocation &Loc) : Loc(Loc) {}
1545 void Enter(CodeGenFunction &CGF) override {
1546 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
1547 .emitGenericVarsProlog(CGF, Loc);
1548 }
1549 void Exit(CodeGenFunction &CGF) override {
1550 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
1551 .emitGenericVarsEpilog(CGF);
1552 }
1553 } Action(Loc);
1554 CodeGen.setAction(Action);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001555 llvm::Value *OutlinedFunVal = CGOpenMPRuntime::emitTeamsOutlinedFunction(
1556 D, ThreadIDVar, InnermostKind, CodeGen);
1557 llvm::Function *OutlinedFun = cast<llvm::Function>(OutlinedFunVal);
1558 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001559 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001560 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
Carlo Bertollic6872252016-04-04 15:55:02 +00001561
1562 return OutlinedFun;
1563}
1564
Alexey Bataevc99042b2018-03-15 18:10:54 +00001565void CGOpenMPRuntimeNVPTX::emitGenericVarsProlog(CodeGenFunction &CGF,
1566 SourceLocation Loc) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001567 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
1568 return;
1569
Alexey Bataevc99042b2018-03-15 18:10:54 +00001570 CGBuilderTy &Bld = CGF.Builder;
1571
1572 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
1573 if (I == FunctionGlobalizedDecls.end())
1574 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001575 if (const RecordDecl *GlobalizedVarsRecord = I->getSecond().GlobalRecord) {
1576 QualType RecTy = CGM.getContext().getRecordType(GlobalizedVarsRecord);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001577
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001578 // Recover pointer to this function's global record. The runtime will
1579 // handle the specifics of the allocation of the memory.
1580 // Use actual memory size of the record including the padding
1581 // for alignment purposes.
1582 unsigned Alignment =
1583 CGM.getContext().getTypeAlignInChars(RecTy).getQuantity();
1584 unsigned GlobalRecordSize =
1585 CGM.getContext().getTypeSizeInChars(RecTy).getQuantity();
1586 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
1587 // TODO: allow the usage of shared memory to be controlled by
1588 // the user, for now, default to global.
1589 llvm::Value *GlobalRecordSizeArg[] = {
1590 llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize),
1591 CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
1592 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
1593 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_push_stack),
1594 GlobalRecordSizeArg);
1595 llvm::Value *GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
1596 GlobalRecValue, CGF.ConvertTypeForMem(RecTy)->getPointerTo());
1597 LValue Base =
1598 CGF.MakeNaturalAlignPointeeAddrLValue(GlobalRecCastAddr, RecTy);
1599 I->getSecond().GlobalRecordAddr = GlobalRecValue;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001600
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001601 // Emit the "global alloca" which is a GEP from the global declaration
1602 // record using the pointer returned by the runtime.
1603 for (auto &Rec : I->getSecond().LocalVarData) {
1604 bool EscapedParam = I->getSecond().EscapedParameters.count(Rec.first);
1605 llvm::Value *ParValue;
1606 if (EscapedParam) {
1607 const auto *VD = cast<VarDecl>(Rec.first);
1608 LValue ParLVal =
1609 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
1610 ParValue = CGF.EmitLoadOfScalar(ParLVal, Loc);
1611 }
1612 const FieldDecl *FD = Rec.second.first;
1613 LValue VarAddr = CGF.EmitLValueForField(Base, FD);
1614 Rec.second.second = VarAddr.getAddress();
1615 if (EscapedParam) {
1616 const auto *VD = cast<VarDecl>(Rec.first);
1617 CGF.EmitStoreOfScalar(ParValue, VarAddr);
1618 I->getSecond().MappedParams->setVarAddr(CGF, VD, VarAddr.getAddress());
1619 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00001620 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001621 }
1622 for (const ValueDecl *VD : I->getSecond().EscapedVariableLengthDecls) {
1623 // Recover pointer to this function's global record. The runtime will
1624 // handle the specifics of the allocation of the memory.
1625 // Use actual memory size of the record including the padding
1626 // for alignment purposes.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001627 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001628 llvm::Value *Size = CGF.getTypeSize(VD->getType());
1629 CharUnits Align = CGM.getContext().getDeclAlign(VD);
1630 Size = Bld.CreateNUWAdd(
1631 Size, llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity() - 1));
1632 llvm::Value *AlignVal =
1633 llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity());
1634 Size = Bld.CreateUDiv(Size, AlignVal);
1635 Size = Bld.CreateNUWMul(Size, AlignVal);
1636 // TODO: allow the usage of shared memory to be controlled by
1637 // the user, for now, default to global.
1638 llvm::Value *GlobalRecordSizeArg[] = {
1639 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
1640 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
1641 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_push_stack),
1642 GlobalRecordSizeArg);
1643 llvm::Value *GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
1644 GlobalRecValue, CGF.ConvertTypeForMem(VD->getType())->getPointerTo());
1645 LValue Base = CGF.MakeAddrLValue(GlobalRecCastAddr, VD->getType(),
1646 CGM.getContext().getDeclAlign(VD),
1647 AlignmentSource::Decl);
1648 I->getSecond().MappedParams->setVarAddr(CGF, cast<VarDecl>(VD),
1649 Base.getAddress());
1650 I->getSecond().EscapedVariableLengthDeclsAddrs.emplace_back(GlobalRecValue);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001651 }
1652 I->getSecond().MappedParams->apply(CGF);
1653}
1654
1655void CGOpenMPRuntimeNVPTX::emitGenericVarsEpilog(CodeGenFunction &CGF) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001656 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
1657 return;
1658
Alexey Bataevc99042b2018-03-15 18:10:54 +00001659 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001660 if (I != FunctionGlobalizedDecls.end()) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00001661 I->getSecond().MappedParams->restore(CGF);
1662 if (!CGF.HaveInsertPoint())
1663 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001664 for (llvm::Value *Addr :
1665 llvm::reverse(I->getSecond().EscapedVariableLengthDeclsAddrs)) {
1666 CGF.EmitRuntimeCall(
1667 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
1668 Addr);
1669 }
1670 if (I->getSecond().GlobalRecordAddr) {
1671 CGF.EmitRuntimeCall(
1672 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
1673 I->getSecond().GlobalRecordAddr);
1674 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00001675 }
1676}
1677
Carlo Bertollic6872252016-04-04 15:55:02 +00001678void CGOpenMPRuntimeNVPTX::emitTeamsCall(CodeGenFunction &CGF,
1679 const OMPExecutableDirective &D,
1680 SourceLocation Loc,
1681 llvm::Value *OutlinedFn,
1682 ArrayRef<llvm::Value *> CapturedVars) {
1683 if (!CGF.HaveInsertPoint())
1684 return;
1685
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001686 Address ZeroAddr = CGF.CreateMemTemp(
1687 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
1688 /*Name*/ ".zero.addr");
Carlo Bertollic6872252016-04-04 15:55:02 +00001689 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
1690 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001691 OutlinedFnArgs.push_back(emitThreadIDAddress(CGF, Loc).getPointer());
Carlo Bertollic6872252016-04-04 15:55:02 +00001692 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
1693 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00001694 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Carlo Bertollic6872252016-04-04 15:55:02 +00001695}
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001696
1697void CGOpenMPRuntimeNVPTX::emitParallelCall(
1698 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
1699 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
1700 if (!CGF.HaveInsertPoint())
1701 return;
1702
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001703 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001704 emitSpmdParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
1705 else
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001706 emitNonSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001707}
1708
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001709void CGOpenMPRuntimeNVPTX::emitNonSPMDParallelCall(
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001710 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
1711 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
1712 llvm::Function *Fn = cast<llvm::Function>(OutlinedFn);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001713
1714 // Force inline this outlined function at its call site.
1715 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
1716
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001717 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
1718 /*DestWidth=*/32, /*Signed=*/1),
1719 ".zero.addr");
1720 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
1721 Address ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
1722 auto &&CodeGen = [this, Fn, CapturedVars, Loc, ZeroAddr, ThreadIDAddr](
1723 CodeGenFunction &CGF, PrePostActionTy &Action) {
1724 Action.Enter(CGF);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001725
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001726 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
1727 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
1728 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
1729 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
1730 emitOutlinedFunctionCall(CGF, Loc, Fn, OutlinedFnArgs);
1731 };
1732 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
1733 PrePostActionTy &) {
1734
1735 RegionCodeGenTy RCG(CodeGen);
1736 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
1737 llvm::Value *ThreadID = getThreadID(CGF, Loc);
1738 llvm::Value *Args[] = {RTLoc, ThreadID};
1739
1740 NVPTXActionTy Action(
1741 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
1742 Args,
1743 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
1744 Args);
1745 RCG.setAction(Action);
1746 RCG(CGF);
1747 };
1748
1749 auto &&L0ParallelGen = [this, CapturedVars, Fn](CodeGenFunction &CGF,
1750 PrePostActionTy &Action) {
1751 CGBuilderTy &Bld = CGF.Builder;
1752 llvm::Function *WFn = WrapperFunctionsMap[Fn];
1753 assert(WFn && "Wrapper function does not exist!");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001754 llvm::Value *ID = Bld.CreateBitOrPointerCast(WFn, CGM.Int8PtrTy);
1755
1756 // Prepare for parallel region. Indicate the outlined function.
1757 llvm::Value *Args[] = {ID, /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001758 CGF.EmitRuntimeCall(
1759 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_prepare_parallel),
1760 Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001761
1762 // Create a private scope that will globalize the arguments
1763 // passed from the outside of the target region.
1764 CodeGenFunction::OMPPrivateScope PrivateArgScope(CGF);
1765
1766 // There's somehting to share.
1767 if (!CapturedVars.empty()) {
1768 // Prepare for parallel region. Indicate the outlined function.
1769 Address SharedArgs =
1770 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "shared_arg_refs");
1771 llvm::Value *SharedArgsPtr = SharedArgs.getPointer();
1772
1773 llvm::Value *DataSharingArgs[] = {
1774 SharedArgsPtr,
1775 llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size())};
1776 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1777 OMPRTL_NVPTX__kmpc_begin_sharing_variables),
1778 DataSharingArgs);
1779
1780 // Store variable address in a list of references to pass to workers.
1781 unsigned Idx = 0;
1782 ASTContext &Ctx = CGF.getContext();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001783 Address SharedArgListAddress = CGF.EmitLoadOfPointer(
1784 SharedArgs, Ctx.getPointerType(Ctx.getPointerType(Ctx.VoidPtrTy))
1785 .castAs<PointerType>());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001786 for (llvm::Value *V : CapturedVars) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001787 Address Dst = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
1788 CGF.getPointerSize());
1789 llvm::Value *PtrV;
Alexey Bataev17314212018-03-20 15:41:05 +00001790 if (V->getType()->isIntegerTy())
1791 PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
1792 else
1793 PtrV = Bld.CreatePointerBitCastOrAddrSpaceCast(V, CGF.VoidPtrTy);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001794 CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
1795 Ctx.getPointerType(Ctx.VoidPtrTy));
Alexey Bataevc99042b2018-03-15 18:10:54 +00001796 ++Idx;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001797 }
1798 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001799
1800 // Activate workers. This barrier is used by the master to signal
1801 // work for the workers.
1802 syncCTAThreads(CGF);
1803
1804 // OpenMP [2.5, Parallel Construct, p.49]
1805 // There is an implied barrier at the end of a parallel region. After the
1806 // end of a parallel region, only the master thread of the team resumes
1807 // execution of the enclosing task region.
1808 //
1809 // The master waits at this barrier until all workers are done.
1810 syncCTAThreads(CGF);
1811
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001812 if (!CapturedVars.empty())
1813 CGF.EmitRuntimeCall(
1814 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_sharing_variables));
1815
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001816 // Remember for post-processing in worker loop.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001817 Work.emplace_back(WFn);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001818 };
1819
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001820 auto &&LNParallelGen = [this, Loc, &SeqGen, &L0ParallelGen, &CodeGen](
1821 CodeGenFunction &CGF, PrePostActionTy &Action) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001822 RegionCodeGenTy RCG(CodeGen);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001823 if (IsInParallelRegion) {
1824 SeqGen(CGF, Action);
1825 } else if (IsInTargetMasterThreadRegion) {
1826 L0ParallelGen(CGF, Action);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001827 } else if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_NonSPMD) {
1828 RCG(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001829 } else {
1830 // Check for master and then parallelism:
1831 // if (is_master) {
1832 // Worker call.
1833 // } else if (__kmpc_parallel_level(loc, gtid)) {
1834 // Serialized execution.
1835 // } else {
1836 // Outlined function call.
1837 // }
1838 CGBuilderTy &Bld = CGF.Builder;
1839 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001840 llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
1841 llvm::BasicBlock *ParallelCheckBB =
1842 CGF.createBasicBlock(".parallelcheck");
1843 llvm::Value *IsMaster =
1844 Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
1845 Bld.CreateCondBr(IsMaster, MasterCheckBB, ParallelCheckBB);
1846 CGF.EmitBlock(MasterCheckBB);
1847 L0ParallelGen(CGF, Action);
1848 CGF.EmitBranch(ExitBB);
1849 // There is no need to emit line number for unconditional branch.
1850 (void)ApplyDebugLocation::CreateEmpty(CGF);
1851 CGF.EmitBlock(ParallelCheckBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001852 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
1853 llvm::Value *ThreadID = getThreadID(CGF, Loc);
1854 llvm::Value *PL = CGF.EmitRuntimeCall(
1855 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
1856 {RTLoc, ThreadID});
1857 llvm::Value *Res = Bld.CreateIsNotNull(PL);
1858 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("omp_if.then");
1859 llvm::BasicBlock *ElseBlock = CGF.createBasicBlock("omp_if.else");
1860 Bld.CreateCondBr(Res, ThenBlock, ElseBlock);
1861 // Emit the 'then' code.
1862 CGF.EmitBlock(ThenBlock);
1863 SeqGen(CGF, Action);
1864 // There is no need to emit line number for unconditional branch.
1865 (void)ApplyDebugLocation::CreateEmpty(CGF);
1866 // Emit the 'else' code.
1867 CGF.EmitBlock(ElseBlock);
1868 RCG(CGF);
1869 // There is no need to emit line number for unconditional branch.
1870 (void)ApplyDebugLocation::CreateEmpty(CGF);
1871 // Emit the continuation block for code after the if.
1872 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1873 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001874 };
1875
Alexey Bataev9ff80832018-04-16 20:16:21 +00001876 if (IfCond) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001877 emitOMPIfClause(CGF, IfCond, LNParallelGen, SeqGen);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001878 } else {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001879 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001880 RegionCodeGenTy ThenRCG(LNParallelGen);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001881 ThenRCG(CGF);
1882 }
1883}
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001884
1885void CGOpenMPRuntimeNVPTX::emitSpmdParallelCall(
1886 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
1887 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
1888 // Just call the outlined function to execute the parallel region.
1889 // OutlinedFn(&GTid, &zero, CapturedStruct);
1890 //
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001891 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Carlo Bertolli79712092018-02-28 20:48:35 +00001892
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001893 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
1894 /*DestWidth=*/32, /*Signed=*/1),
1895 ".zero.addr");
Carlo Bertolli79712092018-02-28 20:48:35 +00001896 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001897 Address ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
1898 auto &&CodeGen = [this, OutlinedFn, CapturedVars, Loc, ZeroAddr,
1899 ThreadIDAddr](CodeGenFunction &CGF,
1900 PrePostActionTy &Action) {
1901 Action.Enter(CGF);
1902
1903 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
1904 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
1905 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
1906 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
1907 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
1908 };
1909 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
1910 PrePostActionTy &) {
1911
1912 RegionCodeGenTy RCG(CodeGen);
1913 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
1914 llvm::Value *ThreadID = getThreadID(CGF, Loc);
1915 llvm::Value *Args[] = {RTLoc, ThreadID};
1916
1917 NVPTXActionTy Action(
1918 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
1919 Args,
1920 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
1921 Args);
1922 RCG.setAction(Action);
1923 RCG(CGF);
1924 };
1925
1926 if (IsInTargetMasterThreadRegion) {
1927 RegionCodeGenTy RCG(CodeGen);
1928 RCG(CGF);
1929 } else {
1930 // If we are not in the target region, it is definitely L2 parallelism or
1931 // more, because for SPMD mode we always has L1 parallel level, sowe don't
1932 // need to check for orphaned directives.
1933 RegionCodeGenTy RCG(SeqGen);
1934 RCG(CGF);
1935 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001936}
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001937
Alexey Bataev504fc2d2018-05-07 17:23:05 +00001938void CGOpenMPRuntimeNVPTX::emitCriticalRegion(
1939 CodeGenFunction &CGF, StringRef CriticalName,
1940 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
1941 const Expr *Hint) {
1942 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
1943 llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
1944 llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
1945 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
1946 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
1947
1948 // Fetch team-local id of the thread.
1949 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
1950
1951 // Get the width of the team.
1952 llvm::Value *TeamWidth = getNVPTXNumThreads(CGF);
1953
1954 // Initialize the counter variable for the loop.
1955 QualType Int32Ty =
1956 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
1957 Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
1958 LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
1959 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
1960 /*isInit=*/true);
1961
1962 // Block checks if loop counter exceeds upper bound.
1963 CGF.EmitBlock(LoopBB);
1964 llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
1965 llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
1966 CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
1967
1968 // Block tests which single thread should execute region, and which threads
1969 // should go straight to synchronisation point.
1970 CGF.EmitBlock(TestBB);
1971 CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
1972 llvm::Value *CmpThreadToCounter =
1973 CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
1974 CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
1975
1976 // Block emits the body of the critical region.
1977 CGF.EmitBlock(BodyBB);
1978
1979 // Output the critical statement.
1980 CriticalOpGen(CGF);
1981
1982 // After the body surrounded by the critical region, the single executing
1983 // thread will jump to the synchronisation point.
1984 // Block waits for all threads in current team to finish then increments the
1985 // counter variable and returns to the loop.
1986 CGF.EmitBlock(SyncBB);
1987 getNVPTXCTABarrier(CGF);
1988
1989 llvm::Value *IncCounterVal =
1990 CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
1991 CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
1992 CGF.EmitBranch(LoopBB);
1993
1994 // Block that is reached when all threads in the team complete the region.
1995 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1996}
1997
Alexey Bataevb2575932018-01-04 20:18:55 +00001998/// Cast value to the specified type.
Alexey Bataeva453f362018-03-19 17:53:56 +00001999static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
2000 QualType ValTy, QualType CastTy,
2001 SourceLocation Loc) {
2002 assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
2003 "Cast type must sized.");
2004 assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
2005 "Val type must sized.");
2006 llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
2007 if (ValTy == CastTy)
Alexey Bataevb2575932018-01-04 20:18:55 +00002008 return Val;
Alexey Bataeva453f362018-03-19 17:53:56 +00002009 if (CGF.getContext().getTypeSizeInChars(ValTy) ==
2010 CGF.getContext().getTypeSizeInChars(CastTy))
2011 return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
2012 if (CastTy->isIntegerType() && ValTy->isIntegerType())
2013 return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
2014 CastTy->hasSignedIntegerRepresentation());
2015 Address CastItem = CGF.CreateMemTemp(CastTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002016 Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2017 CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
Alexey Bataeva453f362018-03-19 17:53:56 +00002018 CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy);
2019 return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc);
Alexey Bataevb2575932018-01-04 20:18:55 +00002020}
2021
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002022/// This function creates calls to one of two shuffle functions to copy
2023/// variables between lanes in a warp.
2024static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002025 llvm::Value *Elem,
Alexey Bataeva453f362018-03-19 17:53:56 +00002026 QualType ElemType,
2027 llvm::Value *Offset,
2028 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002029 CodeGenModule &CGM = CGF.CGM;
2030 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002031 CGOpenMPRuntimeNVPTX &RT =
2032 *(static_cast<CGOpenMPRuntimeNVPTX *>(&CGM.getOpenMPRuntime()));
2033
Alexey Bataeva453f362018-03-19 17:53:56 +00002034 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2035 assert(Size.getQuantity() <= 8 &&
2036 "Unsupported bitwidth in shuffle instruction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002037
Alexey Bataeva453f362018-03-19 17:53:56 +00002038 OpenMPRTLFunctionNVPTX ShuffleFn = Size.getQuantity() <= 4
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002039 ? OMPRTL_NVPTX__kmpc_shuffle_int32
2040 : OMPRTL_NVPTX__kmpc_shuffle_int64;
2041
2042 // Cast all types to 32- or 64-bit values before calling shuffle routines.
Alexey Bataeva453f362018-03-19 17:53:56 +00002043 QualType CastTy = CGF.getContext().getIntTypeForBitwidth(
2044 Size.getQuantity() <= 4 ? 32 : 64, /*Signed=*/1);
2045 llvm::Value *ElemCast = castValueToType(CGF, Elem, ElemType, CastTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002046 llvm::Value *WarpSize =
Alexey Bataevb2575932018-01-04 20:18:55 +00002047 Bld.CreateIntCast(getNVPTXWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002048
Alexey Bataev9ff80832018-04-16 20:16:21 +00002049 llvm::Value *ShuffledVal = CGF.EmitRuntimeCall(
2050 RT.createNVPTXRuntimeFunction(ShuffleFn), {ElemCast, Offset, WarpSize});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002051
Alexey Bataeva453f362018-03-19 17:53:56 +00002052 return castValueToType(CGF, ShuffledVal, CastTy, ElemType, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002053}
2054
2055namespace {
2056enum CopyAction : unsigned {
2057 // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
2058 // the warp using shuffle instructions.
2059 RemoteLaneToThread,
2060 // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
2061 ThreadCopy,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002062 // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
2063 ThreadToScratchpad,
2064 // ScratchpadToThread: Copy from a scratchpad array in global memory
2065 // containing team-reduced data to a thread's stack.
2066 ScratchpadToThread,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002067};
2068} // namespace
2069
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002070struct CopyOptionsTy {
2071 llvm::Value *RemoteLaneOffset;
2072 llvm::Value *ScratchpadIndex;
2073 llvm::Value *ScratchpadWidth;
2074};
2075
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002076/// Emit instructions to copy a Reduce list, which contains partially
2077/// aggregated values, in the specified direction.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002078static void emitReductionListCopy(
2079 CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
2080 ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
2081 CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002082
Alexey Bataev9ff80832018-04-16 20:16:21 +00002083 CodeGenModule &CGM = CGF.CGM;
2084 ASTContext &C = CGM.getContext();
2085 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002086
Alexey Bataev9ff80832018-04-16 20:16:21 +00002087 llvm::Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
2088 llvm::Value *ScratchpadIndex = CopyOptions.ScratchpadIndex;
2089 llvm::Value *ScratchpadWidth = CopyOptions.ScratchpadWidth;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002090
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002091 // Iterates, element-by-element, through the source Reduce list and
2092 // make a copy.
2093 unsigned Idx = 0;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002094 unsigned Size = Privates.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00002095 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002096 Address SrcElementAddr = Address::invalid();
2097 Address DestElementAddr = Address::invalid();
2098 Address DestElementPtrAddr = Address::invalid();
2099 // Should we shuffle in an element from a remote lane?
2100 bool ShuffleInElement = false;
2101 // Set to true to update the pointer in the dest Reduce list to a
2102 // newly created element.
2103 bool UpdateDestListPtr = false;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002104 // Increment the src or dest pointer to the scratchpad, for each
2105 // new element.
2106 bool IncrScratchpadSrc = false;
2107 bool IncrScratchpadDest = false;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002108
2109 switch (Action) {
2110 case RemoteLaneToThread: {
2111 // Step 1.1: Get the address for the src element in the Reduce list.
2112 Address SrcElementPtrAddr =
2113 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002114 SrcElementAddr = CGF.EmitLoadOfPointer(
2115 SrcElementPtrAddr,
2116 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002117
2118 // Step 1.2: Create a temporary to store the element in the destination
2119 // Reduce list.
2120 DestElementPtrAddr =
2121 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
2122 DestElementAddr =
2123 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2124 ShuffleInElement = true;
2125 UpdateDestListPtr = true;
2126 break;
2127 }
2128 case ThreadCopy: {
2129 // Step 1.1: Get the address for the src element in the Reduce list.
2130 Address SrcElementPtrAddr =
2131 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002132 SrcElementAddr = CGF.EmitLoadOfPointer(
2133 SrcElementPtrAddr,
2134 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002135
2136 // Step 1.2: Get the address for dest element. The destination
2137 // element has already been created on the thread's stack.
2138 DestElementPtrAddr =
2139 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002140 DestElementAddr = CGF.EmitLoadOfPointer(
2141 DestElementPtrAddr,
2142 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002143 break;
2144 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002145 case ThreadToScratchpad: {
2146 // Step 1.1: Get the address for the src element in the Reduce list.
2147 Address SrcElementPtrAddr =
2148 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002149 SrcElementAddr = CGF.EmitLoadOfPointer(
2150 SrcElementPtrAddr,
2151 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002152
2153 // Step 1.2: Get the address for dest element:
2154 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00002155 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00002156 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002157 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002158 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002159 Bld.CreateNUWAdd(DestBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002160 ScratchPadElemAbsolutePtrVal =
2161 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002162 DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
2163 C.getTypeAlignInChars(Private->getType()));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002164 IncrScratchpadDest = true;
2165 break;
2166 }
2167 case ScratchpadToThread: {
2168 // Step 1.1: Get the address for the src element in the scratchpad.
2169 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00002170 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00002171 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002172 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002173 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002174 Bld.CreateNUWAdd(SrcBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002175 ScratchPadElemAbsolutePtrVal =
2176 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
2177 SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
2178 C.getTypeAlignInChars(Private->getType()));
2179 IncrScratchpadSrc = true;
2180
2181 // Step 1.2: Create a temporary to store the element in the destination
2182 // Reduce list.
2183 DestElementPtrAddr =
2184 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
2185 DestElementAddr =
2186 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2187 UpdateDestListPtr = true;
2188 break;
2189 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002190 }
2191
2192 // Regardless of src and dest of copy, we emit the load of src
2193 // element as this is required in all directions
2194 SrcElementAddr = Bld.CreateElementBitCast(
2195 SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
2196 llvm::Value *Elem =
2197 CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002198 Private->getType(), Private->getExprLoc());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002199
2200 // Now that all active lanes have read the element in the
2201 // Reduce list, shuffle over the value from the remote lane.
Alexey Bataeva453f362018-03-19 17:53:56 +00002202 if (ShuffleInElement) {
2203 Elem =
2204 createRuntimeShuffleFunction(CGF, Elem, Private->getType(),
2205 RemoteLaneOffset, Private->getExprLoc());
2206 }
Alexey Bataevb2575932018-01-04 20:18:55 +00002207
2208 DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
2209 SrcElementAddr.getElementType());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002210
2211 // Store the source element value to the dest element address.
2212 CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false,
2213 Private->getType());
2214
2215 // Step 3.1: Modify reference in dest Reduce list as needed.
2216 // Modifying the reference in Reduce list to point to the newly
2217 // created element. The element is live in the current function
2218 // scope and that of functions it invokes (i.e., reduce_function).
2219 // RemoteReduceData[i] = (void*)&RemoteElem
2220 if (UpdateDestListPtr) {
2221 CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
2222 DestElementAddr.getPointer(), CGF.VoidPtrTy),
2223 DestElementPtrAddr, /*Volatile=*/false,
2224 C.VoidPtrTy);
2225 }
2226
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002227 // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
2228 // address of the next element in scratchpad memory, unless we're currently
2229 // processing the last one. Memory alignment is also taken care of here.
2230 if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
2231 llvm::Value *ScratchpadBasePtr =
2232 IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
Alexey Bataeve290ec02018-04-06 16:03:36 +00002233 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
2234 ScratchpadBasePtr = Bld.CreateNUWAdd(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002235 ScratchpadBasePtr,
Alexey Bataeve290ec02018-04-06 16:03:36 +00002236 Bld.CreateNUWMul(ScratchpadWidth, ElementSizeInChars));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002237
2238 // Take care of global memory alignment for performance
Alexey Bataeve290ec02018-04-06 16:03:36 +00002239 ScratchpadBasePtr = Bld.CreateNUWSub(
2240 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
2241 ScratchpadBasePtr = Bld.CreateUDiv(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002242 ScratchpadBasePtr,
2243 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
Alexey Bataeve290ec02018-04-06 16:03:36 +00002244 ScratchpadBasePtr = Bld.CreateNUWAdd(
2245 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
2246 ScratchpadBasePtr = Bld.CreateNUWMul(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002247 ScratchpadBasePtr,
2248 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
2249
2250 if (IncrScratchpadDest)
2251 DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
2252 else /* IncrScratchpadSrc = true */
2253 SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
2254 }
2255
Alexey Bataev9ff80832018-04-16 20:16:21 +00002256 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002257 }
2258}
2259
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002260/// This function emits a helper that loads data from the scratchpad array
2261/// and (optionally) reduces it with the input operand.
2262///
2263/// load_and_reduce(local, scratchpad, index, width, should_reduce)
2264/// reduce_data remote;
2265/// for elem in remote:
2266/// remote.elem = Scratchpad[elem_id][index]
2267/// if (should_reduce)
2268/// local = local @ remote
2269/// else
2270/// local = remote
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002271static llvm::Value *emitReduceScratchpadFunction(
2272 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
2273 QualType ReductionArrayTy, llvm::Value *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002274 ASTContext &C = CGM.getContext();
2275 QualType Int32Ty = C.getIntTypeForBitwidth(32, /*Signed=*/1);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002276
2277 // Destination of the copy.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002278 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2279 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002280 // Base address of the scratchpad array, with each element storing a
2281 // Reduce list per team.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002282 ImplicitParamDecl ScratchPadArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2283 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002284 // A source index into the scratchpad array.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002285 ImplicitParamDecl IndexArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
2286 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002287 // Row width of an element in the scratchpad array, typically
2288 // the number of teams.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002289 ImplicitParamDecl WidthArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
2290 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002291 // If should_reduce == 1, then it's load AND reduce,
2292 // If should_reduce == 0 (or otherwise), then it only loads (+ copy).
2293 // The latter case is used for initialization.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002294 ImplicitParamDecl ShouldReduceArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2295 Int32Ty, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002296
2297 FunctionArgList Args;
2298 Args.push_back(&ReduceListArg);
2299 Args.push_back(&ScratchPadArg);
2300 Args.push_back(&IndexArg);
2301 Args.push_back(&WidthArg);
2302 Args.push_back(&ShouldReduceArg);
2303
Alexey Bataev9ff80832018-04-16 20:16:21 +00002304 const CGFunctionInfo &CGFI =
2305 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002306 auto *Fn = llvm::Function::Create(
2307 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2308 "_omp_reduction_load_and_reduce", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002309 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002310 Fn->setDoesNotRecurse();
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002311 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002312 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002313
Alexey Bataev9ff80832018-04-16 20:16:21 +00002314 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002315
2316 // Get local Reduce list pointer.
2317 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2318 Address ReduceListAddr(
2319 Bld.CreatePointerBitCastOrAddrSpaceCast(
2320 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002321 C.VoidPtrTy, Loc),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002322 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
2323 CGF.getPointerAlign());
2324
2325 Address AddrScratchPadArg = CGF.GetAddrOfLocalVar(&ScratchPadArg);
2326 llvm::Value *ScratchPadBase = CGF.EmitLoadOfScalar(
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002327 AddrScratchPadArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002328
2329 Address AddrIndexArg = CGF.GetAddrOfLocalVar(&IndexArg);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002330 llvm::Value *IndexVal = Bld.CreateIntCast(
2331 CGF.EmitLoadOfScalar(AddrIndexArg, /*Volatile=*/false, Int32Ty, Loc),
2332 CGM.SizeTy, /*isSigned=*/true);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002333
2334 Address AddrWidthArg = CGF.GetAddrOfLocalVar(&WidthArg);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002335 llvm::Value *WidthVal = Bld.CreateIntCast(
2336 CGF.EmitLoadOfScalar(AddrWidthArg, /*Volatile=*/false, Int32Ty, Loc),
2337 CGM.SizeTy, /*isSigned=*/true);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002338
2339 Address AddrShouldReduceArg = CGF.GetAddrOfLocalVar(&ShouldReduceArg);
2340 llvm::Value *ShouldReduceVal = CGF.EmitLoadOfScalar(
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002341 AddrShouldReduceArg, /*Volatile=*/false, Int32Ty, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002342
2343 // The absolute ptr address to the base addr of the next element to copy.
2344 llvm::Value *CumulativeElemBasePtr =
2345 Bld.CreatePtrToInt(ScratchPadBase, CGM.SizeTy);
2346 Address SrcDataAddr(CumulativeElemBasePtr, CGF.getPointerAlign());
2347
2348 // Create a Remote Reduce list to store the elements read from the
2349 // scratchpad array.
2350 Address RemoteReduceList =
2351 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_red_list");
2352
2353 // Assemble remote Reduce list from scratchpad array.
2354 emitReductionListCopy(ScratchpadToThread, CGF, ReductionArrayTy, Privates,
2355 SrcDataAddr, RemoteReduceList,
2356 {/*RemoteLaneOffset=*/nullptr,
2357 /*ScratchpadIndex=*/IndexVal,
2358 /*ScratchpadWidth=*/WidthVal});
2359
2360 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
2361 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
2362 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
2363
Alexey Bataev9ff80832018-04-16 20:16:21 +00002364 llvm::Value *CondReduce = Bld.CreateIsNotNull(ShouldReduceVal);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002365 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
2366
2367 CGF.EmitBlock(ThenBB);
2368 // We should reduce with the local Reduce list.
2369 // reduce_function(LocalReduceList, RemoteReduceList)
2370 llvm::Value *LocalDataPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2371 ReduceListAddr.getPointer(), CGF.VoidPtrTy);
2372 llvm::Value *RemoteDataPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2373 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002374 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
2375 CGF, Loc, ReduceFn, {LocalDataPtr, RemoteDataPtr});
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002376 Bld.CreateBr(MergeBB);
2377
2378 CGF.EmitBlock(ElseBB);
2379 // No reduction; just copy:
2380 // Local Reduce list = Remote Reduce list.
2381 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
2382 RemoteReduceList, ReduceListAddr);
2383 Bld.CreateBr(MergeBB);
2384
2385 CGF.EmitBlock(MergeBB);
2386
2387 CGF.FinishFunction();
2388 return Fn;
2389}
2390
2391/// This function emits a helper that stores reduced data from the team
2392/// master to a scratchpad array in global memory.
2393///
2394/// for elem in Reduce List:
2395/// scratchpad[elem_id][index] = elem
2396///
Benjamin Kramer674d5792017-05-26 20:08:24 +00002397static llvm::Value *emitCopyToScratchpad(CodeGenModule &CGM,
2398 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002399 QualType ReductionArrayTy,
2400 SourceLocation Loc) {
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002401
Alexey Bataev9ff80832018-04-16 20:16:21 +00002402 ASTContext &C = CGM.getContext();
2403 QualType Int32Ty = C.getIntTypeForBitwidth(32, /*Signed=*/1);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002404
2405 // Source of the copy.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002406 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2407 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002408 // Base address of the scratchpad array, with each element storing a
2409 // Reduce list per team.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002410 ImplicitParamDecl ScratchPadArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2411 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002412 // A destination index into the scratchpad array, typically the team
2413 // identifier.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002414 ImplicitParamDecl IndexArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
2415 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002416 // Row width of an element in the scratchpad array, typically
2417 // the number of teams.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002418 ImplicitParamDecl WidthArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
2419 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002420
2421 FunctionArgList Args;
2422 Args.push_back(&ReduceListArg);
2423 Args.push_back(&ScratchPadArg);
2424 Args.push_back(&IndexArg);
2425 Args.push_back(&WidthArg);
2426
Alexey Bataev9ff80832018-04-16 20:16:21 +00002427 const CGFunctionInfo &CGFI =
2428 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002429 auto *Fn = llvm::Function::Create(
2430 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2431 "_omp_reduction_copy_to_scratchpad", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002432 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002433 Fn->setDoesNotRecurse();
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002434 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002435 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002436
Alexey Bataev9ff80832018-04-16 20:16:21 +00002437 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002438
2439 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2440 Address SrcDataAddr(
2441 Bld.CreatePointerBitCastOrAddrSpaceCast(
2442 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002443 C.VoidPtrTy, Loc),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002444 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
2445 CGF.getPointerAlign());
2446
2447 Address AddrScratchPadArg = CGF.GetAddrOfLocalVar(&ScratchPadArg);
2448 llvm::Value *ScratchPadBase = CGF.EmitLoadOfScalar(
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002449 AddrScratchPadArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002450
2451 Address AddrIndexArg = CGF.GetAddrOfLocalVar(&IndexArg);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002452 llvm::Value *IndexVal = Bld.CreateIntCast(
2453 CGF.EmitLoadOfScalar(AddrIndexArg, /*Volatile=*/false, Int32Ty, Loc),
2454 CGF.SizeTy, /*isSigned=*/true);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002455
2456 Address AddrWidthArg = CGF.GetAddrOfLocalVar(&WidthArg);
2457 llvm::Value *WidthVal =
2458 Bld.CreateIntCast(CGF.EmitLoadOfScalar(AddrWidthArg, /*Volatile=*/false,
2459 Int32Ty, SourceLocation()),
2460 CGF.SizeTy, /*isSigned=*/true);
2461
2462 // The absolute ptr address to the base addr of the next element to copy.
2463 llvm::Value *CumulativeElemBasePtr =
2464 Bld.CreatePtrToInt(ScratchPadBase, CGM.SizeTy);
2465 Address DestDataAddr(CumulativeElemBasePtr, CGF.getPointerAlign());
2466
2467 emitReductionListCopy(ThreadToScratchpad, CGF, ReductionArrayTy, Privates,
2468 SrcDataAddr, DestDataAddr,
2469 {/*RemoteLaneOffset=*/nullptr,
2470 /*ScratchpadIndex=*/IndexVal,
2471 /*ScratchpadWidth=*/WidthVal});
2472
2473 CGF.FinishFunction();
2474 return Fn;
2475}
2476
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002477/// This function emits a helper that gathers Reduce lists from the first
2478/// lane of every active warp to lanes in the first warp.
2479///
2480/// void inter_warp_copy_func(void* reduce_data, num_warps)
2481/// shared smem[warp_size];
2482/// For all data entries D in reduce_data:
2483/// If (I am the first lane in each warp)
2484/// Copy my local D to smem[warp_id]
2485/// sync
2486/// if (I am the first warp)
2487/// Copy smem[thread_id] to my local D
2488/// sync
2489static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
2490 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002491 QualType ReductionArrayTy,
2492 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002493 ASTContext &C = CGM.getContext();
2494 llvm::Module &M = CGM.getModule();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002495
2496 // ReduceList: thread local Reduce list.
2497 // At the stage of the computation when this function is called, partially
2498 // aggregated values reside in the first lane of every active warp.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002499 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2500 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002501 // NumWarps: number of warps active in the parallel region. This could
2502 // be smaller than 32 (max warps in a CTA) for partial block reduction.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002503 ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00002504 C.getIntTypeForBitwidth(32, /* Signed */ true),
2505 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002506 FunctionArgList Args;
2507 Args.push_back(&ReduceListArg);
2508 Args.push_back(&NumWarpsArg);
2509
Alexey Bataev9ff80832018-04-16 20:16:21 +00002510 const CGFunctionInfo &CGFI =
2511 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002512 auto *Fn = llvm::Function::Create(
2513 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2514 "_omp_reduction_inter_warp_copy_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002515 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002516 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002517 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002518 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002519
Alexey Bataev9ff80832018-04-16 20:16:21 +00002520 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002521
2522 // This array is used as a medium to transfer, one reduce element at a time,
2523 // the data from the first lane of every warp to lanes in the first warp
2524 // in order to perform the final step of a reduction in a parallel region
2525 // (reduction across warps). The array is placed in NVPTX __shared__ memory
2526 // for reduced latency, as well as to have a distinct copy for concurrently
2527 // executing target regions. The array is declared with common linkage so
2528 // as to be shared across compilation units.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002529 StringRef TransferMediumName =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002530 "__openmp_nvptx_data_transfer_temporary_storage";
2531 llvm::GlobalVariable *TransferMedium =
2532 M.getGlobalVariable(TransferMediumName);
2533 if (!TransferMedium) {
2534 auto *Ty = llvm::ArrayType::get(CGM.Int64Ty, WarpSize);
2535 unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
2536 TransferMedium = new llvm::GlobalVariable(
2537 M, Ty,
2538 /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage,
2539 llvm::Constant::getNullValue(Ty), TransferMediumName,
2540 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
2541 SharedAddressSpace);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002542 CGM.addCompilerUsedGlobal(TransferMedium);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002543 }
2544
2545 // Get the CUDA thread id of the current OpenMP thread on the GPU.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002546 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002547 // nvptx_lane_id = nvptx_id % warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00002548 llvm::Value *LaneID = getNVPTXLaneID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002549 // nvptx_warp_id = nvptx_id / warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00002550 llvm::Value *WarpID = getNVPTXWarpID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002551
2552 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2553 Address LocalReduceList(
2554 Bld.CreatePointerBitCastOrAddrSpaceCast(
2555 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
2556 C.VoidPtrTy, SourceLocation()),
2557 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
2558 CGF.getPointerAlign());
2559
2560 unsigned Idx = 0;
Alexey Bataev9ff80832018-04-16 20:16:21 +00002561 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002562 //
2563 // Warp master copies reduce element to transfer medium in __shared__
2564 // memory.
2565 //
2566 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
2567 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
2568 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
2569
2570 // if (lane_id == 0)
Alexey Bataev9ff80832018-04-16 20:16:21 +00002571 llvm::Value *IsWarpMaster = Bld.CreateIsNull(LaneID, "warp_master");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002572 Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
2573 CGF.EmitBlock(ThenBB);
2574
2575 // Reduce element = LocalReduceList[i]
2576 Address ElemPtrPtrAddr =
2577 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
2578 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
2579 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
2580 // elemptr = (type[i]*)(elemptrptr)
2581 Address ElemPtr =
2582 Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
2583 ElemPtr = Bld.CreateElementBitCast(
2584 ElemPtr, CGF.ConvertTypeForMem(Private->getType()));
2585 // elem = *elemptr
2586 llvm::Value *Elem = CGF.EmitLoadOfScalar(
2587 ElemPtr, /*Volatile=*/false, Private->getType(), SourceLocation());
2588
2589 // Get pointer to location in transfer medium.
2590 // MediumPtr = &medium[warp_id]
2591 llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
2592 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
2593 Address MediumPtr(MediumPtrVal, C.getTypeAlignInChars(Private->getType()));
2594 // Casting to actual data type.
2595 // MediumPtr = (type[i]*)MediumPtrAddr;
2596 MediumPtr = Bld.CreateElementBitCast(
2597 MediumPtr, CGF.ConvertTypeForMem(Private->getType()));
2598
2599 //*MediumPtr = elem
2600 Bld.CreateStore(Elem, MediumPtr);
2601
2602 Bld.CreateBr(MergeBB);
2603
2604 CGF.EmitBlock(ElseBB);
2605 Bld.CreateBr(MergeBB);
2606
2607 CGF.EmitBlock(MergeBB);
2608
2609 Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
2610 llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
2611 AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, SourceLocation());
2612
Alexey Bataev9ff80832018-04-16 20:16:21 +00002613 llvm::Value *NumActiveThreads = Bld.CreateNSWMul(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002614 NumWarpsVal, getNVPTXWarpSize(CGF), "num_active_threads");
2615 // named_barrier_sync(ParallelBarrierID, num_active_threads)
2616 syncParallelThreads(CGF, NumActiveThreads);
2617
2618 //
2619 // Warp 0 copies reduce element from transfer medium.
2620 //
2621 llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
2622 llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
2623 llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
2624
2625 // Up to 32 threads in warp 0 are active.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002626 llvm::Value *IsActiveThread =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002627 Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
2628 Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
2629
2630 CGF.EmitBlock(W0ThenBB);
2631
2632 // SrcMediumPtr = &medium[tid]
2633 llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
2634 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
2635 Address SrcMediumPtr(SrcMediumPtrVal,
2636 C.getTypeAlignInChars(Private->getType()));
2637 // SrcMediumVal = *SrcMediumPtr;
2638 SrcMediumPtr = Bld.CreateElementBitCast(
2639 SrcMediumPtr, CGF.ConvertTypeForMem(Private->getType()));
2640 llvm::Value *SrcMediumValue = CGF.EmitLoadOfScalar(
2641 SrcMediumPtr, /*Volatile=*/false, Private->getType(), SourceLocation());
2642
2643 // TargetElemPtr = (type[i]*)(SrcDataAddr[i])
2644 Address TargetElemPtrPtr =
2645 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
2646 llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
2647 TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
2648 Address TargetElemPtr =
2649 Address(TargetElemPtrVal, C.getTypeAlignInChars(Private->getType()));
2650 TargetElemPtr = Bld.CreateElementBitCast(
2651 TargetElemPtr, CGF.ConvertTypeForMem(Private->getType()));
2652
2653 // *TargetElemPtr = SrcMediumVal;
2654 CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
2655 Private->getType());
2656 Bld.CreateBr(W0MergeBB);
2657
2658 CGF.EmitBlock(W0ElseBB);
2659 Bld.CreateBr(W0MergeBB);
2660
2661 CGF.EmitBlock(W0MergeBB);
2662
2663 // While warp 0 copies values from transfer medium, all other warps must
2664 // wait.
2665 syncParallelThreads(CGF, NumActiveThreads);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002666 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002667 }
2668
2669 CGF.FinishFunction();
2670 return Fn;
2671}
2672
2673/// Emit a helper that reduces data across two OpenMP threads (lanes)
2674/// in the same warp. It uses shuffle instructions to copy over data from
2675/// a remote lane's stack. The reduction algorithm performed is specified
2676/// by the fourth parameter.
2677///
2678/// Algorithm Versions.
2679/// Full Warp Reduce (argument value 0):
2680/// This algorithm assumes that all 32 lanes are active and gathers
2681/// data from these 32 lanes, producing a single resultant value.
2682/// Contiguous Partial Warp Reduce (argument value 1):
2683/// This algorithm assumes that only a *contiguous* subset of lanes
2684/// are active. This happens for the last warp in a parallel region
2685/// when the user specified num_threads is not an integer multiple of
2686/// 32. This contiguous subset always starts with the zeroth lane.
2687/// Partial Warp Reduce (argument value 2):
2688/// This algorithm gathers data from any number of lanes at any position.
2689/// All reduced values are stored in the lowest possible lane. The set
2690/// of problems every algorithm addresses is a super set of those
2691/// addressable by algorithms with a lower version number. Overhead
2692/// increases as algorithm version increases.
2693///
2694/// Terminology
2695/// Reduce element:
2696/// Reduce element refers to the individual data field with primitive
2697/// data types to be combined and reduced across threads.
2698/// Reduce list:
2699/// Reduce list refers to a collection of local, thread-private
2700/// reduce elements.
2701/// Remote Reduce list:
2702/// Remote Reduce list refers to a collection of remote (relative to
2703/// the current thread) reduce elements.
2704///
2705/// We distinguish between three states of threads that are important to
2706/// the implementation of this function.
2707/// Alive threads:
2708/// Threads in a warp executing the SIMT instruction, as distinguished from
2709/// threads that are inactive due to divergent control flow.
2710/// Active threads:
2711/// The minimal set of threads that has to be alive upon entry to this
2712/// function. The computation is correct iff active threads are alive.
2713/// Some threads are alive but they are not active because they do not
2714/// contribute to the computation in any useful manner. Turning them off
2715/// may introduce control flow overheads without any tangible benefits.
2716/// Effective threads:
2717/// In order to comply with the argument requirements of the shuffle
2718/// function, we must keep all lanes holding data alive. But at most
2719/// half of them perform value aggregation; we refer to this half of
2720/// threads as effective. The other half is simply handing off their
2721/// data.
2722///
2723/// Procedure
2724/// Value shuffle:
2725/// In this step active threads transfer data from higher lane positions
2726/// in the warp to lower lane positions, creating Remote Reduce list.
2727/// Value aggregation:
2728/// In this step, effective threads combine their thread local Reduce list
2729/// with Remote Reduce list and store the result in the thread local
2730/// Reduce list.
2731/// Value copy:
2732/// In this step, we deal with the assumption made by algorithm 2
2733/// (i.e. contiguity assumption). When we have an odd number of lanes
2734/// active, say 2k+1, only k threads will be effective and therefore k
2735/// new values will be produced. However, the Reduce list owned by the
2736/// (2k+1)th thread is ignored in the value aggregation. Therefore
2737/// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
2738/// that the contiguity assumption still holds.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002739static llvm::Value *emitShuffleAndReduceFunction(
2740 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
2741 QualType ReductionArrayTy, llvm::Value *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002742 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002743
2744 // Thread local Reduce list used to host the values of data to be reduced.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002745 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2746 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002747 // Current lane id; could be logical.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002748 ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
2749 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002750 // Offset of the remote source lane relative to the current lane.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002751 ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2752 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002753 // Algorithm version. This is expected to be known at compile time.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002754 ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2755 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002756 FunctionArgList Args;
2757 Args.push_back(&ReduceListArg);
2758 Args.push_back(&LaneIDArg);
2759 Args.push_back(&RemoteLaneOffsetArg);
2760 Args.push_back(&AlgoVerArg);
2761
Alexey Bataev9ff80832018-04-16 20:16:21 +00002762 const CGFunctionInfo &CGFI =
2763 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002764 auto *Fn = llvm::Function::Create(
2765 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2766 "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002767 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002768 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002769 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002770 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002771
Alexey Bataev9ff80832018-04-16 20:16:21 +00002772 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002773
2774 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2775 Address LocalReduceList(
2776 Bld.CreatePointerBitCastOrAddrSpaceCast(
2777 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
2778 C.VoidPtrTy, SourceLocation()),
2779 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
2780 CGF.getPointerAlign());
2781
2782 Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
2783 llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
2784 AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
2785
2786 Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
2787 llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
2788 AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
2789
2790 Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
2791 llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
2792 AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
2793
2794 // Create a local thread-private variable to host the Reduce list
2795 // from a remote lane.
2796 Address RemoteReduceList =
2797 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
2798
2799 // This loop iterates through the list of reduce elements and copies,
2800 // element by element, from a remote lane in the warp to RemoteReduceList,
2801 // hosted on the thread's stack.
2802 emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
2803 LocalReduceList, RemoteReduceList,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002804 {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
2805 /*ScratchpadIndex=*/nullptr,
2806 /*ScratchpadWidth=*/nullptr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002807
2808 // The actions to be performed on the Remote Reduce list is dependent
2809 // on the algorithm version.
2810 //
2811 // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
2812 // LaneId % 2 == 0 && Offset > 0):
2813 // do the reduction value aggregation
2814 //
2815 // The thread local variable Reduce list is mutated in place to host the
2816 // reduced data, which is the aggregated value produced from local and
2817 // remote lanes.
2818 //
2819 // Note that AlgoVer is expected to be a constant integer known at compile
2820 // time.
2821 // When AlgoVer==0, the first conjunction evaluates to true, making
2822 // the entire predicate true during compile time.
2823 // When AlgoVer==1, the second conjunction has only the second part to be
2824 // evaluated during runtime. Other conjunctions evaluates to false
2825 // during compile time.
2826 // When AlgoVer==2, the third conjunction has only the second part to be
2827 // evaluated during runtime. Other conjunctions evaluates to false
2828 // during compile time.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002829 llvm::Value *CondAlgo0 = Bld.CreateIsNull(AlgoVerArgVal);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002830
Alexey Bataev9ff80832018-04-16 20:16:21 +00002831 llvm::Value *Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
2832 llvm::Value *CondAlgo1 = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002833 Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
2834
Alexey Bataev9ff80832018-04-16 20:16:21 +00002835 llvm::Value *Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
2836 llvm::Value *CondAlgo2 = Bld.CreateAnd(
2837 Algo2, Bld.CreateIsNull(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1))));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002838 CondAlgo2 = Bld.CreateAnd(
2839 CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
2840
Alexey Bataev9ff80832018-04-16 20:16:21 +00002841 llvm::Value *CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002842 CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
2843
2844 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
2845 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
2846 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
2847 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
2848
2849 CGF.EmitBlock(ThenBB);
2850 // reduce_function(LocalReduceList, RemoteReduceList)
2851 llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2852 LocalReduceList.getPointer(), CGF.VoidPtrTy);
2853 llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2854 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002855 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
2856 CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002857 Bld.CreateBr(MergeBB);
2858
2859 CGF.EmitBlock(ElseBB);
2860 Bld.CreateBr(MergeBB);
2861
2862 CGF.EmitBlock(MergeBB);
2863
2864 // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
2865 // Reduce list.
2866 Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
Alexey Bataev9ff80832018-04-16 20:16:21 +00002867 llvm::Value *CondCopy = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002868 Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
2869
2870 llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
2871 llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
2872 llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
2873 Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
2874
2875 CGF.EmitBlock(CpyThenBB);
2876 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
2877 RemoteReduceList, LocalReduceList);
2878 Bld.CreateBr(CpyMergeBB);
2879
2880 CGF.EmitBlock(CpyElseBB);
2881 Bld.CreateBr(CpyMergeBB);
2882
2883 CGF.EmitBlock(CpyMergeBB);
2884
2885 CGF.FinishFunction();
2886 return Fn;
2887}
2888
2889///
2890/// Design of OpenMP reductions on the GPU
2891///
2892/// Consider a typical OpenMP program with one or more reduction
2893/// clauses:
2894///
2895/// float foo;
2896/// double bar;
2897/// #pragma omp target teams distribute parallel for \
2898/// reduction(+:foo) reduction(*:bar)
2899/// for (int i = 0; i < N; i++) {
2900/// foo += A[i]; bar *= B[i];
2901/// }
2902///
2903/// where 'foo' and 'bar' are reduced across all OpenMP threads in
2904/// all teams. In our OpenMP implementation on the NVPTX device an
2905/// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
2906/// within a team are mapped to CUDA threads within a threadblock.
2907/// Our goal is to efficiently aggregate values across all OpenMP
2908/// threads such that:
2909///
2910/// - the compiler and runtime are logically concise, and
2911/// - the reduction is performed efficiently in a hierarchical
2912/// manner as follows: within OpenMP threads in the same warp,
2913/// across warps in a threadblock, and finally across teams on
2914/// the NVPTX device.
2915///
2916/// Introduction to Decoupling
2917///
2918/// We would like to decouple the compiler and the runtime so that the
2919/// latter is ignorant of the reduction variables (number, data types)
2920/// and the reduction operators. This allows a simpler interface
2921/// and implementation while still attaining good performance.
2922///
2923/// Pseudocode for the aforementioned OpenMP program generated by the
2924/// compiler is as follows:
2925///
2926/// 1. Create private copies of reduction variables on each OpenMP
2927/// thread: 'foo_private', 'bar_private'
2928/// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
2929/// to it and writes the result in 'foo_private' and 'bar_private'
2930/// respectively.
2931/// 3. Call the OpenMP runtime on the GPU to reduce within a team
2932/// and store the result on the team master:
2933///
2934/// __kmpc_nvptx_parallel_reduce_nowait(...,
2935/// reduceData, shuffleReduceFn, interWarpCpyFn)
2936///
2937/// where:
2938/// struct ReduceData {
2939/// double *foo;
2940/// double *bar;
2941/// } reduceData
2942/// reduceData.foo = &foo_private
2943/// reduceData.bar = &bar_private
2944///
2945/// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
2946/// auxiliary functions generated by the compiler that operate on
2947/// variables of type 'ReduceData'. They aid the runtime perform
2948/// algorithmic steps in a data agnostic manner.
2949///
2950/// 'shuffleReduceFn' is a pointer to a function that reduces data
2951/// of type 'ReduceData' across two OpenMP threads (lanes) in the
2952/// same warp. It takes the following arguments as input:
2953///
2954/// a. variable of type 'ReduceData' on the calling lane,
2955/// b. its lane_id,
2956/// c. an offset relative to the current lane_id to generate a
2957/// remote_lane_id. The remote lane contains the second
2958/// variable of type 'ReduceData' that is to be reduced.
2959/// d. an algorithm version parameter determining which reduction
2960/// algorithm to use.
2961///
2962/// 'shuffleReduceFn' retrieves data from the remote lane using
2963/// efficient GPU shuffle intrinsics and reduces, using the
2964/// algorithm specified by the 4th parameter, the two operands
2965/// element-wise. The result is written to the first operand.
2966///
2967/// Different reduction algorithms are implemented in different
2968/// runtime functions, all calling 'shuffleReduceFn' to perform
2969/// the essential reduction step. Therefore, based on the 4th
2970/// parameter, this function behaves slightly differently to
2971/// cooperate with the runtime to ensure correctness under
2972/// different circumstances.
2973///
2974/// 'InterWarpCpyFn' is a pointer to a function that transfers
2975/// reduced variables across warps. It tunnels, through CUDA
2976/// shared memory, the thread-private data of type 'ReduceData'
2977/// from lane 0 of each warp to a lane in the first warp.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002978/// 4. Call the OpenMP runtime on the GPU to reduce across teams.
2979/// The last team writes the global reduced value to memory.
2980///
2981/// ret = __kmpc_nvptx_teams_reduce_nowait(...,
2982/// reduceData, shuffleReduceFn, interWarpCpyFn,
2983/// scratchpadCopyFn, loadAndReduceFn)
2984///
2985/// 'scratchpadCopyFn' is a helper that stores reduced
2986/// data from the team master to a scratchpad array in
2987/// global memory.
2988///
2989/// 'loadAndReduceFn' is a helper that loads data from
2990/// the scratchpad array and reduces it with the input
2991/// operand.
2992///
2993/// These compiler generated functions hide address
2994/// calculation and alignment information from the runtime.
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002995/// 5. if ret == 1:
2996/// The team master of the last team stores the reduced
2997/// result to the globals in memory.
2998/// foo += reduceData.foo; bar *= reduceData.bar
2999///
3000///
3001/// Warp Reduction Algorithms
3002///
3003/// On the warp level, we have three algorithms implemented in the
3004/// OpenMP runtime depending on the number of active lanes:
3005///
3006/// Full Warp Reduction
3007///
3008/// The reduce algorithm within a warp where all lanes are active
3009/// is implemented in the runtime as follows:
3010///
3011/// full_warp_reduce(void *reduce_data,
3012/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3013/// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
3014/// ShuffleReduceFn(reduce_data, 0, offset, 0);
3015/// }
3016///
3017/// The algorithm completes in log(2, WARPSIZE) steps.
3018///
3019/// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
3020/// not used therefore we save instructions by not retrieving lane_id
3021/// from the corresponding special registers. The 4th parameter, which
3022/// represents the version of the algorithm being used, is set to 0 to
3023/// signify full warp reduction.
3024///
3025/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3026///
3027/// #reduce_elem refers to an element in the local lane's data structure
3028/// #remote_elem is retrieved from a remote lane
3029/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3030/// reduce_elem = reduce_elem REDUCE_OP remote_elem;
3031///
3032/// Contiguous Partial Warp Reduction
3033///
3034/// This reduce algorithm is used within a warp where only the first
3035/// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
3036/// number of OpenMP threads in a parallel region is not a multiple of
3037/// WARPSIZE. The algorithm is implemented in the runtime as follows:
3038///
3039/// void
3040/// contiguous_partial_reduce(void *reduce_data,
3041/// kmp_ShuffleReductFctPtr ShuffleReduceFn,
3042/// int size, int lane_id) {
3043/// int curr_size;
3044/// int offset;
3045/// curr_size = size;
3046/// mask = curr_size/2;
3047/// while (offset>0) {
3048/// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
3049/// curr_size = (curr_size+1)/2;
3050/// offset = curr_size/2;
3051/// }
3052/// }
3053///
3054/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3055///
3056/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3057/// if (lane_id < offset)
3058/// reduce_elem = reduce_elem REDUCE_OP remote_elem
3059/// else
3060/// reduce_elem = remote_elem
3061///
3062/// This algorithm assumes that the data to be reduced are located in a
3063/// contiguous subset of lanes starting from the first. When there is
3064/// an odd number of active lanes, the data in the last lane is not
3065/// aggregated with any other lane's dat but is instead copied over.
3066///
3067/// Dispersed Partial Warp Reduction
3068///
3069/// This algorithm is used within a warp when any discontiguous subset of
3070/// lanes are active. It is used to implement the reduction operation
3071/// across lanes in an OpenMP simd region or in a nested parallel region.
3072///
3073/// void
3074/// dispersed_partial_reduce(void *reduce_data,
3075/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3076/// int size, remote_id;
3077/// int logical_lane_id = number_of_active_lanes_before_me() * 2;
3078/// do {
3079/// remote_id = next_active_lane_id_right_after_me();
3080/// # the above function returns 0 of no active lane
3081/// # is present right after the current lane.
3082/// size = number_of_active_lanes_in_this_warp();
3083/// logical_lane_id /= 2;
3084/// ShuffleReduceFn(reduce_data, logical_lane_id,
3085/// remote_id-1-threadIdx.x, 2);
3086/// } while (logical_lane_id % 2 == 0 && size > 1);
3087/// }
3088///
3089/// There is no assumption made about the initial state of the reduction.
3090/// Any number of lanes (>=1) could be active at any position. The reduction
3091/// result is returned in the first active lane.
3092///
3093/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3094///
3095/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3096/// if (lane_id % 2 == 0 && offset > 0)
3097/// reduce_elem = reduce_elem REDUCE_OP remote_elem
3098/// else
3099/// reduce_elem = remote_elem
3100///
3101///
3102/// Intra-Team Reduction
3103///
3104/// This function, as implemented in the runtime call
3105/// '__kmpc_nvptx_parallel_reduce_nowait', aggregates data across OpenMP
3106/// threads in a team. It first reduces within a warp using the
3107/// aforementioned algorithms. We then proceed to gather all such
3108/// reduced values at the first warp.
3109///
3110/// The runtime makes use of the function 'InterWarpCpyFn', which copies
3111/// data from each of the "warp master" (zeroth lane of each warp, where
3112/// warp-reduced data is held) to the zeroth warp. This step reduces (in
3113/// a mathematical sense) the problem of reduction across warp masters in
3114/// a block to the problem of warp reduction.
3115///
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003116///
3117/// Inter-Team Reduction
3118///
3119/// Once a team has reduced its data to a single value, it is stored in
3120/// a global scratchpad array. Since each team has a distinct slot, this
3121/// can be done without locking.
3122///
3123/// The last team to write to the scratchpad array proceeds to reduce the
3124/// scratchpad array. One or more workers in the last team use the helper
3125/// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
3126/// the k'th worker reduces every k'th element.
3127///
3128/// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait' to
3129/// reduce across workers and compute a globally reduced value.
3130///
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003131void CGOpenMPRuntimeNVPTX::emitReduction(
3132 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
3133 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
3134 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
3135 if (!CGF.HaveInsertPoint())
3136 return;
3137
3138 bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003139 bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
Alexey Bataevfac26cf2018-05-02 20:03:27 +00003140 bool SimdReduction = isOpenMPSimdDirective(Options.ReductionKind);
3141 assert((TeamsReduction || ParallelReduction || SimdReduction) &&
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003142 "Invalid reduction selection in emitReduction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003143
Alexey Bataev9ff80832018-04-16 20:16:21 +00003144 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003145
3146 // 1. Build a list of reduction variables.
3147 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3148 auto Size = RHSExprs.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00003149 for (const Expr *E : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003150 if (E->getType()->isVariablyModifiedType())
3151 // Reserve place for array size.
3152 ++Size;
3153 }
3154 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
3155 QualType ReductionArrayTy =
3156 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3157 /*IndexTypeQuals=*/0);
3158 Address ReductionList =
3159 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3160 auto IPriv = Privates.begin();
3161 unsigned Idx = 0;
3162 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
3163 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3164 CGF.getPointerSize());
3165 CGF.Builder.CreateStore(
3166 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3167 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
3168 Elem);
3169 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3170 // Store array size.
3171 ++Idx;
3172 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3173 CGF.getPointerSize());
3174 llvm::Value *Size = CGF.Builder.CreateIntCast(
3175 CGF.getVLASize(
3176 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
Sander de Smalen891af03a2018-02-03 13:55:59 +00003177 .NumElts,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003178 CGF.SizeTy, /*isSigned=*/false);
3179 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3180 Elem);
3181 }
3182 }
3183
3184 // 2. Emit reduce_func().
Alexey Bataev9ff80832018-04-16 20:16:21 +00003185 llvm::Value *ReductionFn = emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003186 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
3187 Privates, LHSExprs, RHSExprs, ReductionOps);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003188
3189 // 4. Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
3190 // RedList, shuffle_reduce_func, interwarp_copy_func);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003191 llvm::Value *ThreadId = getThreadID(CGF, Loc);
3192 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
3193 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003194 ReductionList.getPointer(), CGF.VoidPtrTy);
3195
Alexey Bataev9ff80832018-04-16 20:16:21 +00003196 llvm::Value *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003197 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003198 llvm::Value *InterWarpCopyFn =
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003199 emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003200
Alexey Bataevfac26cf2018-05-02 20:03:27 +00003201 llvm::Value *Args[] = {ThreadId,
3202 CGF.Builder.getInt32(RHSExprs.size()),
3203 ReductionArrayTySize,
3204 RL,
3205 ShuffleAndReduceFn,
3206 InterWarpCopyFn};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003207
Alexey Bataevfac26cf2018-05-02 20:03:27 +00003208 llvm::Value *Res = nullptr;
3209 if (ParallelReduction)
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003210 Res = CGF.EmitRuntimeCall(
3211 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_reduce_nowait),
3212 Args);
Alexey Bataevfac26cf2018-05-02 20:03:27 +00003213 else if (SimdReduction)
3214 Res = CGF.EmitRuntimeCall(
3215 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_simd_reduce_nowait),
3216 Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003217
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003218 if (TeamsReduction) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003219 llvm::Value *ScratchPadCopyFn =
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003220 emitCopyToScratchpad(CGM, Privates, ReductionArrayTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003221 llvm::Value *LoadAndReduceFn = emitReduceScratchpadFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003222 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003223
3224 llvm::Value *Args[] = {ThreadId,
3225 CGF.Builder.getInt32(RHSExprs.size()),
3226 ReductionArrayTySize,
3227 RL,
3228 ShuffleAndReduceFn,
3229 InterWarpCopyFn,
3230 ScratchPadCopyFn,
3231 LoadAndReduceFn};
3232 Res = CGF.EmitRuntimeCall(
3233 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_teams_reduce_nowait),
3234 Args);
3235 }
3236
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003237 // 5. Build switch(res)
Alexey Bataev9ff80832018-04-16 20:16:21 +00003238 llvm::BasicBlock *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
3239 llvm::SwitchInst *SwInst =
3240 CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003241
3242 // 6. Build case 1: where we have reduced values in the master
3243 // thread in each team.
3244 // __kmpc_end_reduce{_nowait}(<gtid>);
3245 // break;
Alexey Bataev9ff80832018-04-16 20:16:21 +00003246 llvm::BasicBlock *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003247 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
3248 CGF.EmitBlock(Case1BB);
3249
3250 // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
3251 llvm::Value *EndArgs[] = {ThreadId};
Alexey Bataev9ff80832018-04-16 20:16:21 +00003252 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003253 this](CodeGenFunction &CGF, PrePostActionTy &Action) {
3254 auto IPriv = Privates.begin();
3255 auto ILHS = LHSExprs.begin();
3256 auto IRHS = RHSExprs.begin();
Alexey Bataev9ff80832018-04-16 20:16:21 +00003257 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003258 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
3259 cast<DeclRefExpr>(*IRHS));
3260 ++IPriv;
3261 ++ILHS;
3262 ++IRHS;
3263 }
3264 };
3265 RegionCodeGenTy RCG(CodeGen);
3266 NVPTXActionTy Action(
3267 nullptr, llvm::None,
3268 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_reduce_nowait),
3269 EndArgs);
3270 RCG.setAction(Action);
3271 RCG(CGF);
3272 CGF.EmitBranch(DefaultBB);
3273 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
3274}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003275
3276const VarDecl *
3277CGOpenMPRuntimeNVPTX::translateParameter(const FieldDecl *FD,
3278 const VarDecl *NativeParam) const {
3279 if (!NativeParam->getType()->isReferenceType())
3280 return NativeParam;
3281 QualType ArgType = NativeParam->getType();
3282 QualifierCollector QC;
3283 const Type *NonQualTy = QC.strip(ArgType);
3284 QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
3285 if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
3286 if (Attr->getCaptureKind() == OMPC_map) {
3287 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
3288 LangAS::opencl_global);
3289 }
3290 }
3291 ArgType = CGM.getContext().getPointerType(PointeeTy);
3292 QC.addRestrict();
3293 enum { NVPTX_local_addr = 5 };
Alexander Richardson6d989432017-10-15 18:48:14 +00003294 QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003295 ArgType = QC.apply(CGM.getContext(), ArgType);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003296 if (isa<ImplicitParamDecl>(NativeParam))
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003297 return ImplicitParamDecl::Create(
3298 CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
3299 NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003300 return ParmVarDecl::Create(
3301 CGM.getContext(),
3302 const_cast<DeclContext *>(NativeParam->getDeclContext()),
3303 NativeParam->getLocStart(), NativeParam->getLocation(),
3304 NativeParam->getIdentifier(), ArgType,
3305 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003306}
3307
3308Address
3309CGOpenMPRuntimeNVPTX::getParameterAddress(CodeGenFunction &CGF,
3310 const VarDecl *NativeParam,
3311 const VarDecl *TargetParam) const {
3312 assert(NativeParam != TargetParam &&
3313 NativeParam->getType()->isReferenceType() &&
3314 "Native arg must not be the same as target arg.");
3315 Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
3316 QualType NativeParamType = NativeParam->getType();
3317 QualifierCollector QC;
3318 const Type *NonQualTy = QC.strip(NativeParamType);
3319 QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
3320 unsigned NativePointeeAddrSpace =
Alexander Richardson6d989432017-10-15 18:48:14 +00003321 CGF.getContext().getTargetAddressSpace(NativePointeeTy);
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00003322 QualType TargetTy = TargetParam->getType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003323 llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00003324 LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003325 // First cast to generic.
3326 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3327 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
3328 /*AddrSpace=*/0));
3329 // Cast from generic to native address space.
3330 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3331 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
3332 NativePointeeAddrSpace));
3333 Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
3334 CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00003335 NativeParamType);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003336 return NativeParamAddr;
3337}
3338
3339void CGOpenMPRuntimeNVPTX::emitOutlinedFunctionCall(
Alexey Bataev3c595a62017-08-14 15:01:03 +00003340 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003341 ArrayRef<llvm::Value *> Args) const {
3342 SmallVector<llvm::Value *, 4> TargetArgs;
Alexey Bataev07ed94a2017-08-15 14:34:04 +00003343 TargetArgs.reserve(Args.size());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003344 auto *FnType =
3345 cast<llvm::FunctionType>(OutlinedFn->getType()->getPointerElementType());
3346 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
Alexey Bataev07ed94a2017-08-15 14:34:04 +00003347 if (FnType->isVarArg() && FnType->getNumParams() <= I) {
3348 TargetArgs.append(std::next(Args.begin(), I), Args.end());
3349 break;
3350 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003351 llvm::Type *TargetType = FnType->getParamType(I);
3352 llvm::Value *NativeArg = Args[I];
3353 if (!TargetType->isPointerTy()) {
3354 TargetArgs.emplace_back(NativeArg);
3355 continue;
3356 }
3357 llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataevc99042b2018-03-15 18:10:54 +00003358 NativeArg,
3359 NativeArg->getType()->getPointerElementType()->getPointerTo());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003360 TargetArgs.emplace_back(
3361 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
3362 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00003363 CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003364}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003365
3366/// Emit function which wraps the outline parallel region
3367/// and controls the arguments which are passed to this function.
3368/// The wrapper ensures that the outlined function is called
3369/// with the correct arguments when data is shared.
3370llvm::Function *CGOpenMPRuntimeNVPTX::createParallelDataSharingWrapper(
3371 llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
3372 ASTContext &Ctx = CGM.getContext();
3373 const auto &CS = *D.getCapturedStmt(OMPD_parallel);
3374
3375 // Create a function that takes as argument the source thread.
3376 FunctionArgList WrapperArgs;
3377 QualType Int16QTy =
3378 Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
3379 QualType Int32QTy =
3380 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
3381 ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getLocStart(),
3382 /*Id=*/nullptr, Int16QTy,
3383 ImplicitParamDecl::Other);
3384 ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getLocStart(),
3385 /*Id=*/nullptr, Int32QTy,
3386 ImplicitParamDecl::Other);
3387 WrapperArgs.emplace_back(&ParallelLevelArg);
3388 WrapperArgs.emplace_back(&WrapperArg);
3389
Alexey Bataev9ff80832018-04-16 20:16:21 +00003390 const CGFunctionInfo &CGFI =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003391 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
3392
3393 auto *Fn = llvm::Function::Create(
3394 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataev9ff80832018-04-16 20:16:21 +00003395 Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
Alexey Bataevc99042b2018-03-15 18:10:54 +00003396 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003397 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003398 Fn->setDoesNotRecurse();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003399
3400 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3401 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
3402 D.getLocStart(), D.getLocStart());
3403
3404 const auto *RD = CS.getCapturedRecordDecl();
3405 auto CurField = RD->field_begin();
3406
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00003407 Address ZeroAddr = CGF.CreateMemTemp(
3408 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
3409 /*Name*/ ".zero.addr");
3410 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003411 // Get the array of arguments.
3412 SmallVector<llvm::Value *, 8> Args;
3413
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00003414 Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).getPointer());
3415 Args.emplace_back(ZeroAddr.getPointer());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003416
3417 CGBuilderTy &Bld = CGF.Builder;
3418 auto CI = CS.capture_begin();
3419
3420 // Use global memory for data sharing.
3421 // Handle passing of global args to workers.
3422 Address GlobalArgs =
3423 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
3424 llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
3425 llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
3426 CGF.EmitRuntimeCall(
3427 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_get_shared_variables),
3428 DataSharingArgs);
3429
3430 // Retrieve the shared variables from the list of references returned
3431 // by the runtime. Pass the variables to the outlined function.
Alexey Bataev17314212018-03-20 15:41:05 +00003432 Address SharedArgListAddress = Address::invalid();
3433 if (CS.capture_size() > 0 ||
3434 isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
3435 SharedArgListAddress = CGF.EmitLoadOfPointer(
3436 GlobalArgs, CGF.getContext()
3437 .getPointerType(CGF.getContext().getPointerType(
3438 CGF.getContext().VoidPtrTy))
3439 .castAs<PointerType>());
3440 }
3441 unsigned Idx = 0;
3442 if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
3443 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
3444 CGF.getPointerSize());
3445 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
3446 Src, CGF.SizeTy->getPointerTo());
3447 llvm::Value *LB = CGF.EmitLoadOfScalar(
3448 TypedAddress,
3449 /*Volatile=*/false,
3450 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
3451 cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
3452 Args.emplace_back(LB);
3453 ++Idx;
3454 Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
3455 CGF.getPointerSize());
3456 TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
3457 Src, CGF.SizeTy->getPointerTo());
3458 llvm::Value *UB = CGF.EmitLoadOfScalar(
3459 TypedAddress,
3460 /*Volatile=*/false,
3461 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
3462 cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
3463 Args.emplace_back(UB);
3464 ++Idx;
3465 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003466 if (CS.capture_size() > 0) {
3467 ASTContext &CGFContext = CGF.getContext();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003468 for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
3469 QualType ElemTy = CurField->getType();
Alexey Bataev17314212018-03-20 15:41:05 +00003470 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx,
3471 CGF.getPointerSize());
3472 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003473 Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)));
3474 llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
3475 /*Volatile=*/false,
3476 CGFContext.getPointerType(ElemTy),
3477 CI->getLocation());
Alexey Bataev2091ca62018-04-23 17:33:41 +00003478 if (CI->capturesVariableByCopy() &&
3479 !CI->getCapturedVar()->getType()->isAnyPointerType()) {
Alexey Bataev17314212018-03-20 15:41:05 +00003480 Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
3481 CI->getLocation());
3482 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003483 Args.emplace_back(Arg);
3484 }
3485 }
3486
3487 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedParallelFn, Args);
3488 CGF.FinishFunction();
3489 return Fn;
3490}
3491
3492void CGOpenMPRuntimeNVPTX::emitFunctionProlog(CodeGenFunction &CGF,
3493 const Decl *D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00003494 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
3495 return;
3496
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003497 assert(D && "Expected function or captured|block decl.");
3498 assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
3499 "Function is registered already.");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003500 const Stmt *Body = nullptr;
Alexey Bataevc99042b2018-03-15 18:10:54 +00003501 bool NeedToDelayGlobalization = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003502 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3503 Body = FD->getBody();
3504 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
3505 Body = BD->getBody();
3506 } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
3507 Body = CD->getBody();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003508 NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003509 }
3510 if (!Body)
3511 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003512 CheckVarsEscapingDeclContext VarChecker(CGF);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003513 VarChecker.Visit(Body);
3514 const RecordDecl *GlobalizedVarsRecord = VarChecker.getGlobalizedRecord();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003515 ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
3516 VarChecker.getEscapedVariableLengthDecls();
3517 if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003518 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +00003519 auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
3520 I->getSecond().MappedParams =
3521 llvm::make_unique<CodeGenFunction::OMPMapVars>();
3522 I->getSecond().GlobalRecord = GlobalizedVarsRecord;
3523 I->getSecond().EscapedParameters.insert(
3524 VarChecker.getEscapedParameters().begin(),
3525 VarChecker.getEscapedParameters().end());
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003526 I->getSecond().EscapedVariableLengthDecls.append(
3527 EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
Alexey Bataevc99042b2018-03-15 18:10:54 +00003528 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003529 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003530 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003531 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataevc99042b2018-03-15 18:10:54 +00003532 Data.insert(std::make_pair(VD, std::make_pair(FD, Address::invalid())));
3533 }
3534 if (!NeedToDelayGlobalization) {
3535 emitGenericVarsProlog(CGF, D->getLocStart());
3536 struct GlobalizationScope final : EHScopeStack::Cleanup {
3537 GlobalizationScope() = default;
3538
3539 void Emit(CodeGenFunction &CGF, Flags flags) override {
3540 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
3541 .emitGenericVarsEpilog(CGF);
3542 }
3543 };
3544 CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003545 }
3546}
3547
3548Address CGOpenMPRuntimeNVPTX::getAddressOfLocalVariable(CodeGenFunction &CGF,
3549 const VarDecl *VD) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00003550 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
3551 return Address::invalid();
3552
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003553 VD = VD->getCanonicalDecl();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003554 auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
3555 if (I == FunctionGlobalizedDecls.end())
3556 return Address::invalid();
Alexey Bataevc99042b2018-03-15 18:10:54 +00003557 auto VDI = I->getSecond().LocalVarData.find(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003558 if (VDI != I->getSecond().LocalVarData.end())
3559 return VDI->second.second;
3560 if (VD->hasAttrs()) {
3561 for (specific_attr_iterator<OMPReferencedVarAttr> IT(VD->attr_begin()),
3562 E(VD->attr_end());
3563 IT != E; ++IT) {
3564 auto VDI = I->getSecond().LocalVarData.find(
3565 cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
3566 ->getCanonicalDecl());
3567 if (VDI != I->getSecond().LocalVarData.end())
3568 return VDI->second.second;
3569 }
3570 }
3571 return Address::invalid();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003572}
3573
3574void CGOpenMPRuntimeNVPTX::functionFinished(CodeGenFunction &CGF) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003575 FunctionGlobalizedDecls.erase(CGF.CurFn);
3576 CGOpenMPRuntime::functionFinished(CGF);
3577}