CGOpenMPRuntimeGPU.h 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. //===------ CGOpenMPRuntimeGPU.h - Interface to OpenMP GPU Runtimes ------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This provides a generalized class for OpenMP runtime code generation
  10. // specialized by GPU targets NVPTX and AMDGCN.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_CLANG_LIB_CODEGEN_CGOPENMPRUNTIMEGPU_H
  14. #define LLVM_CLANG_LIB_CODEGEN_CGOPENMPRUNTIMEGPU_H
  15. #include "CGOpenMPRuntime.h"
  16. #include "CodeGenFunction.h"
  17. #include "clang/AST/StmtOpenMP.h"
  18. namespace clang {
  19. namespace CodeGen {
  20. class CGOpenMPRuntimeGPU : public CGOpenMPRuntime {
  21. public:
  22. /// Defines the execution mode.
  23. enum ExecutionMode {
  24. /// SPMD execution mode (all threads are worker threads).
  25. EM_SPMD,
  26. /// Non-SPMD execution mode (1 master thread, others are workers).
  27. EM_NonSPMD,
  28. /// Unknown execution mode (orphaned directive).
  29. EM_Unknown,
  30. };
  31. private:
  32. /// Parallel outlined function work for workers to execute.
  33. llvm::SmallVector<llvm::Function *, 16> Work;
  34. struct EntryFunctionState {
  35. SourceLocation Loc;
  36. };
  37. ExecutionMode getExecutionMode() const;
  38. bool requiresFullRuntime() const { return RequiresFullRuntime; }
  39. /// Get barrier to synchronize all threads in a block.
  40. void syncCTAThreads(CodeGenFunction &CGF);
  41. /// Helper for target directive initialization.
  42. void emitKernelInit(CodeGenFunction &CGF, EntryFunctionState &EST,
  43. bool IsSPMD);
  44. /// Helper for target directive finalization.
  45. void emitKernelDeinit(CodeGenFunction &CGF, EntryFunctionState &EST,
  46. bool IsSPMD);
  47. /// Helper for generic variables globalization prolog.
  48. void emitGenericVarsProlog(CodeGenFunction &CGF, SourceLocation Loc,
  49. bool WithSPMDCheck = false);
  50. /// Helper for generic variables globalization epilog.
  51. void emitGenericVarsEpilog(CodeGenFunction &CGF, bool WithSPMDCheck = false);
  52. //
  53. // Base class overrides.
  54. //
  55. /// Creates offloading entry for the provided entry ID \a ID,
  56. /// address \a Addr, size \a Size, and flags \a Flags.
  57. void createOffloadEntry(llvm::Constant *ID, llvm::Constant *Addr,
  58. uint64_t Size, int32_t Flags,
  59. llvm::GlobalValue::LinkageTypes Linkage) override;
  60. /// Emit outlined function specialized for the Fork-Join
  61. /// programming model for applicable target directives on the NVPTX device.
  62. /// \param D Directive to emit.
  63. /// \param ParentName Name of the function that encloses the target region.
  64. /// \param OutlinedFn Outlined function value to be defined by this call.
  65. /// \param OutlinedFnID Outlined function ID value to be defined by this call.
  66. /// \param IsOffloadEntry True if the outlined function is an offload entry.
  67. /// An outlined function may not be an entry if, e.g. the if clause always
  68. /// evaluates to false.
  69. void emitNonSPMDKernel(const OMPExecutableDirective &D, StringRef ParentName,
  70. llvm::Function *&OutlinedFn,
  71. llvm::Constant *&OutlinedFnID, bool IsOffloadEntry,
  72. const RegionCodeGenTy &CodeGen);
  73. /// Emit outlined function specialized for the Single Program
  74. /// Multiple Data programming model for applicable target directives on the
  75. /// NVPTX device.
  76. /// \param D Directive to emit.
  77. /// \param ParentName Name of the function that encloses the target region.
  78. /// \param OutlinedFn Outlined function value to be defined by this call.
  79. /// \param OutlinedFnID Outlined function ID value to be defined by this call.
  80. /// \param IsOffloadEntry True if the outlined function is an offload entry.
  81. /// \param CodeGen Object containing the target statements.
  82. /// An outlined function may not be an entry if, e.g. the if clause always
  83. /// evaluates to false.
  84. void emitSPMDKernel(const OMPExecutableDirective &D, StringRef ParentName,
  85. llvm::Function *&OutlinedFn,
  86. llvm::Constant *&OutlinedFnID, bool IsOffloadEntry,
  87. const RegionCodeGenTy &CodeGen);
  88. /// Emit outlined function for 'target' directive on the NVPTX
  89. /// device.
  90. /// \param D Directive to emit.
  91. /// \param ParentName Name of the function that encloses the target region.
  92. /// \param OutlinedFn Outlined function value to be defined by this call.
  93. /// \param OutlinedFnID Outlined function ID value to be defined by this call.
  94. /// \param IsOffloadEntry True if the outlined function is an offload entry.
  95. /// An outlined function may not be an entry if, e.g. the if clause always
  96. /// evaluates to false.
  97. void emitTargetOutlinedFunction(const OMPExecutableDirective &D,
  98. StringRef ParentName,
  99. llvm::Function *&OutlinedFn,
  100. llvm::Constant *&OutlinedFnID,
  101. bool IsOffloadEntry,
  102. const RegionCodeGenTy &CodeGen) override;
  103. /// Emits code for parallel or serial call of the \a OutlinedFn with
  104. /// variables captured in a record which address is stored in \a
  105. /// CapturedStruct.
  106. /// This call is for the Non-SPMD Execution Mode.
  107. /// \param OutlinedFn Outlined function to be run in parallel threads. Type of
  108. /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*).
  109. /// \param CapturedVars A pointer to the record with the references to
  110. /// variables used in \a OutlinedFn function.
  111. /// \param IfCond Condition in the associated 'if' clause, if it was
  112. /// specified, nullptr otherwise.
  113. void emitNonSPMDParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
  114. llvm::Value *OutlinedFn,
  115. ArrayRef<llvm::Value *> CapturedVars,
  116. const Expr *IfCond);
  117. /// Emits code for parallel or serial call of the \a OutlinedFn with
  118. /// variables captured in a record which address is stored in \a
  119. /// CapturedStruct.
  120. /// This call is for a parallel directive within an SPMD target directive.
  121. /// \param OutlinedFn Outlined function to be run in parallel threads. Type of
  122. /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*).
  123. /// \param CapturedVars A pointer to the record with the references to
  124. /// variables used in \a OutlinedFn function.
  125. /// \param IfCond Condition in the associated 'if' clause, if it was
  126. /// specified, nullptr otherwise.
  127. ///
  128. void emitSPMDParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
  129. llvm::Function *OutlinedFn,
  130. ArrayRef<llvm::Value *> CapturedVars,
  131. const Expr *IfCond);
  132. protected:
  133. /// Get the function name of an outlined region.
  134. // The name can be customized depending on the target.
  135. //
  136. StringRef getOutlinedHelperName() const override {
  137. return "__omp_outlined__";
  138. }
  139. /// Check if the default location must be constant.
  140. /// Constant for NVPTX for better optimization.
  141. bool isDefaultLocationConstant() const override { return true; }
  142. /// Returns additional flags that can be stored in reserved_2 field of the
  143. /// default location.
  144. /// For NVPTX target contains data about SPMD/Non-SPMD execution mode +
  145. /// Full/Lightweight runtime mode. Used for better optimization.
  146. unsigned getDefaultLocationReserved2Flags() const override;
  147. public:
  148. explicit CGOpenMPRuntimeGPU(CodeGenModule &CGM);
  149. void clear() override;
  150. /// Declare generalized virtual functions which need to be defined
  151. /// by all specializations of OpenMPGPURuntime Targets like AMDGCN
  152. /// and NVPTX.
  153. /// Get the GPU warp size.
  154. llvm::Value *getGPUWarpSize(CodeGenFunction &CGF);
  155. /// Get the id of the current thread on the GPU.
  156. llvm::Value *getGPUThreadID(CodeGenFunction &CGF);
  157. /// Get the maximum number of threads in a block of the GPU.
  158. llvm::Value *getGPUNumThreads(CodeGenFunction &CGF);
  159. /// Emit call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32
  160. /// global_tid, int proc_bind) to generate code for 'proc_bind' clause.
  161. virtual void emitProcBindClause(CodeGenFunction &CGF,
  162. llvm::omp::ProcBindKind ProcBind,
  163. SourceLocation Loc) override;
  164. /// Emits call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32
  165. /// global_tid, kmp_int32 num_threads) to generate code for 'num_threads'
  166. /// clause.
  167. /// \param NumThreads An integer value of threads.
  168. virtual void emitNumThreadsClause(CodeGenFunction &CGF,
  169. llvm::Value *NumThreads,
  170. SourceLocation Loc) override;
  171. /// This function ought to emit, in the general case, a call to
  172. // the openmp runtime kmpc_push_num_teams. In NVPTX backend it is not needed
  173. // as these numbers are obtained through the PTX grid and block configuration.
  174. /// \param NumTeams An integer expression of teams.
  175. /// \param ThreadLimit An integer expression of threads.
  176. void emitNumTeamsClause(CodeGenFunction &CGF, const Expr *NumTeams,
  177. const Expr *ThreadLimit, SourceLocation Loc) override;
  178. /// Emits inlined function for the specified OpenMP parallel
  179. // directive.
  180. /// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID,
  181. /// kmp_int32 BoundID, struct context_vars*).
  182. /// \param D OpenMP directive.
  183. /// \param ThreadIDVar Variable for thread id in the current OpenMP region.
  184. /// \param InnermostKind Kind of innermost directive (for simple directives it
  185. /// is a directive itself, for combined - its innermost directive).
  186. /// \param CodeGen Code generation sequence for the \a D directive.
  187. llvm::Function *
  188. emitParallelOutlinedFunction(const OMPExecutableDirective &D,
  189. const VarDecl *ThreadIDVar,
  190. OpenMPDirectiveKind InnermostKind,
  191. const RegionCodeGenTy &CodeGen) override;
  192. /// Emits inlined function for the specified OpenMP teams
  193. // directive.
  194. /// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID,
  195. /// kmp_int32 BoundID, struct context_vars*).
  196. /// \param D OpenMP directive.
  197. /// \param ThreadIDVar Variable for thread id in the current OpenMP region.
  198. /// \param InnermostKind Kind of innermost directive (for simple directives it
  199. /// is a directive itself, for combined - its innermost directive).
  200. /// \param CodeGen Code generation sequence for the \a D directive.
  201. llvm::Function *
  202. emitTeamsOutlinedFunction(const OMPExecutableDirective &D,
  203. const VarDecl *ThreadIDVar,
  204. OpenMPDirectiveKind InnermostKind,
  205. const RegionCodeGenTy &CodeGen) override;
  206. /// Emits code for teams call of the \a OutlinedFn with
  207. /// variables captured in a record which address is stored in \a
  208. /// CapturedStruct.
  209. /// \param OutlinedFn Outlined function to be run by team masters. Type of
  210. /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*).
  211. /// \param CapturedVars A pointer to the record with the references to
  212. /// variables used in \a OutlinedFn function.
  213. ///
  214. void emitTeamsCall(CodeGenFunction &CGF, const OMPExecutableDirective &D,
  215. SourceLocation Loc, llvm::Function *OutlinedFn,
  216. ArrayRef<llvm::Value *> CapturedVars) override;
  217. /// Emits code for parallel or serial call of the \a OutlinedFn with
  218. /// variables captured in a record which address is stored in \a
  219. /// CapturedStruct.
  220. /// \param OutlinedFn Outlined function to be run in parallel threads. Type of
  221. /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*).
  222. /// \param CapturedVars A pointer to the record with the references to
  223. /// variables used in \a OutlinedFn function.
  224. /// \param IfCond Condition in the associated 'if' clause, if it was
  225. /// specified, nullptr otherwise.
  226. /// \param NumThreads The value corresponding to the num_threads clause, if
  227. /// any,
  228. /// or nullptr.
  229. void emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
  230. llvm::Function *OutlinedFn,
  231. ArrayRef<llvm::Value *> CapturedVars,
  232. const Expr *IfCond, llvm::Value *NumThreads) override;
  233. /// Emit an implicit/explicit barrier for OpenMP threads.
  234. /// \param Kind Directive for which this implicit barrier call must be
  235. /// generated. Must be OMPD_barrier for explicit barrier generation.
  236. /// \param EmitChecks true if need to emit checks for cancellation barriers.
  237. /// \param ForceSimpleCall true simple barrier call must be emitted, false if
  238. /// runtime class decides which one to emit (simple or with cancellation
  239. /// checks).
  240. ///
  241. void emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
  242. OpenMPDirectiveKind Kind, bool EmitChecks = true,
  243. bool ForceSimpleCall = false) override;
  244. /// Emits a critical region.
  245. /// \param CriticalName Name of the critical region.
  246. /// \param CriticalOpGen Generator for the statement associated with the given
  247. /// critical region.
  248. /// \param Hint Value of the 'hint' clause (optional).
  249. void emitCriticalRegion(CodeGenFunction &CGF, StringRef CriticalName,
  250. const RegionCodeGenTy &CriticalOpGen,
  251. SourceLocation Loc,
  252. const Expr *Hint = nullptr) override;
  253. /// Emit a code for reduction clause.
  254. ///
  255. /// \param Privates List of private copies for original reduction arguments.
  256. /// \param LHSExprs List of LHS in \a ReductionOps reduction operations.
  257. /// \param RHSExprs List of RHS in \a ReductionOps reduction operations.
  258. /// \param ReductionOps List of reduction operations in form 'LHS binop RHS'
  259. /// or 'operator binop(LHS, RHS)'.
  260. /// \param Options List of options for reduction codegen:
  261. /// WithNowait true if parent directive has also nowait clause, false
  262. /// otherwise.
  263. /// SimpleReduction Emit reduction operation only. Used for omp simd
  264. /// directive on the host.
  265. /// ReductionKind The kind of reduction to perform.
  266. virtual void emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
  267. ArrayRef<const Expr *> Privates,
  268. ArrayRef<const Expr *> LHSExprs,
  269. ArrayRef<const Expr *> RHSExprs,
  270. ArrayRef<const Expr *> ReductionOps,
  271. ReductionOptionsTy Options) override;
  272. /// Returns specified OpenMP runtime function for the current OpenMP
  273. /// implementation. Specialized for the NVPTX device.
  274. /// \param Function OpenMP runtime function.
  275. /// \return Specified function.
  276. llvm::FunctionCallee createNVPTXRuntimeFunction(unsigned Function);
  277. /// Translates the native parameter of outlined function if this is required
  278. /// for target.
  279. /// \param FD Field decl from captured record for the parameter.
  280. /// \param NativeParam Parameter itself.
  281. const VarDecl *translateParameter(const FieldDecl *FD,
  282. const VarDecl *NativeParam) const override;
  283. /// Gets the address of the native argument basing on the address of the
  284. /// target-specific parameter.
  285. /// \param NativeParam Parameter itself.
  286. /// \param TargetParam Corresponding target-specific parameter.
  287. Address getParameterAddress(CodeGenFunction &CGF, const VarDecl *NativeParam,
  288. const VarDecl *TargetParam) const override;
  289. /// Emits call of the outlined function with the provided arguments,
  290. /// translating these arguments to correct target-specific arguments.
  291. void emitOutlinedFunctionCall(
  292. CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn,
  293. ArrayRef<llvm::Value *> Args = llvm::None) const override;
  294. /// Emits OpenMP-specific function prolog.
  295. /// Required for device constructs.
  296. void emitFunctionProlog(CodeGenFunction &CGF, const Decl *D) override;
  297. /// Gets the OpenMP-specific address of the local variable.
  298. Address getAddressOfLocalVariable(CodeGenFunction &CGF,
  299. const VarDecl *VD) override;
  300. /// Target codegen is specialized based on two data-sharing modes: CUDA, in
  301. /// which the local variables are actually global threadlocal, and Generic, in
  302. /// which the local variables are placed in global memory if they may escape
  303. /// their declaration context.
  304. enum DataSharingMode {
  305. /// CUDA data sharing mode.
  306. CUDA,
  307. /// Generic data-sharing mode.
  308. Generic,
  309. };
  310. /// Cleans up references to the objects in finished function.
  311. ///
  312. void functionFinished(CodeGenFunction &CGF) override;
  313. /// Choose a default value for the dist_schedule clause.
  314. void getDefaultDistScheduleAndChunk(CodeGenFunction &CGF,
  315. const OMPLoopDirective &S, OpenMPDistScheduleClauseKind &ScheduleKind,
  316. llvm::Value *&Chunk) const override;
  317. /// Choose a default value for the schedule clause.
  318. void getDefaultScheduleAndChunk(CodeGenFunction &CGF,
  319. const OMPLoopDirective &S, OpenMPScheduleClauseKind &ScheduleKind,
  320. const Expr *&ChunkExpr) const override;
  321. /// Adjust some parameters for the target-based directives, like addresses of
  322. /// the variables captured by reference in lambdas.
  323. void adjustTargetSpecificDataForLambdas(
  324. CodeGenFunction &CGF, const OMPExecutableDirective &D) const override;
  325. /// Perform check on requires decl to ensure that target architecture
  326. /// supports unified addressing
  327. void processRequiresDirective(const OMPRequiresDecl *D) override;
  328. /// Checks if the variable has associated OMPAllocateDeclAttr attribute with
  329. /// the predefined allocator and translates it into the corresponding address
  330. /// space.
  331. bool hasAllocateAttributeForGlobalVar(const VarDecl *VD, LangAS &AS) override;
  332. private:
  333. /// Track the execution mode when codegening directives within a target
  334. /// region. The appropriate mode (SPMD/NON-SPMD) is set on entry to the
  335. /// target region and used by containing directives such as 'parallel'
  336. /// to emit optimized code.
  337. ExecutionMode CurrentExecutionMode = EM_Unknown;
  338. /// Check if the full runtime is required (default - yes).
  339. bool RequiresFullRuntime = true;
  340. /// true if we're emitting the code for the target region and next parallel
  341. /// region is L0 for sure.
  342. bool IsInTargetMasterThreadRegion = false;
  343. /// true if currently emitting code for target/teams/distribute region, false
  344. /// - otherwise.
  345. bool IsInTTDRegion = false;
  346. /// true if we're definitely in the parallel region.
  347. bool IsInParallelRegion = false;
  348. /// Map between an outlined function and its wrapper.
  349. llvm::DenseMap<llvm::Function *, llvm::Function *> WrapperFunctionsMap;
  350. /// Emit function which wraps the outline parallel region
  351. /// and controls the parameters which are passed to this function.
  352. /// The wrapper ensures that the outlined function is called
  353. /// with the correct arguments when data is shared.
  354. llvm::Function *createParallelDataSharingWrapper(
  355. llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D);
  356. /// The data for the single globalized variable.
  357. struct MappedVarData {
  358. /// Corresponding field in the global record.
  359. llvm::Value *GlobalizedVal = nullptr;
  360. /// Corresponding address.
  361. Address PrivateAddr = Address::invalid();
  362. };
  363. /// The map of local variables to their addresses in the global memory.
  364. using DeclToAddrMapTy = llvm::MapVector<const Decl *, MappedVarData>;
  365. /// Set of the parameters passed by value escaping OpenMP context.
  366. using EscapedParamsTy = llvm::SmallPtrSet<const Decl *, 4>;
  367. struct FunctionData {
  368. DeclToAddrMapTy LocalVarData;
  369. llvm::Optional<DeclToAddrMapTy> SecondaryLocalVarData = llvm::None;
  370. EscapedParamsTy EscapedParameters;
  371. llvm::SmallVector<const ValueDecl*, 4> EscapedVariableLengthDecls;
  372. llvm::SmallVector<std::pair<llvm::Value *, llvm::Value *>, 4>
  373. EscapedVariableLengthDeclsAddrs;
  374. llvm::Value *IsInSPMDModeFlag = nullptr;
  375. std::unique_ptr<CodeGenFunction::OMPMapVars> MappedParams;
  376. };
  377. /// Maps the function to the list of the globalized variables with their
  378. /// addresses.
  379. llvm::SmallDenseMap<llvm::Function *, FunctionData> FunctionGlobalizedDecls;
  380. llvm::GlobalVariable *KernelTeamsReductionPtr = nullptr;
  381. /// List of the records with the list of fields for the reductions across the
  382. /// teams. Used to build the intermediate buffer for the fast teams
  383. /// reductions.
  384. /// All the records are gathered into a union `union.type` is created.
  385. llvm::SmallVector<const RecordDecl *, 4> TeamsReductions;
  386. /// Shared pointer for the global memory in the global memory buffer used for
  387. /// the given kernel.
  388. llvm::GlobalVariable *KernelStaticGlobalized = nullptr;
  389. /// Pair of the Non-SPMD team and all reductions variables in this team
  390. /// region.
  391. std::pair<const Decl *, llvm::SmallVector<const ValueDecl *, 4>>
  392. TeamAndReductions;
  393. };
  394. } // CodeGen namespace.
  395. } // clang namespace.
  396. #endif // LLVM_CLANG_LIB_CODEGEN_CGOPENMPRUNTIMEGPU_H