Samuel Antao | 45bfe4c | 2016-02-08 15:59:20 +0000 | [diff] [blame] | 1 | //===---- 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 Bertolli | c687225 | 2016-04-04 15:55:02 +0000 | [diff] [blame] | 16 | #include "CodeGenFunction.h" |
Gheorghe-Teodor Bercea | d3dcf2f | 2018-03-14 14:17:45 +0000 | [diff] [blame] | 17 | #include "clang/AST/DeclOpenMP.h" |
Carlo Bertolli | c687225 | 2016-04-04 15:55:02 +0000 | [diff] [blame] | 18 | #include "clang/AST/StmtOpenMP.h" |
Gheorghe-Teodor Bercea | d3dcf2f | 2018-03-14 14:17:45 +0000 | [diff] [blame] | 19 | #include "clang/AST/StmtVisitor.h" |
| 20 | #include "llvm/ADT/SmallPtrSet.h" |
Samuel Antao | 45bfe4c | 2016-02-08 15:59:20 +0000 | [diff] [blame] | 21 | |
| 22 | using namespace clang; |
| 23 | using namespace CodeGen; |
| 24 | |
Arpith Chacko Jacob | ccf2f73 | 2017-01-03 20:19:56 +0000 | [diff] [blame] | 25 | namespace { |
| 26 | enum OpenMPRTLFunctionNVPTX { |
Jonas Hahnfeld | 891c7fb | 2017-11-22 14:46:49 +0000 | [diff] [blame] | 27 | /// \brief Call to void __kmpc_kernel_init(kmp_int32 thread_limit, |
| 28 | /// int16_t RequiresOMPRuntime); |
Arpith Chacko Jacob | ccf2f73 | 2017-01-03 20:19:56 +0000 | [diff] [blame] | 29 | OMPRTL_NVPTX__kmpc_kernel_init, |
Jonas Hahnfeld | 891c7fb | 2017-11-22 14:46:49 +0000 | [diff] [blame] | 30 | /// \brief Call to void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized); |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 31 | OMPRTL_NVPTX__kmpc_kernel_deinit, |
Arpith Chacko Jacob | 44a87c9 | 2017-01-18 19:35:00 +0000 | [diff] [blame] | 32 | /// \brief Call to void __kmpc_spmd_kernel_init(kmp_int32 thread_limit, |
Jonas Hahnfeld | 891c7fb | 2017-11-22 14:46:49 +0000 | [diff] [blame] | 33 | /// int16_t RequiresOMPRuntime, int16_t RequiresDataSharing); |
Arpith Chacko Jacob | 44a87c9 | 2017-01-18 19:35:00 +0000 | [diff] [blame] | 34 | OMPRTL_NVPTX__kmpc_spmd_kernel_init, |
| 35 | /// \brief Call to void __kmpc_spmd_kernel_deinit(); |
| 36 | OMPRTL_NVPTX__kmpc_spmd_kernel_deinit, |
Arpith Chacko Jacob | bb36fe8 | 2017-01-10 15:42:51 +0000 | [diff] [blame] | 37 | /// \brief Call to void __kmpc_kernel_prepare_parallel(void |
Gheorghe-Teodor Bercea | 7d80da1 | 2018-03-07 21:59:50 +0000 | [diff] [blame] | 38 | /// *outlined_function, int16_t |
Jonas Hahnfeld | fa059ba | 2017-12-27 10:39:56 +0000 | [diff] [blame] | 39 | /// IsOMPRuntimeInitialized); |
Arpith Chacko Jacob | bb36fe8 | 2017-01-10 15:42:51 +0000 | [diff] [blame] | 40 | OMPRTL_NVPTX__kmpc_kernel_prepare_parallel, |
Gheorghe-Teodor Bercea | 7d80da1 | 2018-03-07 21:59:50 +0000 | [diff] [blame] | 41 | /// \brief Call to bool __kmpc_kernel_parallel(void **outlined_function, |
| 42 | /// int16_t IsOMPRuntimeInitialized); |
Arpith Chacko Jacob | bb36fe8 | 2017-01-10 15:42:51 +0000 | [diff] [blame] | 43 | OMPRTL_NVPTX__kmpc_kernel_parallel, |
| 44 | /// \brief Call to void __kmpc_kernel_end_parallel(); |
| 45 | 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, |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 52 | /// \brief Call to int32_t __kmpc_shuffle_int32(int32_t element, |
| 53 | /// int16_t lane_offset, int16_t warp_size); |
| 54 | OMPRTL_NVPTX__kmpc_shuffle_int32, |
| 55 | /// \brief Call to int64_t __kmpc_shuffle_int64(int64_t element, |
| 56 | /// int16_t lane_offset, int16_t warp_size); |
| 57 | OMPRTL_NVPTX__kmpc_shuffle_int64, |
| 58 | /// \brief Call to __kmpc_nvptx_parallel_reduce_nowait(kmp_int32 |
| 59 | /// 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, |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 64 | /// \brief Call to __kmpc_nvptx_teams_reduce_nowait(int32_t global_tid, |
| 65 | /// int32_t num_vars, size_t reduce_size, void *reduce_data, |
| 66 | /// void (*kmp_ShuffleReductFctPtr)(void *rhs, int16_t lane_id, int16_t |
| 67 | /// lane_offset, int16_t shortCircuit), |
| 68 | /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num), |
| 69 | /// void (*kmp_CopyToScratchpadFctPtr)(void *reduce_data, void * scratchpad, |
| 70 | /// int32_t index, int32_t width), |
| 71 | /// void (*kmp_LoadReduceFctPtr)(void *reduce_data, void * scratchpad, int32_t |
| 72 | /// index, int32_t width, int32_t reduce)) |
| 73 | OMPRTL_NVPTX__kmpc_teams_reduce_nowait, |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 74 | /// \brief Call to __kmpc_nvptx_end_reduce_nowait(int32_t global_tid); |
Gheorghe-Teodor Bercea | d3dcf2f | 2018-03-14 14:17:45 +0000 | [diff] [blame] | 75 | OMPRTL_NVPTX__kmpc_end_reduce_nowait, |
| 76 | /// \brief Call to void __kmpc_data_sharing_init_stack(); |
| 77 | OMPRTL_NVPTX__kmpc_data_sharing_init_stack, |
| 78 | /// \brief Call to void* __kmpc_data_sharing_push_stack(size_t size, |
| 79 | /// int16_t UseSharedMemory); |
| 80 | OMPRTL_NVPTX__kmpc_data_sharing_push_stack, |
| 81 | /// \brief Call to void __kmpc_data_sharing_pop_stack(void *a); |
| 82 | OMPRTL_NVPTX__kmpc_data_sharing_pop_stack, |
| 83 | /// \brief Call to void __kmpc_begin_sharing_variables(void ***args, |
| 84 | /// size_t n_args); |
| 85 | OMPRTL_NVPTX__kmpc_begin_sharing_variables, |
| 86 | /// \brief Call to void __kmpc_end_sharing_variables(); |
| 87 | OMPRTL_NVPTX__kmpc_end_sharing_variables, |
| 88 | /// \brief Call to void __kmpc_get_shared_variables(void ***GlobalArgs) |
| 89 | OMPRTL_NVPTX__kmpc_get_shared_variables, |
Arpith Chacko Jacob | ccf2f73 | 2017-01-03 20:19:56 +0000 | [diff] [blame] | 90 | }; |
Arpith Chacko Jacob | bb36fe8 | 2017-01-10 15:42:51 +0000 | [diff] [blame] | 91 | |
| 92 | /// Pre(post)-action for different OpenMP constructs specialized for NVPTX. |
| 93 | class NVPTXActionTy final : public PrePostActionTy { |
| 94 | llvm::Value *EnterCallee; |
| 95 | ArrayRef<llvm::Value *> EnterArgs; |
| 96 | llvm::Value *ExitCallee; |
| 97 | ArrayRef<llvm::Value *> ExitArgs; |
| 98 | bool Conditional; |
| 99 | llvm::BasicBlock *ContBlock = nullptr; |
| 100 | |
| 101 | public: |
| 102 | NVPTXActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs, |
| 103 | llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs, |
| 104 | bool Conditional = false) |
| 105 | : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee), |
| 106 | ExitArgs(ExitArgs), Conditional(Conditional) {} |
| 107 | void Enter(CodeGenFunction &CGF) override { |
| 108 | llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs); |
| 109 | if (Conditional) { |
| 110 | llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes); |
| 111 | auto *ThenBlock = CGF.createBasicBlock("omp_if.then"); |
| 112 | ContBlock = CGF.createBasicBlock("omp_if.end"); |
| 113 | // Generate the branch (If-stmt) |
| 114 | CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock); |
| 115 | CGF.EmitBlock(ThenBlock); |
| 116 | } |
| 117 | } |
| 118 | void Done(CodeGenFunction &CGF) { |
| 119 | // Emit the rest of blocks/branches |
| 120 | CGF.EmitBranch(ContBlock); |
| 121 | CGF.EmitBlock(ContBlock, true); |
| 122 | } |
| 123 | void Exit(CodeGenFunction &CGF) override { |
| 124 | CGF.EmitRuntimeCall(ExitCallee, ExitArgs); |
| 125 | } |
| 126 | }; |
Arpith Chacko Jacob | 44a87c9 | 2017-01-18 19:35:00 +0000 | [diff] [blame] | 127 | |
| 128 | // A class to track the execution mode when codegening directives within |
| 129 | // a target region. The appropriate mode (generic/spmd) is set on entry |
| 130 | // to the target region and used by containing directives such as 'parallel' |
| 131 | // to emit optimized code. |
| 132 | class ExecutionModeRAII { |
| 133 | private: |
| 134 | CGOpenMPRuntimeNVPTX::ExecutionMode SavedMode; |
| 135 | CGOpenMPRuntimeNVPTX::ExecutionMode &Mode; |
| 136 | |
| 137 | public: |
| 138 | ExecutionModeRAII(CGOpenMPRuntimeNVPTX::ExecutionMode &Mode, |
| 139 | CGOpenMPRuntimeNVPTX::ExecutionMode NewMode) |
| 140 | : Mode(Mode) { |
| 141 | SavedMode = Mode; |
| 142 | Mode = NewMode; |
| 143 | } |
| 144 | ~ExecutionModeRAII() { Mode = SavedMode; } |
| 145 | }; |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 146 | |
| 147 | /// GPU Configuration: This information can be derived from cuda registers, |
| 148 | /// however, providing compile time constants helps generate more efficient |
| 149 | /// code. For all practical purposes this is fine because the configuration |
| 150 | /// is the same for all known NVPTX architectures. |
| 151 | enum MachineConfiguration : unsigned { |
| 152 | WarpSize = 32, |
| 153 | /// Number of bits required to represent a lane identifier, which is |
| 154 | /// computed as log_2(WarpSize). |
| 155 | LaneIDBits = 5, |
| 156 | LaneIDMask = WarpSize - 1, |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 157 | |
| 158 | /// Global memory alignment for performance. |
| 159 | GlobalMemoryAlignment = 256, |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 160 | }; |
| 161 | |
| 162 | enum NamedBarrier : unsigned { |
| 163 | /// Synchronize on this barrier #ID using a named barrier primitive. |
| 164 | /// Only the subset of active threads in a parallel region arrive at the |
| 165 | /// barrier. |
| 166 | NB_Parallel = 1, |
| 167 | }; |
Gheorghe-Teodor Bercea | d3dcf2f | 2018-03-14 14:17:45 +0000 | [diff] [blame] | 168 | |
| 169 | /// Get the list of variables that can escape their declaration context. |
| 170 | class CheckVarsEscapingDeclContext final |
| 171 | : public ConstStmtVisitor<CheckVarsEscapingDeclContext> { |
| 172 | CodeGenFunction &CGF; |
| 173 | llvm::SetVector<const ValueDecl *> EscapedDecls; |
| 174 | llvm::SmallPtrSet<const ValueDecl *, 4> IgnoredDecls; |
| 175 | bool AllEscaped = false; |
| 176 | RecordDecl *GlobalizedRD = nullptr; |
| 177 | llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields; |
| 178 | |
| 179 | void markAsEscaped(const ValueDecl *VD) { |
| 180 | if (IgnoredDecls.count(VD) || |
| 181 | (CGF.CapturedStmtInfo && |
| 182 | CGF.CapturedStmtInfo->lookup(cast<VarDecl>(VD)))) |
| 183 | return; |
| 184 | EscapedDecls.insert(VD); |
| 185 | } |
| 186 | |
| 187 | void VisitValueDecl(const ValueDecl *VD) { |
| 188 | if (VD->getType()->isLValueReferenceType()) { |
| 189 | markAsEscaped(VD); |
| 190 | if (const auto *VarD = dyn_cast<VarDecl>(VD)) { |
| 191 | if (!isa<ParmVarDecl>(VarD) && VarD->hasInit()) { |
| 192 | const bool SavedAllEscaped = AllEscaped; |
| 193 | AllEscaped = true; |
| 194 | Visit(VarD->getInit()); |
| 195 | AllEscaped = SavedAllEscaped; |
| 196 | } |
| 197 | } |
| 198 | } |
| 199 | } |
| 200 | void VisitOpenMPCapturedStmt(const CapturedStmt *S) { |
| 201 | if (!S) |
| 202 | return; |
| 203 | for (const auto &C : S->captures()) { |
| 204 | if (C.capturesVariable() && !C.capturesVariableByCopy()) { |
| 205 | const ValueDecl *VD = C.getCapturedVar(); |
| 206 | markAsEscaped(VD); |
| 207 | if (isa<OMPCapturedExprDecl>(VD)) |
| 208 | VisitValueDecl(VD); |
| 209 | } |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | typedef std::pair<CharUnits /*Align*/, const ValueDecl *> VarsDataTy; |
| 214 | static bool stable_sort_comparator(const VarsDataTy P1, const VarsDataTy P2) { |
| 215 | return P1.first > P2.first; |
| 216 | } |
| 217 | |
| 218 | void buildRecordForGlobalizedVars() { |
| 219 | assert(!GlobalizedRD && |
| 220 | "Record for globalized variables is built already."); |
| 221 | if (EscapedDecls.empty()) |
| 222 | return; |
| 223 | ASTContext &C = CGF.getContext(); |
| 224 | SmallVector<VarsDataTy, 4> GlobalizedVars; |
| 225 | for (const auto *D : EscapedDecls) |
| 226 | GlobalizedVars.emplace_back(C.getDeclAlign(D), D); |
| 227 | std::stable_sort(GlobalizedVars.begin(), GlobalizedVars.end(), |
| 228 | stable_sort_comparator); |
| 229 | // Build struct _globalized_locals_ty { |
| 230 | // /* globalized vars */ |
| 231 | // }; |
| 232 | GlobalizedRD = C.buildImplicitRecord("_globalized_locals_ty"); |
| 233 | GlobalizedRD->startDefinition(); |
| 234 | for (const auto &Pair : GlobalizedVars) { |
| 235 | const ValueDecl *VD = Pair.second; |
| 236 | QualType Type = VD->getType(); |
| 237 | if (Type->isLValueReferenceType()) |
| 238 | Type = C.getPointerType(Type.getNonReferenceType()); |
| 239 | else |
| 240 | Type = Type.getNonReferenceType(); |
| 241 | SourceLocation Loc = VD->getLocation(); |
| 242 | auto *Field = FieldDecl::Create( |
| 243 | C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type, |
| 244 | C.getTrivialTypeSourceInfo(Type, SourceLocation()), |
| 245 | /*BW=*/nullptr, /*Mutable=*/false, |
| 246 | /*InitStyle=*/ICIS_NoInit); |
| 247 | Field->setAccess(AS_public); |
| 248 | GlobalizedRD->addDecl(Field); |
| 249 | if (VD->hasAttrs()) { |
| 250 | for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()), |
| 251 | E(VD->getAttrs().end()); |
| 252 | I != E; ++I) |
| 253 | Field->addAttr(*I); |
| 254 | } |
| 255 | MappedDeclsFields.try_emplace(VD, Field); |
| 256 | } |
| 257 | GlobalizedRD->completeDefinition(); |
| 258 | } |
| 259 | |
| 260 | public: |
| 261 | CheckVarsEscapingDeclContext(CodeGenFunction &CGF, |
| 262 | ArrayRef<const ValueDecl *> IgnoredDecls) |
| 263 | : CGF(CGF), IgnoredDecls(IgnoredDecls.begin(), IgnoredDecls.end()) {} |
| 264 | virtual ~CheckVarsEscapingDeclContext() = default; |
| 265 | void VisitDeclStmt(const DeclStmt *S) { |
| 266 | if (!S) |
| 267 | return; |
| 268 | for (const auto *D : S->decls()) |
| 269 | if (const auto *VD = dyn_cast_or_null<ValueDecl>(D)) |
| 270 | VisitValueDecl(VD); |
| 271 | } |
| 272 | void VisitOMPExecutableDirective(const OMPExecutableDirective *D) { |
| 273 | if (!D) |
| 274 | return; |
| 275 | if (D->hasAssociatedStmt()) { |
| 276 | if (const auto *S = |
| 277 | dyn_cast_or_null<CapturedStmt>(D->getAssociatedStmt())) |
| 278 | VisitOpenMPCapturedStmt(S); |
| 279 | } |
| 280 | } |
| 281 | void VisitCapturedStmt(const CapturedStmt *S) { |
| 282 | if (!S) |
| 283 | return; |
| 284 | for (const auto &C : S->captures()) { |
| 285 | if (C.capturesVariable() && !C.capturesVariableByCopy()) { |
| 286 | const ValueDecl *VD = C.getCapturedVar(); |
| 287 | markAsEscaped(VD); |
| 288 | if (isa<OMPCapturedExprDecl>(VD)) |
| 289 | VisitValueDecl(VD); |
| 290 | } |
| 291 | } |
| 292 | } |
| 293 | void VisitLambdaExpr(const LambdaExpr *E) { |
| 294 | if (!E) |
| 295 | return; |
| 296 | for (const auto &C : E->captures()) { |
| 297 | if (C.capturesVariable()) { |
| 298 | if (C.getCaptureKind() == LCK_ByRef) { |
| 299 | const ValueDecl *VD = C.getCapturedVar(); |
| 300 | markAsEscaped(VD); |
| 301 | if (E->isInitCapture(&C) || isa<OMPCapturedExprDecl>(VD)) |
| 302 | VisitValueDecl(VD); |
| 303 | } |
| 304 | } |
| 305 | } |
| 306 | } |
| 307 | void VisitBlockExpr(const BlockExpr *E) { |
| 308 | if (!E) |
| 309 | return; |
| 310 | for (const auto &C : E->getBlockDecl()->captures()) { |
| 311 | if (C.isByRef()) { |
| 312 | const VarDecl *VD = C.getVariable(); |
| 313 | markAsEscaped(VD); |
| 314 | if (isa<OMPCapturedExprDecl>(VD) || VD->isInitCapture()) |
| 315 | VisitValueDecl(VD); |
| 316 | } |
| 317 | } |
| 318 | } |
| 319 | void VisitCallExpr(const CallExpr *E) { |
| 320 | if (!E) |
| 321 | return; |
| 322 | for (const Expr *Arg : E->arguments()) { |
| 323 | if (!Arg) |
| 324 | continue; |
| 325 | if (Arg->isLValue()) { |
| 326 | const bool SavedAllEscaped = AllEscaped; |
| 327 | AllEscaped = true; |
| 328 | Visit(Arg); |
| 329 | AllEscaped = SavedAllEscaped; |
| 330 | } else |
| 331 | Visit(Arg); |
| 332 | } |
| 333 | Visit(E->getCallee()); |
| 334 | } |
| 335 | void VisitDeclRefExpr(const DeclRefExpr *E) { |
| 336 | if (!E) |
| 337 | return; |
| 338 | const ValueDecl *VD = E->getDecl(); |
| 339 | if (AllEscaped) |
| 340 | markAsEscaped(VD); |
| 341 | if (isa<OMPCapturedExprDecl>(VD)) |
| 342 | VisitValueDecl(VD); |
| 343 | else if (const auto *VarD = dyn_cast<VarDecl>(VD)) |
| 344 | if (VarD->isInitCapture()) |
| 345 | VisitValueDecl(VD); |
| 346 | } |
| 347 | void VisitUnaryOperator(const UnaryOperator *E) { |
| 348 | if (!E) |
| 349 | return; |
| 350 | if (E->getOpcode() == UO_AddrOf) { |
| 351 | const bool SavedAllEscaped = AllEscaped; |
| 352 | AllEscaped = true; |
| 353 | Visit(E->getSubExpr()); |
| 354 | AllEscaped = SavedAllEscaped; |
| 355 | } else |
| 356 | Visit(E->getSubExpr()); |
| 357 | } |
| 358 | void VisitImplicitCastExpr(const ImplicitCastExpr *E) { |
| 359 | if (!E) |
| 360 | return; |
| 361 | if (E->getCastKind() == CK_ArrayToPointerDecay) { |
| 362 | const bool SavedAllEscaped = AllEscaped; |
| 363 | AllEscaped = true; |
| 364 | Visit(E->getSubExpr()); |
| 365 | AllEscaped = SavedAllEscaped; |
| 366 | } else |
| 367 | Visit(E->getSubExpr()); |
| 368 | } |
| 369 | void VisitExpr(const Expr *E) { |
| 370 | if (!E) |
| 371 | return; |
| 372 | bool SavedAllEscaped = AllEscaped; |
| 373 | if (!E->isLValue()) |
| 374 | AllEscaped = false; |
| 375 | for (const auto *Child : E->children()) |
| 376 | if (Child) |
| 377 | Visit(Child); |
| 378 | AllEscaped = SavedAllEscaped; |
| 379 | } |
| 380 | void VisitStmt(const Stmt *S) { |
| 381 | if (!S) |
| 382 | return; |
| 383 | for (const auto *Child : S->children()) |
| 384 | if (Child) |
| 385 | Visit(Child); |
| 386 | } |
| 387 | |
| 388 | const RecordDecl *getGlobalizedRecord() { |
| 389 | if (!GlobalizedRD) |
| 390 | buildRecordForGlobalizedVars(); |
| 391 | return GlobalizedRD; |
| 392 | } |
| 393 | |
| 394 | const FieldDecl *getFieldForGlobalizedVar(const ValueDecl *VD) const { |
| 395 | assert(GlobalizedRD && |
| 396 | "Record for globalized variables must be generated already."); |
| 397 | auto I = MappedDeclsFields.find(VD); |
| 398 | if (I == MappedDeclsFields.end()) |
| 399 | return nullptr; |
| 400 | return I->getSecond(); |
| 401 | } |
| 402 | |
| 403 | ArrayRef<const ValueDecl *> getEscapedDecls() const { |
| 404 | return EscapedDecls.getArrayRef(); |
| 405 | } |
| 406 | }; |
Arpith Chacko Jacob | bb36fe8 | 2017-01-10 15:42:51 +0000 | [diff] [blame] | 407 | } // anonymous namespace |
Arpith Chacko Jacob | ccf2f73 | 2017-01-03 20:19:56 +0000 | [diff] [blame] | 408 | |
| 409 | /// Get the GPU warp size. |
| 410 | static llvm::Value *getNVPTXWarpSize(CodeGenFunction &CGF) { |
Alexey Bataev | 3c595a6 | 2017-08-14 15:01:03 +0000 | [diff] [blame] | 411 | return CGF.EmitRuntimeCall( |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 412 | llvm::Intrinsic::getDeclaration( |
Arpith Chacko Jacob | ccf2f73 | 2017-01-03 20:19:56 +0000 | [diff] [blame] | 413 | &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_warpsize), |
Alexey Bataev | 3c595a6 | 2017-08-14 15:01:03 +0000 | [diff] [blame] | 414 | "nvptx_warp_size"); |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 415 | } |
| 416 | |
Arpith Chacko Jacob | ccf2f73 | 2017-01-03 20:19:56 +0000 | [diff] [blame] | 417 | /// Get the id of the current thread on the GPU. |
| 418 | static llvm::Value *getNVPTXThreadID(CodeGenFunction &CGF) { |
Alexey Bataev | 3c595a6 | 2017-08-14 15:01:03 +0000 | [diff] [blame] | 419 | return CGF.EmitRuntimeCall( |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 420 | llvm::Intrinsic::getDeclaration( |
Arpith Chacko Jacob | ccf2f73 | 2017-01-03 20:19:56 +0000 | [diff] [blame] | 421 | &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_tid_x), |
Alexey Bataev | 3c595a6 | 2017-08-14 15:01:03 +0000 | [diff] [blame] | 422 | "nvptx_tid"); |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 423 | } |
| 424 | |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 425 | /// Get the id of the warp in the block. |
| 426 | /// We assume that the warp size is 32, which is always the case |
| 427 | /// on the NVPTX device, to generate more efficient code. |
| 428 | static llvm::Value *getNVPTXWarpID(CodeGenFunction &CGF) { |
| 429 | CGBuilderTy &Bld = CGF.Builder; |
| 430 | return Bld.CreateAShr(getNVPTXThreadID(CGF), LaneIDBits, "nvptx_warp_id"); |
| 431 | } |
| 432 | |
| 433 | /// Get the id of the current lane in the Warp. |
| 434 | /// We assume that the warp size is 32, which is always the case |
| 435 | /// on the NVPTX device, to generate more efficient code. |
| 436 | static llvm::Value *getNVPTXLaneID(CodeGenFunction &CGF) { |
| 437 | CGBuilderTy &Bld = CGF.Builder; |
| 438 | return Bld.CreateAnd(getNVPTXThreadID(CGF), Bld.getInt32(LaneIDMask), |
| 439 | "nvptx_lane_id"); |
| 440 | } |
| 441 | |
Arpith Chacko Jacob | ccf2f73 | 2017-01-03 20:19:56 +0000 | [diff] [blame] | 442 | /// Get the maximum number of threads in a block of the GPU. |
| 443 | static llvm::Value *getNVPTXNumThreads(CodeGenFunction &CGF) { |
Alexey Bataev | 3c595a6 | 2017-08-14 15:01:03 +0000 | [diff] [blame] | 444 | return CGF.EmitRuntimeCall( |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 445 | llvm::Intrinsic::getDeclaration( |
Arpith Chacko Jacob | ccf2f73 | 2017-01-03 20:19:56 +0000 | [diff] [blame] | 446 | &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_ntid_x), |
Alexey Bataev | 3c595a6 | 2017-08-14 15:01:03 +0000 | [diff] [blame] | 447 | "nvptx_num_threads"); |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 448 | } |
| 449 | |
Arpith Chacko Jacob | ccf2f73 | 2017-01-03 20:19:56 +0000 | [diff] [blame] | 450 | /// Get barrier to synchronize all threads in a block. |
| 451 | static void getNVPTXCTABarrier(CodeGenFunction &CGF) { |
Alexey Bataev | 3c595a6 | 2017-08-14 15:01:03 +0000 | [diff] [blame] | 452 | CGF.EmitRuntimeCall(llvm::Intrinsic::getDeclaration( |
Arpith Chacko Jacob | ccf2f73 | 2017-01-03 20:19:56 +0000 | [diff] [blame] | 453 | &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_barrier0)); |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 454 | } |
| 455 | |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 456 | /// Get barrier #ID to synchronize selected (multiple of warp size) threads in |
| 457 | /// a CTA. |
| 458 | static void getNVPTXBarrier(CodeGenFunction &CGF, int ID, |
| 459 | llvm::Value *NumThreads) { |
| 460 | CGBuilderTy &Bld = CGF.Builder; |
| 461 | llvm::Value *Args[] = {Bld.getInt32(ID), NumThreads}; |
Alexey Bataev | 3c595a6 | 2017-08-14 15:01:03 +0000 | [diff] [blame] | 462 | CGF.EmitRuntimeCall(llvm::Intrinsic::getDeclaration( |
| 463 | &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_barrier), |
| 464 | Args); |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 465 | } |
| 466 | |
Arpith Chacko Jacob | ccf2f73 | 2017-01-03 20:19:56 +0000 | [diff] [blame] | 467 | /// Synchronize all GPU threads in a block. |
| 468 | static void syncCTAThreads(CodeGenFunction &CGF) { getNVPTXCTABarrier(CGF); } |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 469 | |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 470 | /// Synchronize worker threads in a parallel region. |
| 471 | static void syncParallelThreads(CodeGenFunction &CGF, llvm::Value *NumThreads) { |
| 472 | return getNVPTXBarrier(CGF, NB_Parallel, NumThreads); |
| 473 | } |
| 474 | |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 475 | /// Get the value of the thread_limit clause in the teams directive. |
Arpith Chacko Jacob | 44a87c9 | 2017-01-18 19:35:00 +0000 | [diff] [blame] | 476 | /// For the 'generic' execution mode, the runtime encodes thread_limit in |
| 477 | /// the launch parameters, always starting thread_limit+warpSize threads per |
| 478 | /// CTA. The threads in the last warp are reserved for master execution. |
| 479 | /// For the 'spmd' execution mode, all threads in a CTA are part of the team. |
| 480 | static llvm::Value *getThreadLimit(CodeGenFunction &CGF, |
| 481 | bool IsInSpmdExecutionMode = false) { |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 482 | CGBuilderTy &Bld = CGF.Builder; |
Arpith Chacko Jacob | 44a87c9 | 2017-01-18 19:35:00 +0000 | [diff] [blame] | 483 | return IsInSpmdExecutionMode |
| 484 | ? getNVPTXNumThreads(CGF) |
| 485 | : Bld.CreateSub(getNVPTXNumThreads(CGF), getNVPTXWarpSize(CGF), |
| 486 | "thread_limit"); |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 487 | } |
| 488 | |
Arpith Chacko Jacob | ccf2f73 | 2017-01-03 20:19:56 +0000 | [diff] [blame] | 489 | /// Get the thread id of the OMP master thread. |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 490 | /// The master thread id is the first thread (lane) of the last warp in the |
| 491 | /// GPU block. Warp size is assumed to be some power of 2. |
| 492 | /// Thread id is 0 indexed. |
| 493 | /// E.g: If NumThreads is 33, master id is 32. |
| 494 | /// If NumThreads is 64, master id is 32. |
| 495 | /// If NumThreads is 1024, master id is 992. |
Arpith Chacko Jacob | ccf2f73 | 2017-01-03 20:19:56 +0000 | [diff] [blame] | 496 | static llvm::Value *getMasterThreadID(CodeGenFunction &CGF) { |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 497 | CGBuilderTy &Bld = CGF.Builder; |
| 498 | llvm::Value *NumThreads = getNVPTXNumThreads(CGF); |
| 499 | |
| 500 | // We assume that the warp size is a power of 2. |
| 501 | llvm::Value *Mask = Bld.CreateSub(getNVPTXWarpSize(CGF), Bld.getInt32(1)); |
| 502 | |
| 503 | return Bld.CreateAnd(Bld.CreateSub(NumThreads, Bld.getInt32(1)), |
| 504 | Bld.CreateNot(Mask), "master_tid"); |
| 505 | } |
| 506 | |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 507 | CGOpenMPRuntimeNVPTX::WorkerFunctionState::WorkerFunctionState( |
Alexey Bataev | 7cae94e | 2018-01-04 19:45:16 +0000 | [diff] [blame] | 508 | CodeGenModule &CGM, SourceLocation Loc) |
| 509 | : WorkerFn(nullptr), CGFI(nullptr), Loc(Loc) { |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 510 | createWorkerFunction(CGM); |
Vasileios Kalintiris | e5c0959 | 2016-03-22 10:41:20 +0000 | [diff] [blame] | 511 | } |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 512 | |
| 513 | void CGOpenMPRuntimeNVPTX::WorkerFunctionState::createWorkerFunction( |
| 514 | CodeGenModule &CGM) { |
| 515 | // Create an worker function with no arguments. |
| 516 | CGFI = &CGM.getTypes().arrangeNullaryFunction(); |
| 517 | |
| 518 | WorkerFn = llvm::Function::Create( |
| 519 | CGM.getTypes().GetFunctionType(*CGFI), llvm::GlobalValue::InternalLinkage, |
Alexey Bataev | aee9389 | 2018-01-08 20:09:47 +0000 | [diff] [blame] | 520 | /*placeholder=*/"_worker", &CGM.getModule()); |
Rafael Espindola | 51ec5a9 | 2018-02-28 23:46:35 +0000 | [diff] [blame] | 521 | CGM.SetInternalFunctionAttributes(GlobalDecl(), WorkerFn, *CGFI); |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 522 | } |
| 523 | |
Arpith Chacko Jacob | 44a87c9 | 2017-01-18 19:35:00 +0000 | [diff] [blame] | 524 | bool CGOpenMPRuntimeNVPTX::isInSpmdExecutionMode() const { |
| 525 | return CurrentExecutionMode == CGOpenMPRuntimeNVPTX::ExecutionMode::Spmd; |
| 526 | } |
| 527 | |
| 528 | static CGOpenMPRuntimeNVPTX::ExecutionMode |
Carlo Bertolli | 7971209 | 2018-02-28 20:48:35 +0000 | [diff] [blame] | 529 | getExecutionMode(CodeGenModule &CGM) { |
| 530 | return CGM.getLangOpts().OpenMPCUDAMode |
| 531 | ? CGOpenMPRuntimeNVPTX::ExecutionMode::Spmd |
| 532 | : CGOpenMPRuntimeNVPTX::ExecutionMode::Generic; |
Arpith Chacko Jacob | 44a87c9 | 2017-01-18 19:35:00 +0000 | [diff] [blame] | 533 | } |
| 534 | |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 535 | void CGOpenMPRuntimeNVPTX::emitGenericKernel(const OMPExecutableDirective &D, |
| 536 | StringRef ParentName, |
| 537 | llvm::Function *&OutlinedFn, |
| 538 | llvm::Constant *&OutlinedFnID, |
| 539 | bool IsOffloadEntry, |
| 540 | const RegionCodeGenTy &CodeGen) { |
Arpith Chacko Jacob | 44a87c9 | 2017-01-18 19:35:00 +0000 | [diff] [blame] | 541 | ExecutionModeRAII ModeRAII(CurrentExecutionMode, |
| 542 | CGOpenMPRuntimeNVPTX::ExecutionMode::Generic); |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 543 | EntryFunctionState EST; |
Alexey Bataev | 7cae94e | 2018-01-04 19:45:16 +0000 | [diff] [blame] | 544 | WorkerFunctionState WST(CGM, D.getLocStart()); |
Arpith Chacko Jacob | bb36fe8 | 2017-01-10 15:42:51 +0000 | [diff] [blame] | 545 | Work.clear(); |
Gheorghe-Teodor Bercea | d3dcf2f | 2018-03-14 14:17:45 +0000 | [diff] [blame] | 546 | WrapperFunctionsMap.clear(); |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 547 | |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 548 | // Emit target region as a standalone region. |
| 549 | class NVPTXPrePostActionTy : public PrePostActionTy { |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 550 | CGOpenMPRuntimeNVPTX::EntryFunctionState &EST; |
| 551 | CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST; |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 552 | |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 553 | public: |
Alexey Bataev | 7cae94e | 2018-01-04 19:45:16 +0000 | [diff] [blame] | 554 | NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX::EntryFunctionState &EST, |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 555 | CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST) |
Alexey Bataev | 7cae94e | 2018-01-04 19:45:16 +0000 | [diff] [blame] | 556 | : EST(EST), WST(WST) {} |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 557 | void Enter(CodeGenFunction &CGF) override { |
Alexey Bataev | 7cae94e | 2018-01-04 19:45:16 +0000 | [diff] [blame] | 558 | static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime()) |
| 559 | .emitGenericEntryHeader(CGF, EST, WST); |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 560 | } |
| 561 | void Exit(CodeGenFunction &CGF) override { |
Alexey Bataev | 7cae94e | 2018-01-04 19:45:16 +0000 | [diff] [blame] | 562 | static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime()) |
| 563 | .emitGenericEntryFooter(CGF, EST); |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 564 | } |
Alexey Bataev | 7cae94e | 2018-01-04 19:45:16 +0000 | [diff] [blame] | 565 | } Action(EST, WST); |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 566 | CodeGen.setAction(Action); |
| 567 | emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID, |
| 568 | IsOffloadEntry, CodeGen); |
| 569 | |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 570 | // Now change the name of the worker function to correspond to this target |
| 571 | // region's entry function. |
| 572 | WST.WorkerFn->setName(OutlinedFn->getName() + "_worker"); |
Alexey Bataev | aee9389 | 2018-01-08 20:09:47 +0000 | [diff] [blame] | 573 | |
| 574 | // Create the worker function |
| 575 | emitWorkerFunction(WST); |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 576 | } |
| 577 | |
| 578 | // Setup NVPTX threads for master-worker OpenMP scheme. |
| 579 | void CGOpenMPRuntimeNVPTX::emitGenericEntryHeader(CodeGenFunction &CGF, |
| 580 | EntryFunctionState &EST, |
| 581 | WorkerFunctionState &WST) { |
| 582 | CGBuilderTy &Bld = CGF.Builder; |
| 583 | |
| 584 | llvm::BasicBlock *WorkerBB = CGF.createBasicBlock(".worker"); |
| 585 | llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck"); |
| 586 | llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master"); |
| 587 | EST.ExitBB = CGF.createBasicBlock(".exit"); |
| 588 | |
| 589 | auto *IsWorker = |
| 590 | Bld.CreateICmpULT(getNVPTXThreadID(CGF), getThreadLimit(CGF)); |
| 591 | Bld.CreateCondBr(IsWorker, WorkerBB, MasterCheckBB); |
| 592 | |
| 593 | CGF.EmitBlock(WorkerBB); |
Alexey Bataev | 7cae94e | 2018-01-04 19:45:16 +0000 | [diff] [blame] | 594 | emitOutlinedFunctionCall(CGF, WST.Loc, WST.WorkerFn); |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 595 | CGF.EmitBranch(EST.ExitBB); |
| 596 | |
| 597 | CGF.EmitBlock(MasterCheckBB); |
| 598 | auto *IsMaster = |
| 599 | Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF)); |
| 600 | Bld.CreateCondBr(IsMaster, MasterBB, EST.ExitBB); |
| 601 | |
| 602 | CGF.EmitBlock(MasterBB); |
Gheorghe-Teodor Bercea | d3dcf2f | 2018-03-14 14:17:45 +0000 | [diff] [blame] | 603 | // SEQUENTIAL (MASTER) REGION START |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 604 | // First action in sequential region: |
| 605 | // Initialize the state of the OpenMP runtime library on the GPU. |
Jonas Hahnfeld | 891c7fb | 2017-11-22 14:46:49 +0000 | [diff] [blame] | 606 | // TODO: Optimize runtime initialization and pass in correct value. |
| 607 | llvm::Value *Args[] = {getThreadLimit(CGF), |
| 608 | Bld.getInt16(/*RequiresOMPRuntime=*/1)}; |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 609 | CGF.EmitRuntimeCall( |
| 610 | createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_init), Args); |
Gheorghe-Teodor Bercea | d3dcf2f | 2018-03-14 14:17:45 +0000 | [diff] [blame] | 611 | |
| 612 | // For data sharing, we need to initialize the stack. |
| 613 | CGF.EmitRuntimeCall( |
| 614 | createNVPTXRuntimeFunction( |
| 615 | OMPRTL_NVPTX__kmpc_data_sharing_init_stack)); |
| 616 | |
| 617 | const auto I = FunctionGlobalizedDecls.find(CGF.CurFn); |
| 618 | if (I == FunctionGlobalizedDecls.end()) |
| 619 | return; |
| 620 | const RecordDecl *GlobalizedVarsRecord = I->getSecond().first; |
| 621 | QualType RecTy = CGM.getContext().getRecordType(GlobalizedVarsRecord); |
| 622 | |
| 623 | // Recover pointer to this function's global record. The runtime will |
| 624 | // handle the specifics of the allocation of the memory. |
| 625 | // Use actual memory size of the record including the padding |
| 626 | // for alignment purposes. |
| 627 | unsigned Alignment = |
| 628 | CGM.getContext().getTypeAlignInChars(RecTy).getQuantity(); |
| 629 | unsigned GlobalRecordSize = |
| 630 | CGM.getContext().getTypeSizeInChars(RecTy).getQuantity(); |
| 631 | GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment); |
| 632 | // TODO: allow the usage of shared memory to be controlled by |
| 633 | // the user, for now, default to global. |
| 634 | llvm::Value *GlobalRecordSizeArg[] = { |
| 635 | llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize), |
| 636 | CGF.Builder.getInt16(/*UseSharedMemory=*/0)}; |
| 637 | llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall( |
| 638 | createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_push_stack), |
| 639 | GlobalRecordSizeArg); |
| 640 | llvm::Value *GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast( |
| 641 | GlobalRecValue, CGF.ConvertTypeForMem(RecTy)->getPointerTo()); |
| 642 | FunctionToGlobalRecPtr.try_emplace(CGF.CurFn, GlobalRecValue); |
| 643 | |
| 644 | // Emit the "global alloca" which is a GEP from the global declaration record |
| 645 | // using the pointer returned by the runtime. |
| 646 | LValue Base = CGF.MakeNaturalAlignPointeeAddrLValue(GlobalRecCastAddr, RecTy); |
| 647 | auto &Res = I->getSecond().second; |
| 648 | for (auto &Rec : Res) { |
| 649 | const FieldDecl *FD = Rec.second.first; |
| 650 | LValue VarAddr = CGF.EmitLValueForField(Base, FD); |
| 651 | Rec.second.second = VarAddr.getAddress(); |
| 652 | } |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 653 | } |
| 654 | |
| 655 | void CGOpenMPRuntimeNVPTX::emitGenericEntryFooter(CodeGenFunction &CGF, |
| 656 | EntryFunctionState &EST) { |
Gheorghe-Teodor Bercea | d3dcf2f | 2018-03-14 14:17:45 +0000 | [diff] [blame] | 657 | const auto I = FunctionGlobalizedDecls.find(CGF.CurFn); |
| 658 | if (I != FunctionGlobalizedDecls.end()) { |
| 659 | if (!CGF.HaveInsertPoint()) |
| 660 | return; |
| 661 | auto I = FunctionToGlobalRecPtr.find(CGF.CurFn); |
| 662 | if (I != FunctionToGlobalRecPtr.end()) { |
| 663 | llvm::Value *Args[] = {I->getSecond()}; |
| 664 | CGF.EmitRuntimeCall( |
| 665 | createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_pop_stack), |
| 666 | Args); |
| 667 | } |
| 668 | } |
| 669 | |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 670 | if (!EST.ExitBB) |
| 671 | EST.ExitBB = CGF.createBasicBlock(".exit"); |
| 672 | |
| 673 | llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".termination.notifier"); |
| 674 | CGF.EmitBranch(TerminateBB); |
| 675 | |
| 676 | CGF.EmitBlock(TerminateBB); |
| 677 | // Signal termination condition. |
Jonas Hahnfeld | 891c7fb | 2017-11-22 14:46:49 +0000 | [diff] [blame] | 678 | // TODO: Optimize runtime initialization and pass in correct value. |
| 679 | llvm::Value *Args[] = {CGF.Builder.getInt16(/*IsOMPRuntimeInitialized=*/1)}; |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 680 | CGF.EmitRuntimeCall( |
Jonas Hahnfeld | 891c7fb | 2017-11-22 14:46:49 +0000 | [diff] [blame] | 681 | createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_deinit), Args); |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 682 | // Barrier to terminate worker threads. |
| 683 | syncCTAThreads(CGF); |
| 684 | // Master thread jumps to exit point. |
| 685 | CGF.EmitBranch(EST.ExitBB); |
| 686 | |
| 687 | CGF.EmitBlock(EST.ExitBB); |
| 688 | EST.ExitBB = nullptr; |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 689 | } |
| 690 | |
Arpith Chacko Jacob | 44a87c9 | 2017-01-18 19:35:00 +0000 | [diff] [blame] | 691 | void CGOpenMPRuntimeNVPTX::emitSpmdKernel(const OMPExecutableDirective &D, |
| 692 | StringRef ParentName, |
| 693 | llvm::Function *&OutlinedFn, |
| 694 | llvm::Constant *&OutlinedFnID, |
| 695 | bool IsOffloadEntry, |
| 696 | const RegionCodeGenTy &CodeGen) { |
| 697 | ExecutionModeRAII ModeRAII(CurrentExecutionMode, |
| 698 | CGOpenMPRuntimeNVPTX::ExecutionMode::Spmd); |
| 699 | EntryFunctionState EST; |
| 700 | |
| 701 | // Emit target region as a standalone region. |
| 702 | class NVPTXPrePostActionTy : public PrePostActionTy { |
| 703 | CGOpenMPRuntimeNVPTX &RT; |
| 704 | CGOpenMPRuntimeNVPTX::EntryFunctionState &EST; |
| 705 | const OMPExecutableDirective &D; |
| 706 | |
| 707 | public: |
| 708 | NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT, |
| 709 | CGOpenMPRuntimeNVPTX::EntryFunctionState &EST, |
| 710 | const OMPExecutableDirective &D) |
| 711 | : RT(RT), EST(EST), D(D) {} |
| 712 | void Enter(CodeGenFunction &CGF) override { |
| 713 | RT.emitSpmdEntryHeader(CGF, EST, D); |
| 714 | } |
| 715 | void Exit(CodeGenFunction &CGF) override { |
| 716 | RT.emitSpmdEntryFooter(CGF, EST); |
| 717 | } |
| 718 | } Action(*this, EST, D); |
| 719 | CodeGen.setAction(Action); |
| 720 | emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID, |
| 721 | IsOffloadEntry, CodeGen); |
Arpith Chacko Jacob | 44a87c9 | 2017-01-18 19:35:00 +0000 | [diff] [blame] | 722 | } |
| 723 | |
| 724 | void CGOpenMPRuntimeNVPTX::emitSpmdEntryHeader( |
| 725 | CodeGenFunction &CGF, EntryFunctionState &EST, |
| 726 | const OMPExecutableDirective &D) { |
| 727 | auto &Bld = CGF.Builder; |
| 728 | |
| 729 | // Setup BBs in entry function. |
| 730 | llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute"); |
| 731 | EST.ExitBB = CGF.createBasicBlock(".exit"); |
| 732 | |
| 733 | // Initialize the OMP state in the runtime; called by all active threads. |
| 734 | // TODO: Set RequiresOMPRuntime and RequiresDataSharing parameters |
| 735 | // based on code analysis of the target region. |
| 736 | llvm::Value *Args[] = {getThreadLimit(CGF, /*IsInSpmdExecutionMode=*/true), |
| 737 | /*RequiresOMPRuntime=*/Bld.getInt16(1), |
| 738 | /*RequiresDataSharing=*/Bld.getInt16(1)}; |
| 739 | CGF.EmitRuntimeCall( |
| 740 | createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_init), Args); |
| 741 | CGF.EmitBranch(ExecuteBB); |
| 742 | |
| 743 | CGF.EmitBlock(ExecuteBB); |
| 744 | } |
| 745 | |
| 746 | void CGOpenMPRuntimeNVPTX::emitSpmdEntryFooter(CodeGenFunction &CGF, |
| 747 | EntryFunctionState &EST) { |
| 748 | if (!EST.ExitBB) |
| 749 | EST.ExitBB = CGF.createBasicBlock(".exit"); |
| 750 | |
| 751 | llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit"); |
| 752 | CGF.EmitBranch(OMPDeInitBB); |
| 753 | |
| 754 | CGF.EmitBlock(OMPDeInitBB); |
| 755 | // DeInitialize the OMP state in the runtime; called by all active threads. |
| 756 | CGF.EmitRuntimeCall( |
| 757 | createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_deinit), None); |
| 758 | CGF.EmitBranch(EST.ExitBB); |
| 759 | |
| 760 | CGF.EmitBlock(EST.ExitBB); |
| 761 | EST.ExitBB = nullptr; |
| 762 | } |
| 763 | |
| 764 | // Create a unique global variable to indicate the execution mode of this target |
| 765 | // region. The execution mode is either 'generic', or 'spmd' depending on the |
| 766 | // target directive. This variable is picked up by the offload library to setup |
| 767 | // the device appropriately before kernel launch. If the execution mode is |
| 768 | // 'generic', the runtime reserves one warp for the master, otherwise, all |
| 769 | // warps participate in parallel work. |
| 770 | static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name, |
| 771 | CGOpenMPRuntimeNVPTX::ExecutionMode Mode) { |
| 772 | (void)new llvm::GlobalVariable( |
| 773 | CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true, |
| 774 | llvm::GlobalValue::WeakAnyLinkage, |
| 775 | llvm::ConstantInt::get(CGM.Int8Ty, Mode), Name + Twine("_exec_mode")); |
| 776 | } |
| 777 | |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 778 | void CGOpenMPRuntimeNVPTX::emitWorkerFunction(WorkerFunctionState &WST) { |
Gheorghe-Teodor Bercea | eb89b1d | 2017-11-21 15:54:54 +0000 | [diff] [blame] | 779 | ASTContext &Ctx = CGM.getContext(); |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 780 | |
| 781 | CodeGenFunction CGF(CGM, /*suppressNewContext=*/true); |
Alexey Bataev | 7cae94e | 2018-01-04 19:45:16 +0000 | [diff] [blame] | 782 | CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, *WST.CGFI, {}, |
| 783 | WST.Loc, WST.Loc); |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 784 | emitWorkerLoop(CGF, WST); |
| 785 | CGF.FinishFunction(); |
| 786 | } |
| 787 | |
| 788 | void CGOpenMPRuntimeNVPTX::emitWorkerLoop(CodeGenFunction &CGF, |
| 789 | WorkerFunctionState &WST) { |
| 790 | // |
| 791 | // The workers enter this loop and wait for parallel work from the master. |
| 792 | // When the master encounters a parallel region it sets up the work + variable |
| 793 | // arguments, and wakes up the workers. The workers first check to see if |
| 794 | // they are required for the parallel region, i.e., within the # of requested |
| 795 | // parallel threads. The activated workers load the variable arguments and |
| 796 | // execute the parallel work. |
| 797 | // |
| 798 | |
| 799 | CGBuilderTy &Bld = CGF.Builder; |
| 800 | |
| 801 | llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work"); |
| 802 | llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers"); |
| 803 | llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel"); |
| 804 | llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel"); |
| 805 | llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel"); |
| 806 | llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit"); |
| 807 | |
| 808 | CGF.EmitBranch(AwaitBB); |
| 809 | |
| 810 | // Workers wait for work from master. |
| 811 | CGF.EmitBlock(AwaitBB); |
| 812 | // Wait for parallel work |
| 813 | syncCTAThreads(CGF); |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 814 | |
| 815 | Address WorkFn = |
| 816 | CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn"); |
| 817 | Address ExecStatus = |
| 818 | CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status"); |
| 819 | CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0)); |
| 820 | CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy)); |
| 821 | |
Jonas Hahnfeld | fa059ba | 2017-12-27 10:39:56 +0000 | [diff] [blame] | 822 | // TODO: Optimize runtime initialization and pass in correct value. |
Gheorghe-Teodor Bercea | 7d80da1 | 2018-03-07 21:59:50 +0000 | [diff] [blame] | 823 | llvm::Value *Args[] = {WorkFn.getPointer(), |
Jonas Hahnfeld | fa059ba | 2017-12-27 10:39:56 +0000 | [diff] [blame] | 824 | /*RequiresOMPRuntime=*/Bld.getInt16(1)}; |
Arpith Chacko Jacob | bb36fe8 | 2017-01-10 15:42:51 +0000 | [diff] [blame] | 825 | llvm::Value *Ret = CGF.EmitRuntimeCall( |
| 826 | createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args); |
| 827 | Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus); |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 828 | |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 829 | // On termination condition (workid == 0), exit loop. |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 830 | llvm::Value *ShouldTerminate = |
| 831 | Bld.CreateIsNull(Bld.CreateLoad(WorkFn), "should_terminate"); |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 832 | Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB); |
| 833 | |
| 834 | // Activate requested workers. |
| 835 | CGF.EmitBlock(SelectWorkersBB); |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 836 | llvm::Value *IsActive = |
| 837 | Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active"); |
| 838 | Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB); |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 839 | |
| 840 | // Signal start of parallel region. |
| 841 | CGF.EmitBlock(ExecuteBB); |
Arpith Chacko Jacob | bb36fe8 | 2017-01-10 15:42:51 +0000 | [diff] [blame] | 842 | |
| 843 | // Process work items: outlined parallel functions. |
| 844 | for (auto *W : Work) { |
| 845 | // Try to match this outlined function. |
| 846 | auto *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy); |
| 847 | |
| 848 | llvm::Value *WorkFnMatch = |
| 849 | Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match"); |
| 850 | |
| 851 | llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn"); |
| 852 | llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next"); |
| 853 | Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB); |
| 854 | |
| 855 | // Execute this outlined function. |
| 856 | CGF.EmitBlock(ExecuteFNBB); |
| 857 | |
Gheorghe-Teodor Bercea | d3dcf2f | 2018-03-14 14:17:45 +0000 | [diff] [blame] | 858 | // Insert call to work function via shared wrapper. The shared |
| 859 | // wrapper takes two arguments: |
| 860 | // - the parallelism level; |
| 861 | // - the master thread ID; |
| 862 | emitOutlinedFunctionCall(CGF, WST.Loc, W, |
| 863 | {Bld.getInt16(/*ParallelLevel=*/0), |
| 864 | getMasterThreadID(CGF)}); |
Arpith Chacko Jacob | bb36fe8 | 2017-01-10 15:42:51 +0000 | [diff] [blame] | 865 | |
| 866 | // Go to end of parallel region. |
| 867 | CGF.EmitBranch(TerminateBB); |
| 868 | |
| 869 | CGF.EmitBlock(CheckNextBB); |
| 870 | } |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 871 | |
| 872 | // Signal end of parallel region. |
| 873 | CGF.EmitBlock(TerminateBB); |
Arpith Chacko Jacob | bb36fe8 | 2017-01-10 15:42:51 +0000 | [diff] [blame] | 874 | CGF.EmitRuntimeCall( |
| 875 | createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_end_parallel), |
| 876 | llvm::None); |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 877 | CGF.EmitBranch(BarrierBB); |
| 878 | |
| 879 | // All active and inactive workers wait at a barrier after parallel region. |
| 880 | CGF.EmitBlock(BarrierBB); |
| 881 | // Barrier after parallel region. |
| 882 | syncCTAThreads(CGF); |
| 883 | CGF.EmitBranch(AwaitBB); |
| 884 | |
| 885 | // Exit target region. |
| 886 | CGF.EmitBlock(ExitBB); |
| 887 | } |
| 888 | |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 889 | /// \brief Returns specified OpenMP runtime function for the current OpenMP |
| 890 | /// implementation. Specialized for the NVPTX device. |
| 891 | /// \param Function OpenMP runtime function. |
| 892 | /// \return Specified function. |
| 893 | llvm::Constant * |
| 894 | CGOpenMPRuntimeNVPTX::createNVPTXRuntimeFunction(unsigned Function) { |
| 895 | llvm::Constant *RTLFn = nullptr; |
| 896 | switch (static_cast<OpenMPRTLFunctionNVPTX>(Function)) { |
| 897 | case OMPRTL_NVPTX__kmpc_kernel_init: { |
Jonas Hahnfeld | 891c7fb | 2017-11-22 14:46:49 +0000 | [diff] [blame] | 898 | // Build void __kmpc_kernel_init(kmp_int32 thread_limit, int16_t |
| 899 | // RequiresOMPRuntime); |
| 900 | llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty}; |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 901 | llvm::FunctionType *FnTy = |
| 902 | llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); |
| 903 | RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_init"); |
| 904 | break; |
| 905 | } |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 906 | case OMPRTL_NVPTX__kmpc_kernel_deinit: { |
Jonas Hahnfeld | 891c7fb | 2017-11-22 14:46:49 +0000 | [diff] [blame] | 907 | // Build void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized); |
| 908 | llvm::Type *TypeParams[] = {CGM.Int16Ty}; |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 909 | llvm::FunctionType *FnTy = |
Jonas Hahnfeld | 891c7fb | 2017-11-22 14:46:49 +0000 | [diff] [blame] | 910 | llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); |
Arpith Chacko Jacob | 406acdb | 2017-01-05 15:24:05 +0000 | [diff] [blame] | 911 | RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_deinit"); |
| 912 | break; |
| 913 | } |
Arpith Chacko Jacob | 44a87c9 | 2017-01-18 19:35:00 +0000 | [diff] [blame] | 914 | case OMPRTL_NVPTX__kmpc_spmd_kernel_init: { |
| 915 | // Build void __kmpc_spmd_kernel_init(kmp_int32 thread_limit, |
Jonas Hahnfeld | 891c7fb | 2017-11-22 14:46:49 +0000 | [diff] [blame] | 916 | // int16_t RequiresOMPRuntime, int16_t RequiresDataSharing); |
Arpith Chacko Jacob | 44a87c9 | 2017-01-18 19:35:00 +0000 | [diff] [blame] | 917 | llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty}; |
| 918 | llvm::FunctionType *FnTy = |
| 919 | llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); |
| 920 | RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_init"); |
| 921 | break; |
| 922 | } |
| 923 | case OMPRTL_NVPTX__kmpc_spmd_kernel_deinit: { |
| 924 | // Build void __kmpc_spmd_kernel_deinit(); |
| 925 | llvm::FunctionType *FnTy = |
| 926 | llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false); |
| 927 | RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_deinit"); |
| 928 | break; |
| 929 | } |
Arpith Chacko Jacob | bb36fe8 | 2017-01-10 15:42:51 +0000 | [diff] [blame] | 930 | case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: { |
| 931 | /// Build void __kmpc_kernel_prepare_parallel( |
Gheorghe-Teodor Bercea | 7d80da1 | 2018-03-07 21:59:50 +0000 | [diff] [blame] | 932 | /// void *outlined_function, int16_t IsOMPRuntimeInitialized); |
Gheorghe-Teodor Bercea | d3dcf2f | 2018-03-14 14:17:45 +0000 | [diff] [blame] | 933 | llvm::Type *TypeParams[] = {CGM.Int8PtrTy, CGM.Int16Ty}; |
Arpith Chacko Jacob | bb36fe8 | 2017-01-10 15:42:51 +0000 | [diff] [blame] | 934 | llvm::FunctionType *FnTy = |
| 935 | llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); |
| 936 | RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_prepare_parallel"); |
| 937 | break; |
| 938 | } |
| 939 | case OMPRTL_NVPTX__kmpc_kernel_parallel: { |
Gheorghe-Teodor Bercea | 7d80da1 | 2018-03-07 21:59:50 +0000 | [diff] [blame] | 940 | /// Build bool __kmpc_kernel_parallel(void **outlined_function, |
| 941 | /// int16_t IsOMPRuntimeInitialized); |
| 942 | llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy, CGM.Int16Ty}; |
Arpith Chacko Jacob | bb36fe8 | 2017-01-10 15:42:51 +0000 | [diff] [blame] | 943 | llvm::Type *RetTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy); |
| 944 | llvm::FunctionType *FnTy = |
| 945 | llvm::FunctionType::get(RetTy, TypeParams, /*isVarArg*/ false); |
| 946 | RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_parallel"); |
| 947 | break; |
| 948 | } |
| 949 | case OMPRTL_NVPTX__kmpc_kernel_end_parallel: { |
| 950 | /// Build void __kmpc_kernel_end_parallel(); |
| 951 | llvm::FunctionType *FnTy = |
| 952 | llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false); |
| 953 | RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_end_parallel"); |
| 954 | break; |
| 955 | } |
| 956 | case OMPRTL_NVPTX__kmpc_serialized_parallel: { |
| 957 | // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32 |
| 958 | // global_tid); |
| 959 | llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty}; |
| 960 | llvm::FunctionType *FnTy = |
| 961 | llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); |
| 962 | RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel"); |
| 963 | break; |
| 964 | } |
| 965 | case OMPRTL_NVPTX__kmpc_end_serialized_parallel: { |
| 966 | // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32 |
| 967 | // global_tid); |
| 968 | llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty}; |
| 969 | llvm::FunctionType *FnTy = |
| 970 | llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); |
| 971 | RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel"); |
| 972 | break; |
| 973 | } |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 974 | case OMPRTL_NVPTX__kmpc_shuffle_int32: { |
| 975 | // Build int32_t __kmpc_shuffle_int32(int32_t element, |
| 976 | // int16_t lane_offset, int16_t warp_size); |
| 977 | llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty}; |
| 978 | llvm::FunctionType *FnTy = |
| 979 | llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false); |
| 980 | RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int32"); |
| 981 | break; |
| 982 | } |
| 983 | case OMPRTL_NVPTX__kmpc_shuffle_int64: { |
| 984 | // Build int64_t __kmpc_shuffle_int64(int64_t element, |
| 985 | // int16_t lane_offset, int16_t warp_size); |
| 986 | llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int16Ty, CGM.Int16Ty}; |
| 987 | llvm::FunctionType *FnTy = |
| 988 | llvm::FunctionType::get(CGM.Int64Ty, TypeParams, /*isVarArg*/ false); |
| 989 | RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int64"); |
| 990 | break; |
| 991 | } |
| 992 | case OMPRTL_NVPTX__kmpc_parallel_reduce_nowait: { |
| 993 | // Build int32_t kmpc_nvptx_parallel_reduce_nowait(kmp_int32 global_tid, |
| 994 | // kmp_int32 num_vars, size_t reduce_size, void* reduce_data, |
| 995 | // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t |
| 996 | // lane_offset, int16_t Algorithm Version), |
| 997 | // void (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num)); |
| 998 | llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty, |
| 999 | CGM.Int16Ty, CGM.Int16Ty}; |
| 1000 | auto *ShuffleReduceFnTy = |
| 1001 | llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams, |
| 1002 | /*isVarArg=*/false); |
| 1003 | llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty}; |
| 1004 | auto *InterWarpCopyFnTy = |
| 1005 | llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams, |
| 1006 | /*isVarArg=*/false); |
| 1007 | llvm::Type *TypeParams[] = {CGM.Int32Ty, |
| 1008 | CGM.Int32Ty, |
| 1009 | CGM.SizeTy, |
| 1010 | CGM.VoidPtrTy, |
| 1011 | ShuffleReduceFnTy->getPointerTo(), |
| 1012 | InterWarpCopyFnTy->getPointerTo()}; |
| 1013 | llvm::FunctionType *FnTy = |
| 1014 | llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false); |
| 1015 | RTLFn = CGM.CreateRuntimeFunction( |
| 1016 | FnTy, /*Name=*/"__kmpc_nvptx_parallel_reduce_nowait"); |
| 1017 | break; |
| 1018 | } |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1019 | case OMPRTL_NVPTX__kmpc_teams_reduce_nowait: { |
| 1020 | // Build int32_t __kmpc_nvptx_teams_reduce_nowait(int32_t global_tid, |
| 1021 | // int32_t num_vars, size_t reduce_size, void *reduce_data, |
| 1022 | // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t |
| 1023 | // lane_offset, int16_t shortCircuit), |
| 1024 | // void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num), |
| 1025 | // void (*kmp_CopyToScratchpadFctPtr)(void *reduce_data, void * scratchpad, |
| 1026 | // int32_t index, int32_t width), |
| 1027 | // void (*kmp_LoadReduceFctPtr)(void *reduce_data, void * scratchpad, |
| 1028 | // int32_t index, int32_t width, int32_t reduce)) |
| 1029 | llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty, |
| 1030 | CGM.Int16Ty, CGM.Int16Ty}; |
| 1031 | auto *ShuffleReduceFnTy = |
| 1032 | llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams, |
| 1033 | /*isVarArg=*/false); |
| 1034 | llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty}; |
| 1035 | auto *InterWarpCopyFnTy = |
| 1036 | llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams, |
| 1037 | /*isVarArg=*/false); |
| 1038 | llvm::Type *CopyToScratchpadTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy, |
| 1039 | CGM.Int32Ty, CGM.Int32Ty}; |
| 1040 | auto *CopyToScratchpadFnTy = |
| 1041 | llvm::FunctionType::get(CGM.VoidTy, CopyToScratchpadTypeParams, |
| 1042 | /*isVarArg=*/false); |
| 1043 | llvm::Type *LoadReduceTypeParams[] = { |
| 1044 | CGM.VoidPtrTy, CGM.VoidPtrTy, CGM.Int32Ty, CGM.Int32Ty, CGM.Int32Ty}; |
| 1045 | auto *LoadReduceFnTy = |
| 1046 | llvm::FunctionType::get(CGM.VoidTy, LoadReduceTypeParams, |
| 1047 | /*isVarArg=*/false); |
| 1048 | llvm::Type *TypeParams[] = {CGM.Int32Ty, |
| 1049 | CGM.Int32Ty, |
| 1050 | CGM.SizeTy, |
| 1051 | CGM.VoidPtrTy, |
| 1052 | ShuffleReduceFnTy->getPointerTo(), |
| 1053 | InterWarpCopyFnTy->getPointerTo(), |
| 1054 | CopyToScratchpadFnTy->getPointerTo(), |
| 1055 | LoadReduceFnTy->getPointerTo()}; |
| 1056 | llvm::FunctionType *FnTy = |
| 1057 | llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false); |
| 1058 | RTLFn = CGM.CreateRuntimeFunction( |
| 1059 | FnTy, /*Name=*/"__kmpc_nvptx_teams_reduce_nowait"); |
| 1060 | break; |
| 1061 | } |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1062 | case OMPRTL_NVPTX__kmpc_end_reduce_nowait: { |
| 1063 | // Build __kmpc_end_reduce_nowait(kmp_int32 global_tid); |
| 1064 | llvm::Type *TypeParams[] = {CGM.Int32Ty}; |
| 1065 | llvm::FunctionType *FnTy = |
| 1066 | llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); |
| 1067 | RTLFn = CGM.CreateRuntimeFunction( |
| 1068 | FnTy, /*Name=*/"__kmpc_nvptx_end_reduce_nowait"); |
| 1069 | break; |
| 1070 | } |
Gheorghe-Teodor Bercea | d3dcf2f | 2018-03-14 14:17:45 +0000 | [diff] [blame] | 1071 | case OMPRTL_NVPTX__kmpc_data_sharing_init_stack: { |
| 1072 | /// Build void __kmpc_data_sharing_init_stack(); |
| 1073 | llvm::FunctionType *FnTy = |
| 1074 | llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false); |
| 1075 | RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack"); |
| 1076 | break; |
| 1077 | } |
| 1078 | case OMPRTL_NVPTX__kmpc_data_sharing_push_stack: { |
| 1079 | // Build void *__kmpc_data_sharing_push_stack(size_t size, |
| 1080 | // int16_t UseSharedMemory); |
| 1081 | llvm::Type *TypeParams[] = {CGM.SizeTy, CGM.Int16Ty}; |
| 1082 | llvm::FunctionType *FnTy = |
| 1083 | llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false); |
| 1084 | RTLFn = CGM.CreateRuntimeFunction( |
| 1085 | FnTy, /*Name=*/"__kmpc_data_sharing_push_stack"); |
| 1086 | break; |
| 1087 | } |
| 1088 | case OMPRTL_NVPTX__kmpc_data_sharing_pop_stack: { |
| 1089 | // Build void __kmpc_data_sharing_pop_stack(void *a); |
| 1090 | llvm::Type *TypeParams[] = {CGM.VoidPtrTy}; |
| 1091 | llvm::FunctionType *FnTy = |
| 1092 | llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); |
| 1093 | RTLFn = CGM.CreateRuntimeFunction(FnTy, |
| 1094 | /*Name=*/"__kmpc_data_sharing_pop_stack"); |
| 1095 | break; |
| 1096 | } |
| 1097 | case OMPRTL_NVPTX__kmpc_begin_sharing_variables: { |
| 1098 | /// Build void __kmpc_begin_sharing_variables(void ***args, |
| 1099 | /// size_t n_args); |
| 1100 | llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo(), CGM.SizeTy}; |
| 1101 | llvm::FunctionType *FnTy = |
| 1102 | llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); |
| 1103 | RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_begin_sharing_variables"); |
| 1104 | break; |
| 1105 | } |
| 1106 | case OMPRTL_NVPTX__kmpc_end_sharing_variables: { |
| 1107 | /// Build void __kmpc_end_sharing_variables(); |
| 1108 | llvm::FunctionType *FnTy = |
| 1109 | llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false); |
| 1110 | RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_sharing_variables"); |
| 1111 | break; |
| 1112 | } |
| 1113 | case OMPRTL_NVPTX__kmpc_get_shared_variables: { |
| 1114 | /// Build void __kmpc_get_shared_variables(void ***GlobalArgs); |
| 1115 | llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo()}; |
| 1116 | llvm::FunctionType *FnTy = |
| 1117 | llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); |
| 1118 | RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_shared_variables"); |
| 1119 | break; |
| 1120 | } |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 1121 | } |
| 1122 | return RTLFn; |
| 1123 | } |
| 1124 | |
| 1125 | void CGOpenMPRuntimeNVPTX::createOffloadEntry(llvm::Constant *ID, |
| 1126 | llvm::Constant *Addr, |
Samuel Antao | f83efdb | 2017-01-05 16:02:49 +0000 | [diff] [blame] | 1127 | uint64_t Size, int32_t) { |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 1128 | auto *F = dyn_cast<llvm::Function>(Addr); |
| 1129 | // TODO: Add support for global variables on the device after declare target |
| 1130 | // support. |
| 1131 | if (!F) |
| 1132 | return; |
| 1133 | llvm::Module *M = F->getParent(); |
| 1134 | llvm::LLVMContext &Ctx = M->getContext(); |
| 1135 | |
| 1136 | // Get "nvvm.annotations" metadata node |
| 1137 | llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations"); |
| 1138 | |
| 1139 | llvm::Metadata *MDVals[] = { |
| 1140 | llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, "kernel"), |
| 1141 | llvm::ConstantAsMetadata::get( |
| 1142 | llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))}; |
| 1143 | // Append metadata to nvvm.annotations |
| 1144 | MD->addOperand(llvm::MDNode::get(Ctx, MDVals)); |
| 1145 | } |
| 1146 | |
| 1147 | void CGOpenMPRuntimeNVPTX::emitTargetOutlinedFunction( |
| 1148 | const OMPExecutableDirective &D, StringRef ParentName, |
| 1149 | llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID, |
Alexey Bataev | 14fa1c6 | 2016-03-29 05:34:15 +0000 | [diff] [blame] | 1150 | bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) { |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 1151 | if (!IsOffloadEntry) // Nothing to do. |
| 1152 | return; |
| 1153 | |
| 1154 | assert(!ParentName.empty() && "Invalid target region parent name!"); |
| 1155 | |
Carlo Bertolli | 7971209 | 2018-02-28 20:48:35 +0000 | [diff] [blame] | 1156 | CGOpenMPRuntimeNVPTX::ExecutionMode Mode = getExecutionMode(CGM); |
Arpith Chacko Jacob | 44a87c9 | 2017-01-18 19:35:00 +0000 | [diff] [blame] | 1157 | switch (Mode) { |
| 1158 | case CGOpenMPRuntimeNVPTX::ExecutionMode::Generic: |
| 1159 | emitGenericKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry, |
| 1160 | CodeGen); |
| 1161 | break; |
| 1162 | case CGOpenMPRuntimeNVPTX::ExecutionMode::Spmd: |
| 1163 | emitSpmdKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry, |
| 1164 | CodeGen); |
| 1165 | break; |
| 1166 | case CGOpenMPRuntimeNVPTX::ExecutionMode::Unknown: |
| 1167 | llvm_unreachable( |
| 1168 | "Unknown programming model for OpenMP directive on NVPTX target."); |
| 1169 | } |
| 1170 | |
| 1171 | setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode); |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 1172 | } |
| 1173 | |
Samuel Antao | 45bfe4c | 2016-02-08 15:59:20 +0000 | [diff] [blame] | 1174 | CGOpenMPRuntimeNVPTX::CGOpenMPRuntimeNVPTX(CodeGenModule &CGM) |
Arpith Chacko Jacob | 44a87c9 | 2017-01-18 19:35:00 +0000 | [diff] [blame] | 1175 | : CGOpenMPRuntime(CGM), CurrentExecutionMode(ExecutionMode::Unknown) { |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 1176 | if (!CGM.getLangOpts().OpenMPIsDevice) |
| 1177 | llvm_unreachable("OpenMP NVPTX can only handle device code."); |
Arpith Chacko Jacob | 5c309e4 | 2016-03-22 01:48:56 +0000 | [diff] [blame] | 1178 | } |
Carlo Bertolli | c687225 | 2016-04-04 15:55:02 +0000 | [diff] [blame] | 1179 | |
Arpith Chacko Jacob | 2cd6eea | 2017-01-25 16:55:10 +0000 | [diff] [blame] | 1180 | void CGOpenMPRuntimeNVPTX::emitProcBindClause(CodeGenFunction &CGF, |
| 1181 | OpenMPProcBindClauseKind ProcBind, |
| 1182 | SourceLocation Loc) { |
| 1183 | // Do nothing in case of Spmd mode and L0 parallel. |
| 1184 | // TODO: If in Spmd mode and L1 parallel emit the clause. |
| 1185 | if (isInSpmdExecutionMode()) |
| 1186 | return; |
| 1187 | |
| 1188 | CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc); |
| 1189 | } |
| 1190 | |
Arpith Chacko Jacob | e04da5d | 2017-01-25 01:18:34 +0000 | [diff] [blame] | 1191 | void CGOpenMPRuntimeNVPTX::emitNumThreadsClause(CodeGenFunction &CGF, |
| 1192 | llvm::Value *NumThreads, |
| 1193 | SourceLocation Loc) { |
| 1194 | // Do nothing in case of Spmd mode and L0 parallel. |
| 1195 | // TODO: If in Spmd mode and L1 parallel emit the clause. |
| 1196 | if (isInSpmdExecutionMode()) |
| 1197 | return; |
| 1198 | |
| 1199 | CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc); |
| 1200 | } |
| 1201 | |
Carlo Bertolli | c687225 | 2016-04-04 15:55:02 +0000 | [diff] [blame] | 1202 | void CGOpenMPRuntimeNVPTX::emitNumTeamsClause(CodeGenFunction &CGF, |
| 1203 | const Expr *NumTeams, |
| 1204 | const Expr *ThreadLimit, |
| 1205 | SourceLocation Loc) {} |
| 1206 | |
Arpith Chacko Jacob | 19b911c | 2017-01-18 18:18:53 +0000 | [diff] [blame] | 1207 | llvm::Value *CGOpenMPRuntimeNVPTX::emitParallelOutlinedFunction( |
| 1208 | const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, |
| 1209 | OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) { |
Gheorghe-Teodor Bercea | d3dcf2f | 2018-03-14 14:17:45 +0000 | [diff] [blame] | 1210 | auto *OutlinedFun = |
| 1211 | cast<llvm::Function>(CGOpenMPRuntime::emitParallelOutlinedFunction( |
| 1212 | D, ThreadIDVar, InnermostKind, CodeGen)); |
| 1213 | if (!isInSpmdExecutionMode()) { |
| 1214 | llvm::Function *WrapperFun = |
| 1215 | createParallelDataSharingWrapper(OutlinedFun, D); |
| 1216 | WrapperFunctionsMap[OutlinedFun] = WrapperFun; |
| 1217 | } |
| 1218 | |
| 1219 | return OutlinedFun; |
Arpith Chacko Jacob | 19b911c | 2017-01-18 18:18:53 +0000 | [diff] [blame] | 1220 | } |
| 1221 | |
| 1222 | llvm::Value *CGOpenMPRuntimeNVPTX::emitTeamsOutlinedFunction( |
Carlo Bertolli | c687225 | 2016-04-04 15:55:02 +0000 | [diff] [blame] | 1223 | const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, |
| 1224 | OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) { |
| 1225 | |
Arpith Chacko Jacob | 19b911c | 2017-01-18 18:18:53 +0000 | [diff] [blame] | 1226 | llvm::Value *OutlinedFunVal = CGOpenMPRuntime::emitTeamsOutlinedFunction( |
| 1227 | D, ThreadIDVar, InnermostKind, CodeGen); |
| 1228 | llvm::Function *OutlinedFun = cast<llvm::Function>(OutlinedFunVal); |
| 1229 | OutlinedFun->removeFnAttr(llvm::Attribute::NoInline); |
Mehdi Amini | 6aa9e9b | 2017-05-29 05:38:20 +0000 | [diff] [blame] | 1230 | OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone); |
Arpith Chacko Jacob | 19b911c | 2017-01-18 18:18:53 +0000 | [diff] [blame] | 1231 | OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline); |
Carlo Bertolli | c687225 | 2016-04-04 15:55:02 +0000 | [diff] [blame] | 1232 | |
| 1233 | return OutlinedFun; |
| 1234 | } |
| 1235 | |
| 1236 | void CGOpenMPRuntimeNVPTX::emitTeamsCall(CodeGenFunction &CGF, |
| 1237 | const OMPExecutableDirective &D, |
| 1238 | SourceLocation Loc, |
| 1239 | llvm::Value *OutlinedFn, |
| 1240 | ArrayRef<llvm::Value *> CapturedVars) { |
| 1241 | if (!CGF.HaveInsertPoint()) |
| 1242 | return; |
| 1243 | |
| 1244 | Address ZeroAddr = |
| 1245 | CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4), |
| 1246 | /*Name*/ ".zero.addr"); |
| 1247 | CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0)); |
| 1248 | llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs; |
| 1249 | OutlinedFnArgs.push_back(ZeroAddr.getPointer()); |
| 1250 | OutlinedFnArgs.push_back(ZeroAddr.getPointer()); |
| 1251 | OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end()); |
Alexey Bataev | 3c595a6 | 2017-08-14 15:01:03 +0000 | [diff] [blame] | 1252 | emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs); |
Carlo Bertolli | c687225 | 2016-04-04 15:55:02 +0000 | [diff] [blame] | 1253 | } |
Arpith Chacko Jacob | bb36fe8 | 2017-01-10 15:42:51 +0000 | [diff] [blame] | 1254 | |
| 1255 | void CGOpenMPRuntimeNVPTX::emitParallelCall( |
| 1256 | CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn, |
| 1257 | ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) { |
| 1258 | if (!CGF.HaveInsertPoint()) |
| 1259 | return; |
| 1260 | |
Arpith Chacko Jacob | 44a87c9 | 2017-01-18 19:35:00 +0000 | [diff] [blame] | 1261 | if (isInSpmdExecutionMode()) |
| 1262 | emitSpmdParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond); |
| 1263 | else |
| 1264 | emitGenericParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond); |
Arpith Chacko Jacob | bb36fe8 | 2017-01-10 15:42:51 +0000 | [diff] [blame] | 1265 | } |
| 1266 | |
| 1267 | void CGOpenMPRuntimeNVPTX::emitGenericParallelCall( |
| 1268 | CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn, |
| 1269 | ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) { |
| 1270 | llvm::Function *Fn = cast<llvm::Function>(OutlinedFn); |
Gheorghe-Teodor Bercea | d3dcf2f | 2018-03-14 14:17:45 +0000 | [diff] [blame] | 1271 | llvm::Function *WFn = WrapperFunctionsMap[Fn]; |
Arpith Chacko Jacob | bb36fe8 | 2017-01-10 15:42:51 +0000 | [diff] [blame] | 1272 | |
Gheorghe-Teodor Bercea | d3dcf2f | 2018-03-14 14:17:45 +0000 | [diff] [blame] | 1273 | assert(WFn && "Wrapper function does not exist!"); |
| 1274 | |
| 1275 | // Force inline this outlined function at its call site. |
| 1276 | Fn->setLinkage(llvm::GlobalValue::InternalLinkage); |
| 1277 | |
| 1278 | auto &&L0ParallelGen = [this, WFn, &CapturedVars](CodeGenFunction &CGF, |
| 1279 | PrePostActionTy &) { |
Arpith Chacko Jacob | bb36fe8 | 2017-01-10 15:42:51 +0000 | [diff] [blame] | 1280 | CGBuilderTy &Bld = CGF.Builder; |
| 1281 | |
Gheorghe-Teodor Bercea | d3dcf2f | 2018-03-14 14:17:45 +0000 | [diff] [blame] | 1282 | llvm::Value *ID = Bld.CreateBitOrPointerCast(WFn, CGM.Int8PtrTy); |
| 1283 | |
| 1284 | // Prepare for parallel region. Indicate the outlined function. |
| 1285 | llvm::Value *Args[] = {ID, /*RequiresOMPRuntime=*/Bld.getInt16(1)}; |
| 1286 | CGF.EmitRuntimeCall(createNVPTXRuntimeFunction( |
| 1287 | OMPRTL_NVPTX__kmpc_kernel_prepare_parallel), |
| 1288 | Args); |
| 1289 | |
| 1290 | // Create a private scope that will globalize the arguments |
| 1291 | // passed from the outside of the target region. |
| 1292 | CodeGenFunction::OMPPrivateScope PrivateArgScope(CGF); |
| 1293 | |
| 1294 | // There's somehting to share. |
| 1295 | if (!CapturedVars.empty()) { |
| 1296 | // Prepare for parallel region. Indicate the outlined function. |
| 1297 | Address SharedArgs = |
| 1298 | CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "shared_arg_refs"); |
| 1299 | llvm::Value *SharedArgsPtr = SharedArgs.getPointer(); |
| 1300 | |
| 1301 | llvm::Value *DataSharingArgs[] = { |
| 1302 | SharedArgsPtr, |
| 1303 | llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size())}; |
| 1304 | CGF.EmitRuntimeCall(createNVPTXRuntimeFunction( |
| 1305 | OMPRTL_NVPTX__kmpc_begin_sharing_variables), |
| 1306 | DataSharingArgs); |
| 1307 | |
| 1308 | // Store variable address in a list of references to pass to workers. |
| 1309 | unsigned Idx = 0; |
| 1310 | ASTContext &Ctx = CGF.getContext(); |
| 1311 | Address SharedArgListAddress = CGF.EmitLoadOfPointer(SharedArgs, |
| 1312 | Ctx.getPointerType(Ctx.getPointerType(Ctx.VoidPtrTy)) |
| 1313 | .castAs<PointerType>()); |
| 1314 | for (llvm::Value *V : CapturedVars) { |
| 1315 | Address Dst = Bld.CreateConstInBoundsGEP( |
| 1316 | SharedArgListAddress, Idx, CGF.getPointerSize()); |
| 1317 | llvm::Value *PtrV = Bld.CreateBitCast(V, CGF.VoidPtrTy); |
| 1318 | CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false, |
| 1319 | Ctx.getPointerType(Ctx.VoidPtrTy)); |
| 1320 | Idx++; |
| 1321 | } |
| 1322 | } |
Arpith Chacko Jacob | bb36fe8 | 2017-01-10 15:42:51 +0000 | [diff] [blame] | 1323 | |
| 1324 | // Activate workers. This barrier is used by the master to signal |
| 1325 | // work for the workers. |
| 1326 | syncCTAThreads(CGF); |
| 1327 | |
| 1328 | // OpenMP [2.5, Parallel Construct, p.49] |
| 1329 | // There is an implied barrier at the end of a parallel region. After the |
| 1330 | // end of a parallel region, only the master thread of the team resumes |
| 1331 | // execution of the enclosing task region. |
| 1332 | // |
| 1333 | // The master waits at this barrier until all workers are done. |
| 1334 | syncCTAThreads(CGF); |
| 1335 | |
Gheorghe-Teodor Bercea | d3dcf2f | 2018-03-14 14:17:45 +0000 | [diff] [blame] | 1336 | if (!CapturedVars.empty()) |
| 1337 | CGF.EmitRuntimeCall( |
| 1338 | createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_sharing_variables)); |
| 1339 | |
Arpith Chacko Jacob | bb36fe8 | 2017-01-10 15:42:51 +0000 | [diff] [blame] | 1340 | // Remember for post-processing in worker loop. |
Gheorghe-Teodor Bercea | d3dcf2f | 2018-03-14 14:17:45 +0000 | [diff] [blame] | 1341 | Work.emplace_back(WFn); |
Arpith Chacko Jacob | bb36fe8 | 2017-01-10 15:42:51 +0000 | [diff] [blame] | 1342 | }; |
| 1343 | |
| 1344 | auto *RTLoc = emitUpdateLocation(CGF, Loc); |
| 1345 | auto *ThreadID = getThreadID(CGF, Loc); |
| 1346 | llvm::Value *Args[] = {RTLoc, ThreadID}; |
| 1347 | |
Alexey Bataev | 3c595a6 | 2017-08-14 15:01:03 +0000 | [diff] [blame] | 1348 | auto &&SeqGen = [this, Fn, &CapturedVars, &Args, Loc](CodeGenFunction &CGF, |
| 1349 | PrePostActionTy &) { |
| 1350 | auto &&CodeGen = [this, Fn, &CapturedVars, Loc](CodeGenFunction &CGF, |
| 1351 | PrePostActionTy &Action) { |
Arpith Chacko Jacob | bb36fe8 | 2017-01-10 15:42:51 +0000 | [diff] [blame] | 1352 | Action.Enter(CGF); |
| 1353 | |
| 1354 | llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs; |
| 1355 | OutlinedFnArgs.push_back( |
| 1356 | llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo())); |
| 1357 | OutlinedFnArgs.push_back( |
| 1358 | llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo())); |
| 1359 | OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end()); |
Alexey Bataev | 3c595a6 | 2017-08-14 15:01:03 +0000 | [diff] [blame] | 1360 | emitOutlinedFunctionCall(CGF, Loc, Fn, OutlinedFnArgs); |
Arpith Chacko Jacob | bb36fe8 | 2017-01-10 15:42:51 +0000 | [diff] [blame] | 1361 | }; |
| 1362 | |
| 1363 | RegionCodeGenTy RCG(CodeGen); |
| 1364 | NVPTXActionTy Action( |
| 1365 | createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel), |
| 1366 | Args, |
| 1367 | createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel), |
| 1368 | Args); |
| 1369 | RCG.setAction(Action); |
| 1370 | RCG(CGF); |
| 1371 | }; |
| 1372 | |
| 1373 | if (IfCond) |
| 1374 | emitOMPIfClause(CGF, IfCond, L0ParallelGen, SeqGen); |
| 1375 | else { |
| 1376 | CodeGenFunction::RunCleanupsScope Scope(CGF); |
| 1377 | RegionCodeGenTy ThenRCG(L0ParallelGen); |
| 1378 | ThenRCG(CGF); |
| 1379 | } |
| 1380 | } |
Arpith Chacko Jacob | 44a87c9 | 2017-01-18 19:35:00 +0000 | [diff] [blame] | 1381 | |
| 1382 | void CGOpenMPRuntimeNVPTX::emitSpmdParallelCall( |
| 1383 | CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn, |
| 1384 | ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) { |
| 1385 | // Just call the outlined function to execute the parallel region. |
| 1386 | // OutlinedFn(>id, &zero, CapturedStruct); |
| 1387 | // |
| 1388 | // TODO: Do something with IfCond when support for the 'if' clause |
| 1389 | // is added on Spmd target directives. |
| 1390 | llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs; |
Carlo Bertolli | 7971209 | 2018-02-28 20:48:35 +0000 | [diff] [blame] | 1391 | |
| 1392 | Address ZeroAddr = CGF.CreateMemTemp( |
| 1393 | CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1), |
| 1394 | ".zero.addr"); |
| 1395 | CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0)); |
| 1396 | OutlinedFnArgs.push_back(ZeroAddr.getPointer()); |
| 1397 | OutlinedFnArgs.push_back(ZeroAddr.getPointer()); |
Arpith Chacko Jacob | 44a87c9 | 2017-01-18 19:35:00 +0000 | [diff] [blame] | 1398 | OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end()); |
Alexey Bataev | 3c595a6 | 2017-08-14 15:01:03 +0000 | [diff] [blame] | 1399 | emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs); |
Arpith Chacko Jacob | 44a87c9 | 2017-01-18 19:35:00 +0000 | [diff] [blame] | 1400 | } |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1401 | |
Alexey Bataev | b257593 | 2018-01-04 20:18:55 +0000 | [diff] [blame] | 1402 | /// Cast value to the specified type. |
| 1403 | static llvm::Value * |
| 1404 | castValueToType(CodeGenFunction &CGF, llvm::Value *Val, llvm::Type *CastTy, |
| 1405 | llvm::Optional<bool> IsSigned = llvm::None) { |
| 1406 | if (Val->getType() == CastTy) |
| 1407 | return Val; |
| 1408 | if (Val->getType()->getPrimitiveSizeInBits() > 0 && |
| 1409 | CastTy->getPrimitiveSizeInBits() > 0 && |
| 1410 | Val->getType()->getPrimitiveSizeInBits() == |
| 1411 | CastTy->getPrimitiveSizeInBits()) |
| 1412 | return CGF.Builder.CreateBitCast(Val, CastTy); |
| 1413 | if (IsSigned.hasValue() && CastTy->isIntegerTy() && |
| 1414 | Val->getType()->isIntegerTy()) |
| 1415 | return CGF.Builder.CreateIntCast(Val, CastTy, *IsSigned); |
| 1416 | Address CastItem = CGF.CreateTempAlloca( |
| 1417 | CastTy, |
| 1418 | CharUnits::fromQuantity( |
| 1419 | CGF.CGM.getDataLayout().getPrefTypeAlignment(Val->getType()))); |
| 1420 | Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( |
| 1421 | CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace())); |
| 1422 | CGF.Builder.CreateStore(Val, ValCastItem); |
| 1423 | return CGF.Builder.CreateLoad(CastItem); |
| 1424 | } |
| 1425 | |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1426 | /// This function creates calls to one of two shuffle functions to copy |
| 1427 | /// variables between lanes in a warp. |
| 1428 | static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF, |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1429 | llvm::Value *Elem, |
| 1430 | llvm::Value *Offset) { |
| 1431 | auto &CGM = CGF.CGM; |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1432 | auto &Bld = CGF.Builder; |
| 1433 | CGOpenMPRuntimeNVPTX &RT = |
| 1434 | *(static_cast<CGOpenMPRuntimeNVPTX *>(&CGM.getOpenMPRuntime())); |
| 1435 | |
Alexey Bataev | b257593 | 2018-01-04 20:18:55 +0000 | [diff] [blame] | 1436 | unsigned Size = CGM.getDataLayout().getTypeStoreSize(Elem->getType()); |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1437 | assert(Size <= 8 && "Unsupported bitwidth in shuffle instruction."); |
| 1438 | |
| 1439 | OpenMPRTLFunctionNVPTX ShuffleFn = Size <= 4 |
| 1440 | ? OMPRTL_NVPTX__kmpc_shuffle_int32 |
| 1441 | : OMPRTL_NVPTX__kmpc_shuffle_int64; |
| 1442 | |
| 1443 | // Cast all types to 32- or 64-bit values before calling shuffle routines. |
Alexey Bataev | b257593 | 2018-01-04 20:18:55 +0000 | [diff] [blame] | 1444 | llvm::Type *CastTy = Size <= 4 ? CGM.Int32Ty : CGM.Int64Ty; |
| 1445 | llvm::Value *ElemCast = castValueToType(CGF, Elem, CastTy, /*isSigned=*/true); |
| 1446 | auto *WarpSize = |
| 1447 | Bld.CreateIntCast(getNVPTXWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true); |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1448 | |
| 1449 | auto *ShuffledVal = |
| 1450 | CGF.EmitRuntimeCall(RT.createNVPTXRuntimeFunction(ShuffleFn), |
| 1451 | {ElemCast, Offset, WarpSize}); |
| 1452 | |
Alexey Bataev | b257593 | 2018-01-04 20:18:55 +0000 | [diff] [blame] | 1453 | return castValueToType(CGF, ShuffledVal, Elem->getType(), /*isSigned=*/true); |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1454 | } |
| 1455 | |
| 1456 | namespace { |
| 1457 | enum CopyAction : unsigned { |
| 1458 | // RemoteLaneToThread: Copy over a Reduce list from a remote lane in |
| 1459 | // the warp using shuffle instructions. |
| 1460 | RemoteLaneToThread, |
| 1461 | // ThreadCopy: Make a copy of a Reduce list on the thread's stack. |
| 1462 | ThreadCopy, |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1463 | // ThreadToScratchpad: Copy a team-reduced array to the scratchpad. |
| 1464 | ThreadToScratchpad, |
| 1465 | // ScratchpadToThread: Copy from a scratchpad array in global memory |
| 1466 | // containing team-reduced data to a thread's stack. |
| 1467 | ScratchpadToThread, |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1468 | }; |
| 1469 | } // namespace |
| 1470 | |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1471 | struct CopyOptionsTy { |
| 1472 | llvm::Value *RemoteLaneOffset; |
| 1473 | llvm::Value *ScratchpadIndex; |
| 1474 | llvm::Value *ScratchpadWidth; |
| 1475 | }; |
| 1476 | |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1477 | /// Emit instructions to copy a Reduce list, which contains partially |
| 1478 | /// aggregated values, in the specified direction. |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1479 | static void emitReductionListCopy( |
| 1480 | CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy, |
| 1481 | ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase, |
| 1482 | CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) { |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1483 | |
| 1484 | auto &CGM = CGF.CGM; |
| 1485 | auto &C = CGM.getContext(); |
| 1486 | auto &Bld = CGF.Builder; |
| 1487 | |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1488 | auto *RemoteLaneOffset = CopyOptions.RemoteLaneOffset; |
| 1489 | auto *ScratchpadIndex = CopyOptions.ScratchpadIndex; |
| 1490 | auto *ScratchpadWidth = CopyOptions.ScratchpadWidth; |
| 1491 | |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1492 | // Iterates, element-by-element, through the source Reduce list and |
| 1493 | // make a copy. |
| 1494 | unsigned Idx = 0; |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1495 | unsigned Size = Privates.size(); |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1496 | for (auto &Private : Privates) { |
| 1497 | Address SrcElementAddr = Address::invalid(); |
| 1498 | Address DestElementAddr = Address::invalid(); |
| 1499 | Address DestElementPtrAddr = Address::invalid(); |
| 1500 | // Should we shuffle in an element from a remote lane? |
| 1501 | bool ShuffleInElement = false; |
| 1502 | // Set to true to update the pointer in the dest Reduce list to a |
| 1503 | // newly created element. |
| 1504 | bool UpdateDestListPtr = false; |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1505 | // Increment the src or dest pointer to the scratchpad, for each |
| 1506 | // new element. |
| 1507 | bool IncrScratchpadSrc = false; |
| 1508 | bool IncrScratchpadDest = false; |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1509 | |
| 1510 | switch (Action) { |
| 1511 | case RemoteLaneToThread: { |
| 1512 | // Step 1.1: Get the address for the src element in the Reduce list. |
| 1513 | Address SrcElementPtrAddr = |
| 1514 | Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize()); |
Alexey Bataev | b257593 | 2018-01-04 20:18:55 +0000 | [diff] [blame] | 1515 | SrcElementAddr = CGF.EmitLoadOfPointer( |
| 1516 | SrcElementPtrAddr, |
| 1517 | C.getPointerType(Private->getType())->castAs<PointerType>()); |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1518 | |
| 1519 | // Step 1.2: Create a temporary to store the element in the destination |
| 1520 | // Reduce list. |
| 1521 | DestElementPtrAddr = |
| 1522 | Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize()); |
| 1523 | DestElementAddr = |
| 1524 | CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element"); |
| 1525 | ShuffleInElement = true; |
| 1526 | UpdateDestListPtr = true; |
| 1527 | break; |
| 1528 | } |
| 1529 | case ThreadCopy: { |
| 1530 | // Step 1.1: Get the address for the src element in the Reduce list. |
| 1531 | Address SrcElementPtrAddr = |
| 1532 | Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize()); |
Alexey Bataev | b257593 | 2018-01-04 20:18:55 +0000 | [diff] [blame] | 1533 | SrcElementAddr = CGF.EmitLoadOfPointer( |
| 1534 | SrcElementPtrAddr, |
| 1535 | C.getPointerType(Private->getType())->castAs<PointerType>()); |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1536 | |
| 1537 | // Step 1.2: Get the address for dest element. The destination |
| 1538 | // element has already been created on the thread's stack. |
| 1539 | DestElementPtrAddr = |
| 1540 | Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize()); |
Alexey Bataev | b257593 | 2018-01-04 20:18:55 +0000 | [diff] [blame] | 1541 | DestElementAddr = CGF.EmitLoadOfPointer( |
| 1542 | DestElementPtrAddr, |
| 1543 | C.getPointerType(Private->getType())->castAs<PointerType>()); |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1544 | break; |
| 1545 | } |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1546 | case ThreadToScratchpad: { |
| 1547 | // Step 1.1: Get the address for the src element in the Reduce list. |
| 1548 | Address SrcElementPtrAddr = |
| 1549 | Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize()); |
Alexey Bataev | b257593 | 2018-01-04 20:18:55 +0000 | [diff] [blame] | 1550 | SrcElementAddr = CGF.EmitLoadOfPointer( |
| 1551 | SrcElementPtrAddr, |
| 1552 | C.getPointerType(Private->getType())->castAs<PointerType>()); |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1553 | |
| 1554 | // Step 1.2: Get the address for dest element: |
| 1555 | // address = base + index * ElementSizeInChars. |
| 1556 | unsigned ElementSizeInChars = |
| 1557 | C.getTypeSizeInChars(Private->getType()).getQuantity(); |
| 1558 | auto *CurrentOffset = |
| 1559 | Bld.CreateMul(llvm::ConstantInt::get(CGM.SizeTy, ElementSizeInChars), |
| 1560 | ScratchpadIndex); |
| 1561 | auto *ScratchPadElemAbsolutePtrVal = |
| 1562 | Bld.CreateAdd(DestBase.getPointer(), CurrentOffset); |
| 1563 | ScratchPadElemAbsolutePtrVal = |
| 1564 | Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy); |
Alexey Bataev | b257593 | 2018-01-04 20:18:55 +0000 | [diff] [blame] | 1565 | DestElementAddr = Address(ScratchPadElemAbsolutePtrVal, |
| 1566 | C.getTypeAlignInChars(Private->getType())); |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1567 | IncrScratchpadDest = true; |
| 1568 | break; |
| 1569 | } |
| 1570 | case ScratchpadToThread: { |
| 1571 | // Step 1.1: Get the address for the src element in the scratchpad. |
| 1572 | // address = base + index * ElementSizeInChars. |
| 1573 | unsigned ElementSizeInChars = |
| 1574 | C.getTypeSizeInChars(Private->getType()).getQuantity(); |
| 1575 | auto *CurrentOffset = |
| 1576 | Bld.CreateMul(llvm::ConstantInt::get(CGM.SizeTy, ElementSizeInChars), |
| 1577 | ScratchpadIndex); |
| 1578 | auto *ScratchPadElemAbsolutePtrVal = |
| 1579 | Bld.CreateAdd(SrcBase.getPointer(), CurrentOffset); |
| 1580 | ScratchPadElemAbsolutePtrVal = |
| 1581 | Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy); |
| 1582 | SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal, |
| 1583 | C.getTypeAlignInChars(Private->getType())); |
| 1584 | IncrScratchpadSrc = true; |
| 1585 | |
| 1586 | // Step 1.2: Create a temporary to store the element in the destination |
| 1587 | // Reduce list. |
| 1588 | DestElementPtrAddr = |
| 1589 | Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize()); |
| 1590 | DestElementAddr = |
| 1591 | CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element"); |
| 1592 | UpdateDestListPtr = true; |
| 1593 | break; |
| 1594 | } |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1595 | } |
| 1596 | |
| 1597 | // Regardless of src and dest of copy, we emit the load of src |
| 1598 | // element as this is required in all directions |
| 1599 | SrcElementAddr = Bld.CreateElementBitCast( |
| 1600 | SrcElementAddr, CGF.ConvertTypeForMem(Private->getType())); |
| 1601 | llvm::Value *Elem = |
| 1602 | CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false, |
Alexey Bataev | a9b9cc0 | 2018-01-23 18:12:38 +0000 | [diff] [blame] | 1603 | Private->getType(), Private->getExprLoc()); |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1604 | |
| 1605 | // Now that all active lanes have read the element in the |
| 1606 | // Reduce list, shuffle over the value from the remote lane. |
Alexey Bataev | b257593 | 2018-01-04 20:18:55 +0000 | [diff] [blame] | 1607 | if (ShuffleInElement) |
| 1608 | Elem = createRuntimeShuffleFunction(CGF, Elem, RemoteLaneOffset); |
| 1609 | |
| 1610 | DestElementAddr = Bld.CreateElementBitCast(DestElementAddr, |
| 1611 | SrcElementAddr.getElementType()); |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1612 | |
| 1613 | // Store the source element value to the dest element address. |
| 1614 | CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false, |
| 1615 | Private->getType()); |
| 1616 | |
| 1617 | // Step 3.1: Modify reference in dest Reduce list as needed. |
| 1618 | // Modifying the reference in Reduce list to point to the newly |
| 1619 | // created element. The element is live in the current function |
| 1620 | // scope and that of functions it invokes (i.e., reduce_function). |
| 1621 | // RemoteReduceData[i] = (void*)&RemoteElem |
| 1622 | if (UpdateDestListPtr) { |
| 1623 | CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast( |
| 1624 | DestElementAddr.getPointer(), CGF.VoidPtrTy), |
| 1625 | DestElementPtrAddr, /*Volatile=*/false, |
| 1626 | C.VoidPtrTy); |
| 1627 | } |
| 1628 | |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1629 | // Step 4.1: Increment SrcBase/DestBase so that it points to the starting |
| 1630 | // address of the next element in scratchpad memory, unless we're currently |
| 1631 | // processing the last one. Memory alignment is also taken care of here. |
| 1632 | if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) { |
| 1633 | llvm::Value *ScratchpadBasePtr = |
| 1634 | IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer(); |
| 1635 | unsigned ElementSizeInChars = |
| 1636 | C.getTypeSizeInChars(Private->getType()).getQuantity(); |
| 1637 | ScratchpadBasePtr = Bld.CreateAdd( |
| 1638 | ScratchpadBasePtr, |
| 1639 | Bld.CreateMul(ScratchpadWidth, llvm::ConstantInt::get( |
| 1640 | CGM.SizeTy, ElementSizeInChars))); |
| 1641 | |
| 1642 | // Take care of global memory alignment for performance |
| 1643 | ScratchpadBasePtr = Bld.CreateSub(ScratchpadBasePtr, |
| 1644 | llvm::ConstantInt::get(CGM.SizeTy, 1)); |
| 1645 | ScratchpadBasePtr = Bld.CreateSDiv( |
| 1646 | ScratchpadBasePtr, |
| 1647 | llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment)); |
| 1648 | ScratchpadBasePtr = Bld.CreateAdd(ScratchpadBasePtr, |
| 1649 | llvm::ConstantInt::get(CGM.SizeTy, 1)); |
| 1650 | ScratchpadBasePtr = Bld.CreateMul( |
| 1651 | ScratchpadBasePtr, |
| 1652 | llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment)); |
| 1653 | |
| 1654 | if (IncrScratchpadDest) |
| 1655 | DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign()); |
| 1656 | else /* IncrScratchpadSrc = true */ |
| 1657 | SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign()); |
| 1658 | } |
| 1659 | |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1660 | Idx++; |
| 1661 | } |
| 1662 | } |
| 1663 | |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1664 | /// This function emits a helper that loads data from the scratchpad array |
| 1665 | /// and (optionally) reduces it with the input operand. |
| 1666 | /// |
| 1667 | /// load_and_reduce(local, scratchpad, index, width, should_reduce) |
| 1668 | /// reduce_data remote; |
| 1669 | /// for elem in remote: |
| 1670 | /// remote.elem = Scratchpad[elem_id][index] |
| 1671 | /// if (should_reduce) |
| 1672 | /// local = local @ remote |
| 1673 | /// else |
| 1674 | /// local = remote |
Alexey Bataev | 7cae94e | 2018-01-04 19:45:16 +0000 | [diff] [blame] | 1675 | static llvm::Value *emitReduceScratchpadFunction( |
| 1676 | CodeGenModule &CGM, ArrayRef<const Expr *> Privates, |
| 1677 | QualType ReductionArrayTy, llvm::Value *ReduceFn, SourceLocation Loc) { |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1678 | auto &C = CGM.getContext(); |
| 1679 | auto Int32Ty = C.getIntTypeForBitwidth(32, /* Signed */ true); |
| 1680 | |
| 1681 | // Destination of the copy. |
Alexey Bataev | 7cae94e | 2018-01-04 19:45:16 +0000 | [diff] [blame] | 1682 | ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, |
| 1683 | C.VoidPtrTy, ImplicitParamDecl::Other); |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1684 | // Base address of the scratchpad array, with each element storing a |
| 1685 | // Reduce list per team. |
Alexey Bataev | 7cae94e | 2018-01-04 19:45:16 +0000 | [diff] [blame] | 1686 | ImplicitParamDecl ScratchPadArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, |
| 1687 | C.VoidPtrTy, ImplicitParamDecl::Other); |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1688 | // A source index into the scratchpad array. |
Alexey Bataev | 7cae94e | 2018-01-04 19:45:16 +0000 | [diff] [blame] | 1689 | ImplicitParamDecl IndexArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty, |
| 1690 | ImplicitParamDecl::Other); |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1691 | // Row width of an element in the scratchpad array, typically |
| 1692 | // the number of teams. |
Alexey Bataev | 7cae94e | 2018-01-04 19:45:16 +0000 | [diff] [blame] | 1693 | ImplicitParamDecl WidthArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty, |
| 1694 | ImplicitParamDecl::Other); |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1695 | // If should_reduce == 1, then it's load AND reduce, |
| 1696 | // If should_reduce == 0 (or otherwise), then it only loads (+ copy). |
| 1697 | // The latter case is used for initialization. |
Alexey Bataev | 7cae94e | 2018-01-04 19:45:16 +0000 | [diff] [blame] | 1698 | ImplicitParamDecl ShouldReduceArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, |
| 1699 | Int32Ty, ImplicitParamDecl::Other); |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1700 | |
| 1701 | FunctionArgList Args; |
| 1702 | Args.push_back(&ReduceListArg); |
| 1703 | Args.push_back(&ScratchPadArg); |
| 1704 | Args.push_back(&IndexArg); |
| 1705 | Args.push_back(&WidthArg); |
| 1706 | Args.push_back(&ShouldReduceArg); |
| 1707 | |
| 1708 | auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); |
| 1709 | auto *Fn = llvm::Function::Create( |
| 1710 | CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage, |
| 1711 | "_omp_reduction_load_and_reduce", &CGM.getModule()); |
Rafael Espindola | 51ec5a9 | 2018-02-28 23:46:35 +0000 | [diff] [blame] | 1712 | CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI); |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1713 | CodeGenFunction CGF(CGM); |
Alexey Bataev | 7cae94e | 2018-01-04 19:45:16 +0000 | [diff] [blame] | 1714 | CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc); |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1715 | |
| 1716 | auto &Bld = CGF.Builder; |
| 1717 | |
| 1718 | // Get local Reduce list pointer. |
| 1719 | Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg); |
| 1720 | Address ReduceListAddr( |
| 1721 | Bld.CreatePointerBitCastOrAddrSpaceCast( |
| 1722 | CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false, |
Alexey Bataev | a9b9cc0 | 2018-01-23 18:12:38 +0000 | [diff] [blame] | 1723 | C.VoidPtrTy, Loc), |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1724 | CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()), |
| 1725 | CGF.getPointerAlign()); |
| 1726 | |
| 1727 | Address AddrScratchPadArg = CGF.GetAddrOfLocalVar(&ScratchPadArg); |
| 1728 | llvm::Value *ScratchPadBase = CGF.EmitLoadOfScalar( |
Alexey Bataev | a9b9cc0 | 2018-01-23 18:12:38 +0000 | [diff] [blame] | 1729 | AddrScratchPadArg, /*Volatile=*/false, C.VoidPtrTy, Loc); |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1730 | |
| 1731 | Address AddrIndexArg = CGF.GetAddrOfLocalVar(&IndexArg); |
Alexey Bataev | a9b9cc0 | 2018-01-23 18:12:38 +0000 | [diff] [blame] | 1732 | llvm::Value *IndexVal = Bld.CreateIntCast( |
| 1733 | CGF.EmitLoadOfScalar(AddrIndexArg, /*Volatile=*/false, Int32Ty, Loc), |
| 1734 | CGM.SizeTy, /*isSigned=*/true); |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1735 | |
| 1736 | Address AddrWidthArg = CGF.GetAddrOfLocalVar(&WidthArg); |
Alexey Bataev | a9b9cc0 | 2018-01-23 18:12:38 +0000 | [diff] [blame] | 1737 | llvm::Value *WidthVal = Bld.CreateIntCast( |
| 1738 | CGF.EmitLoadOfScalar(AddrWidthArg, /*Volatile=*/false, Int32Ty, Loc), |
| 1739 | CGM.SizeTy, /*isSigned=*/true); |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1740 | |
| 1741 | Address AddrShouldReduceArg = CGF.GetAddrOfLocalVar(&ShouldReduceArg); |
| 1742 | llvm::Value *ShouldReduceVal = CGF.EmitLoadOfScalar( |
Alexey Bataev | a9b9cc0 | 2018-01-23 18:12:38 +0000 | [diff] [blame] | 1743 | AddrShouldReduceArg, /*Volatile=*/false, Int32Ty, Loc); |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1744 | |
| 1745 | // The absolute ptr address to the base addr of the next element to copy. |
| 1746 | llvm::Value *CumulativeElemBasePtr = |
| 1747 | Bld.CreatePtrToInt(ScratchPadBase, CGM.SizeTy); |
| 1748 | Address SrcDataAddr(CumulativeElemBasePtr, CGF.getPointerAlign()); |
| 1749 | |
| 1750 | // Create a Remote Reduce list to store the elements read from the |
| 1751 | // scratchpad array. |
| 1752 | Address RemoteReduceList = |
| 1753 | CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_red_list"); |
| 1754 | |
| 1755 | // Assemble remote Reduce list from scratchpad array. |
| 1756 | emitReductionListCopy(ScratchpadToThread, CGF, ReductionArrayTy, Privates, |
| 1757 | SrcDataAddr, RemoteReduceList, |
| 1758 | {/*RemoteLaneOffset=*/nullptr, |
| 1759 | /*ScratchpadIndex=*/IndexVal, |
| 1760 | /*ScratchpadWidth=*/WidthVal}); |
| 1761 | |
| 1762 | llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then"); |
| 1763 | llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else"); |
| 1764 | llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont"); |
| 1765 | |
| 1766 | auto CondReduce = Bld.CreateICmpEQ(ShouldReduceVal, Bld.getInt32(1)); |
| 1767 | Bld.CreateCondBr(CondReduce, ThenBB, ElseBB); |
| 1768 | |
| 1769 | CGF.EmitBlock(ThenBB); |
| 1770 | // We should reduce with the local Reduce list. |
| 1771 | // reduce_function(LocalReduceList, RemoteReduceList) |
| 1772 | llvm::Value *LocalDataPtr = Bld.CreatePointerBitCastOrAddrSpaceCast( |
| 1773 | ReduceListAddr.getPointer(), CGF.VoidPtrTy); |
| 1774 | llvm::Value *RemoteDataPtr = Bld.CreatePointerBitCastOrAddrSpaceCast( |
| 1775 | RemoteReduceList.getPointer(), CGF.VoidPtrTy); |
Alexey Bataev | 7cae94e | 2018-01-04 19:45:16 +0000 | [diff] [blame] | 1776 | CGM.getOpenMPRuntime().emitOutlinedFunctionCall( |
| 1777 | CGF, Loc, ReduceFn, {LocalDataPtr, RemoteDataPtr}); |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1778 | Bld.CreateBr(MergeBB); |
| 1779 | |
| 1780 | CGF.EmitBlock(ElseBB); |
| 1781 | // No reduction; just copy: |
| 1782 | // Local Reduce list = Remote Reduce list. |
| 1783 | emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates, |
| 1784 | RemoteReduceList, ReduceListAddr); |
| 1785 | Bld.CreateBr(MergeBB); |
| 1786 | |
| 1787 | CGF.EmitBlock(MergeBB); |
| 1788 | |
| 1789 | CGF.FinishFunction(); |
| 1790 | return Fn; |
| 1791 | } |
| 1792 | |
| 1793 | /// This function emits a helper that stores reduced data from the team |
| 1794 | /// master to a scratchpad array in global memory. |
| 1795 | /// |
| 1796 | /// for elem in Reduce List: |
| 1797 | /// scratchpad[elem_id][index] = elem |
| 1798 | /// |
Benjamin Kramer | 674d579 | 2017-05-26 20:08:24 +0000 | [diff] [blame] | 1799 | static llvm::Value *emitCopyToScratchpad(CodeGenModule &CGM, |
| 1800 | ArrayRef<const Expr *> Privates, |
Alexey Bataev | 7cae94e | 2018-01-04 19:45:16 +0000 | [diff] [blame] | 1801 | QualType ReductionArrayTy, |
| 1802 | SourceLocation Loc) { |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1803 | |
| 1804 | auto &C = CGM.getContext(); |
| 1805 | auto Int32Ty = C.getIntTypeForBitwidth(32, /* Signed */ true); |
| 1806 | |
| 1807 | // Source of the copy. |
Alexey Bataev | 7cae94e | 2018-01-04 19:45:16 +0000 | [diff] [blame] | 1808 | ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, |
| 1809 | C.VoidPtrTy, ImplicitParamDecl::Other); |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1810 | // Base address of the scratchpad array, with each element storing a |
| 1811 | // Reduce list per team. |
Alexey Bataev | 7cae94e | 2018-01-04 19:45:16 +0000 | [diff] [blame] | 1812 | ImplicitParamDecl ScratchPadArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, |
| 1813 | C.VoidPtrTy, ImplicitParamDecl::Other); |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1814 | // A destination index into the scratchpad array, typically the team |
| 1815 | // identifier. |
Alexey Bataev | 7cae94e | 2018-01-04 19:45:16 +0000 | [diff] [blame] | 1816 | ImplicitParamDecl IndexArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty, |
| 1817 | ImplicitParamDecl::Other); |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1818 | // Row width of an element in the scratchpad array, typically |
| 1819 | // the number of teams. |
Alexey Bataev | 7cae94e | 2018-01-04 19:45:16 +0000 | [diff] [blame] | 1820 | ImplicitParamDecl WidthArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty, |
| 1821 | ImplicitParamDecl::Other); |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1822 | |
| 1823 | FunctionArgList Args; |
| 1824 | Args.push_back(&ReduceListArg); |
| 1825 | Args.push_back(&ScratchPadArg); |
| 1826 | Args.push_back(&IndexArg); |
| 1827 | Args.push_back(&WidthArg); |
| 1828 | |
| 1829 | auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); |
| 1830 | auto *Fn = llvm::Function::Create( |
| 1831 | CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage, |
| 1832 | "_omp_reduction_copy_to_scratchpad", &CGM.getModule()); |
Rafael Espindola | 51ec5a9 | 2018-02-28 23:46:35 +0000 | [diff] [blame] | 1833 | CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI); |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1834 | CodeGenFunction CGF(CGM); |
Alexey Bataev | 7cae94e | 2018-01-04 19:45:16 +0000 | [diff] [blame] | 1835 | CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc); |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1836 | |
| 1837 | auto &Bld = CGF.Builder; |
| 1838 | |
| 1839 | Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg); |
| 1840 | Address SrcDataAddr( |
| 1841 | Bld.CreatePointerBitCastOrAddrSpaceCast( |
| 1842 | CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false, |
Alexey Bataev | a9b9cc0 | 2018-01-23 18:12:38 +0000 | [diff] [blame] | 1843 | C.VoidPtrTy, Loc), |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1844 | CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()), |
| 1845 | CGF.getPointerAlign()); |
| 1846 | |
| 1847 | Address AddrScratchPadArg = CGF.GetAddrOfLocalVar(&ScratchPadArg); |
| 1848 | llvm::Value *ScratchPadBase = CGF.EmitLoadOfScalar( |
Alexey Bataev | a9b9cc0 | 2018-01-23 18:12:38 +0000 | [diff] [blame] | 1849 | AddrScratchPadArg, /*Volatile=*/false, C.VoidPtrTy, Loc); |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1850 | |
| 1851 | Address AddrIndexArg = CGF.GetAddrOfLocalVar(&IndexArg); |
Alexey Bataev | a9b9cc0 | 2018-01-23 18:12:38 +0000 | [diff] [blame] | 1852 | llvm::Value *IndexVal = Bld.CreateIntCast( |
| 1853 | CGF.EmitLoadOfScalar(AddrIndexArg, /*Volatile=*/false, Int32Ty, Loc), |
| 1854 | CGF.SizeTy, /*isSigned=*/true); |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 1855 | |
| 1856 | Address AddrWidthArg = CGF.GetAddrOfLocalVar(&WidthArg); |
| 1857 | llvm::Value *WidthVal = |
| 1858 | Bld.CreateIntCast(CGF.EmitLoadOfScalar(AddrWidthArg, /*Volatile=*/false, |
| 1859 | Int32Ty, SourceLocation()), |
| 1860 | CGF.SizeTy, /*isSigned=*/true); |
| 1861 | |
| 1862 | // The absolute ptr address to the base addr of the next element to copy. |
| 1863 | llvm::Value *CumulativeElemBasePtr = |
| 1864 | Bld.CreatePtrToInt(ScratchPadBase, CGM.SizeTy); |
| 1865 | Address DestDataAddr(CumulativeElemBasePtr, CGF.getPointerAlign()); |
| 1866 | |
| 1867 | emitReductionListCopy(ThreadToScratchpad, CGF, ReductionArrayTy, Privates, |
| 1868 | SrcDataAddr, DestDataAddr, |
| 1869 | {/*RemoteLaneOffset=*/nullptr, |
| 1870 | /*ScratchpadIndex=*/IndexVal, |
| 1871 | /*ScratchpadWidth=*/WidthVal}); |
| 1872 | |
| 1873 | CGF.FinishFunction(); |
| 1874 | return Fn; |
| 1875 | } |
| 1876 | |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1877 | /// This function emits a helper that gathers Reduce lists from the first |
| 1878 | /// lane of every active warp to lanes in the first warp. |
| 1879 | /// |
| 1880 | /// void inter_warp_copy_func(void* reduce_data, num_warps) |
| 1881 | /// shared smem[warp_size]; |
| 1882 | /// For all data entries D in reduce_data: |
| 1883 | /// If (I am the first lane in each warp) |
| 1884 | /// Copy my local D to smem[warp_id] |
| 1885 | /// sync |
| 1886 | /// if (I am the first warp) |
| 1887 | /// Copy smem[thread_id] to my local D |
| 1888 | /// sync |
| 1889 | static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM, |
| 1890 | ArrayRef<const Expr *> Privates, |
Alexey Bataev | 7cae94e | 2018-01-04 19:45:16 +0000 | [diff] [blame] | 1891 | QualType ReductionArrayTy, |
| 1892 | SourceLocation Loc) { |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1893 | auto &C = CGM.getContext(); |
| 1894 | auto &M = CGM.getModule(); |
| 1895 | |
| 1896 | // ReduceList: thread local Reduce list. |
| 1897 | // At the stage of the computation when this function is called, partially |
| 1898 | // aggregated values reside in the first lane of every active warp. |
Alexey Bataev | 7cae94e | 2018-01-04 19:45:16 +0000 | [diff] [blame] | 1899 | ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, |
| 1900 | C.VoidPtrTy, ImplicitParamDecl::Other); |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1901 | // NumWarps: number of warps active in the parallel region. This could |
| 1902 | // be smaller than 32 (max warps in a CTA) for partial block reduction. |
Alexey Bataev | 7cae94e | 2018-01-04 19:45:16 +0000 | [diff] [blame] | 1903 | ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, |
Alexey Bataev | 5622323 | 2017-06-09 13:40:18 +0000 | [diff] [blame] | 1904 | C.getIntTypeForBitwidth(32, /* Signed */ true), |
| 1905 | ImplicitParamDecl::Other); |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1906 | FunctionArgList Args; |
| 1907 | Args.push_back(&ReduceListArg); |
| 1908 | Args.push_back(&NumWarpsArg); |
| 1909 | |
| 1910 | auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); |
| 1911 | auto *Fn = llvm::Function::Create( |
| 1912 | CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage, |
| 1913 | "_omp_reduction_inter_warp_copy_func", &CGM.getModule()); |
Rafael Espindola | 51ec5a9 | 2018-02-28 23:46:35 +0000 | [diff] [blame] | 1914 | CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI); |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1915 | CodeGenFunction CGF(CGM); |
Alexey Bataev | 7cae94e | 2018-01-04 19:45:16 +0000 | [diff] [blame] | 1916 | CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc); |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 1917 | |
| 1918 | auto &Bld = CGF.Builder; |
| 1919 | |
| 1920 | // This array is used as a medium to transfer, one reduce element at a time, |
| 1921 | // the data from the first lane of every warp to lanes in the first warp |
| 1922 | // in order to perform the final step of a reduction in a parallel region |
| 1923 | // (reduction across warps). The array is placed in NVPTX __shared__ memory |
| 1924 | // for reduced latency, as well as to have a distinct copy for concurrently |
| 1925 | // executing target regions. The array is declared with common linkage so |
| 1926 | // as to be shared across compilation units. |
| 1927 | const char *TransferMediumName = |
| 1928 | "__openmp_nvptx_data_transfer_temporary_storage"; |
| 1929 | llvm::GlobalVariable *TransferMedium = |
| 1930 | M.getGlobalVariable(TransferMediumName); |
| 1931 | if (!TransferMedium) { |
| 1932 | auto *Ty = llvm::ArrayType::get(CGM.Int64Ty, WarpSize); |
| 1933 | unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared); |
| 1934 | TransferMedium = new llvm::GlobalVariable( |
| 1935 | M, Ty, |
| 1936 | /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage, |
| 1937 | llvm::Constant::getNullValue(Ty), TransferMediumName, |
| 1938 | /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, |
| 1939 | SharedAddressSpace); |
| 1940 | } |
| 1941 | |
| 1942 | // Get the CUDA thread id of the current OpenMP thread on the GPU. |
| 1943 | auto *ThreadID = getNVPTXThreadID(CGF); |
| 1944 | // nvptx_lane_id = nvptx_id % warpsize |
| 1945 | auto *LaneID = getNVPTXLaneID(CGF); |
| 1946 | // nvptx_warp_id = nvptx_id / warpsize |
| 1947 | auto *WarpID = getNVPTXWarpID(CGF); |
| 1948 | |
| 1949 | Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg); |
| 1950 | Address LocalReduceList( |
| 1951 | Bld.CreatePointerBitCastOrAddrSpaceCast( |
| 1952 | CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false, |
| 1953 | C.VoidPtrTy, SourceLocation()), |
| 1954 | CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()), |
| 1955 | CGF.getPointerAlign()); |
| 1956 | |
| 1957 | unsigned Idx = 0; |
| 1958 | for (auto &Private : Privates) { |
| 1959 | // |
| 1960 | // Warp master copies reduce element to transfer medium in __shared__ |
| 1961 | // memory. |
| 1962 | // |
| 1963 | llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then"); |
| 1964 | llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else"); |
| 1965 | llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont"); |
| 1966 | |
| 1967 | // if (lane_id == 0) |
| 1968 | auto IsWarpMaster = |
| 1969 | Bld.CreateICmpEQ(LaneID, Bld.getInt32(0), "warp_master"); |
| 1970 | Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB); |
| 1971 | CGF.EmitBlock(ThenBB); |
| 1972 | |
| 1973 | // Reduce element = LocalReduceList[i] |
| 1974 | Address ElemPtrPtrAddr = |
| 1975 | Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize()); |
| 1976 | llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar( |
| 1977 | ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation()); |
| 1978 | // elemptr = (type[i]*)(elemptrptr) |
| 1979 | Address ElemPtr = |
| 1980 | Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType())); |
| 1981 | ElemPtr = Bld.CreateElementBitCast( |
| 1982 | ElemPtr, CGF.ConvertTypeForMem(Private->getType())); |
| 1983 | // elem = *elemptr |
| 1984 | llvm::Value *Elem = CGF.EmitLoadOfScalar( |
| 1985 | ElemPtr, /*Volatile=*/false, Private->getType(), SourceLocation()); |
| 1986 | |
| 1987 | // Get pointer to location in transfer medium. |
| 1988 | // MediumPtr = &medium[warp_id] |
| 1989 | llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP( |
| 1990 | TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID}); |
| 1991 | Address MediumPtr(MediumPtrVal, C.getTypeAlignInChars(Private->getType())); |
| 1992 | // Casting to actual data type. |
| 1993 | // MediumPtr = (type[i]*)MediumPtrAddr; |
| 1994 | MediumPtr = Bld.CreateElementBitCast( |
| 1995 | MediumPtr, CGF.ConvertTypeForMem(Private->getType())); |
| 1996 | |
| 1997 | //*MediumPtr = elem |
| 1998 | Bld.CreateStore(Elem, MediumPtr); |
| 1999 | |
| 2000 | Bld.CreateBr(MergeBB); |
| 2001 | |
| 2002 | CGF.EmitBlock(ElseBB); |
| 2003 | Bld.CreateBr(MergeBB); |
| 2004 | |
| 2005 | CGF.EmitBlock(MergeBB); |
| 2006 | |
| 2007 | Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg); |
| 2008 | llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar( |
| 2009 | AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, SourceLocation()); |
| 2010 | |
| 2011 | auto *NumActiveThreads = Bld.CreateNSWMul( |
| 2012 | NumWarpsVal, getNVPTXWarpSize(CGF), "num_active_threads"); |
| 2013 | // named_barrier_sync(ParallelBarrierID, num_active_threads) |
| 2014 | syncParallelThreads(CGF, NumActiveThreads); |
| 2015 | |
| 2016 | // |
| 2017 | // Warp 0 copies reduce element from transfer medium. |
| 2018 | // |
| 2019 | llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then"); |
| 2020 | llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else"); |
| 2021 | llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont"); |
| 2022 | |
| 2023 | // Up to 32 threads in warp 0 are active. |
| 2024 | auto IsActiveThread = |
| 2025 | Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread"); |
| 2026 | Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB); |
| 2027 | |
| 2028 | CGF.EmitBlock(W0ThenBB); |
| 2029 | |
| 2030 | // SrcMediumPtr = &medium[tid] |
| 2031 | llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP( |
| 2032 | TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID}); |
| 2033 | Address SrcMediumPtr(SrcMediumPtrVal, |
| 2034 | C.getTypeAlignInChars(Private->getType())); |
| 2035 | // SrcMediumVal = *SrcMediumPtr; |
| 2036 | SrcMediumPtr = Bld.CreateElementBitCast( |
| 2037 | SrcMediumPtr, CGF.ConvertTypeForMem(Private->getType())); |
| 2038 | llvm::Value *SrcMediumValue = CGF.EmitLoadOfScalar( |
| 2039 | SrcMediumPtr, /*Volatile=*/false, Private->getType(), SourceLocation()); |
| 2040 | |
| 2041 | // TargetElemPtr = (type[i]*)(SrcDataAddr[i]) |
| 2042 | Address TargetElemPtrPtr = |
| 2043 | Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize()); |
| 2044 | llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar( |
| 2045 | TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation()); |
| 2046 | Address TargetElemPtr = |
| 2047 | Address(TargetElemPtrVal, C.getTypeAlignInChars(Private->getType())); |
| 2048 | TargetElemPtr = Bld.CreateElementBitCast( |
| 2049 | TargetElemPtr, CGF.ConvertTypeForMem(Private->getType())); |
| 2050 | |
| 2051 | // *TargetElemPtr = SrcMediumVal; |
| 2052 | CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false, |
| 2053 | Private->getType()); |
| 2054 | Bld.CreateBr(W0MergeBB); |
| 2055 | |
| 2056 | CGF.EmitBlock(W0ElseBB); |
| 2057 | Bld.CreateBr(W0MergeBB); |
| 2058 | |
| 2059 | CGF.EmitBlock(W0MergeBB); |
| 2060 | |
| 2061 | // While warp 0 copies values from transfer medium, all other warps must |
| 2062 | // wait. |
| 2063 | syncParallelThreads(CGF, NumActiveThreads); |
| 2064 | Idx++; |
| 2065 | } |
| 2066 | |
| 2067 | CGF.FinishFunction(); |
| 2068 | return Fn; |
| 2069 | } |
| 2070 | |
| 2071 | /// Emit a helper that reduces data across two OpenMP threads (lanes) |
| 2072 | /// in the same warp. It uses shuffle instructions to copy over data from |
| 2073 | /// a remote lane's stack. The reduction algorithm performed is specified |
| 2074 | /// by the fourth parameter. |
| 2075 | /// |
| 2076 | /// Algorithm Versions. |
| 2077 | /// Full Warp Reduce (argument value 0): |
| 2078 | /// This algorithm assumes that all 32 lanes are active and gathers |
| 2079 | /// data from these 32 lanes, producing a single resultant value. |
| 2080 | /// Contiguous Partial Warp Reduce (argument value 1): |
| 2081 | /// This algorithm assumes that only a *contiguous* subset of lanes |
| 2082 | /// are active. This happens for the last warp in a parallel region |
| 2083 | /// when the user specified num_threads is not an integer multiple of |
| 2084 | /// 32. This contiguous subset always starts with the zeroth lane. |
| 2085 | /// Partial Warp Reduce (argument value 2): |
| 2086 | /// This algorithm gathers data from any number of lanes at any position. |
| 2087 | /// All reduced values are stored in the lowest possible lane. The set |
| 2088 | /// of problems every algorithm addresses is a super set of those |
| 2089 | /// addressable by algorithms with a lower version number. Overhead |
| 2090 | /// increases as algorithm version increases. |
| 2091 | /// |
| 2092 | /// Terminology |
| 2093 | /// Reduce element: |
| 2094 | /// Reduce element refers to the individual data field with primitive |
| 2095 | /// data types to be combined and reduced across threads. |
| 2096 | /// Reduce list: |
| 2097 | /// Reduce list refers to a collection of local, thread-private |
| 2098 | /// reduce elements. |
| 2099 | /// Remote Reduce list: |
| 2100 | /// Remote Reduce list refers to a collection of remote (relative to |
| 2101 | /// the current thread) reduce elements. |
| 2102 | /// |
| 2103 | /// We distinguish between three states of threads that are important to |
| 2104 | /// the implementation of this function. |
| 2105 | /// Alive threads: |
| 2106 | /// Threads in a warp executing the SIMT instruction, as distinguished from |
| 2107 | /// threads that are inactive due to divergent control flow. |
| 2108 | /// Active threads: |
| 2109 | /// The minimal set of threads that has to be alive upon entry to this |
| 2110 | /// function. The computation is correct iff active threads are alive. |
| 2111 | /// Some threads are alive but they are not active because they do not |
| 2112 | /// contribute to the computation in any useful manner. Turning them off |
| 2113 | /// may introduce control flow overheads without any tangible benefits. |
| 2114 | /// Effective threads: |
| 2115 | /// In order to comply with the argument requirements of the shuffle |
| 2116 | /// function, we must keep all lanes holding data alive. But at most |
| 2117 | /// half of them perform value aggregation; we refer to this half of |
| 2118 | /// threads as effective. The other half is simply handing off their |
| 2119 | /// data. |
| 2120 | /// |
| 2121 | /// Procedure |
| 2122 | /// Value shuffle: |
| 2123 | /// In this step active threads transfer data from higher lane positions |
| 2124 | /// in the warp to lower lane positions, creating Remote Reduce list. |
| 2125 | /// Value aggregation: |
| 2126 | /// In this step, effective threads combine their thread local Reduce list |
| 2127 | /// with Remote Reduce list and store the result in the thread local |
| 2128 | /// Reduce list. |
| 2129 | /// Value copy: |
| 2130 | /// In this step, we deal with the assumption made by algorithm 2 |
| 2131 | /// (i.e. contiguity assumption). When we have an odd number of lanes |
| 2132 | /// active, say 2k+1, only k threads will be effective and therefore k |
| 2133 | /// new values will be produced. However, the Reduce list owned by the |
| 2134 | /// (2k+1)th thread is ignored in the value aggregation. Therefore |
| 2135 | /// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so |
| 2136 | /// that the contiguity assumption still holds. |
Alexey Bataev | 7cae94e | 2018-01-04 19:45:16 +0000 | [diff] [blame] | 2137 | static llvm::Value *emitShuffleAndReduceFunction( |
| 2138 | CodeGenModule &CGM, ArrayRef<const Expr *> Privates, |
| 2139 | QualType ReductionArrayTy, llvm::Value *ReduceFn, SourceLocation Loc) { |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 2140 | auto &C = CGM.getContext(); |
| 2141 | |
| 2142 | // Thread local Reduce list used to host the values of data to be reduced. |
Alexey Bataev | 7cae94e | 2018-01-04 19:45:16 +0000 | [diff] [blame] | 2143 | ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, |
| 2144 | C.VoidPtrTy, ImplicitParamDecl::Other); |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 2145 | // Current lane id; could be logical. |
Alexey Bataev | 7cae94e | 2018-01-04 19:45:16 +0000 | [diff] [blame] | 2146 | ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy, |
| 2147 | ImplicitParamDecl::Other); |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 2148 | // Offset of the remote source lane relative to the current lane. |
Alexey Bataev | 7cae94e | 2018-01-04 19:45:16 +0000 | [diff] [blame] | 2149 | ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, |
| 2150 | C.ShortTy, ImplicitParamDecl::Other); |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 2151 | // Algorithm version. This is expected to be known at compile time. |
Alexey Bataev | 7cae94e | 2018-01-04 19:45:16 +0000 | [diff] [blame] | 2152 | ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, |
| 2153 | C.ShortTy, ImplicitParamDecl::Other); |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 2154 | FunctionArgList Args; |
| 2155 | Args.push_back(&ReduceListArg); |
| 2156 | Args.push_back(&LaneIDArg); |
| 2157 | Args.push_back(&RemoteLaneOffsetArg); |
| 2158 | Args.push_back(&AlgoVerArg); |
| 2159 | |
| 2160 | auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); |
| 2161 | auto *Fn = llvm::Function::Create( |
| 2162 | CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage, |
| 2163 | "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule()); |
Rafael Espindola | 51ec5a9 | 2018-02-28 23:46:35 +0000 | [diff] [blame] | 2164 | CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI); |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 2165 | CodeGenFunction CGF(CGM); |
Alexey Bataev | 7cae94e | 2018-01-04 19:45:16 +0000 | [diff] [blame] | 2166 | CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc); |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 2167 | |
| 2168 | auto &Bld = CGF.Builder; |
| 2169 | |
| 2170 | Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg); |
| 2171 | Address LocalReduceList( |
| 2172 | Bld.CreatePointerBitCastOrAddrSpaceCast( |
| 2173 | CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false, |
| 2174 | C.VoidPtrTy, SourceLocation()), |
| 2175 | CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()), |
| 2176 | CGF.getPointerAlign()); |
| 2177 | |
| 2178 | Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg); |
| 2179 | llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar( |
| 2180 | AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation()); |
| 2181 | |
| 2182 | Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg); |
| 2183 | llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar( |
| 2184 | AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation()); |
| 2185 | |
| 2186 | Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg); |
| 2187 | llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar( |
| 2188 | AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation()); |
| 2189 | |
| 2190 | // Create a local thread-private variable to host the Reduce list |
| 2191 | // from a remote lane. |
| 2192 | Address RemoteReduceList = |
| 2193 | CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list"); |
| 2194 | |
| 2195 | // This loop iterates through the list of reduce elements and copies, |
| 2196 | // element by element, from a remote lane in the warp to RemoteReduceList, |
| 2197 | // hosted on the thread's stack. |
| 2198 | emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates, |
| 2199 | LocalReduceList, RemoteReduceList, |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 2200 | {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal, |
| 2201 | /*ScratchpadIndex=*/nullptr, |
| 2202 | /*ScratchpadWidth=*/nullptr}); |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 2203 | |
| 2204 | // The actions to be performed on the Remote Reduce list is dependent |
| 2205 | // on the algorithm version. |
| 2206 | // |
| 2207 | // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 && |
| 2208 | // LaneId % 2 == 0 && Offset > 0): |
| 2209 | // do the reduction value aggregation |
| 2210 | // |
| 2211 | // The thread local variable Reduce list is mutated in place to host the |
| 2212 | // reduced data, which is the aggregated value produced from local and |
| 2213 | // remote lanes. |
| 2214 | // |
| 2215 | // Note that AlgoVer is expected to be a constant integer known at compile |
| 2216 | // time. |
| 2217 | // When AlgoVer==0, the first conjunction evaluates to true, making |
| 2218 | // the entire predicate true during compile time. |
| 2219 | // When AlgoVer==1, the second conjunction has only the second part to be |
| 2220 | // evaluated during runtime. Other conjunctions evaluates to false |
| 2221 | // during compile time. |
| 2222 | // When AlgoVer==2, the third conjunction has only the second part to be |
| 2223 | // evaluated during runtime. Other conjunctions evaluates to false |
| 2224 | // during compile time. |
| 2225 | auto CondAlgo0 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(0)); |
| 2226 | |
| 2227 | auto Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1)); |
| 2228 | auto CondAlgo1 = Bld.CreateAnd( |
| 2229 | Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal)); |
| 2230 | |
| 2231 | auto Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2)); |
| 2232 | auto CondAlgo2 = Bld.CreateAnd( |
| 2233 | Algo2, |
| 2234 | Bld.CreateICmpEQ(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1)), |
| 2235 | Bld.getInt16(0))); |
| 2236 | CondAlgo2 = Bld.CreateAnd( |
| 2237 | CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0))); |
| 2238 | |
| 2239 | auto CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1); |
| 2240 | CondReduce = Bld.CreateOr(CondReduce, CondAlgo2); |
| 2241 | |
| 2242 | llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then"); |
| 2243 | llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else"); |
| 2244 | llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont"); |
| 2245 | Bld.CreateCondBr(CondReduce, ThenBB, ElseBB); |
| 2246 | |
| 2247 | CGF.EmitBlock(ThenBB); |
| 2248 | // reduce_function(LocalReduceList, RemoteReduceList) |
| 2249 | llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast( |
| 2250 | LocalReduceList.getPointer(), CGF.VoidPtrTy); |
| 2251 | llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast( |
| 2252 | RemoteReduceList.getPointer(), CGF.VoidPtrTy); |
Alexey Bataev | 7cae94e | 2018-01-04 19:45:16 +0000 | [diff] [blame] | 2253 | CGM.getOpenMPRuntime().emitOutlinedFunctionCall( |
| 2254 | CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr}); |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 2255 | Bld.CreateBr(MergeBB); |
| 2256 | |
| 2257 | CGF.EmitBlock(ElseBB); |
| 2258 | Bld.CreateBr(MergeBB); |
| 2259 | |
| 2260 | CGF.EmitBlock(MergeBB); |
| 2261 | |
| 2262 | // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local |
| 2263 | // Reduce list. |
| 2264 | Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1)); |
| 2265 | auto CondCopy = Bld.CreateAnd( |
| 2266 | Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal)); |
| 2267 | |
| 2268 | llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then"); |
| 2269 | llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else"); |
| 2270 | llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont"); |
| 2271 | Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB); |
| 2272 | |
| 2273 | CGF.EmitBlock(CpyThenBB); |
| 2274 | emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates, |
| 2275 | RemoteReduceList, LocalReduceList); |
| 2276 | Bld.CreateBr(CpyMergeBB); |
| 2277 | |
| 2278 | CGF.EmitBlock(CpyElseBB); |
| 2279 | Bld.CreateBr(CpyMergeBB); |
| 2280 | |
| 2281 | CGF.EmitBlock(CpyMergeBB); |
| 2282 | |
| 2283 | CGF.FinishFunction(); |
| 2284 | return Fn; |
| 2285 | } |
| 2286 | |
| 2287 | /// |
| 2288 | /// Design of OpenMP reductions on the GPU |
| 2289 | /// |
| 2290 | /// Consider a typical OpenMP program with one or more reduction |
| 2291 | /// clauses: |
| 2292 | /// |
| 2293 | /// float foo; |
| 2294 | /// double bar; |
| 2295 | /// #pragma omp target teams distribute parallel for \ |
| 2296 | /// reduction(+:foo) reduction(*:bar) |
| 2297 | /// for (int i = 0; i < N; i++) { |
| 2298 | /// foo += A[i]; bar *= B[i]; |
| 2299 | /// } |
| 2300 | /// |
| 2301 | /// where 'foo' and 'bar' are reduced across all OpenMP threads in |
| 2302 | /// all teams. In our OpenMP implementation on the NVPTX device an |
| 2303 | /// OpenMP team is mapped to a CUDA threadblock and OpenMP threads |
| 2304 | /// within a team are mapped to CUDA threads within a threadblock. |
| 2305 | /// Our goal is to efficiently aggregate values across all OpenMP |
| 2306 | /// threads such that: |
| 2307 | /// |
| 2308 | /// - the compiler and runtime are logically concise, and |
| 2309 | /// - the reduction is performed efficiently in a hierarchical |
| 2310 | /// manner as follows: within OpenMP threads in the same warp, |
| 2311 | /// across warps in a threadblock, and finally across teams on |
| 2312 | /// the NVPTX device. |
| 2313 | /// |
| 2314 | /// Introduction to Decoupling |
| 2315 | /// |
| 2316 | /// We would like to decouple the compiler and the runtime so that the |
| 2317 | /// latter is ignorant of the reduction variables (number, data types) |
| 2318 | /// and the reduction operators. This allows a simpler interface |
| 2319 | /// and implementation while still attaining good performance. |
| 2320 | /// |
| 2321 | /// Pseudocode for the aforementioned OpenMP program generated by the |
| 2322 | /// compiler is as follows: |
| 2323 | /// |
| 2324 | /// 1. Create private copies of reduction variables on each OpenMP |
| 2325 | /// thread: 'foo_private', 'bar_private' |
| 2326 | /// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned |
| 2327 | /// to it and writes the result in 'foo_private' and 'bar_private' |
| 2328 | /// respectively. |
| 2329 | /// 3. Call the OpenMP runtime on the GPU to reduce within a team |
| 2330 | /// and store the result on the team master: |
| 2331 | /// |
| 2332 | /// __kmpc_nvptx_parallel_reduce_nowait(..., |
| 2333 | /// reduceData, shuffleReduceFn, interWarpCpyFn) |
| 2334 | /// |
| 2335 | /// where: |
| 2336 | /// struct ReduceData { |
| 2337 | /// double *foo; |
| 2338 | /// double *bar; |
| 2339 | /// } reduceData |
| 2340 | /// reduceData.foo = &foo_private |
| 2341 | /// reduceData.bar = &bar_private |
| 2342 | /// |
| 2343 | /// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two |
| 2344 | /// auxiliary functions generated by the compiler that operate on |
| 2345 | /// variables of type 'ReduceData'. They aid the runtime perform |
| 2346 | /// algorithmic steps in a data agnostic manner. |
| 2347 | /// |
| 2348 | /// 'shuffleReduceFn' is a pointer to a function that reduces data |
| 2349 | /// of type 'ReduceData' across two OpenMP threads (lanes) in the |
| 2350 | /// same warp. It takes the following arguments as input: |
| 2351 | /// |
| 2352 | /// a. variable of type 'ReduceData' on the calling lane, |
| 2353 | /// b. its lane_id, |
| 2354 | /// c. an offset relative to the current lane_id to generate a |
| 2355 | /// remote_lane_id. The remote lane contains the second |
| 2356 | /// variable of type 'ReduceData' that is to be reduced. |
| 2357 | /// d. an algorithm version parameter determining which reduction |
| 2358 | /// algorithm to use. |
| 2359 | /// |
| 2360 | /// 'shuffleReduceFn' retrieves data from the remote lane using |
| 2361 | /// efficient GPU shuffle intrinsics and reduces, using the |
| 2362 | /// algorithm specified by the 4th parameter, the two operands |
| 2363 | /// element-wise. The result is written to the first operand. |
| 2364 | /// |
| 2365 | /// Different reduction algorithms are implemented in different |
| 2366 | /// runtime functions, all calling 'shuffleReduceFn' to perform |
| 2367 | /// the essential reduction step. Therefore, based on the 4th |
| 2368 | /// parameter, this function behaves slightly differently to |
| 2369 | /// cooperate with the runtime to ensure correctness under |
| 2370 | /// different circumstances. |
| 2371 | /// |
| 2372 | /// 'InterWarpCpyFn' is a pointer to a function that transfers |
| 2373 | /// reduced variables across warps. It tunnels, through CUDA |
| 2374 | /// shared memory, the thread-private data of type 'ReduceData' |
| 2375 | /// from lane 0 of each warp to a lane in the first warp. |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 2376 | /// 4. Call the OpenMP runtime on the GPU to reduce across teams. |
| 2377 | /// The last team writes the global reduced value to memory. |
| 2378 | /// |
| 2379 | /// ret = __kmpc_nvptx_teams_reduce_nowait(..., |
| 2380 | /// reduceData, shuffleReduceFn, interWarpCpyFn, |
| 2381 | /// scratchpadCopyFn, loadAndReduceFn) |
| 2382 | /// |
| 2383 | /// 'scratchpadCopyFn' is a helper that stores reduced |
| 2384 | /// data from the team master to a scratchpad array in |
| 2385 | /// global memory. |
| 2386 | /// |
| 2387 | /// 'loadAndReduceFn' is a helper that loads data from |
| 2388 | /// the scratchpad array and reduces it with the input |
| 2389 | /// operand. |
| 2390 | /// |
| 2391 | /// These compiler generated functions hide address |
| 2392 | /// calculation and alignment information from the runtime. |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 2393 | /// 5. if ret == 1: |
| 2394 | /// The team master of the last team stores the reduced |
| 2395 | /// result to the globals in memory. |
| 2396 | /// foo += reduceData.foo; bar *= reduceData.bar |
| 2397 | /// |
| 2398 | /// |
| 2399 | /// Warp Reduction Algorithms |
| 2400 | /// |
| 2401 | /// On the warp level, we have three algorithms implemented in the |
| 2402 | /// OpenMP runtime depending on the number of active lanes: |
| 2403 | /// |
| 2404 | /// Full Warp Reduction |
| 2405 | /// |
| 2406 | /// The reduce algorithm within a warp where all lanes are active |
| 2407 | /// is implemented in the runtime as follows: |
| 2408 | /// |
| 2409 | /// full_warp_reduce(void *reduce_data, |
| 2410 | /// kmp_ShuffleReductFctPtr ShuffleReduceFn) { |
| 2411 | /// for (int offset = WARPSIZE/2; offset > 0; offset /= 2) |
| 2412 | /// ShuffleReduceFn(reduce_data, 0, offset, 0); |
| 2413 | /// } |
| 2414 | /// |
| 2415 | /// The algorithm completes in log(2, WARPSIZE) steps. |
| 2416 | /// |
| 2417 | /// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is |
| 2418 | /// not used therefore we save instructions by not retrieving lane_id |
| 2419 | /// from the corresponding special registers. The 4th parameter, which |
| 2420 | /// represents the version of the algorithm being used, is set to 0 to |
| 2421 | /// signify full warp reduction. |
| 2422 | /// |
| 2423 | /// In this version, 'ShuffleReduceFn' behaves, per element, as follows: |
| 2424 | /// |
| 2425 | /// #reduce_elem refers to an element in the local lane's data structure |
| 2426 | /// #remote_elem is retrieved from a remote lane |
| 2427 | /// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE); |
| 2428 | /// reduce_elem = reduce_elem REDUCE_OP remote_elem; |
| 2429 | /// |
| 2430 | /// Contiguous Partial Warp Reduction |
| 2431 | /// |
| 2432 | /// This reduce algorithm is used within a warp where only the first |
| 2433 | /// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the |
| 2434 | /// number of OpenMP threads in a parallel region is not a multiple of |
| 2435 | /// WARPSIZE. The algorithm is implemented in the runtime as follows: |
| 2436 | /// |
| 2437 | /// void |
| 2438 | /// contiguous_partial_reduce(void *reduce_data, |
| 2439 | /// kmp_ShuffleReductFctPtr ShuffleReduceFn, |
| 2440 | /// int size, int lane_id) { |
| 2441 | /// int curr_size; |
| 2442 | /// int offset; |
| 2443 | /// curr_size = size; |
| 2444 | /// mask = curr_size/2; |
| 2445 | /// while (offset>0) { |
| 2446 | /// ShuffleReduceFn(reduce_data, lane_id, offset, 1); |
| 2447 | /// curr_size = (curr_size+1)/2; |
| 2448 | /// offset = curr_size/2; |
| 2449 | /// } |
| 2450 | /// } |
| 2451 | /// |
| 2452 | /// In this version, 'ShuffleReduceFn' behaves, per element, as follows: |
| 2453 | /// |
| 2454 | /// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE); |
| 2455 | /// if (lane_id < offset) |
| 2456 | /// reduce_elem = reduce_elem REDUCE_OP remote_elem |
| 2457 | /// else |
| 2458 | /// reduce_elem = remote_elem |
| 2459 | /// |
| 2460 | /// This algorithm assumes that the data to be reduced are located in a |
| 2461 | /// contiguous subset of lanes starting from the first. When there is |
| 2462 | /// an odd number of active lanes, the data in the last lane is not |
| 2463 | /// aggregated with any other lane's dat but is instead copied over. |
| 2464 | /// |
| 2465 | /// Dispersed Partial Warp Reduction |
| 2466 | /// |
| 2467 | /// This algorithm is used within a warp when any discontiguous subset of |
| 2468 | /// lanes are active. It is used to implement the reduction operation |
| 2469 | /// across lanes in an OpenMP simd region or in a nested parallel region. |
| 2470 | /// |
| 2471 | /// void |
| 2472 | /// dispersed_partial_reduce(void *reduce_data, |
| 2473 | /// kmp_ShuffleReductFctPtr ShuffleReduceFn) { |
| 2474 | /// int size, remote_id; |
| 2475 | /// int logical_lane_id = number_of_active_lanes_before_me() * 2; |
| 2476 | /// do { |
| 2477 | /// remote_id = next_active_lane_id_right_after_me(); |
| 2478 | /// # the above function returns 0 of no active lane |
| 2479 | /// # is present right after the current lane. |
| 2480 | /// size = number_of_active_lanes_in_this_warp(); |
| 2481 | /// logical_lane_id /= 2; |
| 2482 | /// ShuffleReduceFn(reduce_data, logical_lane_id, |
| 2483 | /// remote_id-1-threadIdx.x, 2); |
| 2484 | /// } while (logical_lane_id % 2 == 0 && size > 1); |
| 2485 | /// } |
| 2486 | /// |
| 2487 | /// There is no assumption made about the initial state of the reduction. |
| 2488 | /// Any number of lanes (>=1) could be active at any position. The reduction |
| 2489 | /// result is returned in the first active lane. |
| 2490 | /// |
| 2491 | /// In this version, 'ShuffleReduceFn' behaves, per element, as follows: |
| 2492 | /// |
| 2493 | /// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE); |
| 2494 | /// if (lane_id % 2 == 0 && offset > 0) |
| 2495 | /// reduce_elem = reduce_elem REDUCE_OP remote_elem |
| 2496 | /// else |
| 2497 | /// reduce_elem = remote_elem |
| 2498 | /// |
| 2499 | /// |
| 2500 | /// Intra-Team Reduction |
| 2501 | /// |
| 2502 | /// This function, as implemented in the runtime call |
| 2503 | /// '__kmpc_nvptx_parallel_reduce_nowait', aggregates data across OpenMP |
| 2504 | /// threads in a team. It first reduces within a warp using the |
| 2505 | /// aforementioned algorithms. We then proceed to gather all such |
| 2506 | /// reduced values at the first warp. |
| 2507 | /// |
| 2508 | /// The runtime makes use of the function 'InterWarpCpyFn', which copies |
| 2509 | /// data from each of the "warp master" (zeroth lane of each warp, where |
| 2510 | /// warp-reduced data is held) to the zeroth warp. This step reduces (in |
| 2511 | /// a mathematical sense) the problem of reduction across warp masters in |
| 2512 | /// a block to the problem of warp reduction. |
| 2513 | /// |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 2514 | /// |
| 2515 | /// Inter-Team Reduction |
| 2516 | /// |
| 2517 | /// Once a team has reduced its data to a single value, it is stored in |
| 2518 | /// a global scratchpad array. Since each team has a distinct slot, this |
| 2519 | /// can be done without locking. |
| 2520 | /// |
| 2521 | /// The last team to write to the scratchpad array proceeds to reduce the |
| 2522 | /// scratchpad array. One or more workers in the last team use the helper |
| 2523 | /// 'loadAndReduceDataFn' to load and reduce values from the array, i.e., |
| 2524 | /// the k'th worker reduces every k'th element. |
| 2525 | /// |
| 2526 | /// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait' to |
| 2527 | /// reduce across workers and compute a globally reduced value. |
| 2528 | /// |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 2529 | void CGOpenMPRuntimeNVPTX::emitReduction( |
| 2530 | CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates, |
| 2531 | ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs, |
| 2532 | ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) { |
| 2533 | if (!CGF.HaveInsertPoint()) |
| 2534 | return; |
| 2535 | |
| 2536 | bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind); |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 2537 | bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind); |
| 2538 | // FIXME: Add support for simd reduction. |
| 2539 | assert((TeamsReduction || ParallelReduction) && |
| 2540 | "Invalid reduction selection in emitReduction."); |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 2541 | |
| 2542 | auto &C = CGM.getContext(); |
| 2543 | |
| 2544 | // 1. Build a list of reduction variables. |
| 2545 | // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]}; |
| 2546 | auto Size = RHSExprs.size(); |
| 2547 | for (auto *E : Privates) { |
| 2548 | if (E->getType()->isVariablyModifiedType()) |
| 2549 | // Reserve place for array size. |
| 2550 | ++Size; |
| 2551 | } |
| 2552 | llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size); |
| 2553 | QualType ReductionArrayTy = |
| 2554 | C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal, |
| 2555 | /*IndexTypeQuals=*/0); |
| 2556 | Address ReductionList = |
| 2557 | CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list"); |
| 2558 | auto IPriv = Privates.begin(); |
| 2559 | unsigned Idx = 0; |
| 2560 | for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) { |
| 2561 | Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, |
| 2562 | CGF.getPointerSize()); |
| 2563 | CGF.Builder.CreateStore( |
| 2564 | CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( |
| 2565 | CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy), |
| 2566 | Elem); |
| 2567 | if ((*IPriv)->getType()->isVariablyModifiedType()) { |
| 2568 | // Store array size. |
| 2569 | ++Idx; |
| 2570 | Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, |
| 2571 | CGF.getPointerSize()); |
| 2572 | llvm::Value *Size = CGF.Builder.CreateIntCast( |
| 2573 | CGF.getVLASize( |
| 2574 | CGF.getContext().getAsVariableArrayType((*IPriv)->getType())) |
Sander de Smalen | 891af03a | 2018-02-03 13:55:59 +0000 | [diff] [blame] | 2575 | .NumElts, |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 2576 | CGF.SizeTy, /*isSigned=*/false); |
| 2577 | CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy), |
| 2578 | Elem); |
| 2579 | } |
| 2580 | } |
| 2581 | |
| 2582 | // 2. Emit reduce_func(). |
| 2583 | auto *ReductionFn = emitReductionFunction( |
Alexey Bataev | 7cae94e | 2018-01-04 19:45:16 +0000 | [diff] [blame] | 2584 | CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), |
| 2585 | Privates, LHSExprs, RHSExprs, ReductionOps); |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 2586 | |
| 2587 | // 4. Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList), |
| 2588 | // RedList, shuffle_reduce_func, interwarp_copy_func); |
| 2589 | auto *ThreadId = getThreadID(CGF, Loc); |
| 2590 | auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy); |
| 2591 | auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( |
| 2592 | ReductionList.getPointer(), CGF.VoidPtrTy); |
| 2593 | |
| 2594 | auto *ShuffleAndReduceFn = emitShuffleAndReduceFunction( |
Alexey Bataev | 7cae94e | 2018-01-04 19:45:16 +0000 | [diff] [blame] | 2595 | CGM, Privates, ReductionArrayTy, ReductionFn, Loc); |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 2596 | auto *InterWarpCopyFn = |
Alexey Bataev | 7cae94e | 2018-01-04 19:45:16 +0000 | [diff] [blame] | 2597 | emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc); |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 2598 | |
| 2599 | llvm::Value *Res = nullptr; |
| 2600 | if (ParallelReduction) { |
| 2601 | llvm::Value *Args[] = {ThreadId, |
| 2602 | CGF.Builder.getInt32(RHSExprs.size()), |
| 2603 | ReductionArrayTySize, |
| 2604 | RL, |
| 2605 | ShuffleAndReduceFn, |
| 2606 | InterWarpCopyFn}; |
| 2607 | |
| 2608 | Res = CGF.EmitRuntimeCall( |
| 2609 | createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_reduce_nowait), |
| 2610 | Args); |
| 2611 | } |
| 2612 | |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 2613 | if (TeamsReduction) { |
| 2614 | auto *ScratchPadCopyFn = |
Alexey Bataev | 7cae94e | 2018-01-04 19:45:16 +0000 | [diff] [blame] | 2615 | emitCopyToScratchpad(CGM, Privates, ReductionArrayTy, Loc); |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 2616 | auto *LoadAndReduceFn = emitReduceScratchpadFunction( |
Alexey Bataev | 7cae94e | 2018-01-04 19:45:16 +0000 | [diff] [blame] | 2617 | CGM, Privates, ReductionArrayTy, ReductionFn, Loc); |
Arpith Chacko Jacob | fc711b1 | 2017-02-16 16:48:49 +0000 | [diff] [blame] | 2618 | |
| 2619 | llvm::Value *Args[] = {ThreadId, |
| 2620 | CGF.Builder.getInt32(RHSExprs.size()), |
| 2621 | ReductionArrayTySize, |
| 2622 | RL, |
| 2623 | ShuffleAndReduceFn, |
| 2624 | InterWarpCopyFn, |
| 2625 | ScratchPadCopyFn, |
| 2626 | LoadAndReduceFn}; |
| 2627 | Res = CGF.EmitRuntimeCall( |
| 2628 | createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_teams_reduce_nowait), |
| 2629 | Args); |
| 2630 | } |
| 2631 | |
Arpith Chacko Jacob | 101e8fb | 2017-02-16 16:20:16 +0000 | [diff] [blame] | 2632 | // 5. Build switch(res) |
| 2633 | auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default"); |
| 2634 | auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/1); |
| 2635 | |
| 2636 | // 6. Build case 1: where we have reduced values in the master |
| 2637 | // thread in each team. |
| 2638 | // __kmpc_end_reduce{_nowait}(<gtid>); |
| 2639 | // break; |
| 2640 | auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1"); |
| 2641 | SwInst->addCase(CGF.Builder.getInt32(1), Case1BB); |
| 2642 | CGF.EmitBlock(Case1BB); |
| 2643 | |
| 2644 | // Add emission of __kmpc_end_reduce{_nowait}(<gtid>); |
| 2645 | llvm::Value *EndArgs[] = {ThreadId}; |
| 2646 | auto &&CodeGen = [&Privates, &LHSExprs, &RHSExprs, &ReductionOps, |
| 2647 | this](CodeGenFunction &CGF, PrePostActionTy &Action) { |
| 2648 | auto IPriv = Privates.begin(); |
| 2649 | auto ILHS = LHSExprs.begin(); |
| 2650 | auto IRHS = RHSExprs.begin(); |
| 2651 | for (auto *E : ReductionOps) { |
| 2652 | emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS), |
| 2653 | cast<DeclRefExpr>(*IRHS)); |
| 2654 | ++IPriv; |
| 2655 | ++ILHS; |
| 2656 | ++IRHS; |
| 2657 | } |
| 2658 | }; |
| 2659 | RegionCodeGenTy RCG(CodeGen); |
| 2660 | NVPTXActionTy Action( |
| 2661 | nullptr, llvm::None, |
| 2662 | createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_reduce_nowait), |
| 2663 | EndArgs); |
| 2664 | RCG.setAction(Action); |
| 2665 | RCG(CGF); |
| 2666 | CGF.EmitBranch(DefaultBB); |
| 2667 | CGF.EmitBlock(DefaultBB, /*IsFinished=*/true); |
| 2668 | } |
Alexey Bataev | 3b8d558 | 2017-08-08 18:04:06 +0000 | [diff] [blame] | 2669 | |
| 2670 | const VarDecl * |
| 2671 | CGOpenMPRuntimeNVPTX::translateParameter(const FieldDecl *FD, |
| 2672 | const VarDecl *NativeParam) const { |
| 2673 | if (!NativeParam->getType()->isReferenceType()) |
| 2674 | return NativeParam; |
| 2675 | QualType ArgType = NativeParam->getType(); |
| 2676 | QualifierCollector QC; |
| 2677 | const Type *NonQualTy = QC.strip(ArgType); |
| 2678 | QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType(); |
| 2679 | if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) { |
| 2680 | if (Attr->getCaptureKind() == OMPC_map) { |
| 2681 | PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy, |
| 2682 | LangAS::opencl_global); |
| 2683 | } |
| 2684 | } |
| 2685 | ArgType = CGM.getContext().getPointerType(PointeeTy); |
| 2686 | QC.addRestrict(); |
| 2687 | enum { NVPTX_local_addr = 5 }; |
Alexander Richardson | 6d98943 | 2017-10-15 18:48:14 +0000 | [diff] [blame] | 2688 | QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr)); |
Alexey Bataev | 3b8d558 | 2017-08-08 18:04:06 +0000 | [diff] [blame] | 2689 | ArgType = QC.apply(CGM.getContext(), ArgType); |
Alexey Bataev | b45d43c | 2017-11-22 16:02:03 +0000 | [diff] [blame] | 2690 | if (isa<ImplicitParamDecl>(NativeParam)) { |
| 2691 | return ImplicitParamDecl::Create( |
| 2692 | CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(), |
| 2693 | NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other); |
| 2694 | } |
| 2695 | return ParmVarDecl::Create( |
| 2696 | CGM.getContext(), |
| 2697 | const_cast<DeclContext *>(NativeParam->getDeclContext()), |
| 2698 | NativeParam->getLocStart(), NativeParam->getLocation(), |
| 2699 | NativeParam->getIdentifier(), ArgType, |
| 2700 | /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr); |
Alexey Bataev | 3b8d558 | 2017-08-08 18:04:06 +0000 | [diff] [blame] | 2701 | } |
| 2702 | |
| 2703 | Address |
| 2704 | CGOpenMPRuntimeNVPTX::getParameterAddress(CodeGenFunction &CGF, |
| 2705 | const VarDecl *NativeParam, |
| 2706 | const VarDecl *TargetParam) const { |
| 2707 | assert(NativeParam != TargetParam && |
| 2708 | NativeParam->getType()->isReferenceType() && |
| 2709 | "Native arg must not be the same as target arg."); |
| 2710 | Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam); |
| 2711 | QualType NativeParamType = NativeParam->getType(); |
| 2712 | QualifierCollector QC; |
| 2713 | const Type *NonQualTy = QC.strip(NativeParamType); |
| 2714 | QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType(); |
| 2715 | unsigned NativePointeeAddrSpace = |
Alexander Richardson | 6d98943 | 2017-10-15 18:48:14 +0000 | [diff] [blame] | 2716 | CGF.getContext().getTargetAddressSpace(NativePointeeTy); |
Alexey Bataev | 36f2c4d | 2017-09-13 20:20:59 +0000 | [diff] [blame] | 2717 | QualType TargetTy = TargetParam->getType(); |
Alexey Bataev | 3b8d558 | 2017-08-08 18:04:06 +0000 | [diff] [blame] | 2718 | llvm::Value *TargetAddr = CGF.EmitLoadOfScalar( |
Alexey Bataev | 36f2c4d | 2017-09-13 20:20:59 +0000 | [diff] [blame] | 2719 | LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation()); |
Alexey Bataev | 3b8d558 | 2017-08-08 18:04:06 +0000 | [diff] [blame] | 2720 | // First cast to generic. |
| 2721 | TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( |
| 2722 | TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo( |
| 2723 | /*AddrSpace=*/0)); |
| 2724 | // Cast from generic to native address space. |
| 2725 | TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( |
| 2726 | TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo( |
| 2727 | NativePointeeAddrSpace)); |
| 2728 | Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType); |
| 2729 | CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false, |
Alexey Bataev | 36f2c4d | 2017-09-13 20:20:59 +0000 | [diff] [blame] | 2730 | NativeParamType); |
Alexey Bataev | 3b8d558 | 2017-08-08 18:04:06 +0000 | [diff] [blame] | 2731 | return NativeParamAddr; |
| 2732 | } |
| 2733 | |
| 2734 | void CGOpenMPRuntimeNVPTX::emitOutlinedFunctionCall( |
Alexey Bataev | 3c595a6 | 2017-08-14 15:01:03 +0000 | [diff] [blame] | 2735 | CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn, |
Alexey Bataev | 3b8d558 | 2017-08-08 18:04:06 +0000 | [diff] [blame] | 2736 | ArrayRef<llvm::Value *> Args) const { |
| 2737 | SmallVector<llvm::Value *, 4> TargetArgs; |
Alexey Bataev | 07ed94a | 2017-08-15 14:34:04 +0000 | [diff] [blame] | 2738 | TargetArgs.reserve(Args.size()); |
Alexey Bataev | 3b8d558 | 2017-08-08 18:04:06 +0000 | [diff] [blame] | 2739 | auto *FnType = |
| 2740 | cast<llvm::FunctionType>(OutlinedFn->getType()->getPointerElementType()); |
| 2741 | for (unsigned I = 0, E = Args.size(); I < E; ++I) { |
Alexey Bataev | 07ed94a | 2017-08-15 14:34:04 +0000 | [diff] [blame] | 2742 | if (FnType->isVarArg() && FnType->getNumParams() <= I) { |
| 2743 | TargetArgs.append(std::next(Args.begin(), I), Args.end()); |
| 2744 | break; |
| 2745 | } |
Alexey Bataev | 3b8d558 | 2017-08-08 18:04:06 +0000 | [diff] [blame] | 2746 | llvm::Type *TargetType = FnType->getParamType(I); |
| 2747 | llvm::Value *NativeArg = Args[I]; |
| 2748 | if (!TargetType->isPointerTy()) { |
| 2749 | TargetArgs.emplace_back(NativeArg); |
| 2750 | continue; |
| 2751 | } |
| 2752 | llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( |
| 2753 | NativeArg, NativeArg->getType()->getPointerElementType()->getPointerTo( |
| 2754 | /*AddrSpace=*/0)); |
| 2755 | TargetArgs.emplace_back( |
| 2756 | CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType)); |
| 2757 | } |
Alexey Bataev | 3c595a6 | 2017-08-14 15:01:03 +0000 | [diff] [blame] | 2758 | CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs); |
Alexey Bataev | 3b8d558 | 2017-08-08 18:04:06 +0000 | [diff] [blame] | 2759 | } |
Gheorghe-Teodor Bercea | d3dcf2f | 2018-03-14 14:17:45 +0000 | [diff] [blame] | 2760 | |
| 2761 | /// Emit function which wraps the outline parallel region |
| 2762 | /// and controls the arguments which are passed to this function. |
| 2763 | /// The wrapper ensures that the outlined function is called |
| 2764 | /// with the correct arguments when data is shared. |
| 2765 | llvm::Function *CGOpenMPRuntimeNVPTX::createParallelDataSharingWrapper( |
| 2766 | llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) { |
| 2767 | ASTContext &Ctx = CGM.getContext(); |
| 2768 | const auto &CS = *D.getCapturedStmt(OMPD_parallel); |
| 2769 | |
| 2770 | // Create a function that takes as argument the source thread. |
| 2771 | FunctionArgList WrapperArgs; |
| 2772 | QualType Int16QTy = |
| 2773 | Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false); |
| 2774 | QualType Int32QTy = |
| 2775 | Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false); |
| 2776 | ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getLocStart(), |
| 2777 | /*Id=*/nullptr, Int16QTy, |
| 2778 | ImplicitParamDecl::Other); |
| 2779 | ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getLocStart(), |
| 2780 | /*Id=*/nullptr, Int32QTy, |
| 2781 | ImplicitParamDecl::Other); |
| 2782 | WrapperArgs.emplace_back(&ParallelLevelArg); |
| 2783 | WrapperArgs.emplace_back(&WrapperArg); |
| 2784 | |
| 2785 | auto &CGFI = |
| 2786 | CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs); |
| 2787 | |
| 2788 | auto *Fn = llvm::Function::Create( |
| 2789 | CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage, |
| 2790 | OutlinedParallelFn->getName() + "_wrapper", &CGM.getModule()); |
| 2791 | CGM.SetInternalFunctionAttributes(/*D=*/GlobalDecl(), Fn, CGFI); |
| 2792 | Fn->setLinkage(llvm::GlobalValue::InternalLinkage); |
| 2793 | |
| 2794 | CodeGenFunction CGF(CGM, /*suppressNewContext=*/true); |
| 2795 | CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs, |
| 2796 | D.getLocStart(), D.getLocStart()); |
| 2797 | |
| 2798 | const auto *RD = CS.getCapturedRecordDecl(); |
| 2799 | auto CurField = RD->field_begin(); |
| 2800 | |
| 2801 | // Get the array of arguments. |
| 2802 | SmallVector<llvm::Value *, 8> Args; |
| 2803 | |
| 2804 | // TODO: suppport SIMD and pass actual values |
| 2805 | Args.emplace_back( |
| 2806 | llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo())); |
| 2807 | Args.emplace_back( |
| 2808 | llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo())); |
| 2809 | |
| 2810 | CGBuilderTy &Bld = CGF.Builder; |
| 2811 | auto CI = CS.capture_begin(); |
| 2812 | |
| 2813 | // Use global memory for data sharing. |
| 2814 | // Handle passing of global args to workers. |
| 2815 | Address GlobalArgs = |
| 2816 | CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args"); |
| 2817 | llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer(); |
| 2818 | llvm::Value *DataSharingArgs[] = {GlobalArgsPtr}; |
| 2819 | CGF.EmitRuntimeCall( |
| 2820 | createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_get_shared_variables), |
| 2821 | DataSharingArgs); |
| 2822 | |
| 2823 | // Retrieve the shared variables from the list of references returned |
| 2824 | // by the runtime. Pass the variables to the outlined function. |
| 2825 | if (CS.capture_size() > 0) { |
| 2826 | ASTContext &CGFContext = CGF.getContext(); |
| 2827 | Address SharedArgListAddress = CGF.EmitLoadOfPointer(GlobalArgs, |
| 2828 | CGFContext |
| 2829 | .getPointerType(CGFContext.getPointerType(CGFContext.VoidPtrTy)) |
| 2830 | .castAs<PointerType>()); |
| 2831 | for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) { |
| 2832 | QualType ElemTy = CurField->getType(); |
| 2833 | Address Src = Bld.CreateConstInBoundsGEP( |
| 2834 | SharedArgListAddress, I, CGF.getPointerSize()); |
| 2835 | Address TypedAddress = Bld.CreateBitCast( |
| 2836 | Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy))); |
| 2837 | llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress, |
| 2838 | /*Volatile=*/false, |
| 2839 | CGFContext.getPointerType(ElemTy), |
| 2840 | CI->getLocation()); |
| 2841 | Args.emplace_back(Arg); |
| 2842 | } |
| 2843 | } |
| 2844 | |
| 2845 | emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedParallelFn, Args); |
| 2846 | CGF.FinishFunction(); |
| 2847 | return Fn; |
| 2848 | } |
| 2849 | |
| 2850 | void CGOpenMPRuntimeNVPTX::emitFunctionProlog(CodeGenFunction &CGF, |
| 2851 | const Decl *D) { |
| 2852 | assert(D && "Expected function or captured|block decl."); |
| 2853 | assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 && |
| 2854 | "Function is registered already."); |
| 2855 | SmallVector<const ValueDecl *, 4> IgnoredDecls; |
| 2856 | const Stmt *Body = nullptr; |
| 2857 | if (const auto *FD = dyn_cast<FunctionDecl>(D)) { |
| 2858 | Body = FD->getBody(); |
| 2859 | } else if (const auto *BD = dyn_cast<BlockDecl>(D)) { |
| 2860 | Body = BD->getBody(); |
| 2861 | } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) { |
| 2862 | Body = CD->getBody(); |
| 2863 | if (CGF.CapturedStmtInfo->getKind() == CR_OpenMP) { |
| 2864 | if (const auto *CS = dyn_cast<CapturedStmt>(Body)) { |
| 2865 | IgnoredDecls.reserve(CS->capture_size()); |
| 2866 | for (const auto &Capture : CS->captures()) |
| 2867 | if (Capture.capturesVariable()) |
| 2868 | IgnoredDecls.emplace_back(Capture.getCapturedVar()); |
| 2869 | } |
| 2870 | } |
| 2871 | } |
| 2872 | if (!Body) |
| 2873 | return; |
| 2874 | CheckVarsEscapingDeclContext VarChecker(CGF, IgnoredDecls); |
| 2875 | VarChecker.Visit(Body); |
| 2876 | const RecordDecl *GlobalizedVarsRecord = VarChecker.getGlobalizedRecord(); |
| 2877 | if (!GlobalizedVarsRecord) |
| 2878 | return; |
| 2879 | auto &Res = |
| 2880 | FunctionGlobalizedDecls |
| 2881 | .try_emplace(CGF.CurFn, GlobalizedVarsRecord, DeclToAddrMapTy()) |
| 2882 | .first->getSecond() |
| 2883 | .second; |
| 2884 | for (const ValueDecl *VD : VarChecker.getEscapedDecls()) { |
| 2885 | const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD); |
| 2886 | Res.insert(std::make_pair(VD, std::make_pair(FD, Address::invalid()))); |
| 2887 | } |
| 2888 | } |
| 2889 | |
| 2890 | Address CGOpenMPRuntimeNVPTX::getAddressOfLocalVariable(CodeGenFunction &CGF, |
| 2891 | const VarDecl *VD) { |
| 2892 | auto I = FunctionGlobalizedDecls.find(CGF.CurFn); |
| 2893 | if (I == FunctionGlobalizedDecls.end()) |
| 2894 | return Address::invalid(); |
| 2895 | auto VDI = I->getSecond().second.find(VD); |
| 2896 | if (VDI == I->getSecond().second.end()) |
| 2897 | return Address::invalid(); |
| 2898 | return VDI->second.second; |
| 2899 | } |
| 2900 | |
| 2901 | void CGOpenMPRuntimeNVPTX::functionFinished(CodeGenFunction &CGF) { |
| 2902 | FunctionToGlobalRecPtr.erase(CGF.CurFn); |
| 2903 | FunctionGlobalizedDecls.erase(CGF.CurFn); |
| 2904 | CGOpenMPRuntime::functionFinished(CGF); |
| 2905 | } |